1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/SmallBitVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/SelectionDAG.h" 28 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/DerivedTypes.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/KnownBits.h" 37 #include "llvm/Support/MathExtras.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/Target/TargetLowering.h" 40 #include "llvm/Target/TargetOptions.h" 41 #include "llvm/Target/TargetRegisterInfo.h" 42 #include "llvm/Target/TargetSubtargetInfo.h" 43 #include <algorithm> 44 using namespace llvm; 45 46 #define DEBUG_TYPE "dagcombine" 47 48 STATISTIC(NodesCombined , "Number of dag nodes combined"); 49 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 50 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 51 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 52 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 53 STATISTIC(SlicedLoads, "Number of load sliced"); 54 55 namespace { 56 static cl::opt<bool> 57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 58 cl::desc("Enable DAG combiner's use of IR alias analysis")); 59 60 static cl::opt<bool> 61 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 62 cl::desc("Enable DAG combiner's use of TBAA")); 63 64 #ifndef NDEBUG 65 static cl::opt<std::string> 66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 67 cl::desc("Only use DAG-combiner alias analysis in this" 68 " function")); 69 #endif 70 71 /// Hidden option to stress test load slicing, i.e., when this option 72 /// is enabled, load slicing bypasses most of its profitability guards. 73 static cl::opt<bool> 74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 75 cl::desc("Bypass the profitability model of load " 76 "slicing"), 77 cl::init(false)); 78 79 static cl::opt<bool> 80 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 81 cl::desc("DAG combiner may split indexing from loads")); 82 83 //------------------------------ DAGCombiner ---------------------------------// 84 85 class DAGCombiner { 86 SelectionDAG &DAG; 87 const TargetLowering &TLI; 88 CombineLevel Level; 89 CodeGenOpt::Level OptLevel; 90 bool LegalOperations; 91 bool LegalTypes; 92 bool ForCodeSize; 93 94 /// \brief Worklist of all of the nodes that need to be simplified. 95 /// 96 /// This must behave as a stack -- new nodes to process are pushed onto the 97 /// back and when processing we pop off of the back. 98 /// 99 /// The worklist will not contain duplicates but may contain null entries 100 /// due to nodes being deleted from the underlying DAG. 101 SmallVector<SDNode *, 64> Worklist; 102 103 /// \brief Mapping from an SDNode to its position on the worklist. 104 /// 105 /// This is used to find and remove nodes from the worklist (by nulling 106 /// them) when they are deleted from the underlying DAG. It relies on 107 /// stable indices of nodes within the worklist. 108 DenseMap<SDNode *, unsigned> WorklistMap; 109 110 /// \brief Set of nodes which have been combined (at least once). 111 /// 112 /// This is used to allow us to reliably add any operands of a DAG node 113 /// which have not yet been combined to the worklist. 114 SmallPtrSet<SDNode *, 32> CombinedNodes; 115 116 // AA - Used for DAG load/store alias analysis. 117 AliasAnalysis *AA; 118 119 /// When an instruction is simplified, add all users of the instruction to 120 /// the work lists because they might get more simplified now. 121 void AddUsersToWorklist(SDNode *N) { 122 for (SDNode *Node : N->uses()) 123 AddToWorklist(Node); 124 } 125 126 /// Call the node-specific routine that folds each particular type of node. 127 SDValue visit(SDNode *N); 128 129 public: 130 /// Add to the worklist making sure its instance is at the back (next to be 131 /// processed.) 132 void AddToWorklist(SDNode *N) { 133 assert(N->getOpcode() != ISD::DELETED_NODE && 134 "Deleted Node added to Worklist"); 135 136 // Skip handle nodes as they can't usefully be combined and confuse the 137 // zero-use deletion strategy. 138 if (N->getOpcode() == ISD::HANDLENODE) 139 return; 140 141 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 142 Worklist.push_back(N); 143 } 144 145 /// Remove all instances of N from the worklist. 146 void removeFromWorklist(SDNode *N) { 147 CombinedNodes.erase(N); 148 149 auto It = WorklistMap.find(N); 150 if (It == WorklistMap.end()) 151 return; // Not in the worklist. 152 153 // Null out the entry rather than erasing it to avoid a linear operation. 154 Worklist[It->second] = nullptr; 155 WorklistMap.erase(It); 156 } 157 158 void deleteAndRecombine(SDNode *N); 159 bool recursivelyDeleteUnusedNodes(SDNode *N); 160 161 /// Replaces all uses of the results of one DAG node with new values. 162 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 163 bool AddTo = true); 164 165 /// Replaces all uses of the results of one DAG node with new values. 166 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 167 return CombineTo(N, &Res, 1, AddTo); 168 } 169 170 /// Replaces all uses of the results of one DAG node with new values. 171 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 172 bool AddTo = true) { 173 SDValue To[] = { Res0, Res1 }; 174 return CombineTo(N, To, 2, AddTo); 175 } 176 177 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 178 179 private: 180 unsigned MaximumLegalStoreInBits; 181 182 /// Check the specified integer node value to see if it can be simplified or 183 /// if things it uses can be simplified by bit propagation. 184 /// If so, return true. 185 bool SimplifyDemandedBits(SDValue Op) { 186 unsigned BitWidth = Op.getScalarValueSizeInBits(); 187 APInt Demanded = APInt::getAllOnesValue(BitWidth); 188 return SimplifyDemandedBits(Op, Demanded); 189 } 190 191 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 192 193 bool CombineToPreIndexedLoadStore(SDNode *N); 194 bool CombineToPostIndexedLoadStore(SDNode *N); 195 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 196 bool SliceUpLoad(SDNode *N); 197 198 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 199 /// load. 200 /// 201 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 202 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 203 /// \param EltNo index of the vector element to load. 204 /// \param OriginalLoad load that EVE came from to be replaced. 205 /// \returns EVE on success SDValue() on failure. 206 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 207 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 208 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 209 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 210 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 211 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 212 SDValue PromoteIntBinOp(SDValue Op); 213 SDValue PromoteIntShiftOp(SDValue Op); 214 SDValue PromoteExtend(SDValue Op); 215 bool PromoteLoad(SDValue Op); 216 217 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 218 SDValue ExtLoad, const SDLoc &DL, 219 ISD::NodeType ExtType); 220 221 /// Call the node-specific routine that knows how to fold each 222 /// particular type of node. If that doesn't do anything, try the 223 /// target-specific DAG combines. 224 SDValue combine(SDNode *N); 225 226 // Visitation implementation - Implement dag node combining for different 227 // node types. The semantics are as follows: 228 // Return Value: 229 // SDValue.getNode() == 0 - No change was made 230 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 231 // otherwise - N should be replaced by the returned Operand. 232 // 233 SDValue visitTokenFactor(SDNode *N); 234 SDValue visitMERGE_VALUES(SDNode *N); 235 SDValue visitADD(SDNode *N); 236 SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference); 237 SDValue visitSUB(SDNode *N); 238 SDValue visitADDC(SDNode *N); 239 SDValue visitUADDO(SDNode *N); 240 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); 241 SDValue visitSUBC(SDNode *N); 242 SDValue visitUSUBO(SDNode *N); 243 SDValue visitADDE(SDNode *N); 244 SDValue visitADDCARRY(SDNode *N); 245 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); 246 SDValue visitSUBE(SDNode *N); 247 SDValue visitSUBCARRY(SDNode *N); 248 SDValue visitMUL(SDNode *N); 249 SDValue useDivRem(SDNode *N); 250 SDValue visitSDIV(SDNode *N); 251 SDValue visitUDIV(SDNode *N); 252 SDValue visitREM(SDNode *N); 253 SDValue visitMULHU(SDNode *N); 254 SDValue visitMULHS(SDNode *N); 255 SDValue visitSMUL_LOHI(SDNode *N); 256 SDValue visitUMUL_LOHI(SDNode *N); 257 SDValue visitSMULO(SDNode *N); 258 SDValue visitUMULO(SDNode *N); 259 SDValue visitIMINMAX(SDNode *N); 260 SDValue visitAND(SDNode *N); 261 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 262 SDValue visitOR(SDNode *N); 263 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 264 SDValue visitXOR(SDNode *N); 265 SDValue SimplifyVBinOp(SDNode *N); 266 SDValue visitSHL(SDNode *N); 267 SDValue visitSRA(SDNode *N); 268 SDValue visitSRL(SDNode *N); 269 SDValue visitRotate(SDNode *N); 270 SDValue visitABS(SDNode *N); 271 SDValue visitBSWAP(SDNode *N); 272 SDValue visitBITREVERSE(SDNode *N); 273 SDValue visitCTLZ(SDNode *N); 274 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 275 SDValue visitCTTZ(SDNode *N); 276 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 277 SDValue visitCTPOP(SDNode *N); 278 SDValue visitSELECT(SDNode *N); 279 SDValue visitVSELECT(SDNode *N); 280 SDValue visitSELECT_CC(SDNode *N); 281 SDValue visitSETCC(SDNode *N); 282 SDValue visitSETCCE(SDNode *N); 283 SDValue visitSIGN_EXTEND(SDNode *N); 284 SDValue visitZERO_EXTEND(SDNode *N); 285 SDValue visitANY_EXTEND(SDNode *N); 286 SDValue visitAssertZext(SDNode *N); 287 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 288 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 289 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 290 SDValue visitTRUNCATE(SDNode *N); 291 SDValue visitBITCAST(SDNode *N); 292 SDValue visitBUILD_PAIR(SDNode *N); 293 SDValue visitFADD(SDNode *N); 294 SDValue visitFSUB(SDNode *N); 295 SDValue visitFMUL(SDNode *N); 296 SDValue visitFMA(SDNode *N); 297 SDValue visitFDIV(SDNode *N); 298 SDValue visitFREM(SDNode *N); 299 SDValue visitFSQRT(SDNode *N); 300 SDValue visitFCOPYSIGN(SDNode *N); 301 SDValue visitSINT_TO_FP(SDNode *N); 302 SDValue visitUINT_TO_FP(SDNode *N); 303 SDValue visitFP_TO_SINT(SDNode *N); 304 SDValue visitFP_TO_UINT(SDNode *N); 305 SDValue visitFP_ROUND(SDNode *N); 306 SDValue visitFP_ROUND_INREG(SDNode *N); 307 SDValue visitFP_EXTEND(SDNode *N); 308 SDValue visitFNEG(SDNode *N); 309 SDValue visitFABS(SDNode *N); 310 SDValue visitFCEIL(SDNode *N); 311 SDValue visitFTRUNC(SDNode *N); 312 SDValue visitFFLOOR(SDNode *N); 313 SDValue visitFMINNUM(SDNode *N); 314 SDValue visitFMAXNUM(SDNode *N); 315 SDValue visitBRCOND(SDNode *N); 316 SDValue visitBR_CC(SDNode *N); 317 SDValue visitLOAD(SDNode *N); 318 319 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 320 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 321 322 SDValue visitSTORE(SDNode *N); 323 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 324 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 325 SDValue visitBUILD_VECTOR(SDNode *N); 326 SDValue visitCONCAT_VECTORS(SDNode *N); 327 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 328 SDValue visitVECTOR_SHUFFLE(SDNode *N); 329 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 330 SDValue visitINSERT_SUBVECTOR(SDNode *N); 331 SDValue visitMLOAD(SDNode *N); 332 SDValue visitMSTORE(SDNode *N); 333 SDValue visitMGATHER(SDNode *N); 334 SDValue visitMSCATTER(SDNode *N); 335 SDValue visitFP_TO_FP16(SDNode *N); 336 SDValue visitFP16_TO_FP(SDNode *N); 337 338 SDValue visitFADDForFMACombine(SDNode *N); 339 SDValue visitFSUBForFMACombine(SDNode *N); 340 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 341 342 SDValue XformToShuffleWithZero(SDNode *N); 343 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 344 SDValue RHS); 345 346 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 347 348 SDValue foldSelectOfConstants(SDNode *N); 349 SDValue foldBinOpIntoSelect(SDNode *BO); 350 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 351 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 352 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 353 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 354 SDValue N2, SDValue N3, ISD::CondCode CC, 355 bool NotExtCompare = false); 356 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 357 SDValue N2, SDValue N3, ISD::CondCode CC); 358 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 359 const SDLoc &DL); 360 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 361 const SDLoc &DL, bool foldBooleans = true); 362 363 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 364 SDValue &CC) const; 365 bool isOneUseSetCC(SDValue N) const; 366 367 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 368 unsigned HiOp); 369 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 370 SDValue CombineExtLoad(SDNode *N); 371 SDValue combineRepeatedFPDivisors(SDNode *N); 372 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 373 SDValue BuildSDIV(SDNode *N); 374 SDValue BuildSDIVPow2(SDNode *N); 375 SDValue BuildUDIV(SDNode *N); 376 SDValue BuildLogBase2(SDValue Op, const SDLoc &DL); 377 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags); 378 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 379 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 380 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 381 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 382 SDNodeFlags Flags, bool Reciprocal); 383 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 384 SDNodeFlags Flags, bool Reciprocal); 385 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 386 bool DemandHighBits = true); 387 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 388 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 389 SDValue InnerPos, SDValue InnerNeg, 390 unsigned PosOpcode, unsigned NegOpcode, 391 const SDLoc &DL); 392 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 393 SDValue MatchLoadCombine(SDNode *N); 394 SDValue ReduceLoadWidth(SDNode *N); 395 SDValue ReduceLoadOpStoreWidth(SDNode *N); 396 SDValue splitMergedValStore(StoreSDNode *ST); 397 SDValue TransformFPLoadStorePair(SDNode *N); 398 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 399 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 400 SDValue reduceBuildVecToShuffle(SDNode *N); 401 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 402 ArrayRef<int> VectorMask, SDValue VecIn1, 403 SDValue VecIn2, unsigned LeftIdx); 404 SDValue matchVSelectOpSizesWithSetCC(SDNode *N); 405 406 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 407 408 /// Walk up chain skipping non-aliasing memory nodes, 409 /// looking for aliasing nodes and adding them to the Aliases vector. 410 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 411 SmallVectorImpl<SDValue> &Aliases); 412 413 /// Return true if there is any possibility that the two addresses overlap. 414 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 415 416 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 417 /// chain (aliasing node.) 418 SDValue FindBetterChain(SDNode *N, SDValue Chain); 419 420 /// Try to replace a store and any possibly adjacent stores on 421 /// consecutive chains with better chains. Return true only if St is 422 /// replaced. 423 /// 424 /// Notice that other chains may still be replaced even if the function 425 /// returns false. 426 bool findBetterNeighborChains(StoreSDNode *St); 427 428 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 429 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 430 431 /// Holds a pointer to an LSBaseSDNode as well as information on where it 432 /// is located in a sequence of memory operations connected by a chain. 433 struct MemOpLink { 434 MemOpLink(LSBaseSDNode *N, int64_t Offset) 435 : MemNode(N), OffsetFromBase(Offset) {} 436 // Ptr to the mem node. 437 LSBaseSDNode *MemNode; 438 // Offset from the base ptr. 439 int64_t OffsetFromBase; 440 }; 441 442 /// This is a helper function for visitMUL to check the profitability 443 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 444 /// MulNode is the original multiply, AddNode is (add x, c1), 445 /// and ConstNode is c2. 446 bool isMulAddWithConstProfitable(SDNode *MulNode, 447 SDValue &AddNode, 448 SDValue &ConstNode); 449 450 451 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 452 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 453 /// the type of the loaded value to be extended. LoadedVT returns the type 454 /// of the original loaded value. NarrowLoad returns whether the load would 455 /// need to be narrowed in order to match. 456 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 457 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 458 bool &NarrowLoad); 459 460 /// Helper function for MergeConsecutiveStores which merges the 461 /// component store chains. 462 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 463 unsigned NumStores); 464 465 /// This is a helper function for MergeConsecutiveStores. When the source 466 /// elements of the consecutive stores are all constants or all extracted 467 /// vector elements, try to merge them into one larger store. 468 /// \return True if a merged store was created. 469 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 470 EVT MemVT, unsigned NumStores, 471 bool IsConstantSrc, bool UseVector); 472 473 /// This is a helper function for MergeConsecutiveStores. 474 /// Stores that may be merged are placed in StoreNodes. 475 void getStoreMergeCandidates(StoreSDNode *St, 476 SmallVectorImpl<MemOpLink> &StoreNodes); 477 478 /// Helper function for MergeConsecutiveStores. Checks if 479 /// Candidate stores have indirect dependency through their 480 /// operands. \return True if safe to merge 481 bool checkMergeStoreCandidatesForDependencies( 482 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores); 483 484 /// Merge consecutive store operations into a wide store. 485 /// This optimization uses wide integers or vectors when possible. 486 /// \return number of stores that were merged into a merged store (the 487 /// affected nodes are stored as a prefix in \p StoreNodes). 488 bool MergeConsecutiveStores(StoreSDNode *N); 489 490 /// \brief Try to transform a truncation where C is a constant: 491 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 492 /// 493 /// \p N needs to be a truncation and its first operand an AND. Other 494 /// requirements are checked by the function (e.g. that trunc is 495 /// single-use) and if missed an empty SDValue is returned. 496 SDValue distributeTruncateThroughAnd(SDNode *N); 497 498 public: 499 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL) 500 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 501 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(AA) { 502 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 503 504 MaximumLegalStoreInBits = 0; 505 for (MVT VT : MVT::all_valuetypes()) 506 if (EVT(VT).isSimple() && VT != MVT::Other && 507 TLI.isTypeLegal(EVT(VT)) && 508 VT.getSizeInBits() >= MaximumLegalStoreInBits) 509 MaximumLegalStoreInBits = VT.getSizeInBits(); 510 } 511 512 /// Runs the dag combiner on all nodes in the work list 513 void Run(CombineLevel AtLevel); 514 515 SelectionDAG &getDAG() const { return DAG; } 516 517 /// Returns a type large enough to hold any valid shift amount - before type 518 /// legalization these can be huge. 519 EVT getShiftAmountTy(EVT LHSTy) { 520 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 521 if (LHSTy.isVector()) 522 return LHSTy; 523 auto &DL = DAG.getDataLayout(); 524 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 525 : TLI.getPointerTy(DL); 526 } 527 528 /// This method returns true if we are running before type legalization or 529 /// if the specified VT is legal. 530 bool isTypeLegal(const EVT &VT) { 531 if (!LegalTypes) return true; 532 return TLI.isTypeLegal(VT); 533 } 534 535 /// Convenience wrapper around TargetLowering::getSetCCResultType 536 EVT getSetCCResultType(EVT VT) const { 537 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 538 } 539 }; 540 } 541 542 543 namespace { 544 /// This class is a DAGUpdateListener that removes any deleted 545 /// nodes from the worklist. 546 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 547 DAGCombiner &DC; 548 public: 549 explicit WorklistRemover(DAGCombiner &dc) 550 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 551 552 void NodeDeleted(SDNode *N, SDNode *E) override { 553 DC.removeFromWorklist(N); 554 } 555 }; 556 } 557 558 //===----------------------------------------------------------------------===// 559 // TargetLowering::DAGCombinerInfo implementation 560 //===----------------------------------------------------------------------===// 561 562 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 563 ((DAGCombiner*)DC)->AddToWorklist(N); 564 } 565 566 SDValue TargetLowering::DAGCombinerInfo:: 567 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 568 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 569 } 570 571 SDValue TargetLowering::DAGCombinerInfo:: 572 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 573 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 574 } 575 576 577 SDValue TargetLowering::DAGCombinerInfo:: 578 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 579 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 580 } 581 582 void TargetLowering::DAGCombinerInfo:: 583 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 584 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 585 } 586 587 //===----------------------------------------------------------------------===// 588 // Helper Functions 589 //===----------------------------------------------------------------------===// 590 591 void DAGCombiner::deleteAndRecombine(SDNode *N) { 592 removeFromWorklist(N); 593 594 // If the operands of this node are only used by the node, they will now be 595 // dead. Make sure to re-visit them and recursively delete dead nodes. 596 for (const SDValue &Op : N->ops()) 597 // For an operand generating multiple values, one of the values may 598 // become dead allowing further simplification (e.g. split index 599 // arithmetic from an indexed load). 600 if (Op->hasOneUse() || Op->getNumValues() > 1) 601 AddToWorklist(Op.getNode()); 602 603 DAG.DeleteNode(N); 604 } 605 606 /// Return 1 if we can compute the negated form of the specified expression for 607 /// the same cost as the expression itself, or 2 if we can compute the negated 608 /// form more cheaply than the expression itself. 609 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 610 const TargetLowering &TLI, 611 const TargetOptions *Options, 612 unsigned Depth = 0) { 613 // fneg is removable even if it has multiple uses. 614 if (Op.getOpcode() == ISD::FNEG) return 2; 615 616 // Don't allow anything with multiple uses. 617 if (!Op.hasOneUse()) return 0; 618 619 // Don't recurse exponentially. 620 if (Depth > 6) return 0; 621 622 switch (Op.getOpcode()) { 623 default: return false; 624 case ISD::ConstantFP: { 625 if (!LegalOperations) 626 return 1; 627 628 // Don't invert constant FP values after legalization unless the target says 629 // the negated constant is legal. 630 EVT VT = Op.getValueType(); 631 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 632 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT); 633 } 634 case ISD::FADD: 635 // FIXME: determine better conditions for this xform. 636 if (!Options->UnsafeFPMath) return 0; 637 638 // After operation legalization, it might not be legal to create new FSUBs. 639 if (LegalOperations && 640 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 641 return 0; 642 643 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 644 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 645 Options, Depth + 1)) 646 return V; 647 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 648 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 649 Depth + 1); 650 case ISD::FSUB: 651 // We can't turn -(A-B) into B-A when we honor signed zeros. 652 if (!Options->NoSignedZerosFPMath && 653 !Op.getNode()->getFlags().hasNoSignedZeros()) 654 return 0; 655 656 // fold (fneg (fsub A, B)) -> (fsub B, A) 657 return 1; 658 659 case ISD::FMUL: 660 case ISD::FDIV: 661 if (Options->HonorSignDependentRoundingFPMath()) return 0; 662 663 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 664 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 665 Options, Depth + 1)) 666 return V; 667 668 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 669 Depth + 1); 670 671 case ISD::FP_EXTEND: 672 case ISD::FP_ROUND: 673 case ISD::FSIN: 674 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 675 Depth + 1); 676 } 677 } 678 679 /// If isNegatibleForFree returns true, return the newly negated expression. 680 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 681 bool LegalOperations, unsigned Depth = 0) { 682 const TargetOptions &Options = DAG.getTarget().Options; 683 // fneg is removable even if it has multiple uses. 684 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 685 686 // Don't allow anything with multiple uses. 687 assert(Op.hasOneUse() && "Unknown reuse!"); 688 689 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 690 691 const SDNodeFlags Flags = Op.getNode()->getFlags(); 692 693 switch (Op.getOpcode()) { 694 default: llvm_unreachable("Unknown code"); 695 case ISD::ConstantFP: { 696 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 697 V.changeSign(); 698 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 699 } 700 case ISD::FADD: 701 // FIXME: determine better conditions for this xform. 702 assert(Options.UnsafeFPMath); 703 704 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 705 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 706 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 707 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 708 GetNegatedExpression(Op.getOperand(0), DAG, 709 LegalOperations, Depth+1), 710 Op.getOperand(1), Flags); 711 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 712 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 713 GetNegatedExpression(Op.getOperand(1), DAG, 714 LegalOperations, Depth+1), 715 Op.getOperand(0), Flags); 716 case ISD::FSUB: 717 // fold (fneg (fsub 0, B)) -> B 718 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 719 if (N0CFP->isZero()) 720 return Op.getOperand(1); 721 722 // fold (fneg (fsub A, B)) -> (fsub B, A) 723 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 724 Op.getOperand(1), Op.getOperand(0), Flags); 725 726 case ISD::FMUL: 727 case ISD::FDIV: 728 assert(!Options.HonorSignDependentRoundingFPMath()); 729 730 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 731 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 732 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 733 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 734 GetNegatedExpression(Op.getOperand(0), DAG, 735 LegalOperations, Depth+1), 736 Op.getOperand(1), Flags); 737 738 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 739 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 740 Op.getOperand(0), 741 GetNegatedExpression(Op.getOperand(1), DAG, 742 LegalOperations, Depth+1), Flags); 743 744 case ISD::FP_EXTEND: 745 case ISD::FSIN: 746 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 747 GetNegatedExpression(Op.getOperand(0), DAG, 748 LegalOperations, Depth+1)); 749 case ISD::FP_ROUND: 750 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 751 GetNegatedExpression(Op.getOperand(0), DAG, 752 LegalOperations, Depth+1), 753 Op.getOperand(1)); 754 } 755 } 756 757 // APInts must be the same size for most operations, this helper 758 // function zero extends the shorter of the pair so that they match. 759 // We provide an Offset so that we can create bitwidths that won't overflow. 760 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 761 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 762 LHS = LHS.zextOrSelf(Bits); 763 RHS = RHS.zextOrSelf(Bits); 764 } 765 766 // Return true if this node is a setcc, or is a select_cc 767 // that selects between the target values used for true and false, making it 768 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 769 // the appropriate nodes based on the type of node we are checking. This 770 // simplifies life a bit for the callers. 771 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 772 SDValue &CC) const { 773 if (N.getOpcode() == ISD::SETCC) { 774 LHS = N.getOperand(0); 775 RHS = N.getOperand(1); 776 CC = N.getOperand(2); 777 return true; 778 } 779 780 if (N.getOpcode() != ISD::SELECT_CC || 781 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 782 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 783 return false; 784 785 if (TLI.getBooleanContents(N.getValueType()) == 786 TargetLowering::UndefinedBooleanContent) 787 return false; 788 789 LHS = N.getOperand(0); 790 RHS = N.getOperand(1); 791 CC = N.getOperand(4); 792 return true; 793 } 794 795 /// Return true if this is a SetCC-equivalent operation with only one use. 796 /// If this is true, it allows the users to invert the operation for free when 797 /// it is profitable to do so. 798 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 799 SDValue N0, N1, N2; 800 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 801 return true; 802 return false; 803 } 804 805 // \brief Returns the SDNode if it is a constant float BuildVector 806 // or constant float. 807 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 808 if (isa<ConstantFPSDNode>(N)) 809 return N.getNode(); 810 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 811 return N.getNode(); 812 return nullptr; 813 } 814 815 // Determines if it is a constant integer or a build vector of constant 816 // integers (and undefs). 817 // Do not permit build vector implicit truncation. 818 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 819 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 820 return !(Const->isOpaque() && NoOpaques); 821 if (N.getOpcode() != ISD::BUILD_VECTOR) 822 return false; 823 unsigned BitWidth = N.getScalarValueSizeInBits(); 824 for (const SDValue &Op : N->op_values()) { 825 if (Op.isUndef()) 826 continue; 827 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 828 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 829 (Const->isOpaque() && NoOpaques)) 830 return false; 831 } 832 return true; 833 } 834 835 // Determines if it is a constant null integer or a splatted vector of a 836 // constant null integer (with no undefs). 837 // Build vector implicit truncation is not an issue for null values. 838 static bool isNullConstantOrNullSplatConstant(SDValue N) { 839 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 840 return Splat->isNullValue(); 841 return false; 842 } 843 844 // Determines if it is a constant integer of one or a splatted vector of a 845 // constant integer of one (with no undefs). 846 // Do not permit build vector implicit truncation. 847 static bool isOneConstantOrOneSplatConstant(SDValue N) { 848 unsigned BitWidth = N.getScalarValueSizeInBits(); 849 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 850 return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth; 851 return false; 852 } 853 854 // Determines if it is a constant integer of all ones or a splatted vector of a 855 // constant integer of all ones (with no undefs). 856 // Do not permit build vector implicit truncation. 857 static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) { 858 unsigned BitWidth = N.getScalarValueSizeInBits(); 859 if (ConstantSDNode *Splat = isConstOrConstSplat(N)) 860 return Splat->isAllOnesValue() && 861 Splat->getAPIntValue().getBitWidth() == BitWidth; 862 return false; 863 } 864 865 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 866 // undef's. 867 static bool isAnyConstantBuildVector(const SDNode *N) { 868 return ISD::isBuildVectorOfConstantSDNodes(N) || 869 ISD::isBuildVectorOfConstantFPSDNodes(N); 870 } 871 872 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 873 SDValue N1) { 874 EVT VT = N0.getValueType(); 875 if (N0.getOpcode() == Opc) { 876 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 877 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 878 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 879 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 880 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 881 return SDValue(); 882 } 883 if (N0.hasOneUse()) { 884 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 885 // use 886 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 887 if (!OpNode.getNode()) 888 return SDValue(); 889 AddToWorklist(OpNode.getNode()); 890 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 891 } 892 } 893 } 894 895 if (N1.getOpcode() == Opc) { 896 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 897 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 898 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 899 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 900 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 901 return SDValue(); 902 } 903 if (N1.hasOneUse()) { 904 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 905 // use 906 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 907 if (!OpNode.getNode()) 908 return SDValue(); 909 AddToWorklist(OpNode.getNode()); 910 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 911 } 912 } 913 } 914 915 return SDValue(); 916 } 917 918 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 919 bool AddTo) { 920 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 921 ++NodesCombined; 922 DEBUG(dbgs() << "\nReplacing.1 "; 923 N->dump(&DAG); 924 dbgs() << "\nWith: "; 925 To[0].getNode()->dump(&DAG); 926 dbgs() << " and " << NumTo-1 << " other values\n"); 927 for (unsigned i = 0, e = NumTo; i != e; ++i) 928 assert((!To[i].getNode() || 929 N->getValueType(i) == To[i].getValueType()) && 930 "Cannot combine value to value of different type!"); 931 932 WorklistRemover DeadNodes(*this); 933 DAG.ReplaceAllUsesWith(N, To); 934 if (AddTo) { 935 // Push the new nodes and any users onto the worklist 936 for (unsigned i = 0, e = NumTo; i != e; ++i) { 937 if (To[i].getNode()) { 938 AddToWorklist(To[i].getNode()); 939 AddUsersToWorklist(To[i].getNode()); 940 } 941 } 942 } 943 944 // Finally, if the node is now dead, remove it from the graph. The node 945 // may not be dead if the replacement process recursively simplified to 946 // something else needing this node. 947 if (N->use_empty()) 948 deleteAndRecombine(N); 949 return SDValue(N, 0); 950 } 951 952 void DAGCombiner:: 953 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 954 // Replace all uses. If any nodes become isomorphic to other nodes and 955 // are deleted, make sure to remove them from our worklist. 956 WorklistRemover DeadNodes(*this); 957 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 958 959 // Push the new node and any (possibly new) users onto the worklist. 960 AddToWorklist(TLO.New.getNode()); 961 AddUsersToWorklist(TLO.New.getNode()); 962 963 // Finally, if the node is now dead, remove it from the graph. The node 964 // may not be dead if the replacement process recursively simplified to 965 // something else needing this node. 966 if (TLO.Old.getNode()->use_empty()) 967 deleteAndRecombine(TLO.Old.getNode()); 968 } 969 970 /// Check the specified integer node value to see if it can be simplified or if 971 /// things it uses can be simplified by bit propagation. If so, return true. 972 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 973 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 974 KnownBits Known; 975 if (!TLI.SimplifyDemandedBits(Op, Demanded, Known, TLO)) 976 return false; 977 978 // Revisit the node. 979 AddToWorklist(Op.getNode()); 980 981 // Replace the old value with the new one. 982 ++NodesCombined; 983 DEBUG(dbgs() << "\nReplacing.2 "; 984 TLO.Old.getNode()->dump(&DAG); 985 dbgs() << "\nWith: "; 986 TLO.New.getNode()->dump(&DAG); 987 dbgs() << '\n'); 988 989 CommitTargetLoweringOpt(TLO); 990 return true; 991 } 992 993 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 994 SDLoc DL(Load); 995 EVT VT = Load->getValueType(0); 996 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 997 998 DEBUG(dbgs() << "\nReplacing.9 "; 999 Load->dump(&DAG); 1000 dbgs() << "\nWith: "; 1001 Trunc.getNode()->dump(&DAG); 1002 dbgs() << '\n'); 1003 WorklistRemover DeadNodes(*this); 1004 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1005 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1006 deleteAndRecombine(Load); 1007 AddToWorklist(Trunc.getNode()); 1008 } 1009 1010 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1011 Replace = false; 1012 SDLoc DL(Op); 1013 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1014 LoadSDNode *LD = cast<LoadSDNode>(Op); 1015 EVT MemVT = LD->getMemoryVT(); 1016 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1017 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1018 : ISD::EXTLOAD) 1019 : LD->getExtensionType(); 1020 Replace = true; 1021 return DAG.getExtLoad(ExtType, DL, PVT, 1022 LD->getChain(), LD->getBasePtr(), 1023 MemVT, LD->getMemOperand()); 1024 } 1025 1026 unsigned Opc = Op.getOpcode(); 1027 switch (Opc) { 1028 default: break; 1029 case ISD::AssertSext: 1030 return DAG.getNode(ISD::AssertSext, DL, PVT, 1031 SExtPromoteOperand(Op.getOperand(0), PVT), 1032 Op.getOperand(1)); 1033 case ISD::AssertZext: 1034 return DAG.getNode(ISD::AssertZext, DL, PVT, 1035 ZExtPromoteOperand(Op.getOperand(0), PVT), 1036 Op.getOperand(1)); 1037 case ISD::Constant: { 1038 unsigned ExtOpc = 1039 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1040 return DAG.getNode(ExtOpc, DL, PVT, Op); 1041 } 1042 } 1043 1044 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1045 return SDValue(); 1046 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1047 } 1048 1049 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1050 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1051 return SDValue(); 1052 EVT OldVT = Op.getValueType(); 1053 SDLoc DL(Op); 1054 bool Replace = false; 1055 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1056 if (!NewOp.getNode()) 1057 return SDValue(); 1058 AddToWorklist(NewOp.getNode()); 1059 1060 if (Replace) 1061 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1062 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1063 DAG.getValueType(OldVT)); 1064 } 1065 1066 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1067 EVT OldVT = Op.getValueType(); 1068 SDLoc DL(Op); 1069 bool Replace = false; 1070 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1071 if (!NewOp.getNode()) 1072 return SDValue(); 1073 AddToWorklist(NewOp.getNode()); 1074 1075 if (Replace) 1076 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1077 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1078 } 1079 1080 /// Promote the specified integer binary operation if the target indicates it is 1081 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1082 /// i32 since i16 instructions are longer. 1083 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1084 if (!LegalOperations) 1085 return SDValue(); 1086 1087 EVT VT = Op.getValueType(); 1088 if (VT.isVector() || !VT.isInteger()) 1089 return SDValue(); 1090 1091 // If operation type is 'undesirable', e.g. i16 on x86, consider 1092 // promoting it. 1093 unsigned Opc = Op.getOpcode(); 1094 if (TLI.isTypeDesirableForOp(Opc, VT)) 1095 return SDValue(); 1096 1097 EVT PVT = VT; 1098 // Consult target whether it is a good idea to promote this operation and 1099 // what's the right type to promote it to. 1100 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1101 assert(PVT != VT && "Don't know what type to promote to!"); 1102 1103 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1104 1105 bool Replace0 = false; 1106 SDValue N0 = Op.getOperand(0); 1107 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1108 1109 bool Replace1 = false; 1110 SDValue N1 = Op.getOperand(1); 1111 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1112 SDLoc DL(Op); 1113 1114 SDValue RV = 1115 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1116 1117 // New replace instances of N0 and N1 1118 if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 && 1119 NN0.getOpcode() != ISD::DELETED_NODE) { 1120 AddToWorklist(NN0.getNode()); 1121 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1122 } 1123 1124 if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 && 1125 NN1.getOpcode() != ISD::DELETED_NODE) { 1126 AddToWorklist(NN1.getNode()); 1127 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1128 } 1129 1130 // Deal with Op being deleted. 1131 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1132 return RV; 1133 } 1134 return SDValue(); 1135 } 1136 1137 /// Promote the specified integer shift operation if the target indicates it is 1138 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1139 /// i32 since i16 instructions are longer. 1140 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1141 if (!LegalOperations) 1142 return SDValue(); 1143 1144 EVT VT = Op.getValueType(); 1145 if (VT.isVector() || !VT.isInteger()) 1146 return SDValue(); 1147 1148 // If operation type is 'undesirable', e.g. i16 on x86, consider 1149 // promoting it. 1150 unsigned Opc = Op.getOpcode(); 1151 if (TLI.isTypeDesirableForOp(Opc, VT)) 1152 return SDValue(); 1153 1154 EVT PVT = VT; 1155 // Consult target whether it is a good idea to promote this operation and 1156 // what's the right type to promote it to. 1157 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1158 assert(PVT != VT && "Don't know what type to promote to!"); 1159 1160 DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1161 1162 bool Replace = false; 1163 SDValue N0 = Op.getOperand(0); 1164 SDValue N1 = Op.getOperand(1); 1165 if (Opc == ISD::SRA) 1166 N0 = SExtPromoteOperand(N0, PVT); 1167 else if (Opc == ISD::SRL) 1168 N0 = ZExtPromoteOperand(N0, PVT); 1169 else 1170 N0 = PromoteOperand(N0, PVT, Replace); 1171 1172 if (!N0.getNode()) 1173 return SDValue(); 1174 1175 SDLoc DL(Op); 1176 SDValue RV = 1177 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1178 1179 AddToWorklist(N0.getNode()); 1180 if (Replace) 1181 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1182 1183 // Deal with Op being deleted. 1184 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1185 return RV; 1186 } 1187 return SDValue(); 1188 } 1189 1190 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1191 if (!LegalOperations) 1192 return SDValue(); 1193 1194 EVT VT = Op.getValueType(); 1195 if (VT.isVector() || !VT.isInteger()) 1196 return SDValue(); 1197 1198 // If operation type is 'undesirable', e.g. i16 on x86, consider 1199 // promoting it. 1200 unsigned Opc = Op.getOpcode(); 1201 if (TLI.isTypeDesirableForOp(Opc, VT)) 1202 return SDValue(); 1203 1204 EVT PVT = VT; 1205 // Consult target whether it is a good idea to promote this operation and 1206 // what's the right type to promote it to. 1207 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1208 assert(PVT != VT && "Don't know what type to promote to!"); 1209 // fold (aext (aext x)) -> (aext x) 1210 // fold (aext (zext x)) -> (zext x) 1211 // fold (aext (sext x)) -> (sext x) 1212 DEBUG(dbgs() << "\nPromoting "; 1213 Op.getNode()->dump(&DAG)); 1214 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1215 } 1216 return SDValue(); 1217 } 1218 1219 bool DAGCombiner::PromoteLoad(SDValue Op) { 1220 if (!LegalOperations) 1221 return false; 1222 1223 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1224 return false; 1225 1226 EVT VT = Op.getValueType(); 1227 if (VT.isVector() || !VT.isInteger()) 1228 return false; 1229 1230 // If operation type is 'undesirable', e.g. i16 on x86, consider 1231 // promoting it. 1232 unsigned Opc = Op.getOpcode(); 1233 if (TLI.isTypeDesirableForOp(Opc, VT)) 1234 return false; 1235 1236 EVT PVT = VT; 1237 // Consult target whether it is a good idea to promote this operation and 1238 // what's the right type to promote it to. 1239 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1240 assert(PVT != VT && "Don't know what type to promote to!"); 1241 1242 SDLoc DL(Op); 1243 SDNode *N = Op.getNode(); 1244 LoadSDNode *LD = cast<LoadSDNode>(N); 1245 EVT MemVT = LD->getMemoryVT(); 1246 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1247 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1248 : ISD::EXTLOAD) 1249 : LD->getExtensionType(); 1250 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1251 LD->getChain(), LD->getBasePtr(), 1252 MemVT, LD->getMemOperand()); 1253 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1254 1255 DEBUG(dbgs() << "\nPromoting "; 1256 N->dump(&DAG); 1257 dbgs() << "\nTo: "; 1258 Result.getNode()->dump(&DAG); 1259 dbgs() << '\n'); 1260 WorklistRemover DeadNodes(*this); 1261 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1262 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1263 deleteAndRecombine(N); 1264 AddToWorklist(Result.getNode()); 1265 return true; 1266 } 1267 return false; 1268 } 1269 1270 /// \brief Recursively delete a node which has no uses and any operands for 1271 /// which it is the only use. 1272 /// 1273 /// Note that this both deletes the nodes and removes them from the worklist. 1274 /// It also adds any nodes who have had a user deleted to the worklist as they 1275 /// may now have only one use and subject to other combines. 1276 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1277 if (!N->use_empty()) 1278 return false; 1279 1280 SmallSetVector<SDNode *, 16> Nodes; 1281 Nodes.insert(N); 1282 do { 1283 N = Nodes.pop_back_val(); 1284 if (!N) 1285 continue; 1286 1287 if (N->use_empty()) { 1288 for (const SDValue &ChildN : N->op_values()) 1289 Nodes.insert(ChildN.getNode()); 1290 1291 removeFromWorklist(N); 1292 DAG.DeleteNode(N); 1293 } else { 1294 AddToWorklist(N); 1295 } 1296 } while (!Nodes.empty()); 1297 return true; 1298 } 1299 1300 //===----------------------------------------------------------------------===// 1301 // Main DAG Combiner implementation 1302 //===----------------------------------------------------------------------===// 1303 1304 void DAGCombiner::Run(CombineLevel AtLevel) { 1305 // set the instance variables, so that the various visit routines may use it. 1306 Level = AtLevel; 1307 LegalOperations = Level >= AfterLegalizeVectorOps; 1308 LegalTypes = Level >= AfterLegalizeTypes; 1309 1310 // Add all the dag nodes to the worklist. 1311 for (SDNode &Node : DAG.allnodes()) 1312 AddToWorklist(&Node); 1313 1314 // Create a dummy node (which is not added to allnodes), that adds a reference 1315 // to the root node, preventing it from being deleted, and tracking any 1316 // changes of the root. 1317 HandleSDNode Dummy(DAG.getRoot()); 1318 1319 // While the worklist isn't empty, find a node and try to combine it. 1320 while (!WorklistMap.empty()) { 1321 SDNode *N; 1322 // The Worklist holds the SDNodes in order, but it may contain null entries. 1323 do { 1324 N = Worklist.pop_back_val(); 1325 } while (!N); 1326 1327 bool GoodWorklistEntry = WorklistMap.erase(N); 1328 (void)GoodWorklistEntry; 1329 assert(GoodWorklistEntry && 1330 "Found a worklist entry without a corresponding map entry!"); 1331 1332 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1333 // N is deleted from the DAG, since they too may now be dead or may have a 1334 // reduced number of uses, allowing other xforms. 1335 if (recursivelyDeleteUnusedNodes(N)) 1336 continue; 1337 1338 WorklistRemover DeadNodes(*this); 1339 1340 // If this combine is running after legalizing the DAG, re-legalize any 1341 // nodes pulled off the worklist. 1342 if (Level == AfterLegalizeDAG) { 1343 SmallSetVector<SDNode *, 16> UpdatedNodes; 1344 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1345 1346 for (SDNode *LN : UpdatedNodes) { 1347 AddToWorklist(LN); 1348 AddUsersToWorklist(LN); 1349 } 1350 if (!NIsValid) 1351 continue; 1352 } 1353 1354 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1355 1356 // Add any operands of the new node which have not yet been combined to the 1357 // worklist as well. Because the worklist uniques things already, this 1358 // won't repeatedly process the same operand. 1359 CombinedNodes.insert(N); 1360 for (const SDValue &ChildN : N->op_values()) 1361 if (!CombinedNodes.count(ChildN.getNode())) 1362 AddToWorklist(ChildN.getNode()); 1363 1364 SDValue RV = combine(N); 1365 1366 if (!RV.getNode()) 1367 continue; 1368 1369 ++NodesCombined; 1370 1371 // If we get back the same node we passed in, rather than a new node or 1372 // zero, we know that the node must have defined multiple values and 1373 // CombineTo was used. Since CombineTo takes care of the worklist 1374 // mechanics for us, we have no work to do in this case. 1375 if (RV.getNode() == N) 1376 continue; 1377 1378 assert(N->getOpcode() != ISD::DELETED_NODE && 1379 RV.getOpcode() != ISD::DELETED_NODE && 1380 "Node was deleted but visit returned new node!"); 1381 1382 DEBUG(dbgs() << " ... into: "; 1383 RV.getNode()->dump(&DAG)); 1384 1385 if (N->getNumValues() == RV.getNode()->getNumValues()) 1386 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1387 else { 1388 assert(N->getValueType(0) == RV.getValueType() && 1389 N->getNumValues() == 1 && "Type mismatch"); 1390 DAG.ReplaceAllUsesWith(N, &RV); 1391 } 1392 1393 // Push the new node and any users onto the worklist 1394 AddToWorklist(RV.getNode()); 1395 AddUsersToWorklist(RV.getNode()); 1396 1397 // Finally, if the node is now dead, remove it from the graph. The node 1398 // may not be dead if the replacement process recursively simplified to 1399 // something else needing this node. This will also take care of adding any 1400 // operands which have lost a user to the worklist. 1401 recursivelyDeleteUnusedNodes(N); 1402 } 1403 1404 // If the root changed (e.g. it was a dead load, update the root). 1405 DAG.setRoot(Dummy.getValue()); 1406 DAG.RemoveDeadNodes(); 1407 } 1408 1409 SDValue DAGCombiner::visit(SDNode *N) { 1410 switch (N->getOpcode()) { 1411 default: break; 1412 case ISD::TokenFactor: return visitTokenFactor(N); 1413 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1414 case ISD::ADD: return visitADD(N); 1415 case ISD::SUB: return visitSUB(N); 1416 case ISD::ADDC: return visitADDC(N); 1417 case ISD::UADDO: return visitUADDO(N); 1418 case ISD::SUBC: return visitSUBC(N); 1419 case ISD::USUBO: return visitUSUBO(N); 1420 case ISD::ADDE: return visitADDE(N); 1421 case ISD::ADDCARRY: return visitADDCARRY(N); 1422 case ISD::SUBE: return visitSUBE(N); 1423 case ISD::SUBCARRY: return visitSUBCARRY(N); 1424 case ISD::MUL: return visitMUL(N); 1425 case ISD::SDIV: return visitSDIV(N); 1426 case ISD::UDIV: return visitUDIV(N); 1427 case ISD::SREM: 1428 case ISD::UREM: return visitREM(N); 1429 case ISD::MULHU: return visitMULHU(N); 1430 case ISD::MULHS: return visitMULHS(N); 1431 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1432 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1433 case ISD::SMULO: return visitSMULO(N); 1434 case ISD::UMULO: return visitUMULO(N); 1435 case ISD::SMIN: 1436 case ISD::SMAX: 1437 case ISD::UMIN: 1438 case ISD::UMAX: return visitIMINMAX(N); 1439 case ISD::AND: return visitAND(N); 1440 case ISD::OR: return visitOR(N); 1441 case ISD::XOR: return visitXOR(N); 1442 case ISD::SHL: return visitSHL(N); 1443 case ISD::SRA: return visitSRA(N); 1444 case ISD::SRL: return visitSRL(N); 1445 case ISD::ROTR: 1446 case ISD::ROTL: return visitRotate(N); 1447 case ISD::ABS: return visitABS(N); 1448 case ISD::BSWAP: return visitBSWAP(N); 1449 case ISD::BITREVERSE: return visitBITREVERSE(N); 1450 case ISD::CTLZ: return visitCTLZ(N); 1451 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1452 case ISD::CTTZ: return visitCTTZ(N); 1453 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1454 case ISD::CTPOP: return visitCTPOP(N); 1455 case ISD::SELECT: return visitSELECT(N); 1456 case ISD::VSELECT: return visitVSELECT(N); 1457 case ISD::SELECT_CC: return visitSELECT_CC(N); 1458 case ISD::SETCC: return visitSETCC(N); 1459 case ISD::SETCCE: return visitSETCCE(N); 1460 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1461 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1462 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1463 case ISD::AssertZext: return visitAssertZext(N); 1464 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1465 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1466 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1467 case ISD::TRUNCATE: return visitTRUNCATE(N); 1468 case ISD::BITCAST: return visitBITCAST(N); 1469 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1470 case ISD::FADD: return visitFADD(N); 1471 case ISD::FSUB: return visitFSUB(N); 1472 case ISD::FMUL: return visitFMUL(N); 1473 case ISD::FMA: return visitFMA(N); 1474 case ISD::FDIV: return visitFDIV(N); 1475 case ISD::FREM: return visitFREM(N); 1476 case ISD::FSQRT: return visitFSQRT(N); 1477 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1478 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1479 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1480 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1481 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1482 case ISD::FP_ROUND: return visitFP_ROUND(N); 1483 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1484 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1485 case ISD::FNEG: return visitFNEG(N); 1486 case ISD::FABS: return visitFABS(N); 1487 case ISD::FFLOOR: return visitFFLOOR(N); 1488 case ISD::FMINNUM: return visitFMINNUM(N); 1489 case ISD::FMAXNUM: return visitFMAXNUM(N); 1490 case ISD::FCEIL: return visitFCEIL(N); 1491 case ISD::FTRUNC: return visitFTRUNC(N); 1492 case ISD::BRCOND: return visitBRCOND(N); 1493 case ISD::BR_CC: return visitBR_CC(N); 1494 case ISD::LOAD: return visitLOAD(N); 1495 case ISD::STORE: return visitSTORE(N); 1496 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1497 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1498 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1499 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1500 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1501 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1502 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1503 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1504 case ISD::MGATHER: return visitMGATHER(N); 1505 case ISD::MLOAD: return visitMLOAD(N); 1506 case ISD::MSCATTER: return visitMSCATTER(N); 1507 case ISD::MSTORE: return visitMSTORE(N); 1508 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1509 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1510 } 1511 return SDValue(); 1512 } 1513 1514 SDValue DAGCombiner::combine(SDNode *N) { 1515 SDValue RV = visit(N); 1516 1517 // If nothing happened, try a target-specific DAG combine. 1518 if (!RV.getNode()) { 1519 assert(N->getOpcode() != ISD::DELETED_NODE && 1520 "Node was deleted but visit returned NULL!"); 1521 1522 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1523 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1524 1525 // Expose the DAG combiner to the target combiner impls. 1526 TargetLowering::DAGCombinerInfo 1527 DagCombineInfo(DAG, Level, false, this); 1528 1529 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1530 } 1531 } 1532 1533 // If nothing happened still, try promoting the operation. 1534 if (!RV.getNode()) { 1535 switch (N->getOpcode()) { 1536 default: break; 1537 case ISD::ADD: 1538 case ISD::SUB: 1539 case ISD::MUL: 1540 case ISD::AND: 1541 case ISD::OR: 1542 case ISD::XOR: 1543 RV = PromoteIntBinOp(SDValue(N, 0)); 1544 break; 1545 case ISD::SHL: 1546 case ISD::SRA: 1547 case ISD::SRL: 1548 RV = PromoteIntShiftOp(SDValue(N, 0)); 1549 break; 1550 case ISD::SIGN_EXTEND: 1551 case ISD::ZERO_EXTEND: 1552 case ISD::ANY_EXTEND: 1553 RV = PromoteExtend(SDValue(N, 0)); 1554 break; 1555 case ISD::LOAD: 1556 if (PromoteLoad(SDValue(N, 0))) 1557 RV = SDValue(N, 0); 1558 break; 1559 } 1560 } 1561 1562 // If N is a commutative binary node, try commuting it to enable more 1563 // sdisel CSE. 1564 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1565 N->getNumValues() == 1) { 1566 SDValue N0 = N->getOperand(0); 1567 SDValue N1 = N->getOperand(1); 1568 1569 // Constant operands are canonicalized to RHS. 1570 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1571 SDValue Ops[] = {N1, N0}; 1572 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1573 N->getFlags()); 1574 if (CSENode) 1575 return SDValue(CSENode, 0); 1576 } 1577 } 1578 1579 return RV; 1580 } 1581 1582 /// Given a node, return its input chain if it has one, otherwise return a null 1583 /// sd operand. 1584 static SDValue getInputChainForNode(SDNode *N) { 1585 if (unsigned NumOps = N->getNumOperands()) { 1586 if (N->getOperand(0).getValueType() == MVT::Other) 1587 return N->getOperand(0); 1588 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1589 return N->getOperand(NumOps-1); 1590 for (unsigned i = 1; i < NumOps-1; ++i) 1591 if (N->getOperand(i).getValueType() == MVT::Other) 1592 return N->getOperand(i); 1593 } 1594 return SDValue(); 1595 } 1596 1597 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1598 // If N has two operands, where one has an input chain equal to the other, 1599 // the 'other' chain is redundant. 1600 if (N->getNumOperands() == 2) { 1601 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1602 return N->getOperand(0); 1603 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1604 return N->getOperand(1); 1605 } 1606 1607 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1608 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1609 SmallPtrSet<SDNode*, 16> SeenOps; 1610 bool Changed = false; // If we should replace this token factor. 1611 1612 // Start out with this token factor. 1613 TFs.push_back(N); 1614 1615 // Iterate through token factors. The TFs grows when new token factors are 1616 // encountered. 1617 for (unsigned i = 0; i < TFs.size(); ++i) { 1618 SDNode *TF = TFs[i]; 1619 1620 // Check each of the operands. 1621 for (const SDValue &Op : TF->op_values()) { 1622 1623 switch (Op.getOpcode()) { 1624 case ISD::EntryToken: 1625 // Entry tokens don't need to be added to the list. They are 1626 // redundant. 1627 Changed = true; 1628 break; 1629 1630 case ISD::TokenFactor: 1631 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1632 // Queue up for processing. 1633 TFs.push_back(Op.getNode()); 1634 // Clean up in case the token factor is removed. 1635 AddToWorklist(Op.getNode()); 1636 Changed = true; 1637 break; 1638 } 1639 LLVM_FALLTHROUGH; 1640 1641 default: 1642 // Only add if it isn't already in the list. 1643 if (SeenOps.insert(Op.getNode()).second) 1644 Ops.push_back(Op); 1645 else 1646 Changed = true; 1647 break; 1648 } 1649 } 1650 } 1651 1652 // Remove Nodes that are chained to another node in the list. Do so 1653 // by walking up chains breath-first stopping when we've seen 1654 // another operand. In general we must climb to the EntryNode, but we can exit 1655 // early if we find all remaining work is associated with just one operand as 1656 // no further pruning is possible. 1657 1658 // List of nodes to search through and original Ops from which they originate. 1659 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1660 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1661 SmallPtrSet<SDNode *, 16> SeenChains; 1662 bool DidPruneOps = false; 1663 1664 unsigned NumLeftToConsider = 0; 1665 for (const SDValue &Op : Ops) { 1666 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1667 OpWorkCount.push_back(1); 1668 } 1669 1670 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1671 // If this is an Op, we can remove the op from the list. Remark any 1672 // search associated with it as from the current OpNumber. 1673 if (SeenOps.count(Op) != 0) { 1674 Changed = true; 1675 DidPruneOps = true; 1676 unsigned OrigOpNumber = 0; 1677 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1678 OrigOpNumber++; 1679 assert((OrigOpNumber != Ops.size()) && 1680 "expected to find TokenFactor Operand"); 1681 // Re-mark worklist from OrigOpNumber to OpNumber 1682 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1683 if (Worklist[i].second == OrigOpNumber) { 1684 Worklist[i].second = OpNumber; 1685 } 1686 } 1687 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1688 OpWorkCount[OrigOpNumber] = 0; 1689 NumLeftToConsider--; 1690 } 1691 // Add if it's a new chain 1692 if (SeenChains.insert(Op).second) { 1693 OpWorkCount[OpNumber]++; 1694 Worklist.push_back(std::make_pair(Op, OpNumber)); 1695 } 1696 }; 1697 1698 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1699 // We need at least be consider at least 2 Ops to prune. 1700 if (NumLeftToConsider <= 1) 1701 break; 1702 auto CurNode = Worklist[i].first; 1703 auto CurOpNumber = Worklist[i].second; 1704 assert((OpWorkCount[CurOpNumber] > 0) && 1705 "Node should not appear in worklist"); 1706 switch (CurNode->getOpcode()) { 1707 case ISD::EntryToken: 1708 // Hitting EntryToken is the only way for the search to terminate without 1709 // hitting 1710 // another operand's search. Prevent us from marking this operand 1711 // considered. 1712 NumLeftToConsider++; 1713 break; 1714 case ISD::TokenFactor: 1715 for (const SDValue &Op : CurNode->op_values()) 1716 AddToWorklist(i, Op.getNode(), CurOpNumber); 1717 break; 1718 case ISD::CopyFromReg: 1719 case ISD::CopyToReg: 1720 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1721 break; 1722 default: 1723 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1724 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1725 break; 1726 } 1727 OpWorkCount[CurOpNumber]--; 1728 if (OpWorkCount[CurOpNumber] == 0) 1729 NumLeftToConsider--; 1730 } 1731 1732 // If we've changed things around then replace token factor. 1733 if (Changed) { 1734 SDValue Result; 1735 if (Ops.empty()) { 1736 // The entry token is the only possible outcome. 1737 Result = DAG.getEntryNode(); 1738 } else { 1739 if (DidPruneOps) { 1740 SmallVector<SDValue, 8> PrunedOps; 1741 // 1742 for (const SDValue &Op : Ops) { 1743 if (SeenChains.count(Op.getNode()) == 0) 1744 PrunedOps.push_back(Op); 1745 } 1746 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1747 } else { 1748 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1749 } 1750 } 1751 return Result; 1752 } 1753 return SDValue(); 1754 } 1755 1756 /// MERGE_VALUES can always be eliminated. 1757 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1758 WorklistRemover DeadNodes(*this); 1759 // Replacing results may cause a different MERGE_VALUES to suddenly 1760 // be CSE'd with N, and carry its uses with it. Iterate until no 1761 // uses remain, to ensure that the node can be safely deleted. 1762 // First add the users of this node to the work list so that they 1763 // can be tried again once they have new operands. 1764 AddUsersToWorklist(N); 1765 do { 1766 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1767 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1768 } while (!N->use_empty()); 1769 deleteAndRecombine(N); 1770 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1771 } 1772 1773 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1774 /// ConstantSDNode pointer else nullptr. 1775 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1776 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1777 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1778 } 1779 1780 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1781 auto BinOpcode = BO->getOpcode(); 1782 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || 1783 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || 1784 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || 1785 BinOpcode == ISD::UREM || BinOpcode == ISD::AND || 1786 BinOpcode == ISD::OR || BinOpcode == ISD::XOR || 1787 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || 1788 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || 1789 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || 1790 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && 1791 "Unexpected binary operator"); 1792 1793 // Bail out if any constants are opaque because we can't constant fold those. 1794 SDValue C1 = BO->getOperand(1); 1795 if (!isConstantOrConstantVector(C1, true) && 1796 !isConstantFPBuildVectorOrConstantFP(C1)) 1797 return SDValue(); 1798 1799 // Don't do this unless the old select is going away. We want to eliminate the 1800 // binary operator, not replace a binop with a select. 1801 // TODO: Handle ISD::SELECT_CC. 1802 SDValue Sel = BO->getOperand(0); 1803 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1804 return SDValue(); 1805 1806 SDValue CT = Sel.getOperand(1); 1807 if (!isConstantOrConstantVector(CT, true) && 1808 !isConstantFPBuildVectorOrConstantFP(CT)) 1809 return SDValue(); 1810 1811 SDValue CF = Sel.getOperand(2); 1812 if (!isConstantOrConstantVector(CF, true) && 1813 !isConstantFPBuildVectorOrConstantFP(CF)) 1814 return SDValue(); 1815 1816 // We have a select-of-constants followed by a binary operator with a 1817 // constant. Eliminate the binop by pulling the constant math into the select. 1818 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1 1819 EVT VT = Sel.getValueType(); 1820 SDLoc DL(Sel); 1821 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1); 1822 assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) || 1823 isConstantFPBuildVectorOrConstantFP(NewCT)) && 1824 "Failed to constant fold a binop with constant operands"); 1825 1826 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1); 1827 assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) || 1828 isConstantFPBuildVectorOrConstantFP(NewCF)) && 1829 "Failed to constant fold a binop with constant operands"); 1830 1831 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1832 } 1833 1834 SDValue DAGCombiner::visitADD(SDNode *N) { 1835 SDValue N0 = N->getOperand(0); 1836 SDValue N1 = N->getOperand(1); 1837 EVT VT = N0.getValueType(); 1838 SDLoc DL(N); 1839 1840 // fold vector ops 1841 if (VT.isVector()) { 1842 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1843 return FoldedVOp; 1844 1845 // fold (add x, 0) -> x, vector edition 1846 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1847 return N0; 1848 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1849 return N1; 1850 } 1851 1852 // fold (add x, undef) -> undef 1853 if (N0.isUndef()) 1854 return N0; 1855 1856 if (N1.isUndef()) 1857 return N1; 1858 1859 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1860 // canonicalize constant to RHS 1861 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1862 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1863 // fold (add c1, c2) -> c1+c2 1864 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1865 N1.getNode()); 1866 } 1867 1868 // fold (add x, 0) -> x 1869 if (isNullConstant(N1)) 1870 return N0; 1871 1872 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1873 // fold ((c1-A)+c2) -> (c1+c2)-A 1874 if (N0.getOpcode() == ISD::SUB && 1875 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1876 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 1877 return DAG.getNode(ISD::SUB, DL, VT, 1878 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1879 N0.getOperand(1)); 1880 } 1881 1882 // add (sext i1 X), 1 -> zext (not i1 X) 1883 // We don't transform this pattern: 1884 // add (zext i1 X), -1 -> sext (not i1 X) 1885 // because most (?) targets generate better code for the zext form. 1886 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 1887 isOneConstantOrOneSplatConstant(N1)) { 1888 SDValue X = N0.getOperand(0); 1889 if ((!LegalOperations || 1890 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 1891 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 1892 X.getScalarValueSizeInBits() == 1) { 1893 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 1894 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 1895 } 1896 } 1897 } 1898 1899 if (SDValue NewSel = foldBinOpIntoSelect(N)) 1900 return NewSel; 1901 1902 // reassociate add 1903 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 1904 return RADD; 1905 1906 // fold ((0-A) + B) -> B-A 1907 if (N0.getOpcode() == ISD::SUB && 1908 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 1909 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 1910 1911 // fold (A + (0-B)) -> A-B 1912 if (N1.getOpcode() == ISD::SUB && 1913 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 1914 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 1915 1916 // fold (A+(B-A)) -> B 1917 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1918 return N1.getOperand(0); 1919 1920 // fold ((B-A)+A) -> B 1921 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1922 return N0.getOperand(0); 1923 1924 // fold (A+(B-(A+C))) to (B-C) 1925 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1926 N0 == N1.getOperand(1).getOperand(0)) 1927 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1928 N1.getOperand(1).getOperand(1)); 1929 1930 // fold (A+(B-(C+A))) to (B-C) 1931 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1932 N0 == N1.getOperand(1).getOperand(1)) 1933 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1934 N1.getOperand(1).getOperand(0)); 1935 1936 // fold (A+((B-A)+or-C)) to (B+or-C) 1937 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1938 N1.getOperand(0).getOpcode() == ISD::SUB && 1939 N0 == N1.getOperand(0).getOperand(1)) 1940 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 1941 N1.getOperand(1)); 1942 1943 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1944 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1945 SDValue N00 = N0.getOperand(0); 1946 SDValue N01 = N0.getOperand(1); 1947 SDValue N10 = N1.getOperand(0); 1948 SDValue N11 = N1.getOperand(1); 1949 1950 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 1951 return DAG.getNode(ISD::SUB, DL, VT, 1952 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1953 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1954 } 1955 1956 if (SimplifyDemandedBits(SDValue(N, 0))) 1957 return SDValue(N, 0); 1958 1959 // fold (a+b) -> (a|b) iff a and b share no bits. 1960 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1961 VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1)) 1962 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 1963 1964 if (SDValue Combined = visitADDLike(N0, N1, N)) 1965 return Combined; 1966 1967 if (SDValue Combined = visitADDLike(N1, N0, N)) 1968 return Combined; 1969 1970 return SDValue(); 1971 } 1972 1973 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 1974 EVT VT = N0.getValueType(); 1975 SDLoc DL(LocReference); 1976 1977 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1978 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1979 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 1980 return DAG.getNode(ISD::SUB, DL, VT, N0, 1981 DAG.getNode(ISD::SHL, DL, VT, 1982 N1.getOperand(0).getOperand(1), 1983 N1.getOperand(1))); 1984 1985 if (N1.getOpcode() == ISD::AND) { 1986 SDValue AndOp0 = N1.getOperand(0); 1987 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1988 unsigned DestBits = VT.getScalarSizeInBits(); 1989 1990 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1991 // and similar xforms where the inner op is either ~0 or 0. 1992 if (NumSignBits == DestBits && 1993 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 1994 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 1995 } 1996 1997 // add (sext i1), X -> sub X, (zext i1) 1998 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1999 N0.getOperand(0).getValueType() == MVT::i1 && 2000 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 2001 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2002 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2003 } 2004 2005 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2006 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2007 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2008 if (TN->getVT() == MVT::i1) { 2009 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2010 DAG.getConstant(1, DL, VT)); 2011 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2012 } 2013 } 2014 2015 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2016 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) 2017 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2018 N0, N1.getOperand(0), N1.getOperand(2)); 2019 2020 return SDValue(); 2021 } 2022 2023 SDValue DAGCombiner::visitADDC(SDNode *N) { 2024 SDValue N0 = N->getOperand(0); 2025 SDValue N1 = N->getOperand(1); 2026 EVT VT = N0.getValueType(); 2027 SDLoc DL(N); 2028 2029 // If the flag result is dead, turn this into an ADD. 2030 if (!N->hasAnyUseOfValue(1)) 2031 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2032 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2033 2034 // canonicalize constant to RHS. 2035 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2036 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2037 if (N0C && !N1C) 2038 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2039 2040 // fold (addc x, 0) -> x + no carry out 2041 if (isNullConstant(N1)) 2042 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2043 DL, MVT::Glue)); 2044 2045 // If it cannot overflow, transform into an add. 2046 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2047 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2048 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2049 2050 return SDValue(); 2051 } 2052 2053 SDValue DAGCombiner::visitUADDO(SDNode *N) { 2054 SDValue N0 = N->getOperand(0); 2055 SDValue N1 = N->getOperand(1); 2056 EVT VT = N0.getValueType(); 2057 if (VT.isVector()) 2058 return SDValue(); 2059 2060 EVT CarryVT = N->getValueType(1); 2061 SDLoc DL(N); 2062 2063 // If the flag result is dead, turn this into an ADD. 2064 if (!N->hasAnyUseOfValue(1)) 2065 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2066 DAG.getUNDEF(CarryVT)); 2067 2068 // canonicalize constant to RHS. 2069 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2070 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2071 if (N0C && !N1C) 2072 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0); 2073 2074 // fold (uaddo x, 0) -> x + no carry out 2075 if (isNullConstant(N1)) 2076 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2077 2078 // If it cannot overflow, transform into an add. 2079 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2080 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2081 DAG.getConstant(0, DL, CarryVT)); 2082 2083 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2084 return Combined; 2085 2086 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2087 return Combined; 2088 2089 return SDValue(); 2090 } 2091 2092 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2093 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2094 // If Y + 1 cannot overflow. 2095 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2096 SDValue Y = N1.getOperand(0); 2097 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2098 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2099 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2100 N1.getOperand(2)); 2101 } 2102 2103 return SDValue(); 2104 } 2105 2106 SDValue DAGCombiner::visitADDE(SDNode *N) { 2107 SDValue N0 = N->getOperand(0); 2108 SDValue N1 = N->getOperand(1); 2109 SDValue CarryIn = N->getOperand(2); 2110 2111 // canonicalize constant to RHS 2112 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2113 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2114 if (N0C && !N1C) 2115 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2116 N1, N0, CarryIn); 2117 2118 // fold (adde x, y, false) -> (addc x, y) 2119 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2120 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2121 2122 return SDValue(); 2123 } 2124 2125 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2126 SDValue N0 = N->getOperand(0); 2127 SDValue N1 = N->getOperand(1); 2128 SDValue CarryIn = N->getOperand(2); 2129 SDLoc DL(N); 2130 2131 // canonicalize constant to RHS 2132 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2133 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2134 if (N0C && !N1C) 2135 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2136 2137 // fold (addcarry x, y, false) -> (uaddo x, y) 2138 if (isNullConstant(CarryIn)) 2139 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2140 2141 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2142 if (isNullConstant(N0) && isNullConstant(N1)) { 2143 EVT VT = N0.getValueType(); 2144 EVT CarryVT = CarryIn.getValueType(); 2145 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2146 AddToWorklist(CarryExt.getNode()); 2147 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2148 DAG.getConstant(1, DL, VT)), 2149 DAG.getConstant(0, DL, CarryVT)); 2150 } 2151 2152 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2153 return Combined; 2154 2155 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2156 return Combined; 2157 2158 return SDValue(); 2159 } 2160 2161 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2162 SDNode *N) { 2163 // Iff the flag result is dead: 2164 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2165 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::UADDO) && 2166 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2167 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2168 N0.getOperand(0), N0.getOperand(1), CarryIn); 2169 2170 return SDValue(); 2171 } 2172 2173 // Since it may not be valid to emit a fold to zero for vector initializers 2174 // check if we can before folding. 2175 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2176 SelectionDAG &DAG, bool LegalOperations, 2177 bool LegalTypes) { 2178 if (!VT.isVector()) 2179 return DAG.getConstant(0, DL, VT); 2180 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2181 return DAG.getConstant(0, DL, VT); 2182 return SDValue(); 2183 } 2184 2185 SDValue DAGCombiner::visitSUB(SDNode *N) { 2186 SDValue N0 = N->getOperand(0); 2187 SDValue N1 = N->getOperand(1); 2188 EVT VT = N0.getValueType(); 2189 SDLoc DL(N); 2190 2191 // fold vector ops 2192 if (VT.isVector()) { 2193 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2194 return FoldedVOp; 2195 2196 // fold (sub x, 0) -> x, vector edition 2197 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2198 return N0; 2199 } 2200 2201 // fold (sub x, x) -> 0 2202 // FIXME: Refactor this and xor and other similar operations together. 2203 if (N0 == N1) 2204 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2205 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2206 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2207 // fold (sub c1, c2) -> c1-c2 2208 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2209 N1.getNode()); 2210 } 2211 2212 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2213 return NewSel; 2214 2215 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2216 2217 // fold (sub x, c) -> (add x, -c) 2218 if (N1C) { 2219 return DAG.getNode(ISD::ADD, DL, VT, N0, 2220 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2221 } 2222 2223 if (isNullConstantOrNullSplatConstant(N0)) { 2224 unsigned BitWidth = VT.getScalarSizeInBits(); 2225 // Right-shifting everything out but the sign bit followed by negation is 2226 // the same as flipping arithmetic/logical shift type without the negation: 2227 // -(X >>u 31) -> (X >>s 31) 2228 // -(X >>s 31) -> (X >>u 31) 2229 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2230 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2231 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2232 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2233 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2234 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2235 } 2236 } 2237 2238 // 0 - X --> 0 if the sub is NUW. 2239 if (N->getFlags().hasNoUnsignedWrap()) 2240 return N0; 2241 2242 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2243 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2244 // N1 must be 0 because negating the minimum signed value is undefined. 2245 if (N->getFlags().hasNoSignedWrap()) 2246 return N0; 2247 2248 // 0 - X --> X if X is 0 or the minimum signed value. 2249 return N1; 2250 } 2251 } 2252 2253 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2254 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2255 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2256 2257 // fold A-(A-B) -> B 2258 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2259 return N1.getOperand(1); 2260 2261 // fold (A+B)-A -> B 2262 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2263 return N0.getOperand(1); 2264 2265 // fold (A+B)-B -> A 2266 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2267 return N0.getOperand(0); 2268 2269 // fold C2-(A+C1) -> (C2-C1)-A 2270 if (N1.getOpcode() == ISD::ADD) { 2271 SDValue N11 = N1.getOperand(1); 2272 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2273 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2274 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2275 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2276 } 2277 } 2278 2279 // fold ((A+(B+or-C))-B) -> A+or-C 2280 if (N0.getOpcode() == ISD::ADD && 2281 (N0.getOperand(1).getOpcode() == ISD::SUB || 2282 N0.getOperand(1).getOpcode() == ISD::ADD) && 2283 N0.getOperand(1).getOperand(0) == N1) 2284 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2285 N0.getOperand(1).getOperand(1)); 2286 2287 // fold ((A+(C+B))-B) -> A+C 2288 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2289 N0.getOperand(1).getOperand(1) == N1) 2290 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2291 N0.getOperand(1).getOperand(0)); 2292 2293 // fold ((A-(B-C))-C) -> A-B 2294 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2295 N0.getOperand(1).getOperand(1) == N1) 2296 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2297 N0.getOperand(1).getOperand(0)); 2298 2299 // If either operand of a sub is undef, the result is undef 2300 if (N0.isUndef()) 2301 return N0; 2302 if (N1.isUndef()) 2303 return N1; 2304 2305 // If the relocation model supports it, consider symbol offsets. 2306 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2307 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2308 // fold (sub Sym, c) -> Sym-c 2309 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2310 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2311 GA->getOffset() - 2312 (uint64_t)N1C->getSExtValue()); 2313 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2314 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2315 if (GA->getGlobal() == GB->getGlobal()) 2316 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2317 DL, VT); 2318 } 2319 2320 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2321 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2322 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2323 if (TN->getVT() == MVT::i1) { 2324 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2325 DAG.getConstant(1, DL, VT)); 2326 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2327 } 2328 } 2329 2330 return SDValue(); 2331 } 2332 2333 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2334 SDValue N0 = N->getOperand(0); 2335 SDValue N1 = N->getOperand(1); 2336 EVT VT = N0.getValueType(); 2337 SDLoc DL(N); 2338 2339 // If the flag result is dead, turn this into an SUB. 2340 if (!N->hasAnyUseOfValue(1)) 2341 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2342 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2343 2344 // fold (subc x, x) -> 0 + no borrow 2345 if (N0 == N1) 2346 return CombineTo(N, DAG.getConstant(0, DL, VT), 2347 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2348 2349 // fold (subc x, 0) -> x + no borrow 2350 if (isNullConstant(N1)) 2351 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2352 2353 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2354 if (isAllOnesConstant(N0)) 2355 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2356 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2357 2358 return SDValue(); 2359 } 2360 2361 SDValue DAGCombiner::visitUSUBO(SDNode *N) { 2362 SDValue N0 = N->getOperand(0); 2363 SDValue N1 = N->getOperand(1); 2364 EVT VT = N0.getValueType(); 2365 if (VT.isVector()) 2366 return SDValue(); 2367 2368 EVT CarryVT = N->getValueType(1); 2369 SDLoc DL(N); 2370 2371 // If the flag result is dead, turn this into an SUB. 2372 if (!N->hasAnyUseOfValue(1)) 2373 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2374 DAG.getUNDEF(CarryVT)); 2375 2376 // fold (usubo x, x) -> 0 + no borrow 2377 if (N0 == N1) 2378 return CombineTo(N, DAG.getConstant(0, DL, VT), 2379 DAG.getConstant(0, DL, CarryVT)); 2380 2381 // fold (usubo x, 0) -> x + no borrow 2382 if (isNullConstant(N1)) 2383 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2384 2385 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2386 if (isAllOnesConstant(N0)) 2387 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2388 DAG.getConstant(0, DL, CarryVT)); 2389 2390 return SDValue(); 2391 } 2392 2393 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2394 SDValue N0 = N->getOperand(0); 2395 SDValue N1 = N->getOperand(1); 2396 SDValue CarryIn = N->getOperand(2); 2397 2398 // fold (sube x, y, false) -> (subc x, y) 2399 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2400 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2401 2402 return SDValue(); 2403 } 2404 2405 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 2406 SDValue N0 = N->getOperand(0); 2407 SDValue N1 = N->getOperand(1); 2408 SDValue CarryIn = N->getOperand(2); 2409 2410 // fold (subcarry x, y, false) -> (usubo x, y) 2411 if (isNullConstant(CarryIn)) 2412 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 2413 2414 return SDValue(); 2415 } 2416 2417 SDValue DAGCombiner::visitMUL(SDNode *N) { 2418 SDValue N0 = N->getOperand(0); 2419 SDValue N1 = N->getOperand(1); 2420 EVT VT = N0.getValueType(); 2421 2422 // fold (mul x, undef) -> 0 2423 if (N0.isUndef() || N1.isUndef()) 2424 return DAG.getConstant(0, SDLoc(N), VT); 2425 2426 bool N0IsConst = false; 2427 bool N1IsConst = false; 2428 bool N1IsOpaqueConst = false; 2429 bool N0IsOpaqueConst = false; 2430 APInt ConstValue0, ConstValue1; 2431 // fold vector ops 2432 if (VT.isVector()) { 2433 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2434 return FoldedVOp; 2435 2436 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2437 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2438 } else { 2439 N0IsConst = isa<ConstantSDNode>(N0); 2440 if (N0IsConst) { 2441 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2442 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2443 } 2444 N1IsConst = isa<ConstantSDNode>(N1); 2445 if (N1IsConst) { 2446 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2447 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2448 } 2449 } 2450 2451 // fold (mul c1, c2) -> c1*c2 2452 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2453 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2454 N0.getNode(), N1.getNode()); 2455 2456 // canonicalize constant to RHS (vector doesn't have to splat) 2457 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2458 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2459 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2460 // fold (mul x, 0) -> 0 2461 if (N1IsConst && ConstValue1 == 0) 2462 return N1; 2463 // We require a splat of the entire scalar bit width for non-contiguous 2464 // bit patterns. 2465 bool IsFullSplat = 2466 ConstValue1.getBitWidth() == VT.getScalarSizeInBits(); 2467 // fold (mul x, 1) -> x 2468 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2469 return N0; 2470 2471 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2472 return NewSel; 2473 2474 // fold (mul x, -1) -> 0-x 2475 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2476 SDLoc DL(N); 2477 return DAG.getNode(ISD::SUB, DL, VT, 2478 DAG.getConstant(0, DL, VT), N0); 2479 } 2480 // fold (mul x, (1 << c)) -> x << c 2481 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2482 IsFullSplat) { 2483 SDLoc DL(N); 2484 return DAG.getNode(ISD::SHL, DL, VT, N0, 2485 DAG.getConstant(ConstValue1.logBase2(), DL, 2486 getShiftAmountTy(N0.getValueType()))); 2487 } 2488 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2489 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2490 IsFullSplat) { 2491 unsigned Log2Val = (-ConstValue1).logBase2(); 2492 SDLoc DL(N); 2493 // FIXME: If the input is something that is easily negated (e.g. a 2494 // single-use add), we should put the negate there. 2495 return DAG.getNode(ISD::SUB, DL, VT, 2496 DAG.getConstant(0, DL, VT), 2497 DAG.getNode(ISD::SHL, DL, VT, N0, 2498 DAG.getConstant(Log2Val, DL, 2499 getShiftAmountTy(N0.getValueType())))); 2500 } 2501 2502 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2503 if (N0.getOpcode() == ISD::SHL && 2504 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2505 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2506 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2507 if (isConstantOrConstantVector(C3)) 2508 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2509 } 2510 2511 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2512 // use. 2513 { 2514 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2515 2516 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2517 if (N0.getOpcode() == ISD::SHL && 2518 isConstantOrConstantVector(N0.getOperand(1)) && 2519 N0.getNode()->hasOneUse()) { 2520 Sh = N0; Y = N1; 2521 } else if (N1.getOpcode() == ISD::SHL && 2522 isConstantOrConstantVector(N1.getOperand(1)) && 2523 N1.getNode()->hasOneUse()) { 2524 Sh = N1; Y = N0; 2525 } 2526 2527 if (Sh.getNode()) { 2528 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2529 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2530 } 2531 } 2532 2533 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2534 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2535 N0.getOpcode() == ISD::ADD && 2536 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2537 isMulAddWithConstProfitable(N, N0, N1)) 2538 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2539 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2540 N0.getOperand(0), N1), 2541 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2542 N0.getOperand(1), N1)); 2543 2544 // reassociate mul 2545 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2546 return RMUL; 2547 2548 return SDValue(); 2549 } 2550 2551 /// Return true if divmod libcall is available. 2552 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2553 const TargetLowering &TLI) { 2554 RTLIB::Libcall LC; 2555 EVT NodeType = Node->getValueType(0); 2556 if (!NodeType.isSimple()) 2557 return false; 2558 switch (NodeType.getSimpleVT().SimpleTy) { 2559 default: return false; // No libcall for vector types. 2560 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2561 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2562 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2563 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2564 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2565 } 2566 2567 return TLI.getLibcallName(LC) != nullptr; 2568 } 2569 2570 /// Issue divrem if both quotient and remainder are needed. 2571 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2572 if (Node->use_empty()) 2573 return SDValue(); // This is a dead node, leave it alone. 2574 2575 unsigned Opcode = Node->getOpcode(); 2576 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2577 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2578 2579 // DivMod lib calls can still work on non-legal types if using lib-calls. 2580 EVT VT = Node->getValueType(0); 2581 if (VT.isVector() || !VT.isInteger()) 2582 return SDValue(); 2583 2584 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2585 return SDValue(); 2586 2587 // If DIVREM is going to get expanded into a libcall, 2588 // but there is no libcall available, then don't combine. 2589 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2590 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2591 return SDValue(); 2592 2593 // If div is legal, it's better to do the normal expansion 2594 unsigned OtherOpcode = 0; 2595 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2596 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2597 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2598 return SDValue(); 2599 } else { 2600 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2601 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2602 return SDValue(); 2603 } 2604 2605 SDValue Op0 = Node->getOperand(0); 2606 SDValue Op1 = Node->getOperand(1); 2607 SDValue combined; 2608 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2609 UE = Op0.getNode()->use_end(); UI != UE;) { 2610 SDNode *User = *UI++; 2611 if (User == Node || User->use_empty()) 2612 continue; 2613 // Convert the other matching node(s), too; 2614 // otherwise, the DIVREM may get target-legalized into something 2615 // target-specific that we won't be able to recognize. 2616 unsigned UserOpc = User->getOpcode(); 2617 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2618 User->getOperand(0) == Op0 && 2619 User->getOperand(1) == Op1) { 2620 if (!combined) { 2621 if (UserOpc == OtherOpcode) { 2622 SDVTList VTs = DAG.getVTList(VT, VT); 2623 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2624 } else if (UserOpc == DivRemOpc) { 2625 combined = SDValue(User, 0); 2626 } else { 2627 assert(UserOpc == Opcode); 2628 continue; 2629 } 2630 } 2631 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2632 CombineTo(User, combined); 2633 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2634 CombineTo(User, combined.getValue(1)); 2635 } 2636 } 2637 return combined; 2638 } 2639 2640 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 2641 SDValue N0 = N->getOperand(0); 2642 SDValue N1 = N->getOperand(1); 2643 EVT VT = N->getValueType(0); 2644 SDLoc DL(N); 2645 2646 if (DAG.isUndef(N->getOpcode(), {N0, N1})) 2647 return DAG.getUNDEF(VT); 2648 2649 // undef / X -> 0 2650 // undef % X -> 0 2651 if (N0.isUndef()) 2652 return DAG.getConstant(0, DL, VT); 2653 2654 return SDValue(); 2655 } 2656 2657 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2658 SDValue N0 = N->getOperand(0); 2659 SDValue N1 = N->getOperand(1); 2660 EVT VT = N->getValueType(0); 2661 2662 // fold vector ops 2663 if (VT.isVector()) 2664 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2665 return FoldedVOp; 2666 2667 SDLoc DL(N); 2668 2669 // fold (sdiv c1, c2) -> c1/c2 2670 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2671 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2672 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2673 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2674 // fold (sdiv X, 1) -> X 2675 if (N1C && N1C->isOne()) 2676 return N0; 2677 // fold (sdiv X, -1) -> 0-X 2678 if (N1C && N1C->isAllOnesValue()) 2679 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 2680 2681 if (SDValue V = simplifyDivRem(N, DAG)) 2682 return V; 2683 2684 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2685 return NewSel; 2686 2687 // If we know the sign bits of both operands are zero, strength reduce to a 2688 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2689 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2690 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2691 2692 // fold (sdiv X, pow2) -> simple ops after legalize 2693 // FIXME: We check for the exact bit here because the generic lowering gives 2694 // better results in that case. The target-specific lowering should learn how 2695 // to handle exact sdivs efficiently. 2696 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2697 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() || 2698 (-N1C->getAPIntValue()).isPowerOf2())) { 2699 // Target-specific implementation of sdiv x, pow2. 2700 if (SDValue Res = BuildSDIVPow2(N)) 2701 return Res; 2702 2703 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2704 2705 // Splat the sign bit into the register 2706 SDValue SGN = 2707 DAG.getNode(ISD::SRA, DL, VT, N0, 2708 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2709 getShiftAmountTy(N0.getValueType()))); 2710 AddToWorklist(SGN.getNode()); 2711 2712 // Add (N0 < 0) ? abs2 - 1 : 0; 2713 SDValue SRL = 2714 DAG.getNode(ISD::SRL, DL, VT, SGN, 2715 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2716 getShiftAmountTy(SGN.getValueType()))); 2717 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2718 AddToWorklist(SRL.getNode()); 2719 AddToWorklist(ADD.getNode()); // Divide by pow2 2720 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2721 DAG.getConstant(lg2, DL, 2722 getShiftAmountTy(ADD.getValueType()))); 2723 2724 // If we're dividing by a positive value, we're done. Otherwise, we must 2725 // negate the result. 2726 if (N1C->getAPIntValue().isNonNegative()) 2727 return SRA; 2728 2729 AddToWorklist(SRA.getNode()); 2730 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2731 } 2732 2733 // If integer divide is expensive and we satisfy the requirements, emit an 2734 // alternate sequence. Targets may check function attributes for size/speed 2735 // trade-offs. 2736 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2737 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2738 if (SDValue Op = BuildSDIV(N)) 2739 return Op; 2740 2741 // sdiv, srem -> sdivrem 2742 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2743 // true. Otherwise, we break the simplification logic in visitREM(). 2744 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2745 if (SDValue DivRem = useDivRem(N)) 2746 return DivRem; 2747 2748 return SDValue(); 2749 } 2750 2751 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2752 SDValue N0 = N->getOperand(0); 2753 SDValue N1 = N->getOperand(1); 2754 EVT VT = N->getValueType(0); 2755 2756 // fold vector ops 2757 if (VT.isVector()) 2758 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2759 return FoldedVOp; 2760 2761 SDLoc DL(N); 2762 2763 // fold (udiv c1, c2) -> c1/c2 2764 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2765 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2766 if (N0C && N1C) 2767 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2768 N0C, N1C)) 2769 return Folded; 2770 2771 if (SDValue V = simplifyDivRem(N, DAG)) 2772 return V; 2773 2774 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2775 return NewSel; 2776 2777 // fold (udiv x, (1 << c)) -> x >>u c 2778 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2779 DAG.isKnownToBeAPowerOfTwo(N1)) { 2780 SDValue LogBase2 = BuildLogBase2(N1, DL); 2781 AddToWorklist(LogBase2.getNode()); 2782 2783 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2784 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2785 AddToWorklist(Trunc.getNode()); 2786 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 2787 } 2788 2789 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2790 if (N1.getOpcode() == ISD::SHL) { 2791 SDValue N10 = N1.getOperand(0); 2792 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 2793 DAG.isKnownToBeAPowerOfTwo(N10)) { 2794 SDValue LogBase2 = BuildLogBase2(N10, DL); 2795 AddToWorklist(LogBase2.getNode()); 2796 2797 EVT ADDVT = N1.getOperand(1).getValueType(); 2798 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 2799 AddToWorklist(Trunc.getNode()); 2800 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 2801 AddToWorklist(Add.getNode()); 2802 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2803 } 2804 } 2805 2806 // fold (udiv x, c) -> alternate 2807 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2808 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2809 if (SDValue Op = BuildUDIV(N)) 2810 return Op; 2811 2812 // sdiv, srem -> sdivrem 2813 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2814 // true. Otherwise, we break the simplification logic in visitREM(). 2815 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2816 if (SDValue DivRem = useDivRem(N)) 2817 return DivRem; 2818 2819 return SDValue(); 2820 } 2821 2822 // handles ISD::SREM and ISD::UREM 2823 SDValue DAGCombiner::visitREM(SDNode *N) { 2824 unsigned Opcode = N->getOpcode(); 2825 SDValue N0 = N->getOperand(0); 2826 SDValue N1 = N->getOperand(1); 2827 EVT VT = N->getValueType(0); 2828 bool isSigned = (Opcode == ISD::SREM); 2829 SDLoc DL(N); 2830 2831 // fold (rem c1, c2) -> c1%c2 2832 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2833 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2834 if (N0C && N1C) 2835 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2836 return Folded; 2837 2838 if (SDValue V = simplifyDivRem(N, DAG)) 2839 return V; 2840 2841 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2842 return NewSel; 2843 2844 if (isSigned) { 2845 // If we know the sign bits of both operands are zero, strength reduce to a 2846 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2847 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2848 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2849 } else { 2850 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 2851 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 2852 // fold (urem x, pow2) -> (and x, pow2-1) 2853 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2854 AddToWorklist(Add.getNode()); 2855 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2856 } 2857 if (N1.getOpcode() == ISD::SHL && 2858 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 2859 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2860 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2861 AddToWorklist(Add.getNode()); 2862 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2863 } 2864 } 2865 2866 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2867 2868 // If X/C can be simplified by the division-by-constant logic, lower 2869 // X%C to the equivalent of X-X/C*C. 2870 // To avoid mangling nodes, this simplification requires that the combine() 2871 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2872 // against this by skipping the simplification if isIntDivCheap(). When 2873 // div is not cheap, combine will not return a DIVREM. Regardless, 2874 // checking cheapness here makes sense since the simplification results in 2875 // fatter code. 2876 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2877 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2878 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2879 AddToWorklist(Div.getNode()); 2880 SDValue OptimizedDiv = combine(Div.getNode()); 2881 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2882 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2883 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2884 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2885 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2886 AddToWorklist(Mul.getNode()); 2887 return Sub; 2888 } 2889 } 2890 2891 // sdiv, srem -> sdivrem 2892 if (SDValue DivRem = useDivRem(N)) 2893 return DivRem.getValue(1); 2894 2895 return SDValue(); 2896 } 2897 2898 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2899 SDValue N0 = N->getOperand(0); 2900 SDValue N1 = N->getOperand(1); 2901 EVT VT = N->getValueType(0); 2902 SDLoc DL(N); 2903 2904 // fold (mulhs x, 0) -> 0 2905 if (isNullConstant(N1)) 2906 return N1; 2907 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2908 if (isOneConstant(N1)) { 2909 SDLoc DL(N); 2910 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2911 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 2912 getShiftAmountTy(N0.getValueType()))); 2913 } 2914 // fold (mulhs x, undef) -> 0 2915 if (N0.isUndef() || N1.isUndef()) 2916 return DAG.getConstant(0, SDLoc(N), VT); 2917 2918 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2919 // plus a shift. 2920 if (VT.isSimple() && !VT.isVector()) { 2921 MVT Simple = VT.getSimpleVT(); 2922 unsigned SimpleSize = Simple.getSizeInBits(); 2923 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2924 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2925 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2926 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2927 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2928 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2929 DAG.getConstant(SimpleSize, DL, 2930 getShiftAmountTy(N1.getValueType()))); 2931 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2932 } 2933 } 2934 2935 return SDValue(); 2936 } 2937 2938 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2939 SDValue N0 = N->getOperand(0); 2940 SDValue N1 = N->getOperand(1); 2941 EVT VT = N->getValueType(0); 2942 SDLoc DL(N); 2943 2944 // fold (mulhu x, 0) -> 0 2945 if (isNullConstant(N1)) 2946 return N1; 2947 // fold (mulhu x, 1) -> 0 2948 if (isOneConstant(N1)) 2949 return DAG.getConstant(0, DL, N0.getValueType()); 2950 // fold (mulhu x, undef) -> 0 2951 if (N0.isUndef() || N1.isUndef()) 2952 return DAG.getConstant(0, DL, VT); 2953 2954 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2955 // plus a shift. 2956 if (VT.isSimple() && !VT.isVector()) { 2957 MVT Simple = VT.getSimpleVT(); 2958 unsigned SimpleSize = Simple.getSizeInBits(); 2959 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2960 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2961 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2962 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2963 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2964 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2965 DAG.getConstant(SimpleSize, DL, 2966 getShiftAmountTy(N1.getValueType()))); 2967 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2968 } 2969 } 2970 2971 return SDValue(); 2972 } 2973 2974 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2975 /// give the opcodes for the two computations that are being performed. Return 2976 /// true if a simplification was made. 2977 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2978 unsigned HiOp) { 2979 // If the high half is not needed, just compute the low half. 2980 bool HiExists = N->hasAnyUseOfValue(1); 2981 if (!HiExists && 2982 (!LegalOperations || 2983 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2984 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2985 return CombineTo(N, Res, Res); 2986 } 2987 2988 // If the low half is not needed, just compute the high half. 2989 bool LoExists = N->hasAnyUseOfValue(0); 2990 if (!LoExists && 2991 (!LegalOperations || 2992 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2993 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2994 return CombineTo(N, Res, Res); 2995 } 2996 2997 // If both halves are used, return as it is. 2998 if (LoExists && HiExists) 2999 return SDValue(); 3000 3001 // If the two computed results can be simplified separately, separate them. 3002 if (LoExists) { 3003 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3004 AddToWorklist(Lo.getNode()); 3005 SDValue LoOpt = combine(Lo.getNode()); 3006 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3007 (!LegalOperations || 3008 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 3009 return CombineTo(N, LoOpt, LoOpt); 3010 } 3011 3012 if (HiExists) { 3013 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3014 AddToWorklist(Hi.getNode()); 3015 SDValue HiOpt = combine(Hi.getNode()); 3016 if (HiOpt.getNode() && HiOpt != Hi && 3017 (!LegalOperations || 3018 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 3019 return CombineTo(N, HiOpt, HiOpt); 3020 } 3021 3022 return SDValue(); 3023 } 3024 3025 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3026 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3027 return Res; 3028 3029 EVT VT = N->getValueType(0); 3030 SDLoc DL(N); 3031 3032 // If the type is twice as wide is legal, transform the mulhu to a wider 3033 // multiply plus a shift. 3034 if (VT.isSimple() && !VT.isVector()) { 3035 MVT Simple = VT.getSimpleVT(); 3036 unsigned SimpleSize = Simple.getSizeInBits(); 3037 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3038 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3039 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3040 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3041 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3042 // Compute the high part as N1. 3043 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3044 DAG.getConstant(SimpleSize, DL, 3045 getShiftAmountTy(Lo.getValueType()))); 3046 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3047 // Compute the low part as N0. 3048 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3049 return CombineTo(N, Lo, Hi); 3050 } 3051 } 3052 3053 return SDValue(); 3054 } 3055 3056 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3057 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3058 return Res; 3059 3060 EVT VT = N->getValueType(0); 3061 SDLoc DL(N); 3062 3063 // If the type is twice as wide is legal, transform the mulhu to a wider 3064 // multiply plus a shift. 3065 if (VT.isSimple() && !VT.isVector()) { 3066 MVT Simple = VT.getSimpleVT(); 3067 unsigned SimpleSize = Simple.getSizeInBits(); 3068 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3069 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3070 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3071 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3072 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3073 // Compute the high part as N1. 3074 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3075 DAG.getConstant(SimpleSize, DL, 3076 getShiftAmountTy(Lo.getValueType()))); 3077 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3078 // Compute the low part as N0. 3079 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3080 return CombineTo(N, Lo, Hi); 3081 } 3082 } 3083 3084 return SDValue(); 3085 } 3086 3087 SDValue DAGCombiner::visitSMULO(SDNode *N) { 3088 // (smulo x, 2) -> (saddo x, x) 3089 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3090 if (C2->getAPIntValue() == 2) 3091 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 3092 N->getOperand(0), N->getOperand(0)); 3093 3094 return SDValue(); 3095 } 3096 3097 SDValue DAGCombiner::visitUMULO(SDNode *N) { 3098 // (umulo x, 2) -> (uaddo x, x) 3099 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3100 if (C2->getAPIntValue() == 2) 3101 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 3102 N->getOperand(0), N->getOperand(0)); 3103 3104 return SDValue(); 3105 } 3106 3107 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3108 SDValue N0 = N->getOperand(0); 3109 SDValue N1 = N->getOperand(1); 3110 EVT VT = N0.getValueType(); 3111 3112 // fold vector ops 3113 if (VT.isVector()) 3114 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3115 return FoldedVOp; 3116 3117 // fold (add c1, c2) -> c1+c2 3118 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3119 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3120 if (N0C && N1C) 3121 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3122 3123 // canonicalize constant to RHS 3124 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3125 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3126 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3127 3128 return SDValue(); 3129 } 3130 3131 /// If this is a binary operator with two operands of the same opcode, try to 3132 /// simplify it. 3133 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 3134 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 3135 EVT VT = N0.getValueType(); 3136 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 3137 3138 // Bail early if none of these transforms apply. 3139 if (N0.getNumOperands() == 0) return SDValue(); 3140 3141 // For each of OP in AND/OR/XOR: 3142 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 3143 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 3144 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 3145 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 3146 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 3147 // 3148 // do not sink logical op inside of a vector extend, since it may combine 3149 // into a vsetcc. 3150 EVT Op0VT = N0.getOperand(0).getValueType(); 3151 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 3152 N0.getOpcode() == ISD::SIGN_EXTEND || 3153 N0.getOpcode() == ISD::BSWAP || 3154 // Avoid infinite looping with PromoteIntBinOp. 3155 (N0.getOpcode() == ISD::ANY_EXTEND && 3156 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 3157 (N0.getOpcode() == ISD::TRUNCATE && 3158 (!TLI.isZExtFree(VT, Op0VT) || 3159 !TLI.isTruncateFree(Op0VT, VT)) && 3160 TLI.isTypeLegal(Op0VT))) && 3161 !VT.isVector() && 3162 Op0VT == N1.getOperand(0).getValueType() && 3163 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 3164 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3165 N0.getOperand(0).getValueType(), 3166 N0.getOperand(0), N1.getOperand(0)); 3167 AddToWorklist(ORNode.getNode()); 3168 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 3169 } 3170 3171 // For each of OP in SHL/SRL/SRA/AND... 3172 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 3173 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 3174 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 3175 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 3176 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 3177 N0.getOperand(1) == N1.getOperand(1)) { 3178 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3179 N0.getOperand(0).getValueType(), 3180 N0.getOperand(0), N1.getOperand(0)); 3181 AddToWorklist(ORNode.getNode()); 3182 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 3183 ORNode, N0.getOperand(1)); 3184 } 3185 3186 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 3187 // Only perform this optimization up until type legalization, before 3188 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 3189 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 3190 // we don't want to undo this promotion. 3191 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 3192 // on scalars. 3193 if ((N0.getOpcode() == ISD::BITCAST || 3194 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 3195 Level <= AfterLegalizeTypes) { 3196 SDValue In0 = N0.getOperand(0); 3197 SDValue In1 = N1.getOperand(0); 3198 EVT In0Ty = In0.getValueType(); 3199 EVT In1Ty = In1.getValueType(); 3200 SDLoc DL(N); 3201 // If both incoming values are integers, and the original types are the 3202 // same. 3203 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3204 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3205 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3206 AddToWorklist(Op.getNode()); 3207 return BC; 3208 } 3209 } 3210 3211 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3212 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3213 // If both shuffles use the same mask, and both shuffle within a single 3214 // vector, then it is worthwhile to move the swizzle after the operation. 3215 // The type-legalizer generates this pattern when loading illegal 3216 // vector types from memory. In many cases this allows additional shuffle 3217 // optimizations. 3218 // There are other cases where moving the shuffle after the xor/and/or 3219 // is profitable even if shuffles don't perform a swizzle. 3220 // If both shuffles use the same mask, and both shuffles have the same first 3221 // or second operand, then it might still be profitable to move the shuffle 3222 // after the xor/and/or operation. 3223 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3224 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3225 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3226 3227 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3228 "Inputs to shuffles are not the same type"); 3229 3230 // Check that both shuffles use the same mask. The masks are known to be of 3231 // the same length because the result vector type is the same. 3232 // Check also that shuffles have only one use to avoid introducing extra 3233 // instructions. 3234 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3235 SVN0->getMask().equals(SVN1->getMask())) { 3236 SDValue ShOp = N0->getOperand(1); 3237 3238 // Don't try to fold this node if it requires introducing a 3239 // build vector of all zeros that might be illegal at this stage. 3240 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3241 if (!LegalTypes) 3242 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3243 else 3244 ShOp = SDValue(); 3245 } 3246 3247 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 3248 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 3249 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 3250 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3251 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3252 N0->getOperand(0), N1->getOperand(0)); 3253 AddToWorklist(NewNode.getNode()); 3254 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3255 SVN0->getMask()); 3256 } 3257 3258 // Don't try to fold this node if it requires introducing a 3259 // build vector of all zeros that might be illegal at this stage. 3260 ShOp = N0->getOperand(0); 3261 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3262 if (!LegalTypes) 3263 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3264 else 3265 ShOp = SDValue(); 3266 } 3267 3268 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 3269 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 3270 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 3271 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3272 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3273 N0->getOperand(1), N1->getOperand(1)); 3274 AddToWorklist(NewNode.getNode()); 3275 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3276 SVN0->getMask()); 3277 } 3278 } 3279 } 3280 3281 return SDValue(); 3282 } 3283 3284 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 3285 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 3286 const SDLoc &DL) { 3287 SDValue LL, LR, RL, RR, N0CC, N1CC; 3288 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 3289 !isSetCCEquivalent(N1, RL, RR, N1CC)) 3290 return SDValue(); 3291 3292 assert(N0.getValueType() == N1.getValueType() && 3293 "Unexpected operand types for bitwise logic op"); 3294 assert(LL.getValueType() == LR.getValueType() && 3295 RL.getValueType() == RR.getValueType() && 3296 "Unexpected operand types for setcc"); 3297 3298 // If we're here post-legalization or the logic op type is not i1, the logic 3299 // op type must match a setcc result type. Also, all folds require new 3300 // operations on the left and right operands, so those types must match. 3301 EVT VT = N0.getValueType(); 3302 EVT OpVT = LL.getValueType(); 3303 if (LegalOperations || VT != MVT::i1) 3304 if (VT != getSetCCResultType(OpVT)) 3305 return SDValue(); 3306 if (OpVT != RL.getValueType()) 3307 return SDValue(); 3308 3309 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 3310 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 3311 bool IsInteger = OpVT.isInteger(); 3312 if (LR == RR && CC0 == CC1 && IsInteger) { 3313 bool IsZero = isNullConstantOrNullSplatConstant(LR); 3314 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR); 3315 3316 // All bits clear? 3317 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 3318 // All sign bits clear? 3319 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 3320 // Any bits set? 3321 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 3322 // Any sign bits set? 3323 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 3324 3325 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 3326 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 3327 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 3328 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 3329 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 3330 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 3331 AddToWorklist(Or.getNode()); 3332 return DAG.getSetCC(DL, VT, Or, LR, CC1); 3333 } 3334 3335 // All bits set? 3336 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 3337 // All sign bits set? 3338 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 3339 // Any bits clear? 3340 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 3341 // Any sign bits clear? 3342 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 3343 3344 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 3345 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 3346 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 3347 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 3348 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 3349 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 3350 AddToWorklist(And.getNode()); 3351 return DAG.getSetCC(DL, VT, And, LR, CC1); 3352 } 3353 } 3354 3355 // TODO: What is the 'or' equivalent of this fold? 3356 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 3357 if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE && 3358 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3359 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3360 SDValue One = DAG.getConstant(1, DL, OpVT); 3361 SDValue Two = DAG.getConstant(2, DL, OpVT); 3362 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 3363 AddToWorklist(Add.getNode()); 3364 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 3365 } 3366 3367 // Try more general transforms if the predicates match and the only user of 3368 // the compares is the 'and' or 'or'. 3369 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 3370 N0.hasOneUse() && N1.hasOneUse()) { 3371 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 3372 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 3373 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 3374 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 3375 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 3376 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 3377 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3378 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 3379 } 3380 } 3381 3382 // Canonicalize equivalent operands to LL == RL. 3383 if (LL == RR && LR == RL) { 3384 CC1 = ISD::getSetCCSwappedOperands(CC1); 3385 std::swap(RL, RR); 3386 } 3387 3388 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3389 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3390 if (LL == RL && LR == RR) { 3391 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 3392 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 3393 if (NewCC != ISD::SETCC_INVALID && 3394 (!LegalOperations || 3395 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 3396 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 3397 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 3398 } 3399 3400 return SDValue(); 3401 } 3402 3403 /// This contains all DAGCombine rules which reduce two values combined by 3404 /// an And operation to a single value. This makes them reusable in the context 3405 /// of visitSELECT(). Rules involving constants are not included as 3406 /// visitSELECT() already handles those cases. 3407 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 3408 EVT VT = N1.getValueType(); 3409 SDLoc DL(N); 3410 3411 // fold (and x, undef) -> 0 3412 if (N0.isUndef() || N1.isUndef()) 3413 return DAG.getConstant(0, DL, VT); 3414 3415 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 3416 return V; 3417 3418 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3419 VT.getSizeInBits() <= 64) { 3420 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3421 APInt ADDC = ADDI->getAPIntValue(); 3422 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3423 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3424 // immediate for an add, but it is legal if its top c2 bits are set, 3425 // transform the ADD so the immediate doesn't need to be materialized 3426 // in a register. 3427 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3428 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3429 SRLI->getZExtValue()); 3430 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3431 ADDC |= Mask; 3432 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3433 SDLoc DL0(N0); 3434 SDValue NewAdd = 3435 DAG.getNode(ISD::ADD, DL0, VT, 3436 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3437 CombineTo(N0.getNode(), NewAdd); 3438 // Return N so it doesn't get rechecked! 3439 return SDValue(N, 0); 3440 } 3441 } 3442 } 3443 } 3444 } 3445 } 3446 3447 // Reduce bit extract of low half of an integer to the narrower type. 3448 // (and (srl i64:x, K), KMask) -> 3449 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3450 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3451 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3452 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3453 unsigned Size = VT.getSizeInBits(); 3454 const APInt &AndMask = CAnd->getAPIntValue(); 3455 unsigned ShiftBits = CShift->getZExtValue(); 3456 3457 // Bail out, this node will probably disappear anyway. 3458 if (ShiftBits == 0) 3459 return SDValue(); 3460 3461 unsigned MaskBits = AndMask.countTrailingOnes(); 3462 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3463 3464 if (AndMask.isMask() && 3465 // Required bits must not span the two halves of the integer and 3466 // must fit in the half size type. 3467 (ShiftBits + MaskBits <= Size / 2) && 3468 TLI.isNarrowingProfitable(VT, HalfVT) && 3469 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3470 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3471 TLI.isTruncateFree(VT, HalfVT) && 3472 TLI.isZExtFree(HalfVT, VT)) { 3473 // The isNarrowingProfitable is to avoid regressions on PPC and 3474 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3475 // on downstream users of this. Those patterns could probably be 3476 // extended to handle extensions mixed in. 3477 3478 SDValue SL(N0); 3479 assert(MaskBits <= Size); 3480 3481 // Extracting the highest bit of the low half. 3482 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3483 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3484 N0.getOperand(0)); 3485 3486 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3487 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3488 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3489 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3490 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3491 } 3492 } 3493 } 3494 } 3495 3496 return SDValue(); 3497 } 3498 3499 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3500 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3501 bool &NarrowLoad) { 3502 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3503 3504 if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits)) 3505 return false; 3506 3507 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3508 LoadedVT = LoadN->getMemoryVT(); 3509 3510 if (ExtVT == LoadedVT && 3511 (!LegalOperations || 3512 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3513 // ZEXTLOAD will match without needing to change the size of the value being 3514 // loaded. 3515 NarrowLoad = false; 3516 return true; 3517 } 3518 3519 // Do not change the width of a volatile load. 3520 if (LoadN->isVolatile()) 3521 return false; 3522 3523 // Do not generate loads of non-round integer types since these can 3524 // be expensive (and would be wrong if the type is not byte sized). 3525 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3526 return false; 3527 3528 if (LegalOperations && 3529 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3530 return false; 3531 3532 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3533 return false; 3534 3535 NarrowLoad = true; 3536 return true; 3537 } 3538 3539 SDValue DAGCombiner::visitAND(SDNode *N) { 3540 SDValue N0 = N->getOperand(0); 3541 SDValue N1 = N->getOperand(1); 3542 EVT VT = N1.getValueType(); 3543 3544 // x & x --> x 3545 if (N0 == N1) 3546 return N0; 3547 3548 // fold vector ops 3549 if (VT.isVector()) { 3550 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3551 return FoldedVOp; 3552 3553 // fold (and x, 0) -> 0, vector edition 3554 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3555 // do not return N0, because undef node may exist in N0 3556 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3557 SDLoc(N), N0.getValueType()); 3558 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3559 // do not return N1, because undef node may exist in N1 3560 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3561 SDLoc(N), N1.getValueType()); 3562 3563 // fold (and x, -1) -> x, vector edition 3564 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3565 return N1; 3566 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3567 return N0; 3568 } 3569 3570 // fold (and c1, c2) -> c1&c2 3571 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3572 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3573 if (N0C && N1C && !N1C->isOpaque()) 3574 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3575 // canonicalize constant to RHS 3576 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3577 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3578 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3579 // fold (and x, -1) -> x 3580 if (isAllOnesConstant(N1)) 3581 return N0; 3582 // if (and x, c) is known to be zero, return 0 3583 unsigned BitWidth = VT.getScalarSizeInBits(); 3584 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3585 APInt::getAllOnesValue(BitWidth))) 3586 return DAG.getConstant(0, SDLoc(N), VT); 3587 3588 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3589 return NewSel; 3590 3591 // reassociate and 3592 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3593 return RAND; 3594 // fold (and (or x, C), D) -> D if (C & D) == D 3595 if (N1C && N0.getOpcode() == ISD::OR) 3596 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1))) 3597 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3598 return N1; 3599 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3600 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3601 SDValue N0Op0 = N0.getOperand(0); 3602 APInt Mask = ~N1C->getAPIntValue(); 3603 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 3604 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3605 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3606 N0.getValueType(), N0Op0); 3607 3608 // Replace uses of the AND with uses of the Zero extend node. 3609 CombineTo(N, Zext); 3610 3611 // We actually want to replace all uses of the any_extend with the 3612 // zero_extend, to avoid duplicating things. This will later cause this 3613 // AND to be folded. 3614 CombineTo(N0.getNode(), Zext); 3615 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3616 } 3617 } 3618 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3619 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3620 // already be zero by virtue of the width of the base type of the load. 3621 // 3622 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3623 // more cases. 3624 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3625 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3626 N0.getOperand(0).getOpcode() == ISD::LOAD && 3627 N0.getOperand(0).getResNo() == 0) || 3628 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3629 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3630 N0 : N0.getOperand(0) ); 3631 3632 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3633 // This can be a pure constant or a vector splat, in which case we treat the 3634 // vector as a scalar and use the splat value. 3635 APInt Constant = APInt::getNullValue(1); 3636 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3637 Constant = C->getAPIntValue(); 3638 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3639 APInt SplatValue, SplatUndef; 3640 unsigned SplatBitSize; 3641 bool HasAnyUndefs; 3642 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3643 SplatBitSize, HasAnyUndefs); 3644 if (IsSplat) { 3645 // Undef bits can contribute to a possible optimisation if set, so 3646 // set them. 3647 SplatValue |= SplatUndef; 3648 3649 // The splat value may be something like "0x00FFFFFF", which means 0 for 3650 // the first vector value and FF for the rest, repeating. We need a mask 3651 // that will apply equally to all members of the vector, so AND all the 3652 // lanes of the constant together. 3653 EVT VT = Vector->getValueType(0); 3654 unsigned BitWidth = VT.getScalarSizeInBits(); 3655 3656 // If the splat value has been compressed to a bitlength lower 3657 // than the size of the vector lane, we need to re-expand it to 3658 // the lane size. 3659 if (BitWidth > SplatBitSize) 3660 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3661 SplatBitSize < BitWidth; 3662 SplatBitSize = SplatBitSize * 2) 3663 SplatValue |= SplatValue.shl(SplatBitSize); 3664 3665 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3666 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3667 if (SplatBitSize % BitWidth == 0) { 3668 Constant = APInt::getAllOnesValue(BitWidth); 3669 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3670 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3671 } 3672 } 3673 } 3674 3675 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3676 // actually legal and isn't going to get expanded, else this is a false 3677 // optimisation. 3678 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3679 Load->getValueType(0), 3680 Load->getMemoryVT()); 3681 3682 // Resize the constant to the same size as the original memory access before 3683 // extension. If it is still the AllOnesValue then this AND is completely 3684 // unneeded. 3685 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 3686 3687 bool B; 3688 switch (Load->getExtensionType()) { 3689 default: B = false; break; 3690 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3691 case ISD::ZEXTLOAD: 3692 case ISD::NON_EXTLOAD: B = true; break; 3693 } 3694 3695 if (B && Constant.isAllOnesValue()) { 3696 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3697 // preserve semantics once we get rid of the AND. 3698 SDValue NewLoad(Load, 0); 3699 3700 // Fold the AND away. NewLoad may get replaced immediately. 3701 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3702 3703 if (Load->getExtensionType() == ISD::EXTLOAD) { 3704 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3705 Load->getValueType(0), SDLoc(Load), 3706 Load->getChain(), Load->getBasePtr(), 3707 Load->getOffset(), Load->getMemoryVT(), 3708 Load->getMemOperand()); 3709 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3710 if (Load->getNumValues() == 3) { 3711 // PRE/POST_INC loads have 3 values. 3712 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3713 NewLoad.getValue(2) }; 3714 CombineTo(Load, To, 3, true); 3715 } else { 3716 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3717 } 3718 } 3719 3720 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3721 } 3722 } 3723 3724 // fold (and (load x), 255) -> (zextload x, i8) 3725 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3726 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3727 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 3728 (N0.getOpcode() == ISD::ANY_EXTEND && 3729 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3730 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3731 LoadSDNode *LN0 = HasAnyExt 3732 ? cast<LoadSDNode>(N0.getOperand(0)) 3733 : cast<LoadSDNode>(N0); 3734 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3735 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3736 auto NarrowLoad = false; 3737 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3738 EVT ExtVT, LoadedVT; 3739 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3740 NarrowLoad)) { 3741 if (!NarrowLoad) { 3742 SDValue NewLoad = 3743 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3744 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3745 LN0->getMemOperand()); 3746 AddToWorklist(N); 3747 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3748 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3749 } else { 3750 EVT PtrType = LN0->getOperand(1).getValueType(); 3751 3752 unsigned Alignment = LN0->getAlignment(); 3753 SDValue NewPtr = LN0->getBasePtr(); 3754 3755 // For big endian targets, we need to add an offset to the pointer 3756 // to load the correct bytes. For little endian systems, we merely 3757 // need to read fewer bytes from the same pointer. 3758 if (DAG.getDataLayout().isBigEndian()) { 3759 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3760 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3761 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3762 SDLoc DL(LN0); 3763 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3764 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3765 Alignment = MinAlign(Alignment, PtrOff); 3766 } 3767 3768 AddToWorklist(NewPtr.getNode()); 3769 3770 SDValue Load = DAG.getExtLoad( 3771 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3772 LN0->getPointerInfo(), ExtVT, Alignment, 3773 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3774 AddToWorklist(N); 3775 CombineTo(LN0, Load, Load.getValue(1)); 3776 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3777 } 3778 } 3779 } 3780 } 3781 3782 if (SDValue Combined = visitANDLike(N0, N1, N)) 3783 return Combined; 3784 3785 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3786 if (N0.getOpcode() == N1.getOpcode()) 3787 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3788 return Tmp; 3789 3790 // Masking the negated extension of a boolean is just the zero-extended 3791 // boolean: 3792 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 3793 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 3794 // 3795 // Note: the SimplifyDemandedBits fold below can make an information-losing 3796 // transform, and then we have no way to find this better fold. 3797 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 3798 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0)); 3799 SDValue SubRHS = N0.getOperand(1); 3800 if (SubLHS && SubLHS->isNullValue()) { 3801 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 3802 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3803 return SubRHS; 3804 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 3805 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3806 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 3807 } 3808 } 3809 3810 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3811 // fold (and (sra)) -> (and (srl)) when possible. 3812 if (SimplifyDemandedBits(SDValue(N, 0))) 3813 return SDValue(N, 0); 3814 3815 // fold (zext_inreg (extload x)) -> (zextload x) 3816 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3817 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3818 EVT MemVT = LN0->getMemoryVT(); 3819 // If we zero all the possible extended bits, then we can turn this into 3820 // a zextload if we are running before legalize or the operation is legal. 3821 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3822 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3823 BitWidth - MemVT.getScalarSizeInBits())) && 3824 ((!LegalOperations && !LN0->isVolatile()) || 3825 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3826 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3827 LN0->getChain(), LN0->getBasePtr(), 3828 MemVT, LN0->getMemOperand()); 3829 AddToWorklist(N); 3830 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3831 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3832 } 3833 } 3834 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3835 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3836 N0.hasOneUse()) { 3837 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3838 EVT MemVT = LN0->getMemoryVT(); 3839 // If we zero all the possible extended bits, then we can turn this into 3840 // a zextload if we are running before legalize or the operation is legal. 3841 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3842 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3843 BitWidth - MemVT.getScalarSizeInBits())) && 3844 ((!LegalOperations && !LN0->isVolatile()) || 3845 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3846 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3847 LN0->getChain(), LN0->getBasePtr(), 3848 MemVT, LN0->getMemOperand()); 3849 AddToWorklist(N); 3850 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3851 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3852 } 3853 } 3854 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3855 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3856 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3857 N0.getOperand(1), false)) 3858 return BSwap; 3859 } 3860 3861 return SDValue(); 3862 } 3863 3864 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3865 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3866 bool DemandHighBits) { 3867 if (!LegalOperations) 3868 return SDValue(); 3869 3870 EVT VT = N->getValueType(0); 3871 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3872 return SDValue(); 3873 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 3874 return SDValue(); 3875 3876 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3877 bool LookPassAnd0 = false; 3878 bool LookPassAnd1 = false; 3879 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3880 std::swap(N0, N1); 3881 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3882 std::swap(N0, N1); 3883 if (N0.getOpcode() == ISD::AND) { 3884 if (!N0.getNode()->hasOneUse()) 3885 return SDValue(); 3886 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3887 if (!N01C || N01C->getZExtValue() != 0xFF00) 3888 return SDValue(); 3889 N0 = N0.getOperand(0); 3890 LookPassAnd0 = true; 3891 } 3892 3893 if (N1.getOpcode() == ISD::AND) { 3894 if (!N1.getNode()->hasOneUse()) 3895 return SDValue(); 3896 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3897 if (!N11C || N11C->getZExtValue() != 0xFF) 3898 return SDValue(); 3899 N1 = N1.getOperand(0); 3900 LookPassAnd1 = true; 3901 } 3902 3903 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3904 std::swap(N0, N1); 3905 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3906 return SDValue(); 3907 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 3908 return SDValue(); 3909 3910 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3911 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3912 if (!N01C || !N11C) 3913 return SDValue(); 3914 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3915 return SDValue(); 3916 3917 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3918 SDValue N00 = N0->getOperand(0); 3919 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3920 if (!N00.getNode()->hasOneUse()) 3921 return SDValue(); 3922 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3923 if (!N001C || N001C->getZExtValue() != 0xFF) 3924 return SDValue(); 3925 N00 = N00.getOperand(0); 3926 LookPassAnd0 = true; 3927 } 3928 3929 SDValue N10 = N1->getOperand(0); 3930 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3931 if (!N10.getNode()->hasOneUse()) 3932 return SDValue(); 3933 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3934 if (!N101C || N101C->getZExtValue() != 0xFF00) 3935 return SDValue(); 3936 N10 = N10.getOperand(0); 3937 LookPassAnd1 = true; 3938 } 3939 3940 if (N00 != N10) 3941 return SDValue(); 3942 3943 // Make sure everything beyond the low halfword gets set to zero since the SRL 3944 // 16 will clear the top bits. 3945 unsigned OpSizeInBits = VT.getSizeInBits(); 3946 if (DemandHighBits && OpSizeInBits > 16) { 3947 // If the left-shift isn't masked out then the only way this is a bswap is 3948 // if all bits beyond the low 8 are 0. In that case the entire pattern 3949 // reduces to a left shift anyway: leave it for other parts of the combiner. 3950 if (!LookPassAnd0) 3951 return SDValue(); 3952 3953 // However, if the right shift isn't masked out then it might be because 3954 // it's not needed. See if we can spot that too. 3955 if (!LookPassAnd1 && 3956 !DAG.MaskedValueIsZero( 3957 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3958 return SDValue(); 3959 } 3960 3961 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3962 if (OpSizeInBits > 16) { 3963 SDLoc DL(N); 3964 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3965 DAG.getConstant(OpSizeInBits - 16, DL, 3966 getShiftAmountTy(VT))); 3967 } 3968 return Res; 3969 } 3970 3971 /// Return true if the specified node is an element that makes up a 32-bit 3972 /// packed halfword byteswap. 3973 /// ((x & 0x000000ff) << 8) | 3974 /// ((x & 0x0000ff00) >> 8) | 3975 /// ((x & 0x00ff0000) << 8) | 3976 /// ((x & 0xff000000) >> 8) 3977 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3978 if (!N.getNode()->hasOneUse()) 3979 return false; 3980 3981 unsigned Opc = N.getOpcode(); 3982 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3983 return false; 3984 3985 SDValue N0 = N.getOperand(0); 3986 unsigned Opc0 = N0.getOpcode(); 3987 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 3988 return false; 3989 3990 ConstantSDNode *N1C = nullptr; 3991 // SHL or SRL: look upstream for AND mask operand 3992 if (Opc == ISD::AND) 3993 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3994 else if (Opc0 == ISD::AND) 3995 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3996 if (!N1C) 3997 return false; 3998 3999 unsigned MaskByteOffset; 4000 switch (N1C->getZExtValue()) { 4001 default: 4002 return false; 4003 case 0xFF: MaskByteOffset = 0; break; 4004 case 0xFF00: MaskByteOffset = 1; break; 4005 case 0xFF0000: MaskByteOffset = 2; break; 4006 case 0xFF000000: MaskByteOffset = 3; break; 4007 } 4008 4009 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4010 if (Opc == ISD::AND) { 4011 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4012 // (x >> 8) & 0xff 4013 // (x >> 8) & 0xff0000 4014 if (Opc0 != ISD::SRL) 4015 return false; 4016 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4017 if (!C || C->getZExtValue() != 8) 4018 return false; 4019 } else { 4020 // (x << 8) & 0xff00 4021 // (x << 8) & 0xff000000 4022 if (Opc0 != ISD::SHL) 4023 return false; 4024 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4025 if (!C || C->getZExtValue() != 8) 4026 return false; 4027 } 4028 } else if (Opc == ISD::SHL) { 4029 // (x & 0xff) << 8 4030 // (x & 0xff0000) << 8 4031 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4032 return false; 4033 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4034 if (!C || C->getZExtValue() != 8) 4035 return false; 4036 } else { // Opc == ISD::SRL 4037 // (x & 0xff00) >> 8 4038 // (x & 0xff000000) >> 8 4039 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4040 return false; 4041 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4042 if (!C || C->getZExtValue() != 8) 4043 return false; 4044 } 4045 4046 if (Parts[MaskByteOffset]) 4047 return false; 4048 4049 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4050 return true; 4051 } 4052 4053 /// Match a 32-bit packed halfword bswap. That is 4054 /// ((x & 0x000000ff) << 8) | 4055 /// ((x & 0x0000ff00) >> 8) | 4056 /// ((x & 0x00ff0000) << 8) | 4057 /// ((x & 0xff000000) >> 8) 4058 /// => (rotl (bswap x), 16) 4059 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4060 if (!LegalOperations) 4061 return SDValue(); 4062 4063 EVT VT = N->getValueType(0); 4064 if (VT != MVT::i32) 4065 return SDValue(); 4066 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4067 return SDValue(); 4068 4069 // Look for either 4070 // (or (or (and), (and)), (or (and), (and))) 4071 // (or (or (or (and), (and)), (and)), (and)) 4072 if (N0.getOpcode() != ISD::OR) 4073 return SDValue(); 4074 SDValue N00 = N0.getOperand(0); 4075 SDValue N01 = N0.getOperand(1); 4076 SDNode *Parts[4] = {}; 4077 4078 if (N1.getOpcode() == ISD::OR && 4079 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4080 // (or (or (and), (and)), (or (and), (and))) 4081 if (!isBSwapHWordElement(N00, Parts)) 4082 return SDValue(); 4083 4084 if (!isBSwapHWordElement(N01, Parts)) 4085 return SDValue(); 4086 SDValue N10 = N1.getOperand(0); 4087 if (!isBSwapHWordElement(N10, Parts)) 4088 return SDValue(); 4089 SDValue N11 = N1.getOperand(1); 4090 if (!isBSwapHWordElement(N11, Parts)) 4091 return SDValue(); 4092 } else { 4093 // (or (or (or (and), (and)), (and)), (and)) 4094 if (!isBSwapHWordElement(N1, Parts)) 4095 return SDValue(); 4096 if (!isBSwapHWordElement(N01, Parts)) 4097 return SDValue(); 4098 if (N00.getOpcode() != ISD::OR) 4099 return SDValue(); 4100 SDValue N000 = N00.getOperand(0); 4101 if (!isBSwapHWordElement(N000, Parts)) 4102 return SDValue(); 4103 SDValue N001 = N00.getOperand(1); 4104 if (!isBSwapHWordElement(N001, Parts)) 4105 return SDValue(); 4106 } 4107 4108 // Make sure the parts are all coming from the same node. 4109 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4110 return SDValue(); 4111 4112 SDLoc DL(N); 4113 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4114 SDValue(Parts[0], 0)); 4115 4116 // Result of the bswap should be rotated by 16. If it's not legal, then 4117 // do (x << 16) | (x >> 16). 4118 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 4119 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4120 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 4121 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 4122 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 4123 return DAG.getNode(ISD::OR, DL, VT, 4124 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 4125 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 4126 } 4127 4128 /// This contains all DAGCombine rules which reduce two values combined by 4129 /// an Or operation to a single value \see visitANDLike(). 4130 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 4131 EVT VT = N1.getValueType(); 4132 SDLoc DL(N); 4133 4134 // fold (or x, undef) -> -1 4135 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 4136 return DAG.getAllOnesConstant(DL, VT); 4137 4138 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 4139 return V; 4140 4141 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 4142 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 4143 // Don't increase # computations. 4144 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4145 // We can only do this xform if we know that bits from X that are set in C2 4146 // but not in C1 are already zero. Likewise for Y. 4147 if (const ConstantSDNode *N0O1C = 4148 getAsNonOpaqueConstant(N0.getOperand(1))) { 4149 if (const ConstantSDNode *N1O1C = 4150 getAsNonOpaqueConstant(N1.getOperand(1))) { 4151 // We can only do this xform if we know that bits from X that are set in 4152 // C2 but not in C1 are already zero. Likewise for Y. 4153 const APInt &LHSMask = N0O1C->getAPIntValue(); 4154 const APInt &RHSMask = N1O1C->getAPIntValue(); 4155 4156 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 4157 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 4158 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4159 N0.getOperand(0), N1.getOperand(0)); 4160 return DAG.getNode(ISD::AND, DL, VT, X, 4161 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 4162 } 4163 } 4164 } 4165 } 4166 4167 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 4168 if (N0.getOpcode() == ISD::AND && 4169 N1.getOpcode() == ISD::AND && 4170 N0.getOperand(0) == N1.getOperand(0) && 4171 // Don't increase # computations. 4172 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4173 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4174 N0.getOperand(1), N1.getOperand(1)); 4175 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 4176 } 4177 4178 return SDValue(); 4179 } 4180 4181 SDValue DAGCombiner::visitOR(SDNode *N) { 4182 SDValue N0 = N->getOperand(0); 4183 SDValue N1 = N->getOperand(1); 4184 EVT VT = N1.getValueType(); 4185 4186 // x | x --> x 4187 if (N0 == N1) 4188 return N0; 4189 4190 // fold vector ops 4191 if (VT.isVector()) { 4192 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4193 return FoldedVOp; 4194 4195 // fold (or x, 0) -> x, vector edition 4196 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4197 return N1; 4198 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4199 return N0; 4200 4201 // fold (or x, -1) -> -1, vector edition 4202 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4203 // do not return N0, because undef node may exist in N0 4204 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 4205 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4206 // do not return N1, because undef node may exist in N1 4207 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 4208 4209 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 4210 // Do this only if the resulting shuffle is legal. 4211 if (isa<ShuffleVectorSDNode>(N0) && 4212 isa<ShuffleVectorSDNode>(N1) && 4213 // Avoid folding a node with illegal type. 4214 TLI.isTypeLegal(VT)) { 4215 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 4216 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 4217 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4218 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 4219 // Ensure both shuffles have a zero input. 4220 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 4221 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 4222 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 4223 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 4224 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 4225 bool CanFold = true; 4226 int NumElts = VT.getVectorNumElements(); 4227 SmallVector<int, 4> Mask(NumElts); 4228 4229 for (int i = 0; i != NumElts; ++i) { 4230 int M0 = SV0->getMaskElt(i); 4231 int M1 = SV1->getMaskElt(i); 4232 4233 // Determine if either index is pointing to a zero vector. 4234 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 4235 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 4236 4237 // If one element is zero and the otherside is undef, keep undef. 4238 // This also handles the case that both are undef. 4239 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 4240 Mask[i] = -1; 4241 continue; 4242 } 4243 4244 // Make sure only one of the elements is zero. 4245 if (M0Zero == M1Zero) { 4246 CanFold = false; 4247 break; 4248 } 4249 4250 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 4251 4252 // We have a zero and non-zero element. If the non-zero came from 4253 // SV0 make the index a LHS index. If it came from SV1, make it 4254 // a RHS index. We need to mod by NumElts because we don't care 4255 // which operand it came from in the original shuffles. 4256 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 4257 } 4258 4259 if (CanFold) { 4260 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 4261 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 4262 4263 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4264 if (!LegalMask) { 4265 std::swap(NewLHS, NewRHS); 4266 ShuffleVectorSDNode::commuteMask(Mask); 4267 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4268 } 4269 4270 if (LegalMask) 4271 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 4272 } 4273 } 4274 } 4275 } 4276 4277 // fold (or c1, c2) -> c1|c2 4278 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4279 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4280 if (N0C && N1C && !N1C->isOpaque()) 4281 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 4282 // canonicalize constant to RHS 4283 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4284 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4285 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 4286 // fold (or x, 0) -> x 4287 if (isNullConstant(N1)) 4288 return N0; 4289 // fold (or x, -1) -> -1 4290 if (isAllOnesConstant(N1)) 4291 return N1; 4292 4293 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4294 return NewSel; 4295 4296 // fold (or x, c) -> c iff (x & ~c) == 0 4297 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 4298 return N1; 4299 4300 if (SDValue Combined = visitORLike(N0, N1, N)) 4301 return Combined; 4302 4303 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 4304 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 4305 return BSwap; 4306 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 4307 return BSwap; 4308 4309 // reassociate or 4310 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 4311 return ROR; 4312 4313 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 4314 // iff (c1 & c2) != 0. 4315 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) { 4316 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4317 if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) { 4318 if (SDValue COR = 4319 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1)) 4320 return DAG.getNode( 4321 ISD::AND, SDLoc(N), VT, 4322 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 4323 return SDValue(); 4324 } 4325 } 4326 } 4327 4328 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 4329 if (N0.getOpcode() == N1.getOpcode()) 4330 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4331 return Tmp; 4332 4333 // See if this is some rotate idiom. 4334 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 4335 return SDValue(Rot, 0); 4336 4337 if (SDValue Load = MatchLoadCombine(N)) 4338 return Load; 4339 4340 // Simplify the operands using demanded-bits information. 4341 if (SimplifyDemandedBits(SDValue(N, 0))) 4342 return SDValue(N, 0); 4343 4344 return SDValue(); 4345 } 4346 4347 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 4348 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 4349 if (Op.getOpcode() == ISD::AND) { 4350 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 4351 Mask = Op.getOperand(1); 4352 Op = Op.getOperand(0); 4353 } else { 4354 return false; 4355 } 4356 } 4357 4358 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4359 Shift = Op; 4360 return true; 4361 } 4362 4363 return false; 4364 } 4365 4366 // Return true if we can prove that, whenever Neg and Pos are both in the 4367 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4368 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4369 // 4370 // (or (shift1 X, Neg), (shift2 X, Pos)) 4371 // 4372 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4373 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4374 // to consider shift amounts with defined behavior. 4375 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4376 // If EltSize is a power of 2 then: 4377 // 4378 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4379 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4380 // 4381 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4382 // for the stronger condition: 4383 // 4384 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4385 // 4386 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4387 // we can just replace Neg with Neg' for the rest of the function. 4388 // 4389 // In other cases we check for the even stronger condition: 4390 // 4391 // Neg == EltSize - Pos [B] 4392 // 4393 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4394 // behavior if Pos == 0 (and consequently Neg == EltSize). 4395 // 4396 // We could actually use [A] whenever EltSize is a power of 2, but the 4397 // only extra cases that it would match are those uninteresting ones 4398 // where Neg and Pos are never in range at the same time. E.g. for 4399 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4400 // as well as (sub 32, Pos), but: 4401 // 4402 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4403 // 4404 // always invokes undefined behavior for 32-bit X. 4405 // 4406 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4407 unsigned MaskLoBits = 0; 4408 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4409 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4410 if (NegC->getAPIntValue() == EltSize - 1) { 4411 Neg = Neg.getOperand(0); 4412 MaskLoBits = Log2_64(EltSize); 4413 } 4414 } 4415 } 4416 4417 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4418 if (Neg.getOpcode() != ISD::SUB) 4419 return false; 4420 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4421 if (!NegC) 4422 return false; 4423 SDValue NegOp1 = Neg.getOperand(1); 4424 4425 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4426 // Pos'. The truncation is redundant for the purpose of the equality. 4427 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4428 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4429 if (PosC->getAPIntValue() == EltSize - 1) 4430 Pos = Pos.getOperand(0); 4431 4432 // The condition we need is now: 4433 // 4434 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4435 // 4436 // If NegOp1 == Pos then we need: 4437 // 4438 // EltSize & Mask == NegC & Mask 4439 // 4440 // (because "x & Mask" is a truncation and distributes through subtraction). 4441 APInt Width; 4442 if (Pos == NegOp1) 4443 Width = NegC->getAPIntValue(); 4444 4445 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4446 // Then the condition we want to prove becomes: 4447 // 4448 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4449 // 4450 // which, again because "x & Mask" is a truncation, becomes: 4451 // 4452 // NegC & Mask == (EltSize - PosC) & Mask 4453 // EltSize & Mask == (NegC + PosC) & Mask 4454 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4455 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4456 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4457 else 4458 return false; 4459 } else 4460 return false; 4461 4462 // Now we just need to check that EltSize & Mask == Width & Mask. 4463 if (MaskLoBits) 4464 // EltSize & Mask is 0 since Mask is EltSize - 1. 4465 return Width.getLoBits(MaskLoBits) == 0; 4466 return Width == EltSize; 4467 } 4468 4469 // A subroutine of MatchRotate used once we have found an OR of two opposite 4470 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4471 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4472 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4473 // Neg with outer conversions stripped away. 4474 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4475 SDValue Neg, SDValue InnerPos, 4476 SDValue InnerNeg, unsigned PosOpcode, 4477 unsigned NegOpcode, const SDLoc &DL) { 4478 // fold (or (shl x, (*ext y)), 4479 // (srl x, (*ext (sub 32, y)))) -> 4480 // (rotl x, y) or (rotr x, (sub 32, y)) 4481 // 4482 // fold (or (shl x, (*ext (sub 32, y))), 4483 // (srl x, (*ext y))) -> 4484 // (rotr x, y) or (rotl x, (sub 32, y)) 4485 EVT VT = Shifted.getValueType(); 4486 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4487 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4488 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4489 HasPos ? Pos : Neg).getNode(); 4490 } 4491 4492 return nullptr; 4493 } 4494 4495 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4496 // idioms for rotate, and if the target supports rotation instructions, generate 4497 // a rot[lr]. 4498 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4499 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4500 EVT VT = LHS.getValueType(); 4501 if (!TLI.isTypeLegal(VT)) return nullptr; 4502 4503 // The target must have at least one rotate flavor. 4504 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4505 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4506 if (!HasROTL && !HasROTR) return nullptr; 4507 4508 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4509 SDValue LHSShift; // The shift. 4510 SDValue LHSMask; // AND value if any. 4511 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4512 return nullptr; // Not part of a rotate. 4513 4514 SDValue RHSShift; // The shift. 4515 SDValue RHSMask; // AND value if any. 4516 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4517 return nullptr; // Not part of a rotate. 4518 4519 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4520 return nullptr; // Not shifting the same value. 4521 4522 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4523 return nullptr; // Shifts must disagree. 4524 4525 // Canonicalize shl to left side in a shl/srl pair. 4526 if (RHSShift.getOpcode() == ISD::SHL) { 4527 std::swap(LHS, RHS); 4528 std::swap(LHSShift, RHSShift); 4529 std::swap(LHSMask, RHSMask); 4530 } 4531 4532 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4533 SDValue LHSShiftArg = LHSShift.getOperand(0); 4534 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4535 SDValue RHSShiftArg = RHSShift.getOperand(0); 4536 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4537 4538 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4539 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4540 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4541 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4542 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4543 if ((LShVal + RShVal) != EltSizeInBits) 4544 return nullptr; 4545 4546 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4547 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4548 4549 // If there is an AND of either shifted operand, apply it to the result. 4550 if (LHSMask.getNode() || RHSMask.getNode()) { 4551 SDValue Mask = DAG.getAllOnesConstant(DL, VT); 4552 4553 if (LHSMask.getNode()) { 4554 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4555 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4556 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4557 DAG.getConstant(RHSBits, DL, VT))); 4558 } 4559 if (RHSMask.getNode()) { 4560 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4561 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4562 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4563 DAG.getConstant(LHSBits, DL, VT))); 4564 } 4565 4566 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4567 } 4568 4569 return Rot.getNode(); 4570 } 4571 4572 // If there is a mask here, and we have a variable shift, we can't be sure 4573 // that we're masking out the right stuff. 4574 if (LHSMask.getNode() || RHSMask.getNode()) 4575 return nullptr; 4576 4577 // If the shift amount is sign/zext/any-extended just peel it off. 4578 SDValue LExtOp0 = LHSShiftAmt; 4579 SDValue RExtOp0 = RHSShiftAmt; 4580 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4581 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4582 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4583 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4584 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4585 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4586 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4587 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4588 LExtOp0 = LHSShiftAmt.getOperand(0); 4589 RExtOp0 = RHSShiftAmt.getOperand(0); 4590 } 4591 4592 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4593 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4594 if (TryL) 4595 return TryL; 4596 4597 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4598 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4599 if (TryR) 4600 return TryR; 4601 4602 return nullptr; 4603 } 4604 4605 namespace { 4606 /// Helper struct to parse and store a memory address as base + index + offset. 4607 /// We ignore sign extensions when it is safe to do so. 4608 /// The following two expressions are not equivalent. To differentiate we need 4609 /// to store whether there was a sign extension involved in the index 4610 /// computation. 4611 /// (load (i64 add (i64 copyfromreg %c) 4612 /// (i64 signextend (add (i8 load %index) 4613 /// (i8 1)))) 4614 /// vs 4615 /// 4616 /// (load (i64 add (i64 copyfromreg %c) 4617 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 4618 /// (i32 1))))) 4619 struct BaseIndexOffset { 4620 SDValue Base; 4621 SDValue Index; 4622 int64_t Offset; 4623 bool IsIndexSignExt; 4624 4625 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 4626 4627 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 4628 bool IsIndexSignExt) : 4629 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 4630 4631 bool equalBaseIndex(const BaseIndexOffset &Other) { 4632 return Other.Base == Base && Other.Index == Index && 4633 Other.IsIndexSignExt == IsIndexSignExt; 4634 } 4635 4636 /// Parses tree in Ptr for base, index, offset addresses. 4637 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG, 4638 int64_t PartialOffset = 0) { 4639 bool IsIndexSignExt = false; 4640 4641 // Split up a folded GlobalAddress+Offset into its component parts. 4642 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 4643 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 4644 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 4645 SDLoc(GA), 4646 GA->getValueType(0), 4647 /*Offset=*/PartialOffset, 4648 /*isTargetGA=*/false, 4649 GA->getTargetFlags()), 4650 SDValue(), 4651 GA->getOffset(), 4652 IsIndexSignExt); 4653 } 4654 4655 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 4656 // instruction, then it could be just the BASE or everything else we don't 4657 // know how to handle. Just use Ptr as BASE and give up. 4658 if (Ptr->getOpcode() != ISD::ADD) 4659 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4660 4661 // We know that we have at least an ADD instruction. Try to pattern match 4662 // the simple case of BASE + OFFSET. 4663 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 4664 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 4665 return match(Ptr->getOperand(0), DAG, Offset + PartialOffset); 4666 } 4667 4668 // Inside a loop the current BASE pointer is calculated using an ADD and a 4669 // MUL instruction. In this case Ptr is the actual BASE pointer. 4670 // (i64 add (i64 %array_ptr) 4671 // (i64 mul (i64 %induction_var) 4672 // (i64 %element_size))) 4673 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 4674 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4675 4676 // Look at Base + Index + Offset cases. 4677 SDValue Base = Ptr->getOperand(0); 4678 SDValue IndexOffset = Ptr->getOperand(1); 4679 4680 // Skip signextends. 4681 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 4682 IndexOffset = IndexOffset->getOperand(0); 4683 IsIndexSignExt = true; 4684 } 4685 4686 // Either the case of Base + Index (no offset) or something else. 4687 if (IndexOffset->getOpcode() != ISD::ADD) 4688 return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt); 4689 4690 // Now we have the case of Base + Index + offset. 4691 SDValue Index = IndexOffset->getOperand(0); 4692 SDValue Offset = IndexOffset->getOperand(1); 4693 4694 if (!isa<ConstantSDNode>(Offset)) 4695 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4696 4697 // Ignore signextends. 4698 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 4699 Index = Index->getOperand(0); 4700 IsIndexSignExt = true; 4701 } else IsIndexSignExt = false; 4702 4703 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 4704 return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt); 4705 } 4706 }; 4707 } // namespace 4708 4709 namespace { 4710 /// Represents known origin of an individual byte in load combine pattern. The 4711 /// value of the byte is either constant zero or comes from memory. 4712 struct ByteProvider { 4713 // For constant zero providers Load is set to nullptr. For memory providers 4714 // Load represents the node which loads the byte from memory. 4715 // ByteOffset is the offset of the byte in the value produced by the load. 4716 LoadSDNode *Load; 4717 unsigned ByteOffset; 4718 4719 ByteProvider() : Load(nullptr), ByteOffset(0) {} 4720 4721 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 4722 return ByteProvider(Load, ByteOffset); 4723 } 4724 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 4725 4726 bool isConstantZero() const { return !Load; } 4727 bool isMemory() const { return Load; } 4728 4729 bool operator==(const ByteProvider &Other) const { 4730 return Other.Load == Load && Other.ByteOffset == ByteOffset; 4731 } 4732 4733 private: 4734 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 4735 : Load(Load), ByteOffset(ByteOffset) {} 4736 }; 4737 4738 /// Recursively traverses the expression calculating the origin of the requested 4739 /// byte of the given value. Returns None if the provider can't be calculated. 4740 /// 4741 /// For all the values except the root of the expression verifies that the value 4742 /// has exactly one use and if it's not true return None. This way if the origin 4743 /// of the byte is returned it's guaranteed that the values which contribute to 4744 /// the byte are not used outside of this expression. 4745 /// 4746 /// Because the parts of the expression are not allowed to have more than one 4747 /// use this function iterates over trees, not DAGs. So it never visits the same 4748 /// node more than once. 4749 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index, 4750 unsigned Depth, 4751 bool Root = false) { 4752 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 4753 if (Depth == 10) 4754 return None; 4755 4756 if (!Root && !Op.hasOneUse()) 4757 return None; 4758 4759 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 4760 unsigned BitWidth = Op.getValueSizeInBits(); 4761 if (BitWidth % 8 != 0) 4762 return None; 4763 unsigned ByteWidth = BitWidth / 8; 4764 assert(Index < ByteWidth && "invalid index requested"); 4765 (void) ByteWidth; 4766 4767 switch (Op.getOpcode()) { 4768 case ISD::OR: { 4769 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 4770 if (!LHS) 4771 return None; 4772 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 4773 if (!RHS) 4774 return None; 4775 4776 if (LHS->isConstantZero()) 4777 return RHS; 4778 if (RHS->isConstantZero()) 4779 return LHS; 4780 return None; 4781 } 4782 case ISD::SHL: { 4783 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 4784 if (!ShiftOp) 4785 return None; 4786 4787 uint64_t BitShift = ShiftOp->getZExtValue(); 4788 if (BitShift % 8 != 0) 4789 return None; 4790 uint64_t ByteShift = BitShift / 8; 4791 4792 return Index < ByteShift 4793 ? ByteProvider::getConstantZero() 4794 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 4795 Depth + 1); 4796 } 4797 case ISD::ANY_EXTEND: 4798 case ISD::SIGN_EXTEND: 4799 case ISD::ZERO_EXTEND: { 4800 SDValue NarrowOp = Op->getOperand(0); 4801 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 4802 if (NarrowBitWidth % 8 != 0) 4803 return None; 4804 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4805 4806 if (Index >= NarrowByteWidth) 4807 return Op.getOpcode() == ISD::ZERO_EXTEND 4808 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4809 : None; 4810 return calculateByteProvider(NarrowOp, Index, Depth + 1); 4811 } 4812 case ISD::BSWAP: 4813 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 4814 Depth + 1); 4815 case ISD::LOAD: { 4816 auto L = cast<LoadSDNode>(Op.getNode()); 4817 if (L->isVolatile() || L->isIndexed()) 4818 return None; 4819 4820 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 4821 if (NarrowBitWidth % 8 != 0) 4822 return None; 4823 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4824 4825 if (Index >= NarrowByteWidth) 4826 return L->getExtensionType() == ISD::ZEXTLOAD 4827 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4828 : None; 4829 return ByteProvider::getMemory(L, Index); 4830 } 4831 } 4832 4833 return None; 4834 } 4835 } // namespace 4836 4837 /// Match a pattern where a wide type scalar value is loaded by several narrow 4838 /// loads and combined by shifts and ors. Fold it into a single load or a load 4839 /// and a BSWAP if the targets supports it. 4840 /// 4841 /// Assuming little endian target: 4842 /// i8 *a = ... 4843 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 4844 /// => 4845 /// i32 val = *((i32)a) 4846 /// 4847 /// i8 *a = ... 4848 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 4849 /// => 4850 /// i32 val = BSWAP(*((i32)a)) 4851 /// 4852 /// TODO: This rule matches complex patterns with OR node roots and doesn't 4853 /// interact well with the worklist mechanism. When a part of the pattern is 4854 /// updated (e.g. one of the loads) its direct users are put into the worklist, 4855 /// but the root node of the pattern which triggers the load combine is not 4856 /// necessarily a direct user of the changed node. For example, once the address 4857 /// of t28 load is reassociated load combine won't be triggered: 4858 /// t25: i32 = add t4, Constant:i32<2> 4859 /// t26: i64 = sign_extend t25 4860 /// t27: i64 = add t2, t26 4861 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 4862 /// t29: i32 = zero_extend t28 4863 /// t32: i32 = shl t29, Constant:i8<8> 4864 /// t33: i32 = or t23, t32 4865 /// As a possible fix visitLoad can check if the load can be a part of a load 4866 /// combine pattern and add corresponding OR roots to the worklist. 4867 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 4868 assert(N->getOpcode() == ISD::OR && 4869 "Can only match load combining against OR nodes"); 4870 4871 // Handles simple types only 4872 EVT VT = N->getValueType(0); 4873 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 4874 return SDValue(); 4875 unsigned ByteWidth = VT.getSizeInBits() / 8; 4876 4877 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4878 // Before legalize we can introduce too wide illegal loads which will be later 4879 // split into legal sized loads. This enables us to combine i64 load by i8 4880 // patterns to a couple of i32 loads on 32 bit targets. 4881 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 4882 return SDValue(); 4883 4884 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 4885 unsigned BW, unsigned i) { return i; }; 4886 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 4887 unsigned BW, unsigned i) { return BW - i - 1; }; 4888 4889 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 4890 auto MemoryByteOffset = [&] (ByteProvider P) { 4891 assert(P.isMemory() && "Must be a memory byte provider"); 4892 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 4893 assert(LoadBitWidth % 8 == 0 && 4894 "can only analyze providers for individual bytes not bit"); 4895 unsigned LoadByteWidth = LoadBitWidth / 8; 4896 return IsBigEndianTarget 4897 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 4898 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 4899 }; 4900 4901 Optional<BaseIndexOffset> Base; 4902 SDValue Chain; 4903 4904 SmallSet<LoadSDNode *, 8> Loads; 4905 Optional<ByteProvider> FirstByteProvider; 4906 int64_t FirstOffset = INT64_MAX; 4907 4908 // Check if all the bytes of the OR we are looking at are loaded from the same 4909 // base address. Collect bytes offsets from Base address in ByteOffsets. 4910 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 4911 for (unsigned i = 0; i < ByteWidth; i++) { 4912 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 4913 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 4914 return SDValue(); 4915 4916 LoadSDNode *L = P->Load; 4917 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 4918 "Must be enforced by calculateByteProvider"); 4919 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 4920 4921 // All loads must share the same chain 4922 SDValue LChain = L->getChain(); 4923 if (!Chain) 4924 Chain = LChain; 4925 else if (Chain != LChain) 4926 return SDValue(); 4927 4928 // Loads must share the same base address 4929 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG); 4930 if (!Base) 4931 Base = Ptr; 4932 else if (!Base->equalBaseIndex(Ptr)) 4933 return SDValue(); 4934 4935 // Calculate the offset of the current byte from the base address 4936 int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P); 4937 ByteOffsets[i] = ByteOffsetFromBase; 4938 4939 // Remember the first byte load 4940 if (ByteOffsetFromBase < FirstOffset) { 4941 FirstByteProvider = P; 4942 FirstOffset = ByteOffsetFromBase; 4943 } 4944 4945 Loads.insert(L); 4946 } 4947 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from " 4948 "memory, so there must be at least one load which produces the value"); 4949 assert(Base && "Base address of the accessed memory location must be set"); 4950 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 4951 4952 // Check if the bytes of the OR we are looking at match with either big or 4953 // little endian value load 4954 bool BigEndian = true, LittleEndian = true; 4955 for (unsigned i = 0; i < ByteWidth; i++) { 4956 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 4957 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 4958 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 4959 if (!BigEndian && !LittleEndian) 4960 return SDValue(); 4961 } 4962 assert((BigEndian != LittleEndian) && "should be either or"); 4963 assert(FirstByteProvider && "must be set"); 4964 4965 // Ensure that the first byte is loaded from zero offset of the first load. 4966 // So the combined value can be loaded from the first load address. 4967 if (MemoryByteOffset(*FirstByteProvider) != 0) 4968 return SDValue(); 4969 LoadSDNode *FirstLoad = FirstByteProvider->Load; 4970 4971 // The node we are looking at matches with the pattern, check if we can 4972 // replace it with a single load and bswap if needed. 4973 4974 // If the load needs byte swap check if the target supports it 4975 bool NeedsBswap = IsBigEndianTarget != BigEndian; 4976 4977 // Before legalize we can introduce illegal bswaps which will be later 4978 // converted to an explicit bswap sequence. This way we end up with a single 4979 // load and byte shuffling instead of several loads and byte shuffling. 4980 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 4981 return SDValue(); 4982 4983 // Check that a load of the wide type is both allowed and fast on the target 4984 bool Fast = false; 4985 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 4986 VT, FirstLoad->getAddressSpace(), 4987 FirstLoad->getAlignment(), &Fast); 4988 if (!Allowed || !Fast) 4989 return SDValue(); 4990 4991 SDValue NewLoad = 4992 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 4993 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 4994 4995 // Transfer chain users from old loads to the new load. 4996 for (LoadSDNode *L : Loads) 4997 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 4998 4999 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 5000 } 5001 5002 SDValue DAGCombiner::visitXOR(SDNode *N) { 5003 SDValue N0 = N->getOperand(0); 5004 SDValue N1 = N->getOperand(1); 5005 EVT VT = N0.getValueType(); 5006 5007 // fold vector ops 5008 if (VT.isVector()) { 5009 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5010 return FoldedVOp; 5011 5012 // fold (xor x, 0) -> x, vector edition 5013 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5014 return N1; 5015 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5016 return N0; 5017 } 5018 5019 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 5020 if (N0.isUndef() && N1.isUndef()) 5021 return DAG.getConstant(0, SDLoc(N), VT); 5022 // fold (xor x, undef) -> undef 5023 if (N0.isUndef()) 5024 return N0; 5025 if (N1.isUndef()) 5026 return N1; 5027 // fold (xor c1, c2) -> c1^c2 5028 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5029 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 5030 if (N0C && N1C) 5031 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 5032 // canonicalize constant to RHS 5033 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5034 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5035 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 5036 // fold (xor x, 0) -> x 5037 if (isNullConstant(N1)) 5038 return N0; 5039 5040 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5041 return NewSel; 5042 5043 // reassociate xor 5044 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 5045 return RXOR; 5046 5047 // fold !(x cc y) -> (x !cc y) 5048 SDValue LHS, RHS, CC; 5049 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 5050 bool isInt = LHS.getValueType().isInteger(); 5051 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 5052 isInt); 5053 5054 if (!LegalOperations || 5055 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 5056 switch (N0.getOpcode()) { 5057 default: 5058 llvm_unreachable("Unhandled SetCC Equivalent!"); 5059 case ISD::SETCC: 5060 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 5061 case ISD::SELECT_CC: 5062 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 5063 N0.getOperand(3), NotCC); 5064 } 5065 } 5066 } 5067 5068 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 5069 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 5070 N0.getNode()->hasOneUse() && 5071 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 5072 SDValue V = N0.getOperand(0); 5073 SDLoc DL(N0); 5074 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 5075 DAG.getConstant(1, DL, V.getValueType())); 5076 AddToWorklist(V.getNode()); 5077 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 5078 } 5079 5080 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 5081 if (isOneConstant(N1) && VT == MVT::i1 && 5082 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5083 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5084 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 5085 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5086 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5087 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5088 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5089 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5090 } 5091 } 5092 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 5093 if (isAllOnesConstant(N1) && 5094 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5095 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5096 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 5097 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5098 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5099 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5100 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5101 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5102 } 5103 } 5104 // fold (xor (and x, y), y) -> (and (not x), y) 5105 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5106 N0->getOperand(1) == N1) { 5107 SDValue X = N0->getOperand(0); 5108 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 5109 AddToWorklist(NotX.getNode()); 5110 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 5111 } 5112 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 5113 if (N1C && N0.getOpcode() == ISD::XOR) { 5114 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 5115 SDLoc DL(N); 5116 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 5117 DAG.getConstant(N1C->getAPIntValue() ^ 5118 N00C->getAPIntValue(), DL, VT)); 5119 } 5120 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 5121 SDLoc DL(N); 5122 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 5123 DAG.getConstant(N1C->getAPIntValue() ^ 5124 N01C->getAPIntValue(), DL, VT)); 5125 } 5126 } 5127 5128 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 5129 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5130 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 5131 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) && 5132 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 5133 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 5134 if (C->getAPIntValue() == (OpSizeInBits - 1)) 5135 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0)); 5136 } 5137 5138 // fold (xor x, x) -> 0 5139 if (N0 == N1) 5140 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 5141 5142 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 5143 // Here is a concrete example of this equivalence: 5144 // i16 x == 14 5145 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 5146 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 5147 // 5148 // => 5149 // 5150 // i16 ~1 == 0b1111111111111110 5151 // i16 rol(~1, 14) == 0b1011111111111111 5152 // 5153 // Some additional tips to help conceptualize this transform: 5154 // - Try to see the operation as placing a single zero in a value of all ones. 5155 // - There exists no value for x which would allow the result to contain zero. 5156 // - Values of x larger than the bitwidth are undefined and do not require a 5157 // consistent result. 5158 // - Pushing the zero left requires shifting one bits in from the right. 5159 // A rotate left of ~1 is a nice way of achieving the desired result. 5160 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 5161 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 5162 SDLoc DL(N); 5163 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 5164 N0.getOperand(1)); 5165 } 5166 5167 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 5168 if (N0.getOpcode() == N1.getOpcode()) 5169 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5170 return Tmp; 5171 5172 // Simplify the expression using non-local knowledge. 5173 if (SimplifyDemandedBits(SDValue(N, 0))) 5174 return SDValue(N, 0); 5175 5176 return SDValue(); 5177 } 5178 5179 /// Handle transforms common to the three shifts, when the shift amount is a 5180 /// constant. 5181 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 5182 SDNode *LHS = N->getOperand(0).getNode(); 5183 if (!LHS->hasOneUse()) return SDValue(); 5184 5185 // We want to pull some binops through shifts, so that we have (and (shift)) 5186 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 5187 // thing happens with address calculations, so it's important to canonicalize 5188 // it. 5189 bool HighBitSet = false; // Can we transform this if the high bit is set? 5190 5191 switch (LHS->getOpcode()) { 5192 default: return SDValue(); 5193 case ISD::OR: 5194 case ISD::XOR: 5195 HighBitSet = false; // We can only transform sra if the high bit is clear. 5196 break; 5197 case ISD::AND: 5198 HighBitSet = true; // We can only transform sra if the high bit is set. 5199 break; 5200 case ISD::ADD: 5201 if (N->getOpcode() != ISD::SHL) 5202 return SDValue(); // only shl(add) not sr[al](add). 5203 HighBitSet = false; // We can only transform sra if the high bit is clear. 5204 break; 5205 } 5206 5207 // We require the RHS of the binop to be a constant and not opaque as well. 5208 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 5209 if (!BinOpCst) return SDValue(); 5210 5211 // FIXME: disable this unless the input to the binop is a shift by a constant 5212 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 5213 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 5214 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 5215 BinOpLHSVal->getOpcode() == ISD::SRA || 5216 BinOpLHSVal->getOpcode() == ISD::SRL; 5217 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 5218 BinOpLHSVal->getOpcode() == ISD::SELECT; 5219 5220 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 5221 !isCopyOrSelect) 5222 return SDValue(); 5223 5224 if (isCopyOrSelect && N->hasOneUse()) 5225 return SDValue(); 5226 5227 EVT VT = N->getValueType(0); 5228 5229 // If this is a signed shift right, and the high bit is modified by the 5230 // logical operation, do not perform the transformation. The highBitSet 5231 // boolean indicates the value of the high bit of the constant which would 5232 // cause it to be modified for this operation. 5233 if (N->getOpcode() == ISD::SRA) { 5234 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 5235 if (BinOpRHSSignSet != HighBitSet) 5236 return SDValue(); 5237 } 5238 5239 if (!TLI.isDesirableToCommuteWithShift(LHS)) 5240 return SDValue(); 5241 5242 // Fold the constants, shifting the binop RHS by the shift amount. 5243 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 5244 N->getValueType(0), 5245 LHS->getOperand(1), N->getOperand(1)); 5246 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 5247 5248 // Create the new shift. 5249 SDValue NewShift = DAG.getNode(N->getOpcode(), 5250 SDLoc(LHS->getOperand(0)), 5251 VT, LHS->getOperand(0), N->getOperand(1)); 5252 5253 // Create the new binop. 5254 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 5255 } 5256 5257 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 5258 assert(N->getOpcode() == ISD::TRUNCATE); 5259 assert(N->getOperand(0).getOpcode() == ISD::AND); 5260 5261 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 5262 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 5263 SDValue N01 = N->getOperand(0).getOperand(1); 5264 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 5265 SDLoc DL(N); 5266 EVT TruncVT = N->getValueType(0); 5267 SDValue N00 = N->getOperand(0).getOperand(0); 5268 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 5269 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 5270 AddToWorklist(Trunc00.getNode()); 5271 AddToWorklist(Trunc01.getNode()); 5272 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 5273 } 5274 } 5275 5276 return SDValue(); 5277 } 5278 5279 SDValue DAGCombiner::visitRotate(SDNode *N) { 5280 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 5281 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 5282 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 5283 if (SDValue NewOp1 = 5284 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 5285 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 5286 N->getOperand(0), NewOp1); 5287 } 5288 return SDValue(); 5289 } 5290 5291 SDValue DAGCombiner::visitSHL(SDNode *N) { 5292 SDValue N0 = N->getOperand(0); 5293 SDValue N1 = N->getOperand(1); 5294 EVT VT = N0.getValueType(); 5295 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5296 5297 // fold vector ops 5298 if (VT.isVector()) { 5299 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5300 return FoldedVOp; 5301 5302 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 5303 // If setcc produces all-one true value then: 5304 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 5305 if (N1CV && N1CV->isConstant()) { 5306 if (N0.getOpcode() == ISD::AND) { 5307 SDValue N00 = N0->getOperand(0); 5308 SDValue N01 = N0->getOperand(1); 5309 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 5310 5311 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 5312 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 5313 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5314 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 5315 N01CV, N1CV)) 5316 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 5317 } 5318 } 5319 } 5320 } 5321 5322 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5323 5324 // fold (shl c1, c2) -> c1<<c2 5325 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5326 if (N0C && N1C && !N1C->isOpaque()) 5327 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 5328 // fold (shl 0, x) -> 0 5329 if (isNullConstantOrNullSplatConstant(N0)) 5330 return N0; 5331 // fold (shl x, c >= size(x)) -> undef 5332 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5333 return DAG.getUNDEF(VT); 5334 // fold (shl x, 0) -> x 5335 if (N1C && N1C->isNullValue()) 5336 return N0; 5337 // fold (shl undef, x) -> 0 5338 if (N0.isUndef()) 5339 return DAG.getConstant(0, SDLoc(N), VT); 5340 5341 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5342 return NewSel; 5343 5344 // if (shl x, c) is known to be zero, return 0 5345 if (DAG.MaskedValueIsZero(SDValue(N, 0), 5346 APInt::getAllOnesValue(OpSizeInBits))) 5347 return DAG.getConstant(0, SDLoc(N), VT); 5348 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 5349 if (N1.getOpcode() == ISD::TRUNCATE && 5350 N1.getOperand(0).getOpcode() == ISD::AND) { 5351 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5352 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 5353 } 5354 5355 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5356 return SDValue(N, 0); 5357 5358 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 5359 if (N1C && N0.getOpcode() == ISD::SHL) { 5360 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5361 SDLoc DL(N); 5362 APInt c1 = N0C1->getAPIntValue(); 5363 APInt c2 = N1C->getAPIntValue(); 5364 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5365 5366 APInt Sum = c1 + c2; 5367 if (Sum.uge(OpSizeInBits)) 5368 return DAG.getConstant(0, DL, VT); 5369 5370 return DAG.getNode( 5371 ISD::SHL, DL, VT, N0.getOperand(0), 5372 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5373 } 5374 } 5375 5376 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 5377 // For this to be valid, the second form must not preserve any of the bits 5378 // that are shifted out by the inner shift in the first form. This means 5379 // the outer shift size must be >= the number of bits added by the ext. 5380 // As a corollary, we don't care what kind of ext it is. 5381 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 5382 N0.getOpcode() == ISD::ANY_EXTEND || 5383 N0.getOpcode() == ISD::SIGN_EXTEND) && 5384 N0.getOperand(0).getOpcode() == ISD::SHL) { 5385 SDValue N0Op0 = N0.getOperand(0); 5386 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5387 APInt c1 = N0Op0C1->getAPIntValue(); 5388 APInt c2 = N1C->getAPIntValue(); 5389 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5390 5391 EVT InnerShiftVT = N0Op0.getValueType(); 5392 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5393 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5394 SDLoc DL(N0); 5395 APInt Sum = c1 + c2; 5396 if (Sum.uge(OpSizeInBits)) 5397 return DAG.getConstant(0, DL, VT); 5398 5399 return DAG.getNode( 5400 ISD::SHL, DL, VT, 5401 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5402 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5403 } 5404 } 5405 } 5406 5407 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5408 // Only fold this if the inner zext has no other uses to avoid increasing 5409 // the total number of instructions. 5410 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5411 N0.getOperand(0).getOpcode() == ISD::SRL) { 5412 SDValue N0Op0 = N0.getOperand(0); 5413 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5414 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5415 uint64_t c1 = N0Op0C1->getZExtValue(); 5416 uint64_t c2 = N1C->getZExtValue(); 5417 if (c1 == c2) { 5418 SDValue NewOp0 = N0.getOperand(0); 5419 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5420 SDLoc DL(N); 5421 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5422 NewOp0, 5423 DAG.getConstant(c2, DL, CountVT)); 5424 AddToWorklist(NewSHL.getNode()); 5425 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5426 } 5427 } 5428 } 5429 } 5430 5431 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5432 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5433 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5434 N0->getFlags().hasExact()) { 5435 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5436 uint64_t C1 = N0C1->getZExtValue(); 5437 uint64_t C2 = N1C->getZExtValue(); 5438 SDLoc DL(N); 5439 if (C1 <= C2) 5440 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5441 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5442 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5443 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5444 } 5445 } 5446 5447 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5448 // (and (srl x, (sub c1, c2), MASK) 5449 // Only fold this if the inner shift has no other uses -- if it does, folding 5450 // this will increase the total number of instructions. 5451 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5452 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5453 uint64_t c1 = N0C1->getZExtValue(); 5454 if (c1 < OpSizeInBits) { 5455 uint64_t c2 = N1C->getZExtValue(); 5456 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5457 SDValue Shift; 5458 if (c2 > c1) { 5459 Mask <<= c2 - c1; 5460 SDLoc DL(N); 5461 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5462 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5463 } else { 5464 Mask.lshrInPlace(c1 - c2); 5465 SDLoc DL(N); 5466 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5467 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5468 } 5469 SDLoc DL(N0); 5470 return DAG.getNode(ISD::AND, DL, VT, Shift, 5471 DAG.getConstant(Mask, DL, VT)); 5472 } 5473 } 5474 } 5475 5476 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5477 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5478 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5479 SDLoc DL(N); 5480 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5481 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5482 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5483 } 5484 5485 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5486 // Variant of version done on multiply, except mul by a power of 2 is turned 5487 // into a shift. 5488 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 5489 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5490 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5491 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5492 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5493 AddToWorklist(Shl0.getNode()); 5494 AddToWorklist(Shl1.getNode()); 5495 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 5496 } 5497 5498 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5499 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5500 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5501 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5502 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5503 if (isConstantOrConstantVector(Shl)) 5504 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5505 } 5506 5507 if (N1C && !N1C->isOpaque()) 5508 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5509 return NewSHL; 5510 5511 return SDValue(); 5512 } 5513 5514 SDValue DAGCombiner::visitSRA(SDNode *N) { 5515 SDValue N0 = N->getOperand(0); 5516 SDValue N1 = N->getOperand(1); 5517 EVT VT = N0.getValueType(); 5518 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5519 5520 // Arithmetic shifting an all-sign-bit value is a no-op. 5521 // fold (sra 0, x) -> 0 5522 // fold (sra -1, x) -> -1 5523 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5524 return N0; 5525 5526 // fold vector ops 5527 if (VT.isVector()) 5528 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5529 return FoldedVOp; 5530 5531 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5532 5533 // fold (sra c1, c2) -> (sra c1, c2) 5534 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5535 if (N0C && N1C && !N1C->isOpaque()) 5536 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5537 // fold (sra x, c >= size(x)) -> undef 5538 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5539 return DAG.getUNDEF(VT); 5540 // fold (sra x, 0) -> x 5541 if (N1C && N1C->isNullValue()) 5542 return N0; 5543 5544 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5545 return NewSel; 5546 5547 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5548 // sext_inreg. 5549 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5550 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5551 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5552 if (VT.isVector()) 5553 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5554 ExtVT, VT.getVectorNumElements()); 5555 if ((!LegalOperations || 5556 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5557 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5558 N0.getOperand(0), DAG.getValueType(ExtVT)); 5559 } 5560 5561 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5562 if (N1C && N0.getOpcode() == ISD::SRA) { 5563 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5564 SDLoc DL(N); 5565 APInt c1 = N0C1->getAPIntValue(); 5566 APInt c2 = N1C->getAPIntValue(); 5567 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5568 5569 APInt Sum = c1 + c2; 5570 if (Sum.uge(OpSizeInBits)) 5571 Sum = APInt(OpSizeInBits, OpSizeInBits - 1); 5572 5573 return DAG.getNode( 5574 ISD::SRA, DL, VT, N0.getOperand(0), 5575 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5576 } 5577 } 5578 5579 // fold (sra (shl X, m), (sub result_size, n)) 5580 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5581 // result_size - n != m. 5582 // If truncate is free for the target sext(shl) is likely to result in better 5583 // code. 5584 if (N0.getOpcode() == ISD::SHL && N1C) { 5585 // Get the two constanst of the shifts, CN0 = m, CN = n. 5586 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5587 if (N01C) { 5588 LLVMContext &Ctx = *DAG.getContext(); 5589 // Determine what the truncate's result bitsize and type would be. 5590 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5591 5592 if (VT.isVector()) 5593 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5594 5595 // Determine the residual right-shift amount. 5596 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5597 5598 // If the shift is not a no-op (in which case this should be just a sign 5599 // extend already), the truncated to type is legal, sign_extend is legal 5600 // on that type, and the truncate to that type is both legal and free, 5601 // perform the transform. 5602 if ((ShiftAmt > 0) && 5603 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5604 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5605 TLI.isTruncateFree(VT, TruncVT)) { 5606 5607 SDLoc DL(N); 5608 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5609 getShiftAmountTy(N0.getOperand(0).getValueType())); 5610 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5611 N0.getOperand(0), Amt); 5612 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5613 Shift); 5614 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5615 N->getValueType(0), Trunc); 5616 } 5617 } 5618 } 5619 5620 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5621 if (N1.getOpcode() == ISD::TRUNCATE && 5622 N1.getOperand(0).getOpcode() == ISD::AND) { 5623 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5624 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5625 } 5626 5627 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5628 // if c1 is equal to the number of bits the trunc removes 5629 if (N0.getOpcode() == ISD::TRUNCATE && 5630 (N0.getOperand(0).getOpcode() == ISD::SRL || 5631 N0.getOperand(0).getOpcode() == ISD::SRA) && 5632 N0.getOperand(0).hasOneUse() && 5633 N0.getOperand(0).getOperand(1).hasOneUse() && 5634 N1C) { 5635 SDValue N0Op0 = N0.getOperand(0); 5636 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 5637 unsigned LargeShiftVal = LargeShift->getZExtValue(); 5638 EVT LargeVT = N0Op0.getValueType(); 5639 5640 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 5641 SDLoc DL(N); 5642 SDValue Amt = 5643 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 5644 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 5645 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 5646 N0Op0.getOperand(0), Amt); 5647 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 5648 } 5649 } 5650 } 5651 5652 // Simplify, based on bits shifted out of the LHS. 5653 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5654 return SDValue(N, 0); 5655 5656 5657 // If the sign bit is known to be zero, switch this to a SRL. 5658 if (DAG.SignBitIsZero(N0)) 5659 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 5660 5661 if (N1C && !N1C->isOpaque()) 5662 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 5663 return NewSRA; 5664 5665 return SDValue(); 5666 } 5667 5668 SDValue DAGCombiner::visitSRL(SDNode *N) { 5669 SDValue N0 = N->getOperand(0); 5670 SDValue N1 = N->getOperand(1); 5671 EVT VT = N0.getValueType(); 5672 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5673 5674 // fold vector ops 5675 if (VT.isVector()) 5676 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5677 return FoldedVOp; 5678 5679 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5680 5681 // fold (srl c1, c2) -> c1 >>u c2 5682 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5683 if (N0C && N1C && !N1C->isOpaque()) 5684 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 5685 // fold (srl 0, x) -> 0 5686 if (isNullConstantOrNullSplatConstant(N0)) 5687 return N0; 5688 // fold (srl x, c >= size(x)) -> undef 5689 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5690 return DAG.getUNDEF(VT); 5691 // fold (srl x, 0) -> x 5692 if (N1C && N1C->isNullValue()) 5693 return N0; 5694 5695 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5696 return NewSel; 5697 5698 // if (srl x, c) is known to be zero, return 0 5699 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 5700 APInt::getAllOnesValue(OpSizeInBits))) 5701 return DAG.getConstant(0, SDLoc(N), VT); 5702 5703 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 5704 if (N1C && N0.getOpcode() == ISD::SRL) { 5705 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5706 SDLoc DL(N); 5707 APInt c1 = N0C1->getAPIntValue(); 5708 APInt c2 = N1C->getAPIntValue(); 5709 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5710 5711 APInt Sum = c1 + c2; 5712 if (Sum.uge(OpSizeInBits)) 5713 return DAG.getConstant(0, DL, VT); 5714 5715 return DAG.getNode( 5716 ISD::SRL, DL, VT, N0.getOperand(0), 5717 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5718 } 5719 } 5720 5721 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 5722 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 5723 N0.getOperand(0).getOpcode() == ISD::SRL) { 5724 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 5725 uint64_t c1 = N001C->getZExtValue(); 5726 uint64_t c2 = N1C->getZExtValue(); 5727 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 5728 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 5729 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5730 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 5731 if (c1 + OpSizeInBits == InnerShiftSize) { 5732 SDLoc DL(N0); 5733 if (c1 + c2 >= InnerShiftSize) 5734 return DAG.getConstant(0, DL, VT); 5735 return DAG.getNode(ISD::TRUNCATE, DL, VT, 5736 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 5737 N0.getOperand(0).getOperand(0), 5738 DAG.getConstant(c1 + c2, DL, 5739 ShiftCountVT))); 5740 } 5741 } 5742 } 5743 5744 // fold (srl (shl x, c), c) -> (and x, cst2) 5745 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 5746 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 5747 SDLoc DL(N); 5748 SDValue Mask = 5749 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 5750 AddToWorklist(Mask.getNode()); 5751 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 5752 } 5753 5754 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 5755 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 5756 // Shifting in all undef bits? 5757 EVT SmallVT = N0.getOperand(0).getValueType(); 5758 unsigned BitSize = SmallVT.getScalarSizeInBits(); 5759 if (N1C->getZExtValue() >= BitSize) 5760 return DAG.getUNDEF(VT); 5761 5762 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 5763 uint64_t ShiftAmt = N1C->getZExtValue(); 5764 SDLoc DL0(N0); 5765 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 5766 N0.getOperand(0), 5767 DAG.getConstant(ShiftAmt, DL0, 5768 getShiftAmountTy(SmallVT))); 5769 AddToWorklist(SmallShift.getNode()); 5770 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 5771 SDLoc DL(N); 5772 return DAG.getNode(ISD::AND, DL, VT, 5773 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 5774 DAG.getConstant(Mask, DL, VT)); 5775 } 5776 } 5777 5778 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 5779 // bit, which is unmodified by sra. 5780 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 5781 if (N0.getOpcode() == ISD::SRA) 5782 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 5783 } 5784 5785 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 5786 if (N1C && N0.getOpcode() == ISD::CTLZ && 5787 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 5788 KnownBits Known; 5789 DAG.computeKnownBits(N0.getOperand(0), Known); 5790 5791 // If any of the input bits are KnownOne, then the input couldn't be all 5792 // zeros, thus the result of the srl will always be zero. 5793 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 5794 5795 // If all of the bits input the to ctlz node are known to be zero, then 5796 // the result of the ctlz is "32" and the result of the shift is one. 5797 APInt UnknownBits = ~Known.Zero; 5798 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 5799 5800 // Otherwise, check to see if there is exactly one bit input to the ctlz. 5801 if (UnknownBits.isPowerOf2()) { 5802 // Okay, we know that only that the single bit specified by UnknownBits 5803 // could be set on input to the CTLZ node. If this bit is set, the SRL 5804 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 5805 // to an SRL/XOR pair, which is likely to simplify more. 5806 unsigned ShAmt = UnknownBits.countTrailingZeros(); 5807 SDValue Op = N0.getOperand(0); 5808 5809 if (ShAmt) { 5810 SDLoc DL(N0); 5811 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 5812 DAG.getConstant(ShAmt, DL, 5813 getShiftAmountTy(Op.getValueType()))); 5814 AddToWorklist(Op.getNode()); 5815 } 5816 5817 SDLoc DL(N); 5818 return DAG.getNode(ISD::XOR, DL, VT, 5819 Op, DAG.getConstant(1, DL, VT)); 5820 } 5821 } 5822 5823 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 5824 if (N1.getOpcode() == ISD::TRUNCATE && 5825 N1.getOperand(0).getOpcode() == ISD::AND) { 5826 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5827 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 5828 } 5829 5830 // fold operands of srl based on knowledge that the low bits are not 5831 // demanded. 5832 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5833 return SDValue(N, 0); 5834 5835 if (N1C && !N1C->isOpaque()) 5836 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 5837 return NewSRL; 5838 5839 // Attempt to convert a srl of a load into a narrower zero-extending load. 5840 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 5841 return NarrowLoad; 5842 5843 // Here is a common situation. We want to optimize: 5844 // 5845 // %a = ... 5846 // %b = and i32 %a, 2 5847 // %c = srl i32 %b, 1 5848 // brcond i32 %c ... 5849 // 5850 // into 5851 // 5852 // %a = ... 5853 // %b = and %a, 2 5854 // %c = setcc eq %b, 0 5855 // brcond %c ... 5856 // 5857 // However when after the source operand of SRL is optimized into AND, the SRL 5858 // itself may not be optimized further. Look for it and add the BRCOND into 5859 // the worklist. 5860 if (N->hasOneUse()) { 5861 SDNode *Use = *N->use_begin(); 5862 if (Use->getOpcode() == ISD::BRCOND) 5863 AddToWorklist(Use); 5864 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 5865 // Also look pass the truncate. 5866 Use = *Use->use_begin(); 5867 if (Use->getOpcode() == ISD::BRCOND) 5868 AddToWorklist(Use); 5869 } 5870 } 5871 5872 return SDValue(); 5873 } 5874 5875 SDValue DAGCombiner::visitABS(SDNode *N) { 5876 SDValue N0 = N->getOperand(0); 5877 EVT VT = N->getValueType(0); 5878 5879 // fold (abs c1) -> c2 5880 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5881 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 5882 // fold (abs (abs x)) -> (abs x) 5883 if (N0.getOpcode() == ISD::ABS) 5884 return N0; 5885 // fold (abs x) -> x iff not-negative 5886 if (DAG.SignBitIsZero(N0)) 5887 return N0; 5888 return SDValue(); 5889 } 5890 5891 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 5892 SDValue N0 = N->getOperand(0); 5893 EVT VT = N->getValueType(0); 5894 5895 // fold (bswap c1) -> c2 5896 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5897 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 5898 // fold (bswap (bswap x)) -> x 5899 if (N0.getOpcode() == ISD::BSWAP) 5900 return N0->getOperand(0); 5901 return SDValue(); 5902 } 5903 5904 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 5905 SDValue N0 = N->getOperand(0); 5906 EVT VT = N->getValueType(0); 5907 5908 // fold (bitreverse c1) -> c2 5909 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5910 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 5911 // fold (bitreverse (bitreverse x)) -> x 5912 if (N0.getOpcode() == ISD::BITREVERSE) 5913 return N0.getOperand(0); 5914 return SDValue(); 5915 } 5916 5917 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 5918 SDValue N0 = N->getOperand(0); 5919 EVT VT = N->getValueType(0); 5920 5921 // fold (ctlz c1) -> c2 5922 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5923 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 5924 return SDValue(); 5925 } 5926 5927 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 5928 SDValue N0 = N->getOperand(0); 5929 EVT VT = N->getValueType(0); 5930 5931 // fold (ctlz_zero_undef c1) -> c2 5932 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5933 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5934 return SDValue(); 5935 } 5936 5937 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5938 SDValue N0 = N->getOperand(0); 5939 EVT VT = N->getValueType(0); 5940 5941 // fold (cttz c1) -> c2 5942 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5943 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5944 return SDValue(); 5945 } 5946 5947 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5948 SDValue N0 = N->getOperand(0); 5949 EVT VT = N->getValueType(0); 5950 5951 // fold (cttz_zero_undef c1) -> c2 5952 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5953 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5954 return SDValue(); 5955 } 5956 5957 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5958 SDValue N0 = N->getOperand(0); 5959 EVT VT = N->getValueType(0); 5960 5961 // fold (ctpop c1) -> c2 5962 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5963 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5964 return SDValue(); 5965 } 5966 5967 5968 /// \brief Generate Min/Max node 5969 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 5970 SDValue RHS, SDValue True, SDValue False, 5971 ISD::CondCode CC, const TargetLowering &TLI, 5972 SelectionDAG &DAG) { 5973 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5974 return SDValue(); 5975 5976 switch (CC) { 5977 case ISD::SETOLT: 5978 case ISD::SETOLE: 5979 case ISD::SETLT: 5980 case ISD::SETLE: 5981 case ISD::SETULT: 5982 case ISD::SETULE: { 5983 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5984 if (TLI.isOperationLegal(Opcode, VT)) 5985 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5986 return SDValue(); 5987 } 5988 case ISD::SETOGT: 5989 case ISD::SETOGE: 5990 case ISD::SETGT: 5991 case ISD::SETGE: 5992 case ISD::SETUGT: 5993 case ISD::SETUGE: { 5994 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5995 if (TLI.isOperationLegal(Opcode, VT)) 5996 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5997 return SDValue(); 5998 } 5999 default: 6000 return SDValue(); 6001 } 6002 } 6003 6004 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 6005 SDValue Cond = N->getOperand(0); 6006 SDValue N1 = N->getOperand(1); 6007 SDValue N2 = N->getOperand(2); 6008 EVT VT = N->getValueType(0); 6009 EVT CondVT = Cond.getValueType(); 6010 SDLoc DL(N); 6011 6012 if (!VT.isInteger()) 6013 return SDValue(); 6014 6015 auto *C1 = dyn_cast<ConstantSDNode>(N1); 6016 auto *C2 = dyn_cast<ConstantSDNode>(N2); 6017 if (!C1 || !C2) 6018 return SDValue(); 6019 6020 // Only do this before legalization to avoid conflicting with target-specific 6021 // transforms in the other direction (create a select from a zext/sext). There 6022 // is also a target-independent combine here in DAGCombiner in the other 6023 // direction for (select Cond, -1, 0) when the condition is not i1. 6024 if (CondVT == MVT::i1 && !LegalOperations) { 6025 if (C1->isNullValue() && C2->isOne()) { 6026 // select Cond, 0, 1 --> zext (!Cond) 6027 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6028 if (VT != MVT::i1) 6029 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 6030 return NotCond; 6031 } 6032 if (C1->isNullValue() && C2->isAllOnesValue()) { 6033 // select Cond, 0, -1 --> sext (!Cond) 6034 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6035 if (VT != MVT::i1) 6036 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 6037 return NotCond; 6038 } 6039 if (C1->isOne() && C2->isNullValue()) { 6040 // select Cond, 1, 0 --> zext (Cond) 6041 if (VT != MVT::i1) 6042 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6043 return Cond; 6044 } 6045 if (C1->isAllOnesValue() && C2->isNullValue()) { 6046 // select Cond, -1, 0 --> sext (Cond) 6047 if (VT != MVT::i1) 6048 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6049 return Cond; 6050 } 6051 6052 // For any constants that differ by 1, we can transform the select into an 6053 // extend and add. Use a target hook because some targets may prefer to 6054 // transform in the other direction. 6055 if (TLI.convertSelectOfConstantsToMath()) { 6056 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 6057 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 6058 if (VT != MVT::i1) 6059 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6060 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6061 } 6062 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 6063 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 6064 if (VT != MVT::i1) 6065 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6066 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6067 } 6068 } 6069 6070 return SDValue(); 6071 } 6072 6073 // fold (select Cond, 0, 1) -> (xor Cond, 1) 6074 // We can't do this reliably if integer based booleans have different contents 6075 // to floating point based booleans. This is because we can't tell whether we 6076 // have an integer-based boolean or a floating-point-based boolean unless we 6077 // can find the SETCC that produced it and inspect its operands. This is 6078 // fairly easy if C is the SETCC node, but it can potentially be 6079 // undiscoverable (or not reasonably discoverable). For example, it could be 6080 // in another basic block or it could require searching a complicated 6081 // expression. 6082 if (CondVT.isInteger() && 6083 TLI.getBooleanContents(false, true) == 6084 TargetLowering::ZeroOrOneBooleanContent && 6085 TLI.getBooleanContents(false, false) == 6086 TargetLowering::ZeroOrOneBooleanContent && 6087 C1->isNullValue() && C2->isOne()) { 6088 SDValue NotCond = 6089 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 6090 if (VT.bitsEq(CondVT)) 6091 return NotCond; 6092 return DAG.getZExtOrTrunc(NotCond, DL, VT); 6093 } 6094 6095 return SDValue(); 6096 } 6097 6098 SDValue DAGCombiner::visitSELECT(SDNode *N) { 6099 SDValue N0 = N->getOperand(0); 6100 SDValue N1 = N->getOperand(1); 6101 SDValue N2 = N->getOperand(2); 6102 EVT VT = N->getValueType(0); 6103 EVT VT0 = N0.getValueType(); 6104 6105 // fold (select C, X, X) -> X 6106 if (N1 == N2) 6107 return N1; 6108 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 6109 // fold (select true, X, Y) -> X 6110 // fold (select false, X, Y) -> Y 6111 return !N0C->isNullValue() ? N1 : N2; 6112 } 6113 // fold (select X, X, Y) -> (or X, Y) 6114 // fold (select X, 1, Y) -> (or C, Y) 6115 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 6116 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 6117 6118 if (SDValue V = foldSelectOfConstants(N)) 6119 return V; 6120 6121 // fold (select C, 0, X) -> (and (not C), X) 6122 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 6123 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6124 AddToWorklist(NOTNode.getNode()); 6125 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 6126 } 6127 // fold (select C, X, 1) -> (or (not C), X) 6128 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 6129 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6130 AddToWorklist(NOTNode.getNode()); 6131 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 6132 } 6133 // fold (select X, Y, X) -> (and X, Y) 6134 // fold (select X, Y, 0) -> (and X, Y) 6135 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 6136 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 6137 6138 // If we can fold this based on the true/false value, do so. 6139 if (SimplifySelectOps(N, N1, N2)) 6140 return SDValue(N, 0); // Don't revisit N. 6141 6142 if (VT0 == MVT::i1) { 6143 // The code in this block deals with the following 2 equivalences: 6144 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 6145 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 6146 // The target can specify its preferred form with the 6147 // shouldNormalizeToSelectSequence() callback. However we always transform 6148 // to the right anyway if we find the inner select exists in the DAG anyway 6149 // and we always transform to the left side if we know that we can further 6150 // optimize the combination of the conditions. 6151 bool normalizeToSequence 6152 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 6153 // select (and Cond0, Cond1), X, Y 6154 // -> select Cond0, (select Cond1, X, Y), Y 6155 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 6156 SDValue Cond0 = N0->getOperand(0); 6157 SDValue Cond1 = N0->getOperand(1); 6158 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 6159 N1.getValueType(), Cond1, N1, N2); 6160 if (normalizeToSequence || !InnerSelect.use_empty()) 6161 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 6162 InnerSelect, N2); 6163 } 6164 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 6165 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 6166 SDValue Cond0 = N0->getOperand(0); 6167 SDValue Cond1 = N0->getOperand(1); 6168 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 6169 N1.getValueType(), Cond1, N1, N2); 6170 if (normalizeToSequence || !InnerSelect.use_empty()) 6171 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 6172 InnerSelect); 6173 } 6174 6175 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 6176 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 6177 SDValue N1_0 = N1->getOperand(0); 6178 SDValue N1_1 = N1->getOperand(1); 6179 SDValue N1_2 = N1->getOperand(2); 6180 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 6181 // Create the actual and node if we can generate good code for it. 6182 if (!normalizeToSequence) { 6183 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 6184 N0, N1_0); 6185 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 6186 N1_1, N2); 6187 } 6188 // Otherwise see if we can optimize the "and" to a better pattern. 6189 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 6190 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 6191 N1_1, N2); 6192 } 6193 } 6194 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 6195 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 6196 SDValue N2_0 = N2->getOperand(0); 6197 SDValue N2_1 = N2->getOperand(1); 6198 SDValue N2_2 = N2->getOperand(2); 6199 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 6200 // Create the actual or node if we can generate good code for it. 6201 if (!normalizeToSequence) { 6202 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 6203 N0, N2_0); 6204 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 6205 N1, N2_2); 6206 } 6207 // Otherwise see if we can optimize to a better pattern. 6208 if (SDValue Combined = visitORLike(N0, N2_0, N)) 6209 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 6210 N1, N2_2); 6211 } 6212 } 6213 } 6214 6215 // select (xor Cond, 1), X, Y -> select Cond, Y, X 6216 if (VT0 == MVT::i1) { 6217 if (N0->getOpcode() == ISD::XOR) { 6218 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 6219 SDValue Cond0 = N0->getOperand(0); 6220 if (C->isOne()) 6221 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), 6222 Cond0, N2, N1); 6223 } 6224 } 6225 } 6226 6227 // fold selects based on a setcc into other things, such as min/max/abs 6228 if (N0.getOpcode() == ISD::SETCC) { 6229 // select x, y (fcmp lt x, y) -> fminnum x, y 6230 // select x, y (fcmp gt x, y) -> fmaxnum x, y 6231 // 6232 // This is OK if we don't care about what happens if either operand is a 6233 // NaN. 6234 // 6235 6236 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 6237 // no signed zeros as well as no nans. 6238 const TargetOptions &Options = DAG.getTarget().Options; 6239 if (Options.UnsafeFPMath && 6240 VT.isFloatingPoint() && N0.hasOneUse() && 6241 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 6242 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6243 6244 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 6245 N0.getOperand(1), N1, N2, CC, 6246 TLI, DAG)) 6247 return FMinMax; 6248 } 6249 6250 if ((!LegalOperations && 6251 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 6252 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 6253 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 6254 N0.getOperand(0), N0.getOperand(1), 6255 N1, N2, N0.getOperand(2)); 6256 return SimplifySelect(SDLoc(N), N0, N1, N2); 6257 } 6258 6259 return SDValue(); 6260 } 6261 6262 static 6263 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 6264 SDLoc DL(N); 6265 EVT LoVT, HiVT; 6266 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 6267 6268 // Split the inputs. 6269 SDValue Lo, Hi, LL, LH, RL, RH; 6270 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 6271 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 6272 6273 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 6274 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 6275 6276 return std::make_pair(Lo, Hi); 6277 } 6278 6279 // This function assumes all the vselect's arguments are CONCAT_VECTOR 6280 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 6281 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 6282 SDLoc DL(N); 6283 SDValue Cond = N->getOperand(0); 6284 SDValue LHS = N->getOperand(1); 6285 SDValue RHS = N->getOperand(2); 6286 EVT VT = N->getValueType(0); 6287 int NumElems = VT.getVectorNumElements(); 6288 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 6289 RHS.getOpcode() == ISD::CONCAT_VECTORS && 6290 Cond.getOpcode() == ISD::BUILD_VECTOR); 6291 6292 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 6293 // binary ones here. 6294 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 6295 return SDValue(); 6296 6297 // We're sure we have an even number of elements due to the 6298 // concat_vectors we have as arguments to vselect. 6299 // Skip BV elements until we find one that's not an UNDEF 6300 // After we find an UNDEF element, keep looping until we get to half the 6301 // length of the BV and see if all the non-undef nodes are the same. 6302 ConstantSDNode *BottomHalf = nullptr; 6303 for (int i = 0; i < NumElems / 2; ++i) { 6304 if (Cond->getOperand(i)->isUndef()) 6305 continue; 6306 6307 if (BottomHalf == nullptr) 6308 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6309 else if (Cond->getOperand(i).getNode() != BottomHalf) 6310 return SDValue(); 6311 } 6312 6313 // Do the same for the second half of the BuildVector 6314 ConstantSDNode *TopHalf = nullptr; 6315 for (int i = NumElems / 2; i < NumElems; ++i) { 6316 if (Cond->getOperand(i)->isUndef()) 6317 continue; 6318 6319 if (TopHalf == nullptr) 6320 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6321 else if (Cond->getOperand(i).getNode() != TopHalf) 6322 return SDValue(); 6323 } 6324 6325 assert(TopHalf && BottomHalf && 6326 "One half of the selector was all UNDEFs and the other was all the " 6327 "same value. This should have been addressed before this function."); 6328 return DAG.getNode( 6329 ISD::CONCAT_VECTORS, DL, VT, 6330 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 6331 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 6332 } 6333 6334 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 6335 6336 if (Level >= AfterLegalizeTypes) 6337 return SDValue(); 6338 6339 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 6340 SDValue Mask = MSC->getMask(); 6341 SDValue Data = MSC->getValue(); 6342 SDLoc DL(N); 6343 6344 // If the MSCATTER data type requires splitting and the mask is provided by a 6345 // SETCC, then split both nodes and its operands before legalization. This 6346 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6347 // and enables future optimizations (e.g. min/max pattern matching on X86). 6348 if (Mask.getOpcode() != ISD::SETCC) 6349 return SDValue(); 6350 6351 // Check if any splitting is required. 6352 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 6353 TargetLowering::TypeSplitVector) 6354 return SDValue(); 6355 SDValue MaskLo, MaskHi, Lo, Hi; 6356 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6357 6358 EVT LoVT, HiVT; 6359 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 6360 6361 SDValue Chain = MSC->getChain(); 6362 6363 EVT MemoryVT = MSC->getMemoryVT(); 6364 unsigned Alignment = MSC->getOriginalAlignment(); 6365 6366 EVT LoMemVT, HiMemVT; 6367 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6368 6369 SDValue DataLo, DataHi; 6370 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6371 6372 SDValue BasePtr = MSC->getBasePtr(); 6373 SDValue IndexLo, IndexHi; 6374 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 6375 6376 MachineMemOperand *MMO = DAG.getMachineFunction(). 6377 getMachineMemOperand(MSC->getPointerInfo(), 6378 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6379 Alignment, MSC->getAAInfo(), MSC->getRanges()); 6380 6381 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 6382 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 6383 DL, OpsLo, MMO); 6384 6385 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 6386 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 6387 DL, OpsHi, MMO); 6388 6389 AddToWorklist(Lo.getNode()); 6390 AddToWorklist(Hi.getNode()); 6391 6392 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6393 } 6394 6395 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 6396 6397 if (Level >= AfterLegalizeTypes) 6398 return SDValue(); 6399 6400 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 6401 SDValue Mask = MST->getMask(); 6402 SDValue Data = MST->getValue(); 6403 EVT VT = Data.getValueType(); 6404 SDLoc DL(N); 6405 6406 // If the MSTORE data type requires splitting and the mask is provided by a 6407 // SETCC, then split both nodes and its operands before legalization. This 6408 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6409 // and enables future optimizations (e.g. min/max pattern matching on X86). 6410 if (Mask.getOpcode() == ISD::SETCC) { 6411 6412 // Check if any splitting is required. 6413 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6414 TargetLowering::TypeSplitVector) 6415 return SDValue(); 6416 6417 SDValue MaskLo, MaskHi, Lo, Hi; 6418 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6419 6420 SDValue Chain = MST->getChain(); 6421 SDValue Ptr = MST->getBasePtr(); 6422 6423 EVT MemoryVT = MST->getMemoryVT(); 6424 unsigned Alignment = MST->getOriginalAlignment(); 6425 6426 // if Alignment is equal to the vector size, 6427 // take the half of it for the second part 6428 unsigned SecondHalfAlignment = 6429 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6430 6431 EVT LoMemVT, HiMemVT; 6432 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6433 6434 SDValue DataLo, DataHi; 6435 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6436 6437 MachineMemOperand *MMO = DAG.getMachineFunction(). 6438 getMachineMemOperand(MST->getPointerInfo(), 6439 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6440 Alignment, MST->getAAInfo(), MST->getRanges()); 6441 6442 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6443 MST->isTruncatingStore(), 6444 MST->isCompressingStore()); 6445 6446 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6447 MST->isCompressingStore()); 6448 6449 MMO = DAG.getMachineFunction(). 6450 getMachineMemOperand(MST->getPointerInfo(), 6451 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 6452 SecondHalfAlignment, MST->getAAInfo(), 6453 MST->getRanges()); 6454 6455 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6456 MST->isTruncatingStore(), 6457 MST->isCompressingStore()); 6458 6459 AddToWorklist(Lo.getNode()); 6460 AddToWorklist(Hi.getNode()); 6461 6462 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6463 } 6464 return SDValue(); 6465 } 6466 6467 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6468 6469 if (Level >= AfterLegalizeTypes) 6470 return SDValue(); 6471 6472 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 6473 SDValue Mask = MGT->getMask(); 6474 SDLoc DL(N); 6475 6476 // If the MGATHER result requires splitting and the mask is provided by a 6477 // SETCC, then split both nodes and its operands before legalization. This 6478 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6479 // and enables future optimizations (e.g. min/max pattern matching on X86). 6480 6481 if (Mask.getOpcode() != ISD::SETCC) 6482 return SDValue(); 6483 6484 EVT VT = N->getValueType(0); 6485 6486 // Check if any splitting is required. 6487 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6488 TargetLowering::TypeSplitVector) 6489 return SDValue(); 6490 6491 SDValue MaskLo, MaskHi, Lo, Hi; 6492 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6493 6494 SDValue Src0 = MGT->getValue(); 6495 SDValue Src0Lo, Src0Hi; 6496 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6497 6498 EVT LoVT, HiVT; 6499 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6500 6501 SDValue Chain = MGT->getChain(); 6502 EVT MemoryVT = MGT->getMemoryVT(); 6503 unsigned Alignment = MGT->getOriginalAlignment(); 6504 6505 EVT LoMemVT, HiMemVT; 6506 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6507 6508 SDValue BasePtr = MGT->getBasePtr(); 6509 SDValue Index = MGT->getIndex(); 6510 SDValue IndexLo, IndexHi; 6511 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6512 6513 MachineMemOperand *MMO = DAG.getMachineFunction(). 6514 getMachineMemOperand(MGT->getPointerInfo(), 6515 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6516 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6517 6518 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 6519 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6520 MMO); 6521 6522 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 6523 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6524 MMO); 6525 6526 AddToWorklist(Lo.getNode()); 6527 AddToWorklist(Hi.getNode()); 6528 6529 // Build a factor node to remember that this load is independent of the 6530 // other one. 6531 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6532 Hi.getValue(1)); 6533 6534 // Legalized the chain result - switch anything that used the old chain to 6535 // use the new one. 6536 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6537 6538 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6539 6540 SDValue RetOps[] = { GatherRes, Chain }; 6541 return DAG.getMergeValues(RetOps, DL); 6542 } 6543 6544 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6545 6546 if (Level >= AfterLegalizeTypes) 6547 return SDValue(); 6548 6549 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6550 SDValue Mask = MLD->getMask(); 6551 SDLoc DL(N); 6552 6553 // If the MLOAD result requires splitting and the mask is provided by a 6554 // SETCC, then split both nodes and its operands before legalization. This 6555 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6556 // and enables future optimizations (e.g. min/max pattern matching on X86). 6557 6558 if (Mask.getOpcode() == ISD::SETCC) { 6559 EVT VT = N->getValueType(0); 6560 6561 // Check if any splitting is required. 6562 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6563 TargetLowering::TypeSplitVector) 6564 return SDValue(); 6565 6566 SDValue MaskLo, MaskHi, Lo, Hi; 6567 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6568 6569 SDValue Src0 = MLD->getSrc0(); 6570 SDValue Src0Lo, Src0Hi; 6571 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6572 6573 EVT LoVT, HiVT; 6574 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6575 6576 SDValue Chain = MLD->getChain(); 6577 SDValue Ptr = MLD->getBasePtr(); 6578 EVT MemoryVT = MLD->getMemoryVT(); 6579 unsigned Alignment = MLD->getOriginalAlignment(); 6580 6581 // if Alignment is equal to the vector size, 6582 // take the half of it for the second part 6583 unsigned SecondHalfAlignment = 6584 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6585 Alignment/2 : Alignment; 6586 6587 EVT LoMemVT, HiMemVT; 6588 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6589 6590 MachineMemOperand *MMO = DAG.getMachineFunction(). 6591 getMachineMemOperand(MLD->getPointerInfo(), 6592 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6593 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6594 6595 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6596 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6597 6598 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6599 MLD->isExpandingLoad()); 6600 6601 MMO = DAG.getMachineFunction(). 6602 getMachineMemOperand(MLD->getPointerInfo(), 6603 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 6604 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 6605 6606 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6607 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6608 6609 AddToWorklist(Lo.getNode()); 6610 AddToWorklist(Hi.getNode()); 6611 6612 // Build a factor node to remember that this load is independent of the 6613 // other one. 6614 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6615 Hi.getValue(1)); 6616 6617 // Legalized the chain result - switch anything that used the old chain to 6618 // use the new one. 6619 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 6620 6621 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6622 6623 SDValue RetOps[] = { LoadRes, Chain }; 6624 return DAG.getMergeValues(RetOps, DL); 6625 } 6626 return SDValue(); 6627 } 6628 6629 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 6630 SDValue N0 = N->getOperand(0); 6631 SDValue N1 = N->getOperand(1); 6632 SDValue N2 = N->getOperand(2); 6633 SDLoc DL(N); 6634 6635 // fold (vselect C, X, X) -> X 6636 if (N1 == N2) 6637 return N1; 6638 6639 // Canonicalize integer abs. 6640 // vselect (setg[te] X, 0), X, -X -> 6641 // vselect (setgt X, -1), X, -X -> 6642 // vselect (setl[te] X, 0), -X, X -> 6643 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 6644 if (N0.getOpcode() == ISD::SETCC) { 6645 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6646 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6647 bool isAbs = false; 6648 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 6649 6650 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 6651 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 6652 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 6653 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 6654 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 6655 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 6656 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 6657 6658 if (isAbs) { 6659 EVT VT = LHS.getValueType(); 6660 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 6661 return DAG.getNode(ISD::ABS, DL, VT, LHS); 6662 6663 SDValue Shift = DAG.getNode( 6664 ISD::SRA, DL, VT, LHS, 6665 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 6666 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 6667 AddToWorklist(Shift.getNode()); 6668 AddToWorklist(Add.getNode()); 6669 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 6670 } 6671 } 6672 6673 if (SimplifySelectOps(N, N1, N2)) 6674 return SDValue(N, 0); // Don't revisit N. 6675 6676 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 6677 if (ISD::isBuildVectorAllOnes(N0.getNode())) 6678 return N1; 6679 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 6680 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6681 return N2; 6682 6683 // The ConvertSelectToConcatVector function is assuming both the above 6684 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 6685 // and addressed. 6686 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 6687 N2.getOpcode() == ISD::CONCAT_VECTORS && 6688 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6689 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 6690 return CV; 6691 } 6692 6693 return SDValue(); 6694 } 6695 6696 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 6697 SDValue N0 = N->getOperand(0); 6698 SDValue N1 = N->getOperand(1); 6699 SDValue N2 = N->getOperand(2); 6700 SDValue N3 = N->getOperand(3); 6701 SDValue N4 = N->getOperand(4); 6702 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 6703 6704 // fold select_cc lhs, rhs, x, x, cc -> x 6705 if (N2 == N3) 6706 return N2; 6707 6708 // Determine if the condition we're dealing with is constant 6709 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 6710 CC, SDLoc(N), false)) { 6711 AddToWorklist(SCC.getNode()); 6712 6713 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 6714 if (!SCCC->isNullValue()) 6715 return N2; // cond always true -> true val 6716 else 6717 return N3; // cond always false -> false val 6718 } else if (SCC->isUndef()) { 6719 // When the condition is UNDEF, just return the first operand. This is 6720 // coherent the DAG creation, no setcc node is created in this case 6721 return N2; 6722 } else if (SCC.getOpcode() == ISD::SETCC) { 6723 // Fold to a simpler select_cc 6724 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 6725 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 6726 SCC.getOperand(2)); 6727 } 6728 } 6729 6730 // If we can fold this based on the true/false value, do so. 6731 if (SimplifySelectOps(N, N2, N3)) 6732 return SDValue(N, 0); // Don't revisit N. 6733 6734 // fold select_cc into other things, such as min/max/abs 6735 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 6736 } 6737 6738 SDValue DAGCombiner::visitSETCC(SDNode *N) { 6739 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 6740 cast<CondCodeSDNode>(N->getOperand(2))->get(), 6741 SDLoc(N)); 6742 } 6743 6744 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 6745 SDValue LHS = N->getOperand(0); 6746 SDValue RHS = N->getOperand(1); 6747 SDValue Carry = N->getOperand(2); 6748 SDValue Cond = N->getOperand(3); 6749 6750 // If Carry is false, fold to a regular SETCC. 6751 if (Carry.getOpcode() == ISD::CARRY_FALSE) 6752 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6753 6754 return SDValue(); 6755 } 6756 6757 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 6758 /// a build_vector of constants. 6759 /// This function is called by the DAGCombiner when visiting sext/zext/aext 6760 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 6761 /// Vector extends are not folded if operations are legal; this is to 6762 /// avoid introducing illegal build_vector dag nodes. 6763 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 6764 SelectionDAG &DAG, bool LegalTypes, 6765 bool LegalOperations) { 6766 unsigned Opcode = N->getOpcode(); 6767 SDValue N0 = N->getOperand(0); 6768 EVT VT = N->getValueType(0); 6769 6770 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 6771 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 6772 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 6773 && "Expected EXTEND dag node in input!"); 6774 6775 // fold (sext c1) -> c1 6776 // fold (zext c1) -> c1 6777 // fold (aext c1) -> c1 6778 if (isa<ConstantSDNode>(N0)) 6779 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 6780 6781 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 6782 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 6783 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 6784 EVT SVT = VT.getScalarType(); 6785 if (!(VT.isVector() && 6786 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 6787 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 6788 return nullptr; 6789 6790 // We can fold this node into a build_vector. 6791 unsigned VTBits = SVT.getSizeInBits(); 6792 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 6793 SmallVector<SDValue, 8> Elts; 6794 unsigned NumElts = VT.getVectorNumElements(); 6795 SDLoc DL(N); 6796 6797 for (unsigned i=0; i != NumElts; ++i) { 6798 SDValue Op = N0->getOperand(i); 6799 if (Op->isUndef()) { 6800 Elts.push_back(DAG.getUNDEF(SVT)); 6801 continue; 6802 } 6803 6804 SDLoc DL(Op); 6805 // Get the constant value and if needed trunc it to the size of the type. 6806 // Nodes like build_vector might have constants wider than the scalar type. 6807 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 6808 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 6809 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 6810 else 6811 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 6812 } 6813 6814 return DAG.getBuildVector(VT, DL, Elts).getNode(); 6815 } 6816 6817 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 6818 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 6819 // transformation. Returns true if extension are possible and the above 6820 // mentioned transformation is profitable. 6821 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 6822 unsigned ExtOpc, 6823 SmallVectorImpl<SDNode *> &ExtendNodes, 6824 const TargetLowering &TLI) { 6825 bool HasCopyToRegUses = false; 6826 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 6827 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 6828 UE = N0.getNode()->use_end(); 6829 UI != UE; ++UI) { 6830 SDNode *User = *UI; 6831 if (User == N) 6832 continue; 6833 if (UI.getUse().getResNo() != N0.getResNo()) 6834 continue; 6835 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 6836 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 6837 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 6838 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 6839 // Sign bits will be lost after a zext. 6840 return false; 6841 bool Add = false; 6842 for (unsigned i = 0; i != 2; ++i) { 6843 SDValue UseOp = User->getOperand(i); 6844 if (UseOp == N0) 6845 continue; 6846 if (!isa<ConstantSDNode>(UseOp)) 6847 return false; 6848 Add = true; 6849 } 6850 if (Add) 6851 ExtendNodes.push_back(User); 6852 continue; 6853 } 6854 // If truncates aren't free and there are users we can't 6855 // extend, it isn't worthwhile. 6856 if (!isTruncFree) 6857 return false; 6858 // Remember if this value is live-out. 6859 if (User->getOpcode() == ISD::CopyToReg) 6860 HasCopyToRegUses = true; 6861 } 6862 6863 if (HasCopyToRegUses) { 6864 bool BothLiveOut = false; 6865 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6866 UI != UE; ++UI) { 6867 SDUse &Use = UI.getUse(); 6868 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 6869 BothLiveOut = true; 6870 break; 6871 } 6872 } 6873 if (BothLiveOut) 6874 // Both unextended and extended values are live out. There had better be 6875 // a good reason for the transformation. 6876 return ExtendNodes.size(); 6877 } 6878 return true; 6879 } 6880 6881 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 6882 SDValue Trunc, SDValue ExtLoad, 6883 const SDLoc &DL, ISD::NodeType ExtType) { 6884 // Extend SetCC uses if necessary. 6885 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 6886 SDNode *SetCC = SetCCs[i]; 6887 SmallVector<SDValue, 4> Ops; 6888 6889 for (unsigned j = 0; j != 2; ++j) { 6890 SDValue SOp = SetCC->getOperand(j); 6891 if (SOp == Trunc) 6892 Ops.push_back(ExtLoad); 6893 else 6894 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 6895 } 6896 6897 Ops.push_back(SetCC->getOperand(2)); 6898 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6899 } 6900 } 6901 6902 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 6903 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 6904 SDValue N0 = N->getOperand(0); 6905 EVT DstVT = N->getValueType(0); 6906 EVT SrcVT = N0.getValueType(); 6907 6908 assert((N->getOpcode() == ISD::SIGN_EXTEND || 6909 N->getOpcode() == ISD::ZERO_EXTEND) && 6910 "Unexpected node type (not an extend)!"); 6911 6912 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 6913 // For example, on a target with legal v4i32, but illegal v8i32, turn: 6914 // (v8i32 (sext (v8i16 (load x)))) 6915 // into: 6916 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6917 // (v4i32 (sextload (x + 16))))) 6918 // Where uses of the original load, i.e.: 6919 // (v8i16 (load x)) 6920 // are replaced with: 6921 // (v8i16 (truncate 6922 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6923 // (v4i32 (sextload (x + 16))))))) 6924 // 6925 // This combine is only applicable to illegal, but splittable, vectors. 6926 // All legal types, and illegal non-vector types, are handled elsewhere. 6927 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 6928 // 6929 if (N0->getOpcode() != ISD::LOAD) 6930 return SDValue(); 6931 6932 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6933 6934 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 6935 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 6936 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 6937 return SDValue(); 6938 6939 SmallVector<SDNode *, 4> SetCCs; 6940 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 6941 return SDValue(); 6942 6943 ISD::LoadExtType ExtType = 6944 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 6945 6946 // Try to split the vector types to get down to legal types. 6947 EVT SplitSrcVT = SrcVT; 6948 EVT SplitDstVT = DstVT; 6949 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 6950 SplitSrcVT.getVectorNumElements() > 1) { 6951 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 6952 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 6953 } 6954 6955 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 6956 return SDValue(); 6957 6958 SDLoc DL(N); 6959 const unsigned NumSplits = 6960 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 6961 const unsigned Stride = SplitSrcVT.getStoreSize(); 6962 SmallVector<SDValue, 4> Loads; 6963 SmallVector<SDValue, 4> Chains; 6964 6965 SDValue BasePtr = LN0->getBasePtr(); 6966 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 6967 const unsigned Offset = Idx * Stride; 6968 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 6969 6970 SDValue SplitLoad = DAG.getExtLoad( 6971 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 6972 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 6973 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6974 6975 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 6976 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 6977 6978 Loads.push_back(SplitLoad.getValue(0)); 6979 Chains.push_back(SplitLoad.getValue(1)); 6980 } 6981 6982 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 6983 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 6984 6985 // Simplify TF. 6986 AddToWorklist(NewChain.getNode()); 6987 6988 CombineTo(N, NewValue); 6989 6990 // Replace uses of the original load (before extension) 6991 // with a truncate of the concatenated sextloaded vectors. 6992 SDValue Trunc = 6993 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6994 CombineTo(N0.getNode(), Trunc, NewChain); 6995 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6996 (ISD::NodeType)N->getOpcode()); 6997 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6998 } 6999 7000 /// If we're narrowing or widening the result of a vector select and the final 7001 /// size is the same size as a setcc (compare) feeding the select, then try to 7002 /// apply the cast operation to the select's operands because matching vector 7003 /// sizes for a select condition and other operands should be more efficient. 7004 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 7005 unsigned CastOpcode = Cast->getOpcode(); 7006 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 7007 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 7008 CastOpcode == ISD::FP_ROUND) && 7009 "Unexpected opcode for vector select narrowing/widening"); 7010 7011 // We only do this transform before legal ops because the pattern may be 7012 // obfuscated by target-specific operations after legalization. Do not create 7013 // an illegal select op, however, because that may be difficult to lower. 7014 EVT VT = Cast->getValueType(0); 7015 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 7016 return SDValue(); 7017 7018 SDValue VSel = Cast->getOperand(0); 7019 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 7020 VSel.getOperand(0).getOpcode() != ISD::SETCC) 7021 return SDValue(); 7022 7023 // Does the setcc have the same vector size as the casted select? 7024 SDValue SetCC = VSel.getOperand(0); 7025 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 7026 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 7027 return SDValue(); 7028 7029 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 7030 SDValue A = VSel.getOperand(1); 7031 SDValue B = VSel.getOperand(2); 7032 SDValue CastA, CastB; 7033 SDLoc DL(Cast); 7034 if (CastOpcode == ISD::FP_ROUND) { 7035 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 7036 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 7037 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 7038 } else { 7039 CastA = DAG.getNode(CastOpcode, DL, VT, A); 7040 CastB = DAG.getNode(CastOpcode, DL, VT, B); 7041 } 7042 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 7043 } 7044 7045 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 7046 SDValue N0 = N->getOperand(0); 7047 EVT VT = N->getValueType(0); 7048 SDLoc DL(N); 7049 7050 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7051 LegalOperations)) 7052 return SDValue(Res, 0); 7053 7054 // fold (sext (sext x)) -> (sext x) 7055 // fold (sext (aext x)) -> (sext x) 7056 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7057 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 7058 7059 if (N0.getOpcode() == ISD::TRUNCATE) { 7060 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 7061 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 7062 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7063 SDNode *oye = N0.getOperand(0).getNode(); 7064 if (NarrowLoad.getNode() != N0.getNode()) { 7065 CombineTo(N0.getNode(), NarrowLoad); 7066 // CombineTo deleted the truncate, if needed, but not what's under it. 7067 AddToWorklist(oye); 7068 } 7069 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7070 } 7071 7072 // See if the value being truncated is already sign extended. If so, just 7073 // eliminate the trunc/sext pair. 7074 SDValue Op = N0.getOperand(0); 7075 unsigned OpBits = Op.getScalarValueSizeInBits(); 7076 unsigned MidBits = N0.getScalarValueSizeInBits(); 7077 unsigned DestBits = VT.getScalarSizeInBits(); 7078 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 7079 7080 if (OpBits == DestBits) { 7081 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 7082 // bits, it is already ready. 7083 if (NumSignBits > DestBits-MidBits) 7084 return Op; 7085 } else if (OpBits < DestBits) { 7086 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 7087 // bits, just sext from i32. 7088 if (NumSignBits > OpBits-MidBits) 7089 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 7090 } else { 7091 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 7092 // bits, just truncate to i32. 7093 if (NumSignBits > OpBits-MidBits) 7094 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 7095 } 7096 7097 // fold (sext (truncate x)) -> (sextinreg x). 7098 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 7099 N0.getValueType())) { 7100 if (OpBits < DestBits) 7101 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 7102 else if (OpBits > DestBits) 7103 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 7104 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 7105 DAG.getValueType(N0.getValueType())); 7106 } 7107 } 7108 7109 // fold (sext (load x)) -> (sext (truncate (sextload x))) 7110 // Only generate vector extloads when 1) they're legal, and 2) they are 7111 // deemed desirable by the target. 7112 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7113 ((!LegalOperations && !VT.isVector() && 7114 !cast<LoadSDNode>(N0)->isVolatile()) || 7115 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 7116 bool DoXform = true; 7117 SmallVector<SDNode*, 4> SetCCs; 7118 if (!N0.hasOneUse()) 7119 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 7120 if (VT.isVector()) 7121 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7122 if (DoXform) { 7123 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7124 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7125 LN0->getBasePtr(), N0.getValueType(), 7126 LN0->getMemOperand()); 7127 CombineTo(N, ExtLoad); 7128 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7129 N0.getValueType(), ExtLoad); 7130 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7131 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7132 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7133 } 7134 } 7135 7136 // fold (sext (load x)) to multiple smaller sextloads. 7137 // Only on illegal but splittable vectors. 7138 if (SDValue ExtLoad = CombineExtLoad(N)) 7139 return ExtLoad; 7140 7141 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 7142 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 7143 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7144 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7145 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7146 EVT MemVT = LN0->getMemoryVT(); 7147 if ((!LegalOperations && !LN0->isVolatile()) || 7148 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 7149 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7150 LN0->getBasePtr(), MemVT, 7151 LN0->getMemOperand()); 7152 CombineTo(N, ExtLoad); 7153 CombineTo(N0.getNode(), 7154 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7155 N0.getValueType(), ExtLoad), 7156 ExtLoad.getValue(1)); 7157 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7158 } 7159 } 7160 7161 // fold (sext (and/or/xor (load x), cst)) -> 7162 // (and/or/xor (sextload x), (sext cst)) 7163 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7164 N0.getOpcode() == ISD::XOR) && 7165 isa<LoadSDNode>(N0.getOperand(0)) && 7166 N0.getOperand(1).getOpcode() == ISD::Constant && 7167 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 7168 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7169 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7170 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 7171 bool DoXform = true; 7172 SmallVector<SDNode*, 4> SetCCs; 7173 if (!N0.hasOneUse()) 7174 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 7175 SetCCs, TLI); 7176 if (DoXform) { 7177 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 7178 LN0->getChain(), LN0->getBasePtr(), 7179 LN0->getMemoryVT(), 7180 LN0->getMemOperand()); 7181 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7182 Mask = Mask.sext(VT.getSizeInBits()); 7183 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7184 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7185 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7186 SDLoc(N0.getOperand(0)), 7187 N0.getOperand(0).getValueType(), ExtLoad); 7188 CombineTo(N, And); 7189 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 7190 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7191 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7192 } 7193 } 7194 } 7195 7196 if (N0.getOpcode() == ISD::SETCC) { 7197 SDValue N00 = N0.getOperand(0); 7198 SDValue N01 = N0.getOperand(1); 7199 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7200 EVT N00VT = N0.getOperand(0).getValueType(); 7201 7202 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 7203 // Only do this before legalize for now. 7204 if (VT.isVector() && !LegalOperations && 7205 TLI.getBooleanContents(N00VT) == 7206 TargetLowering::ZeroOrNegativeOneBooleanContent) { 7207 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 7208 // of the same size as the compared operands. Only optimize sext(setcc()) 7209 // if this is the case. 7210 EVT SVT = getSetCCResultType(N00VT); 7211 7212 // We know that the # elements of the results is the same as the 7213 // # elements of the compare (and the # elements of the compare result 7214 // for that matter). Check to see that they are the same size. If so, 7215 // we know that the element size of the sext'd result matches the 7216 // element size of the compare operands. 7217 if (VT.getSizeInBits() == SVT.getSizeInBits()) 7218 return DAG.getSetCC(DL, VT, N00, N01, CC); 7219 7220 // If the desired elements are smaller or larger than the source 7221 // elements, we can use a matching integer vector type and then 7222 // truncate/sign extend. 7223 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 7224 if (SVT == MatchingVecType) { 7225 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 7226 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 7227 } 7228 } 7229 7230 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 7231 // Here, T can be 1 or -1, depending on the type of the setcc and 7232 // getBooleanContents(). 7233 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 7234 7235 // To determine the "true" side of the select, we need to know the high bit 7236 // of the value returned by the setcc if it evaluates to true. 7237 // If the type of the setcc is i1, then the true case of the select is just 7238 // sext(i1 1), that is, -1. 7239 // If the type of the setcc is larger (say, i8) then the value of the high 7240 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 7241 // of the appropriate width. 7242 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT) 7243 : TLI.getConstTrueVal(DAG, VT, DL); 7244 SDValue Zero = DAG.getConstant(0, DL, VT); 7245 if (SDValue SCC = 7246 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 7247 return SCC; 7248 7249 if (!VT.isVector()) { 7250 EVT SetCCVT = getSetCCResultType(N00VT); 7251 // Don't do this transform for i1 because there's a select transform 7252 // that would reverse it. 7253 // TODO: We should not do this transform at all without a target hook 7254 // because a sext is likely cheaper than a select? 7255 if (SetCCVT.getScalarSizeInBits() != 1 && 7256 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 7257 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 7258 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 7259 } 7260 } 7261 } 7262 7263 // fold (sext x) -> (zext x) if the sign bit is known zero. 7264 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 7265 DAG.SignBitIsZero(N0)) 7266 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 7267 7268 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7269 return NewVSel; 7270 7271 return SDValue(); 7272 } 7273 7274 // isTruncateOf - If N is a truncate of some other value, return true, record 7275 // the value being truncated in Op and which of Op's bits are zero/one in Known. 7276 // This function computes KnownBits to avoid a duplicated call to 7277 // computeKnownBits in the caller. 7278 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 7279 KnownBits &Known) { 7280 if (N->getOpcode() == ISD::TRUNCATE) { 7281 Op = N->getOperand(0); 7282 DAG.computeKnownBits(Op, Known); 7283 return true; 7284 } 7285 7286 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 7287 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 7288 return false; 7289 7290 SDValue Op0 = N->getOperand(0); 7291 SDValue Op1 = N->getOperand(1); 7292 assert(Op0.getValueType() == Op1.getValueType()); 7293 7294 if (isNullConstant(Op0)) 7295 Op = Op1; 7296 else if (isNullConstant(Op1)) 7297 Op = Op0; 7298 else 7299 return false; 7300 7301 DAG.computeKnownBits(Op, Known); 7302 7303 if (!(Known.Zero | 1).isAllOnesValue()) 7304 return false; 7305 7306 return true; 7307 } 7308 7309 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 7310 SDValue N0 = N->getOperand(0); 7311 EVT VT = N->getValueType(0); 7312 7313 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7314 LegalOperations)) 7315 return SDValue(Res, 0); 7316 7317 // fold (zext (zext x)) -> (zext x) 7318 // fold (zext (aext x)) -> (zext x) 7319 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7320 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 7321 N0.getOperand(0)); 7322 7323 // fold (zext (truncate x)) -> (zext x) or 7324 // (zext (truncate x)) -> (truncate x) 7325 // This is valid when the truncated bits of x are already zero. 7326 // FIXME: We should extend this to work for vectors too. 7327 SDValue Op; 7328 KnownBits Known; 7329 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 7330 APInt TruncatedBits = 7331 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 7332 APInt(Op.getValueSizeInBits(), 0) : 7333 APInt::getBitsSet(Op.getValueSizeInBits(), 7334 N0.getValueSizeInBits(), 7335 std::min(Op.getValueSizeInBits(), 7336 VT.getSizeInBits())); 7337 if (TruncatedBits.isSubsetOf(Known.Zero)) 7338 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7339 } 7340 7341 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7342 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 7343 if (N0.getOpcode() == ISD::TRUNCATE) { 7344 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7345 SDNode *oye = N0.getOperand(0).getNode(); 7346 if (NarrowLoad.getNode() != N0.getNode()) { 7347 CombineTo(N0.getNode(), NarrowLoad); 7348 // CombineTo deleted the truncate, if needed, but not what's under it. 7349 AddToWorklist(oye); 7350 } 7351 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7352 } 7353 } 7354 7355 // fold (zext (truncate x)) -> (and x, mask) 7356 if (N0.getOpcode() == ISD::TRUNCATE) { 7357 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7358 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 7359 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7360 SDNode *oye = N0.getOperand(0).getNode(); 7361 if (NarrowLoad.getNode() != N0.getNode()) { 7362 CombineTo(N0.getNode(), NarrowLoad); 7363 // CombineTo deleted the truncate, if needed, but not what's under it. 7364 AddToWorklist(oye); 7365 } 7366 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7367 } 7368 7369 EVT SrcVT = N0.getOperand(0).getValueType(); 7370 EVT MinVT = N0.getValueType(); 7371 7372 // Try to mask before the extension to avoid having to generate a larger mask, 7373 // possibly over several sub-vectors. 7374 if (SrcVT.bitsLT(VT)) { 7375 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 7376 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 7377 SDValue Op = N0.getOperand(0); 7378 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7379 AddToWorklist(Op.getNode()); 7380 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7381 } 7382 } 7383 7384 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 7385 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7386 AddToWorklist(Op.getNode()); 7387 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7388 } 7389 } 7390 7391 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 7392 // if either of the casts is not free. 7393 if (N0.getOpcode() == ISD::AND && 7394 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7395 N0.getOperand(1).getOpcode() == ISD::Constant && 7396 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7397 N0.getValueType()) || 7398 !TLI.isZExtFree(N0.getValueType(), VT))) { 7399 SDValue X = N0.getOperand(0).getOperand(0); 7400 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 7401 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7402 Mask = Mask.zext(VT.getSizeInBits()); 7403 SDLoc DL(N); 7404 return DAG.getNode(ISD::AND, DL, VT, 7405 X, DAG.getConstant(Mask, DL, VT)); 7406 } 7407 7408 // fold (zext (load x)) -> (zext (truncate (zextload x))) 7409 // Only generate vector extloads when 1) they're legal, and 2) they are 7410 // deemed desirable by the target. 7411 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7412 ((!LegalOperations && !VT.isVector() && 7413 !cast<LoadSDNode>(N0)->isVolatile()) || 7414 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 7415 bool DoXform = true; 7416 SmallVector<SDNode*, 4> SetCCs; 7417 if (!N0.hasOneUse()) 7418 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 7419 if (VT.isVector()) 7420 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7421 if (DoXform) { 7422 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7423 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7424 LN0->getChain(), 7425 LN0->getBasePtr(), N0.getValueType(), 7426 LN0->getMemOperand()); 7427 7428 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7429 N0.getValueType(), ExtLoad); 7430 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7431 7432 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7433 ISD::ZERO_EXTEND); 7434 CombineTo(N, ExtLoad); 7435 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7436 } 7437 } 7438 7439 // fold (zext (load x)) to multiple smaller zextloads. 7440 // Only on illegal but splittable vectors. 7441 if (SDValue ExtLoad = CombineExtLoad(N)) 7442 return ExtLoad; 7443 7444 // fold (zext (and/or/xor (load x), cst)) -> 7445 // (and/or/xor (zextload x), (zext cst)) 7446 // Unless (and (load x) cst) will match as a zextload already and has 7447 // additional users. 7448 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7449 N0.getOpcode() == ISD::XOR) && 7450 isa<LoadSDNode>(N0.getOperand(0)) && 7451 N0.getOperand(1).getOpcode() == ISD::Constant && 7452 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 7453 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7454 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7455 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 7456 bool DoXform = true; 7457 SmallVector<SDNode*, 4> SetCCs; 7458 if (!N0.hasOneUse()) { 7459 if (N0.getOpcode() == ISD::AND) { 7460 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7461 auto NarrowLoad = false; 7462 EVT LoadResultTy = AndC->getValueType(0); 7463 EVT ExtVT, LoadedVT; 7464 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 7465 NarrowLoad)) 7466 DoXform = false; 7467 } 7468 if (DoXform) 7469 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 7470 ISD::ZERO_EXTEND, SetCCs, TLI); 7471 } 7472 if (DoXform) { 7473 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 7474 LN0->getChain(), LN0->getBasePtr(), 7475 LN0->getMemoryVT(), 7476 LN0->getMemOperand()); 7477 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7478 Mask = Mask.zext(VT.getSizeInBits()); 7479 SDLoc DL(N); 7480 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7481 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7482 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7483 SDLoc(N0.getOperand(0)), 7484 N0.getOperand(0).getValueType(), ExtLoad); 7485 CombineTo(N, And); 7486 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 7487 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 7488 ISD::ZERO_EXTEND); 7489 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7490 } 7491 } 7492 } 7493 7494 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7495 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7496 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7497 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7498 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7499 EVT MemVT = LN0->getMemoryVT(); 7500 if ((!LegalOperations && !LN0->isVolatile()) || 7501 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7502 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7503 LN0->getChain(), 7504 LN0->getBasePtr(), MemVT, 7505 LN0->getMemOperand()); 7506 CombineTo(N, ExtLoad); 7507 CombineTo(N0.getNode(), 7508 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 7509 ExtLoad), 7510 ExtLoad.getValue(1)); 7511 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7512 } 7513 } 7514 7515 if (N0.getOpcode() == ISD::SETCC) { 7516 // Only do this before legalize for now. 7517 if (!LegalOperations && VT.isVector() && 7518 N0.getValueType().getVectorElementType() == MVT::i1) { 7519 EVT N00VT = N0.getOperand(0).getValueType(); 7520 if (getSetCCResultType(N00VT) == N0.getValueType()) 7521 return SDValue(); 7522 7523 // We know that the # elements of the results is the same as the # 7524 // elements of the compare (and the # elements of the compare result for 7525 // that matter). Check to see that they are the same size. If so, we know 7526 // that the element size of the sext'd result matches the element size of 7527 // the compare operands. 7528 SDLoc DL(N); 7529 SDValue VecOnes = DAG.getConstant(1, DL, VT); 7530 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 7531 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 7532 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 7533 N0.getOperand(1), N0.getOperand(2)); 7534 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 7535 } 7536 7537 // If the desired elements are smaller or larger than the source 7538 // elements we can use a matching integer vector type and then 7539 // truncate/sign extend. 7540 EVT MatchingElementType = EVT::getIntegerVT( 7541 *DAG.getContext(), N00VT.getScalarSizeInBits()); 7542 EVT MatchingVectorType = EVT::getVectorVT( 7543 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 7544 SDValue VsetCC = 7545 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 7546 N0.getOperand(1), N0.getOperand(2)); 7547 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 7548 VecOnes); 7549 } 7550 7551 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7552 SDLoc DL(N); 7553 if (SDValue SCC = SimplifySelectCC( 7554 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7555 DAG.getConstant(0, DL, VT), 7556 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7557 return SCC; 7558 } 7559 7560 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 7561 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 7562 isa<ConstantSDNode>(N0.getOperand(1)) && 7563 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 7564 N0.hasOneUse()) { 7565 SDValue ShAmt = N0.getOperand(1); 7566 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 7567 if (N0.getOpcode() == ISD::SHL) { 7568 SDValue InnerZExt = N0.getOperand(0); 7569 // If the original shl may be shifting out bits, do not perform this 7570 // transformation. 7571 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 7572 InnerZExt.getOperand(0).getValueSizeInBits(); 7573 if (ShAmtVal > KnownZeroBits) 7574 return SDValue(); 7575 } 7576 7577 SDLoc DL(N); 7578 7579 // Ensure that the shift amount is wide enough for the shifted value. 7580 if (VT.getSizeInBits() >= 256) 7581 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 7582 7583 return DAG.getNode(N0.getOpcode(), DL, VT, 7584 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 7585 ShAmt); 7586 } 7587 7588 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7589 return NewVSel; 7590 7591 return SDValue(); 7592 } 7593 7594 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 7595 SDValue N0 = N->getOperand(0); 7596 EVT VT = N->getValueType(0); 7597 7598 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7599 LegalOperations)) 7600 return SDValue(Res, 0); 7601 7602 // fold (aext (aext x)) -> (aext x) 7603 // fold (aext (zext x)) -> (zext x) 7604 // fold (aext (sext x)) -> (sext x) 7605 if (N0.getOpcode() == ISD::ANY_EXTEND || 7606 N0.getOpcode() == ISD::ZERO_EXTEND || 7607 N0.getOpcode() == ISD::SIGN_EXTEND) 7608 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7609 7610 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 7611 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 7612 if (N0.getOpcode() == ISD::TRUNCATE) { 7613 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7614 SDNode *oye = N0.getOperand(0).getNode(); 7615 if (NarrowLoad.getNode() != N0.getNode()) { 7616 CombineTo(N0.getNode(), NarrowLoad); 7617 // CombineTo deleted the truncate, if needed, but not what's under it. 7618 AddToWorklist(oye); 7619 } 7620 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7621 } 7622 } 7623 7624 // fold (aext (truncate x)) 7625 if (N0.getOpcode() == ISD::TRUNCATE) 7626 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 7627 7628 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 7629 // if the trunc is not free. 7630 if (N0.getOpcode() == ISD::AND && 7631 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7632 N0.getOperand(1).getOpcode() == ISD::Constant && 7633 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7634 N0.getValueType())) { 7635 SDLoc DL(N); 7636 SDValue X = N0.getOperand(0).getOperand(0); 7637 X = DAG.getAnyExtOrTrunc(X, DL, VT); 7638 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7639 Mask = Mask.zext(VT.getSizeInBits()); 7640 return DAG.getNode(ISD::AND, DL, VT, 7641 X, DAG.getConstant(Mask, DL, VT)); 7642 } 7643 7644 // fold (aext (load x)) -> (aext (truncate (extload x))) 7645 // None of the supported targets knows how to perform load and any_ext 7646 // on vectors in one instruction. We only perform this transformation on 7647 // scalars. 7648 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 7649 ISD::isUNINDEXEDLoad(N0.getNode()) && 7650 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 7651 bool DoXform = true; 7652 SmallVector<SDNode*, 4> SetCCs; 7653 if (!N0.hasOneUse()) 7654 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 7655 if (DoXform) { 7656 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7657 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7658 LN0->getChain(), 7659 LN0->getBasePtr(), N0.getValueType(), 7660 LN0->getMemOperand()); 7661 CombineTo(N, ExtLoad); 7662 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7663 N0.getValueType(), ExtLoad); 7664 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7665 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7666 ISD::ANY_EXTEND); 7667 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7668 } 7669 } 7670 7671 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 7672 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 7673 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 7674 if (N0.getOpcode() == ISD::LOAD && 7675 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7676 N0.hasOneUse()) { 7677 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7678 ISD::LoadExtType ExtType = LN0->getExtensionType(); 7679 EVT MemVT = LN0->getMemoryVT(); 7680 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 7681 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 7682 VT, LN0->getChain(), LN0->getBasePtr(), 7683 MemVT, LN0->getMemOperand()); 7684 CombineTo(N, ExtLoad); 7685 CombineTo(N0.getNode(), 7686 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7687 N0.getValueType(), ExtLoad), 7688 ExtLoad.getValue(1)); 7689 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7690 } 7691 } 7692 7693 if (N0.getOpcode() == ISD::SETCC) { 7694 // For vectors: 7695 // aext(setcc) -> vsetcc 7696 // aext(setcc) -> truncate(vsetcc) 7697 // aext(setcc) -> aext(vsetcc) 7698 // Only do this before legalize for now. 7699 if (VT.isVector() && !LegalOperations) { 7700 EVT N0VT = N0.getOperand(0).getValueType(); 7701 // We know that the # elements of the results is the same as the 7702 // # elements of the compare (and the # elements of the compare result 7703 // for that matter). Check to see that they are the same size. If so, 7704 // we know that the element size of the sext'd result matches the 7705 // element size of the compare operands. 7706 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 7707 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 7708 N0.getOperand(1), 7709 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7710 // If the desired elements are smaller or larger than the source 7711 // elements we can use a matching integer vector type and then 7712 // truncate/any extend 7713 else { 7714 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 7715 SDValue VsetCC = 7716 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 7717 N0.getOperand(1), 7718 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7719 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 7720 } 7721 } 7722 7723 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7724 SDLoc DL(N); 7725 if (SDValue SCC = SimplifySelectCC( 7726 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7727 DAG.getConstant(0, DL, VT), 7728 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7729 return SCC; 7730 } 7731 7732 return SDValue(); 7733 } 7734 7735 SDValue DAGCombiner::visitAssertZext(SDNode *N) { 7736 SDValue N0 = N->getOperand(0); 7737 SDValue N1 = N->getOperand(1); 7738 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7739 7740 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt) 7741 if (N0.getOpcode() == ISD::AssertZext && 7742 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 7743 return N0; 7744 7745 return SDValue(); 7746 } 7747 7748 /// See if the specified operand can be simplified with the knowledge that only 7749 /// the bits specified by Mask are used. If so, return the simpler operand, 7750 /// otherwise return a null SDValue. 7751 /// 7752 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can 7753 /// simplify nodes with multiple uses more aggressively.) 7754 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 7755 switch (V.getOpcode()) { 7756 default: break; 7757 case ISD::Constant: { 7758 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 7759 assert(CV && "Const value should be ConstSDNode."); 7760 const APInt &CVal = CV->getAPIntValue(); 7761 APInt NewVal = CVal & Mask; 7762 if (NewVal != CVal) 7763 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 7764 break; 7765 } 7766 case ISD::OR: 7767 case ISD::XOR: 7768 // If the LHS or RHS don't contribute bits to the or, drop them. 7769 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 7770 return V.getOperand(1); 7771 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 7772 return V.getOperand(0); 7773 break; 7774 case ISD::SRL: 7775 // Only look at single-use SRLs. 7776 if (!V.getNode()->hasOneUse()) 7777 break; 7778 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 7779 // See if we can recursively simplify the LHS. 7780 unsigned Amt = RHSC->getZExtValue(); 7781 7782 // Watch out for shift count overflow though. 7783 if (Amt >= Mask.getBitWidth()) break; 7784 APInt NewMask = Mask << Amt; 7785 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 7786 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 7787 SimplifyLHS, V.getOperand(1)); 7788 } 7789 break; 7790 case ISD::AND: { 7791 // X & -1 -> X (ignoring bits which aren't demanded). 7792 ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1)); 7793 if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask) 7794 return V.getOperand(0); 7795 break; 7796 } 7797 } 7798 return SDValue(); 7799 } 7800 7801 /// If the result of a wider load is shifted to right of N bits and then 7802 /// truncated to a narrower type and where N is a multiple of number of bits of 7803 /// the narrower type, transform it to a narrower load from address + N / num of 7804 /// bits of new type. If the result is to be extended, also fold the extension 7805 /// to form a extending load. 7806 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 7807 unsigned Opc = N->getOpcode(); 7808 7809 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 7810 SDValue N0 = N->getOperand(0); 7811 EVT VT = N->getValueType(0); 7812 EVT ExtVT = VT; 7813 7814 // This transformation isn't valid for vector loads. 7815 if (VT.isVector()) 7816 return SDValue(); 7817 7818 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 7819 // extended to VT. 7820 if (Opc == ISD::SIGN_EXTEND_INREG) { 7821 ExtType = ISD::SEXTLOAD; 7822 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7823 } else if (Opc == ISD::SRL) { 7824 // Another special-case: SRL is basically zero-extending a narrower value. 7825 ExtType = ISD::ZEXTLOAD; 7826 N0 = SDValue(N, 0); 7827 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7828 if (!N01) return SDValue(); 7829 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 7830 VT.getSizeInBits() - N01->getZExtValue()); 7831 } 7832 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 7833 return SDValue(); 7834 7835 unsigned EVTBits = ExtVT.getSizeInBits(); 7836 7837 // Do not generate loads of non-round integer types since these can 7838 // be expensive (and would be wrong if the type is not byte sized). 7839 if (!ExtVT.isRound()) 7840 return SDValue(); 7841 7842 unsigned ShAmt = 0; 7843 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 7844 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7845 ShAmt = N01->getZExtValue(); 7846 // Is the shift amount a multiple of size of VT? 7847 if ((ShAmt & (EVTBits-1)) == 0) { 7848 N0 = N0.getOperand(0); 7849 // Is the load width a multiple of size of VT? 7850 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 7851 return SDValue(); 7852 } 7853 7854 // At this point, we must have a load or else we can't do the transform. 7855 if (!isa<LoadSDNode>(N0)) return SDValue(); 7856 7857 // Because a SRL must be assumed to *need* to zero-extend the high bits 7858 // (as opposed to anyext the high bits), we can't combine the zextload 7859 // lowering of SRL and an sextload. 7860 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 7861 return SDValue(); 7862 7863 // If the shift amount is larger than the input type then we're not 7864 // accessing any of the loaded bytes. If the load was a zextload/extload 7865 // then the result of the shift+trunc is zero/undef (handled elsewhere). 7866 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 7867 return SDValue(); 7868 } 7869 } 7870 7871 // If the load is shifted left (and the result isn't shifted back right), 7872 // we can fold the truncate through the shift. 7873 unsigned ShLeftAmt = 0; 7874 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7875 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 7876 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7877 ShLeftAmt = N01->getZExtValue(); 7878 N0 = N0.getOperand(0); 7879 } 7880 } 7881 7882 // If we haven't found a load, we can't narrow it. Don't transform one with 7883 // multiple uses, this would require adding a new load. 7884 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 7885 return SDValue(); 7886 7887 // Don't change the width of a volatile load. 7888 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7889 if (LN0->isVolatile()) 7890 return SDValue(); 7891 7892 // Verify that we are actually reducing a load width here. 7893 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 7894 return SDValue(); 7895 7896 // For the transform to be legal, the load must produce only two values 7897 // (the value loaded and the chain). Don't transform a pre-increment 7898 // load, for example, which produces an extra value. Otherwise the 7899 // transformation is not equivalent, and the downstream logic to replace 7900 // uses gets things wrong. 7901 if (LN0->getNumValues() > 2) 7902 return SDValue(); 7903 7904 // If the load that we're shrinking is an extload and we're not just 7905 // discarding the extension we can't simply shrink the load. Bail. 7906 // TODO: It would be possible to merge the extensions in some cases. 7907 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 7908 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 7909 return SDValue(); 7910 7911 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 7912 return SDValue(); 7913 7914 EVT PtrType = N0.getOperand(1).getValueType(); 7915 7916 if (PtrType == MVT::Untyped || PtrType.isExtended()) 7917 // It's not possible to generate a constant of extended or untyped type. 7918 return SDValue(); 7919 7920 // For big endian targets, we need to adjust the offset to the pointer to 7921 // load the correct bytes. 7922 if (DAG.getDataLayout().isBigEndian()) { 7923 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 7924 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 7925 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 7926 } 7927 7928 uint64_t PtrOff = ShAmt / 8; 7929 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 7930 SDLoc DL(LN0); 7931 // The original load itself didn't wrap, so an offset within it doesn't. 7932 SDNodeFlags Flags; 7933 Flags.setNoUnsignedWrap(true); 7934 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 7935 PtrType, LN0->getBasePtr(), 7936 DAG.getConstant(PtrOff, DL, PtrType), 7937 Flags); 7938 AddToWorklist(NewPtr.getNode()); 7939 7940 SDValue Load; 7941 if (ExtType == ISD::NON_EXTLOAD) 7942 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 7943 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 7944 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7945 else 7946 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 7947 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 7948 NewAlign, LN0->getMemOperand()->getFlags(), 7949 LN0->getAAInfo()); 7950 7951 // Replace the old load's chain with the new load's chain. 7952 WorklistRemover DeadNodes(*this); 7953 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7954 7955 // Shift the result left, if we've swallowed a left shift. 7956 SDValue Result = Load; 7957 if (ShLeftAmt != 0) { 7958 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 7959 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 7960 ShImmTy = VT; 7961 // If the shift amount is as large as the result size (but, presumably, 7962 // no larger than the source) then the useful bits of the result are 7963 // zero; we can't simply return the shortened shift, because the result 7964 // of that operation is undefined. 7965 SDLoc DL(N0); 7966 if (ShLeftAmt >= VT.getSizeInBits()) 7967 Result = DAG.getConstant(0, DL, VT); 7968 else 7969 Result = DAG.getNode(ISD::SHL, DL, VT, 7970 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 7971 } 7972 7973 // Return the new loaded value. 7974 return Result; 7975 } 7976 7977 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 7978 SDValue N0 = N->getOperand(0); 7979 SDValue N1 = N->getOperand(1); 7980 EVT VT = N->getValueType(0); 7981 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7982 unsigned VTBits = VT.getScalarSizeInBits(); 7983 unsigned EVTBits = EVT.getScalarSizeInBits(); 7984 7985 if (N0.isUndef()) 7986 return DAG.getUNDEF(VT); 7987 7988 // fold (sext_in_reg c1) -> c1 7989 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7990 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 7991 7992 // If the input is already sign extended, just drop the extension. 7993 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 7994 return N0; 7995 7996 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 7997 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 7998 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 7999 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8000 N0.getOperand(0), N1); 8001 8002 // fold (sext_in_reg (sext x)) -> (sext x) 8003 // fold (sext_in_reg (aext x)) -> (sext x) 8004 // if x is small enough. 8005 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 8006 SDValue N00 = N0.getOperand(0); 8007 if (N00.getScalarValueSizeInBits() <= EVTBits && 8008 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8009 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8010 } 8011 8012 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x) 8013 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 8014 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 8015 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 8016 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 8017 if (!LegalOperations || 8018 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 8019 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 8020 } 8021 8022 // fold (sext_in_reg (zext x)) -> (sext x) 8023 // iff we are extending the source sign bit. 8024 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 8025 SDValue N00 = N0.getOperand(0); 8026 if (N00.getScalarValueSizeInBits() == EVTBits && 8027 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8028 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8029 } 8030 8031 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 8032 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 8033 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 8034 8035 // fold operands of sext_in_reg based on knowledge that the top bits are not 8036 // demanded. 8037 if (SimplifyDemandedBits(SDValue(N, 0))) 8038 return SDValue(N, 0); 8039 8040 // fold (sext_in_reg (load x)) -> (smaller sextload x) 8041 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 8042 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 8043 return NarrowLoad; 8044 8045 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 8046 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 8047 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 8048 if (N0.getOpcode() == ISD::SRL) { 8049 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 8050 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 8051 // We can turn this into an SRA iff the input to the SRL is already sign 8052 // extended enough. 8053 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 8054 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 8055 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 8056 N0.getOperand(0), N0.getOperand(1)); 8057 } 8058 } 8059 8060 // fold (sext_inreg (extload x)) -> (sextload x) 8061 if (ISD::isEXTLoad(N0.getNode()) && 8062 ISD::isUNINDEXEDLoad(N0.getNode()) && 8063 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8064 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8065 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8066 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8067 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8068 LN0->getChain(), 8069 LN0->getBasePtr(), EVT, 8070 LN0->getMemOperand()); 8071 CombineTo(N, ExtLoad); 8072 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8073 AddToWorklist(ExtLoad.getNode()); 8074 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8075 } 8076 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 8077 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 8078 N0.hasOneUse() && 8079 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8080 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8081 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8082 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8083 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8084 LN0->getChain(), 8085 LN0->getBasePtr(), EVT, 8086 LN0->getMemOperand()); 8087 CombineTo(N, ExtLoad); 8088 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8089 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8090 } 8091 8092 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 8093 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 8094 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 8095 N0.getOperand(1), false)) 8096 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8097 BSwap, N1); 8098 } 8099 8100 return SDValue(); 8101 } 8102 8103 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 8104 SDValue N0 = N->getOperand(0); 8105 EVT VT = N->getValueType(0); 8106 8107 if (N0.isUndef()) 8108 return DAG.getUNDEF(VT); 8109 8110 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8111 LegalOperations)) 8112 return SDValue(Res, 0); 8113 8114 return SDValue(); 8115 } 8116 8117 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 8118 SDValue N0 = N->getOperand(0); 8119 EVT VT = N->getValueType(0); 8120 8121 if (N0.isUndef()) 8122 return DAG.getUNDEF(VT); 8123 8124 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8125 LegalOperations)) 8126 return SDValue(Res, 0); 8127 8128 return SDValue(); 8129 } 8130 8131 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 8132 SDValue N0 = N->getOperand(0); 8133 EVT VT = N->getValueType(0); 8134 bool isLE = DAG.getDataLayout().isLittleEndian(); 8135 8136 // noop truncate 8137 if (N0.getValueType() == N->getValueType(0)) 8138 return N0; 8139 // fold (truncate c1) -> c1 8140 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8141 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 8142 // fold (truncate (truncate x)) -> (truncate x) 8143 if (N0.getOpcode() == ISD::TRUNCATE) 8144 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8145 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 8146 if (N0.getOpcode() == ISD::ZERO_EXTEND || 8147 N0.getOpcode() == ISD::SIGN_EXTEND || 8148 N0.getOpcode() == ISD::ANY_EXTEND) { 8149 // if the source is smaller than the dest, we still need an extend. 8150 if (N0.getOperand(0).getValueType().bitsLT(VT)) 8151 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8152 // if the source is larger than the dest, than we just need the truncate. 8153 if (N0.getOperand(0).getValueType().bitsGT(VT)) 8154 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8155 // if the source and dest are the same type, we can drop both the extend 8156 // and the truncate. 8157 return N0.getOperand(0); 8158 } 8159 8160 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 8161 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 8162 return SDValue(); 8163 8164 // Fold extract-and-trunc into a narrow extract. For example: 8165 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 8166 // i32 y = TRUNCATE(i64 x) 8167 // -- becomes -- 8168 // v16i8 b = BITCAST (v2i64 val) 8169 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 8170 // 8171 // Note: We only run this optimization after type legalization (which often 8172 // creates this pattern) and before operation legalization after which 8173 // we need to be more careful about the vector instructions that we generate. 8174 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 8175 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 8176 8177 EVT VecTy = N0.getOperand(0).getValueType(); 8178 EVT ExTy = N0.getValueType(); 8179 EVT TrTy = N->getValueType(0); 8180 8181 unsigned NumElem = VecTy.getVectorNumElements(); 8182 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 8183 8184 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 8185 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 8186 8187 SDValue EltNo = N0->getOperand(1); 8188 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 8189 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8190 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8191 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 8192 8193 SDLoc DL(N); 8194 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 8195 DAG.getBitcast(NVT, N0.getOperand(0)), 8196 DAG.getConstant(Index, DL, IndexTy)); 8197 } 8198 } 8199 8200 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 8201 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 8202 EVT SrcVT = N0.getValueType(); 8203 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 8204 TLI.isTruncateFree(SrcVT, VT)) { 8205 SDLoc SL(N0); 8206 SDValue Cond = N0.getOperand(0); 8207 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8208 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 8209 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 8210 } 8211 } 8212 8213 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 8214 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8215 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 8216 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 8217 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 8218 uint64_t Amt = CAmt->getZExtValue(); 8219 unsigned Size = VT.getScalarSizeInBits(); 8220 8221 if (Amt < Size) { 8222 SDLoc SL(N); 8223 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 8224 8225 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8226 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 8227 DAG.getConstant(Amt, SL, AmtVT)); 8228 } 8229 } 8230 } 8231 8232 // Fold a series of buildvector, bitcast, and truncate if possible. 8233 // For example fold 8234 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 8235 // (2xi32 (buildvector x, y)). 8236 if (Level == AfterLegalizeVectorOps && VT.isVector() && 8237 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 8238 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 8239 N0.getOperand(0).hasOneUse()) { 8240 8241 SDValue BuildVect = N0.getOperand(0); 8242 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 8243 EVT TruncVecEltTy = VT.getVectorElementType(); 8244 8245 // Check that the element types match. 8246 if (BuildVectEltTy == TruncVecEltTy) { 8247 // Now we only need to compute the offset of the truncated elements. 8248 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 8249 unsigned TruncVecNumElts = VT.getVectorNumElements(); 8250 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 8251 8252 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 8253 "Invalid number of elements"); 8254 8255 SmallVector<SDValue, 8> Opnds; 8256 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 8257 Opnds.push_back(BuildVect.getOperand(i)); 8258 8259 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 8260 } 8261 } 8262 8263 // See if we can simplify the input to this truncate through knowledge that 8264 // only the low bits are being used. 8265 // For example "trunc (or (shl x, 8), y)" // -> trunc y 8266 // Currently we only perform this optimization on scalars because vectors 8267 // may have different active low bits. 8268 if (!VT.isVector()) { 8269 if (SDValue Shorter = 8270 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 8271 VT.getSizeInBits()))) 8272 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 8273 } 8274 8275 // fold (truncate (load x)) -> (smaller load x) 8276 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 8277 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 8278 if (SDValue Reduced = ReduceLoadWidth(N)) 8279 return Reduced; 8280 8281 // Handle the case where the load remains an extending load even 8282 // after truncation. 8283 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 8284 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8285 if (!LN0->isVolatile() && 8286 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 8287 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 8288 VT, LN0->getChain(), LN0->getBasePtr(), 8289 LN0->getMemoryVT(), 8290 LN0->getMemOperand()); 8291 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 8292 return NewLoad; 8293 } 8294 } 8295 } 8296 8297 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 8298 // where ... are all 'undef'. 8299 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 8300 SmallVector<EVT, 8> VTs; 8301 SDValue V; 8302 unsigned Idx = 0; 8303 unsigned NumDefs = 0; 8304 8305 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 8306 SDValue X = N0.getOperand(i); 8307 if (!X.isUndef()) { 8308 V = X; 8309 Idx = i; 8310 NumDefs++; 8311 } 8312 // Stop if more than one members are non-undef. 8313 if (NumDefs > 1) 8314 break; 8315 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 8316 VT.getVectorElementType(), 8317 X.getValueType().getVectorNumElements())); 8318 } 8319 8320 if (NumDefs == 0) 8321 return DAG.getUNDEF(VT); 8322 8323 if (NumDefs == 1) { 8324 assert(V.getNode() && "The single defined operand is empty!"); 8325 SmallVector<SDValue, 8> Opnds; 8326 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 8327 if (i != Idx) { 8328 Opnds.push_back(DAG.getUNDEF(VTs[i])); 8329 continue; 8330 } 8331 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 8332 AddToWorklist(NV.getNode()); 8333 Opnds.push_back(NV); 8334 } 8335 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 8336 } 8337 } 8338 8339 // Fold truncate of a bitcast of a vector to an extract of the low vector 8340 // element. 8341 // 8342 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 8343 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 8344 SDValue VecSrc = N0.getOperand(0); 8345 EVT SrcVT = VecSrc.getValueType(); 8346 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 8347 (!LegalOperations || 8348 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 8349 SDLoc SL(N); 8350 8351 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 8352 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 8353 VecSrc, DAG.getConstant(0, SL, IdxVT)); 8354 } 8355 } 8356 8357 // Simplify the operands using demanded-bits information. 8358 if (!VT.isVector() && 8359 SimplifyDemandedBits(SDValue(N, 0))) 8360 return SDValue(N, 0); 8361 8362 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 8363 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 8364 // When the adde's carry is not used. 8365 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 8366 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 8367 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 8368 SDLoc SL(N); 8369 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8370 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8371 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 8372 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 8373 } 8374 8375 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8376 return NewVSel; 8377 8378 return SDValue(); 8379 } 8380 8381 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 8382 SDValue Elt = N->getOperand(i); 8383 if (Elt.getOpcode() != ISD::MERGE_VALUES) 8384 return Elt.getNode(); 8385 return Elt.getOperand(Elt.getResNo()).getNode(); 8386 } 8387 8388 /// build_pair (load, load) -> load 8389 /// if load locations are consecutive. 8390 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 8391 assert(N->getOpcode() == ISD::BUILD_PAIR); 8392 8393 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 8394 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 8395 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 8396 LD1->getAddressSpace() != LD2->getAddressSpace()) 8397 return SDValue(); 8398 EVT LD1VT = LD1->getValueType(0); 8399 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 8400 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 8401 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 8402 unsigned Align = LD1->getAlignment(); 8403 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 8404 VT.getTypeForEVT(*DAG.getContext())); 8405 8406 if (NewAlign <= Align && 8407 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 8408 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 8409 LD1->getPointerInfo(), Align); 8410 } 8411 8412 return SDValue(); 8413 } 8414 8415 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 8416 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 8417 // and Lo parts; on big-endian machines it doesn't. 8418 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 8419 } 8420 8421 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 8422 const TargetLowering &TLI) { 8423 // If this is not a bitcast to an FP type or if the target doesn't have 8424 // IEEE754-compliant FP logic, we're done. 8425 EVT VT = N->getValueType(0); 8426 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 8427 return SDValue(); 8428 8429 // TODO: Use splat values for the constant-checking below and remove this 8430 // restriction. 8431 SDValue N0 = N->getOperand(0); 8432 EVT SourceVT = N0.getValueType(); 8433 if (SourceVT.isVector()) 8434 return SDValue(); 8435 8436 unsigned FPOpcode; 8437 APInt SignMask; 8438 switch (N0.getOpcode()) { 8439 case ISD::AND: 8440 FPOpcode = ISD::FABS; 8441 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits()); 8442 break; 8443 case ISD::XOR: 8444 FPOpcode = ISD::FNEG; 8445 SignMask = APInt::getSignMask(SourceVT.getSizeInBits()); 8446 break; 8447 // TODO: ISD::OR --> ISD::FNABS? 8448 default: 8449 return SDValue(); 8450 } 8451 8452 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8453 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8454 SDValue LogicOp0 = N0.getOperand(0); 8455 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8456 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8457 LogicOp0.getOpcode() == ISD::BITCAST && 8458 LogicOp0->getOperand(0).getValueType() == VT) 8459 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8460 8461 return SDValue(); 8462 } 8463 8464 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8465 SDValue N0 = N->getOperand(0); 8466 EVT VT = N->getValueType(0); 8467 8468 if (N0.isUndef()) 8469 return DAG.getUNDEF(VT); 8470 8471 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8472 // Only do this before legalize, since afterward the target may be depending 8473 // on the bitconvert. 8474 // First check to see if this is all constant. 8475 if (!LegalTypes && 8476 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8477 VT.isVector()) { 8478 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8479 8480 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8481 assert(!DestEltVT.isVector() && 8482 "Element type of vector ValueType must not be vector!"); 8483 if (isSimple) 8484 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8485 } 8486 8487 // If the input is a constant, let getNode fold it. 8488 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8489 // If we can't allow illegal operations, we need to check that this is just 8490 // a fp -> int or int -> conversion and that the resulting operation will 8491 // be legal. 8492 if (!LegalOperations || 8493 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8494 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8495 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8496 TLI.isOperationLegal(ISD::Constant, VT))) 8497 return DAG.getBitcast(VT, N0); 8498 } 8499 8500 // (conv (conv x, t1), t2) -> (conv x, t2) 8501 if (N0.getOpcode() == ISD::BITCAST) 8502 return DAG.getBitcast(VT, N0.getOperand(0)); 8503 8504 // fold (conv (load x)) -> (load (conv*)x) 8505 // If the resultant load doesn't need a higher alignment than the original! 8506 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8507 // Do not change the width of a volatile load. 8508 !cast<LoadSDNode>(N0)->isVolatile() && 8509 // Do not remove the cast if the types differ in endian layout. 8510 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8511 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8512 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8513 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8514 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8515 unsigned OrigAlign = LN0->getAlignment(); 8516 8517 bool Fast = false; 8518 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 8519 LN0->getAddressSpace(), OrigAlign, &Fast) && 8520 Fast) { 8521 SDValue Load = 8522 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8523 LN0->getPointerInfo(), OrigAlign, 8524 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8525 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8526 return Load; 8527 } 8528 } 8529 8530 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 8531 return V; 8532 8533 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8534 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8535 // 8536 // For ppc_fp128: 8537 // fold (bitcast (fneg x)) -> 8538 // flipbit = signbit 8539 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8540 // 8541 // fold (bitcast (fabs x)) -> 8542 // flipbit = (and (extract_element (bitcast x), 0), signbit) 8543 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8544 // This often reduces constant pool loads. 8545 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 8546 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 8547 N0.getNode()->hasOneUse() && VT.isInteger() && 8548 !VT.isVector() && !N0.getValueType().isVector()) { 8549 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 8550 AddToWorklist(NewConv.getNode()); 8551 8552 SDLoc DL(N); 8553 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8554 assert(VT.getSizeInBits() == 128); 8555 SDValue SignBit = DAG.getConstant( 8556 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 8557 SDValue FlipBit; 8558 if (N0.getOpcode() == ISD::FNEG) { 8559 FlipBit = SignBit; 8560 AddToWorklist(FlipBit.getNode()); 8561 } else { 8562 assert(N0.getOpcode() == ISD::FABS); 8563 SDValue Hi = 8564 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 8565 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8566 SDLoc(NewConv))); 8567 AddToWorklist(Hi.getNode()); 8568 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 8569 AddToWorklist(FlipBit.getNode()); 8570 } 8571 SDValue FlipBits = 8572 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8573 AddToWorklist(FlipBits.getNode()); 8574 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 8575 } 8576 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8577 if (N0.getOpcode() == ISD::FNEG) 8578 return DAG.getNode(ISD::XOR, DL, VT, 8579 NewConv, DAG.getConstant(SignBit, DL, VT)); 8580 assert(N0.getOpcode() == ISD::FABS); 8581 return DAG.getNode(ISD::AND, DL, VT, 8582 NewConv, DAG.getConstant(~SignBit, DL, VT)); 8583 } 8584 8585 // fold (bitconvert (fcopysign cst, x)) -> 8586 // (or (and (bitconvert x), sign), (and cst, (not sign))) 8587 // Note that we don't handle (copysign x, cst) because this can always be 8588 // folded to an fneg or fabs. 8589 // 8590 // For ppc_fp128: 8591 // fold (bitcast (fcopysign cst, x)) -> 8592 // flipbit = (and (extract_element 8593 // (xor (bitcast cst), (bitcast x)), 0), 8594 // signbit) 8595 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 8596 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 8597 isa<ConstantFPSDNode>(N0.getOperand(0)) && 8598 VT.isInteger() && !VT.isVector()) { 8599 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 8600 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 8601 if (isTypeLegal(IntXVT)) { 8602 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 8603 AddToWorklist(X.getNode()); 8604 8605 // If X has a different width than the result/lhs, sext it or truncate it. 8606 unsigned VTWidth = VT.getSizeInBits(); 8607 if (OrigXWidth < VTWidth) { 8608 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 8609 AddToWorklist(X.getNode()); 8610 } else if (OrigXWidth > VTWidth) { 8611 // To get the sign bit in the right place, we have to shift it right 8612 // before truncating. 8613 SDLoc DL(X); 8614 X = DAG.getNode(ISD::SRL, DL, 8615 X.getValueType(), X, 8616 DAG.getConstant(OrigXWidth-VTWidth, DL, 8617 X.getValueType())); 8618 AddToWorklist(X.getNode()); 8619 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 8620 AddToWorklist(X.getNode()); 8621 } 8622 8623 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8624 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 8625 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8626 AddToWorklist(Cst.getNode()); 8627 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 8628 AddToWorklist(X.getNode()); 8629 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 8630 AddToWorklist(XorResult.getNode()); 8631 SDValue XorResult64 = DAG.getNode( 8632 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 8633 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8634 SDLoc(XorResult))); 8635 AddToWorklist(XorResult64.getNode()); 8636 SDValue FlipBit = 8637 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 8638 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 8639 AddToWorklist(FlipBit.getNode()); 8640 SDValue FlipBits = 8641 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8642 AddToWorklist(FlipBits.getNode()); 8643 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 8644 } 8645 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8646 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 8647 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 8648 AddToWorklist(X.getNode()); 8649 8650 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8651 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 8652 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 8653 AddToWorklist(Cst.getNode()); 8654 8655 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 8656 } 8657 } 8658 8659 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 8660 if (N0.getOpcode() == ISD::BUILD_PAIR) 8661 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 8662 return CombineLD; 8663 8664 // Remove double bitcasts from shuffles - this is often a legacy of 8665 // XformToShuffleWithZero being used to combine bitmaskings (of 8666 // float vectors bitcast to integer vectors) into shuffles. 8667 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 8668 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 8669 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 8670 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 8671 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 8672 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 8673 8674 // If operands are a bitcast, peek through if it casts the original VT. 8675 // If operands are a constant, just bitcast back to original VT. 8676 auto PeekThroughBitcast = [&](SDValue Op) { 8677 if (Op.getOpcode() == ISD::BITCAST && 8678 Op.getOperand(0).getValueType() == VT) 8679 return SDValue(Op.getOperand(0)); 8680 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 8681 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 8682 return DAG.getBitcast(VT, Op); 8683 return SDValue(); 8684 }; 8685 8686 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 8687 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 8688 if (!(SV0 && SV1)) 8689 return SDValue(); 8690 8691 int MaskScale = 8692 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 8693 SmallVector<int, 8> NewMask; 8694 for (int M : SVN->getMask()) 8695 for (int i = 0; i != MaskScale; ++i) 8696 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 8697 8698 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8699 if (!LegalMask) { 8700 std::swap(SV0, SV1); 8701 ShuffleVectorSDNode::commuteMask(NewMask); 8702 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8703 } 8704 8705 if (LegalMask) 8706 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 8707 } 8708 8709 return SDValue(); 8710 } 8711 8712 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 8713 EVT VT = N->getValueType(0); 8714 return CombineConsecutiveLoads(N, VT); 8715 } 8716 8717 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 8718 /// operands. DstEltVT indicates the destination element value type. 8719 SDValue DAGCombiner:: 8720 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 8721 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 8722 8723 // If this is already the right type, we're done. 8724 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 8725 8726 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 8727 unsigned DstBitSize = DstEltVT.getSizeInBits(); 8728 8729 // If this is a conversion of N elements of one type to N elements of another 8730 // type, convert each element. This handles FP<->INT cases. 8731 if (SrcBitSize == DstBitSize) { 8732 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8733 BV->getValueType(0).getVectorNumElements()); 8734 8735 // Due to the FP element handling below calling this routine recursively, 8736 // we can end up with a scalar-to-vector node here. 8737 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 8738 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 8739 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 8740 8741 SmallVector<SDValue, 8> Ops; 8742 for (SDValue Op : BV->op_values()) { 8743 // If the vector element type is not legal, the BUILD_VECTOR operands 8744 // are promoted and implicitly truncated. Make that explicit here. 8745 if (Op.getValueType() != SrcEltVT) 8746 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 8747 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 8748 AddToWorklist(Ops.back().getNode()); 8749 } 8750 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 8751 } 8752 8753 // Otherwise, we're growing or shrinking the elements. To avoid having to 8754 // handle annoying details of growing/shrinking FP values, we convert them to 8755 // int first. 8756 if (SrcEltVT.isFloatingPoint()) { 8757 // Convert the input float vector to a int vector where the elements are the 8758 // same sizes. 8759 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 8760 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 8761 SrcEltVT = IntVT; 8762 } 8763 8764 // Now we know the input is an integer vector. If the output is a FP type, 8765 // convert to integer first, then to FP of the right size. 8766 if (DstEltVT.isFloatingPoint()) { 8767 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 8768 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 8769 8770 // Next, convert to FP elements of the same size. 8771 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 8772 } 8773 8774 SDLoc DL(BV); 8775 8776 // Okay, we know the src/dst types are both integers of differing types. 8777 // Handling growing first. 8778 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 8779 if (SrcBitSize < DstBitSize) { 8780 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 8781 8782 SmallVector<SDValue, 8> Ops; 8783 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 8784 i += NumInputsPerOutput) { 8785 bool isLE = DAG.getDataLayout().isLittleEndian(); 8786 APInt NewBits = APInt(DstBitSize, 0); 8787 bool EltIsUndef = true; 8788 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 8789 // Shift the previously computed bits over. 8790 NewBits <<= SrcBitSize; 8791 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 8792 if (Op.isUndef()) continue; 8793 EltIsUndef = false; 8794 8795 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 8796 zextOrTrunc(SrcBitSize).zext(DstBitSize); 8797 } 8798 8799 if (EltIsUndef) 8800 Ops.push_back(DAG.getUNDEF(DstEltVT)); 8801 else 8802 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 8803 } 8804 8805 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 8806 return DAG.getBuildVector(VT, DL, Ops); 8807 } 8808 8809 // Finally, this must be the case where we are shrinking elements: each input 8810 // turns into multiple outputs. 8811 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 8812 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8813 NumOutputsPerInput*BV->getNumOperands()); 8814 SmallVector<SDValue, 8> Ops; 8815 8816 for (const SDValue &Op : BV->op_values()) { 8817 if (Op.isUndef()) { 8818 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 8819 continue; 8820 } 8821 8822 APInt OpVal = cast<ConstantSDNode>(Op)-> 8823 getAPIntValue().zextOrTrunc(SrcBitSize); 8824 8825 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 8826 APInt ThisVal = OpVal.trunc(DstBitSize); 8827 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 8828 OpVal.lshrInPlace(DstBitSize); 8829 } 8830 8831 // For big endian targets, swap the order of the pieces of each element. 8832 if (DAG.getDataLayout().isBigEndian()) 8833 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 8834 } 8835 8836 return DAG.getBuildVector(VT, DL, Ops); 8837 } 8838 8839 static bool isContractable(SDNode *N) { 8840 SDNodeFlags F = N->getFlags(); 8841 return F.hasAllowContract() || F.hasUnsafeAlgebra(); 8842 } 8843 8844 /// Try to perform FMA combining on a given FADD node. 8845 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 8846 SDValue N0 = N->getOperand(0); 8847 SDValue N1 = N->getOperand(1); 8848 EVT VT = N->getValueType(0); 8849 SDLoc SL(N); 8850 8851 const TargetOptions &Options = DAG.getTarget().Options; 8852 8853 // Floating-point multiply-add with intermediate rounding. 8854 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8855 8856 // Floating-point multiply-add without intermediate rounding. 8857 bool HasFMA = 8858 TLI.isFMAFasterThanFMulAndFAdd(VT) && 8859 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8860 8861 // No valid opcode, do not combine. 8862 if (!HasFMAD && !HasFMA) 8863 return SDValue(); 8864 8865 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 8866 Options.UnsafeFPMath || HasFMAD); 8867 // If the addition is not contractable, do not combine. 8868 if (!AllowFusionGlobally && !isContractable(N)) 8869 return SDValue(); 8870 8871 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8872 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8873 return SDValue(); 8874 8875 // Always prefer FMAD to FMA for precision. 8876 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8877 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8878 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8879 8880 // Is the node an FMUL and contractable either due to global flags or 8881 // SDNodeFlags. 8882 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 8883 if (N.getOpcode() != ISD::FMUL) 8884 return false; 8885 return AllowFusionGlobally || isContractable(N.getNode()); 8886 }; 8887 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 8888 // prefer to fold the multiply with fewer uses. 8889 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 8890 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 8891 std::swap(N0, N1); 8892 } 8893 8894 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 8895 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 8896 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8897 N0.getOperand(0), N0.getOperand(1), N1); 8898 } 8899 8900 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 8901 // Note: Commutes FADD operands. 8902 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 8903 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8904 N1.getOperand(0), N1.getOperand(1), N0); 8905 } 8906 8907 // Look through FP_EXTEND nodes to do more combining. 8908 if (LookThroughFPExt) { 8909 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 8910 if (N0.getOpcode() == ISD::FP_EXTEND) { 8911 SDValue N00 = N0.getOperand(0); 8912 if (isContractableFMUL(N00)) 8913 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8914 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8915 N00.getOperand(0)), 8916 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8917 N00.getOperand(1)), N1); 8918 } 8919 8920 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 8921 // Note: Commutes FADD operands. 8922 if (N1.getOpcode() == ISD::FP_EXTEND) { 8923 SDValue N10 = N1.getOperand(0); 8924 if (isContractableFMUL(N10)) 8925 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8926 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8927 N10.getOperand(0)), 8928 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8929 N10.getOperand(1)), N0); 8930 } 8931 } 8932 8933 // More folding opportunities when target permits. 8934 if (Aggressive) { 8935 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 8936 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8937 // are currently only supported on binary nodes. 8938 if (Options.UnsafeFPMath && 8939 N0.getOpcode() == PreferredFusedOpcode && 8940 N0.getOperand(2).getOpcode() == ISD::FMUL && 8941 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 8942 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8943 N0.getOperand(0), N0.getOperand(1), 8944 DAG.getNode(PreferredFusedOpcode, SL, VT, 8945 N0.getOperand(2).getOperand(0), 8946 N0.getOperand(2).getOperand(1), 8947 N1)); 8948 } 8949 8950 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 8951 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8952 // are currently only supported on binary nodes. 8953 if (Options.UnsafeFPMath && 8954 N1->getOpcode() == PreferredFusedOpcode && 8955 N1.getOperand(2).getOpcode() == ISD::FMUL && 8956 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 8957 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8958 N1.getOperand(0), N1.getOperand(1), 8959 DAG.getNode(PreferredFusedOpcode, SL, VT, 8960 N1.getOperand(2).getOperand(0), 8961 N1.getOperand(2).getOperand(1), 8962 N0)); 8963 } 8964 8965 if (LookThroughFPExt) { 8966 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 8967 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 8968 auto FoldFAddFMAFPExtFMul = [&] ( 8969 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 8970 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 8971 DAG.getNode(PreferredFusedOpcode, SL, VT, 8972 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 8973 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 8974 Z)); 8975 }; 8976 if (N0.getOpcode() == PreferredFusedOpcode) { 8977 SDValue N02 = N0.getOperand(2); 8978 if (N02.getOpcode() == ISD::FP_EXTEND) { 8979 SDValue N020 = N02.getOperand(0); 8980 if (isContractableFMUL(N020)) 8981 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 8982 N020.getOperand(0), N020.getOperand(1), 8983 N1); 8984 } 8985 } 8986 8987 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 8988 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 8989 // FIXME: This turns two single-precision and one double-precision 8990 // operation into two double-precision operations, which might not be 8991 // interesting for all targets, especially GPUs. 8992 auto FoldFAddFPExtFMAFMul = [&] ( 8993 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 8994 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8995 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 8996 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 8997 DAG.getNode(PreferredFusedOpcode, SL, VT, 8998 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 8999 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9000 Z)); 9001 }; 9002 if (N0.getOpcode() == ISD::FP_EXTEND) { 9003 SDValue N00 = N0.getOperand(0); 9004 if (N00.getOpcode() == PreferredFusedOpcode) { 9005 SDValue N002 = N00.getOperand(2); 9006 if (isContractableFMUL(N002)) 9007 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 9008 N002.getOperand(0), N002.getOperand(1), 9009 N1); 9010 } 9011 } 9012 9013 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 9014 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 9015 if (N1.getOpcode() == PreferredFusedOpcode) { 9016 SDValue N12 = N1.getOperand(2); 9017 if (N12.getOpcode() == ISD::FP_EXTEND) { 9018 SDValue N120 = N12.getOperand(0); 9019 if (isContractableFMUL(N120)) 9020 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 9021 N120.getOperand(0), N120.getOperand(1), 9022 N0); 9023 } 9024 } 9025 9026 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 9027 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 9028 // FIXME: This turns two single-precision and one double-precision 9029 // operation into two double-precision operations, which might not be 9030 // interesting for all targets, especially GPUs. 9031 if (N1.getOpcode() == ISD::FP_EXTEND) { 9032 SDValue N10 = N1.getOperand(0); 9033 if (N10.getOpcode() == PreferredFusedOpcode) { 9034 SDValue N102 = N10.getOperand(2); 9035 if (isContractableFMUL(N102)) 9036 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 9037 N102.getOperand(0), N102.getOperand(1), 9038 N0); 9039 } 9040 } 9041 } 9042 } 9043 9044 return SDValue(); 9045 } 9046 9047 /// Try to perform FMA combining on a given FSUB node. 9048 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 9049 SDValue N0 = N->getOperand(0); 9050 SDValue N1 = N->getOperand(1); 9051 EVT VT = N->getValueType(0); 9052 SDLoc SL(N); 9053 9054 const TargetOptions &Options = DAG.getTarget().Options; 9055 // Floating-point multiply-add with intermediate rounding. 9056 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9057 9058 // Floating-point multiply-add without intermediate rounding. 9059 bool HasFMA = 9060 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9061 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9062 9063 // No valid opcode, do not combine. 9064 if (!HasFMAD && !HasFMA) 9065 return SDValue(); 9066 9067 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9068 Options.UnsafeFPMath || HasFMAD); 9069 // If the subtraction is not contractable, do not combine. 9070 if (!AllowFusionGlobally && !isContractable(N)) 9071 return SDValue(); 9072 9073 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9074 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9075 return SDValue(); 9076 9077 // Always prefer FMAD to FMA for precision. 9078 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9079 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9080 bool LookThroughFPExt = TLI.isFPExtFree(VT); 9081 9082 // Is the node an FMUL and contractable either due to global flags or 9083 // SDNodeFlags. 9084 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9085 if (N.getOpcode() != ISD::FMUL) 9086 return false; 9087 return AllowFusionGlobally || isContractable(N.getNode()); 9088 }; 9089 9090 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 9091 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9092 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9093 N0.getOperand(0), N0.getOperand(1), 9094 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9095 } 9096 9097 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 9098 // Note: Commutes FSUB operands. 9099 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) 9100 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9101 DAG.getNode(ISD::FNEG, SL, VT, 9102 N1.getOperand(0)), 9103 N1.getOperand(1), N0); 9104 9105 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 9106 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 9107 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 9108 SDValue N00 = N0.getOperand(0).getOperand(0); 9109 SDValue N01 = N0.getOperand(0).getOperand(1); 9110 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9111 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 9112 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9113 } 9114 9115 // Look through FP_EXTEND nodes to do more combining. 9116 if (LookThroughFPExt) { 9117 // fold (fsub (fpext (fmul x, y)), z) 9118 // -> (fma (fpext x), (fpext y), (fneg z)) 9119 if (N0.getOpcode() == ISD::FP_EXTEND) { 9120 SDValue N00 = N0.getOperand(0); 9121 if (isContractableFMUL(N00)) 9122 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9123 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9124 N00.getOperand(0)), 9125 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9126 N00.getOperand(1)), 9127 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9128 } 9129 9130 // fold (fsub x, (fpext (fmul y, z))) 9131 // -> (fma (fneg (fpext y)), (fpext z), x) 9132 // Note: Commutes FSUB operands. 9133 if (N1.getOpcode() == ISD::FP_EXTEND) { 9134 SDValue N10 = N1.getOperand(0); 9135 if (isContractableFMUL(N10)) 9136 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9137 DAG.getNode(ISD::FNEG, SL, VT, 9138 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9139 N10.getOperand(0))), 9140 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9141 N10.getOperand(1)), 9142 N0); 9143 } 9144 9145 // fold (fsub (fpext (fneg (fmul, x, y))), z) 9146 // -> (fneg (fma (fpext x), (fpext y), z)) 9147 // Note: This could be removed with appropriate canonicalization of the 9148 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9149 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9150 // from implementing the canonicalization in visitFSUB. 9151 if (N0.getOpcode() == ISD::FP_EXTEND) { 9152 SDValue N00 = N0.getOperand(0); 9153 if (N00.getOpcode() == ISD::FNEG) { 9154 SDValue N000 = N00.getOperand(0); 9155 if (isContractableFMUL(N000)) { 9156 return DAG.getNode(ISD::FNEG, SL, VT, 9157 DAG.getNode(PreferredFusedOpcode, SL, VT, 9158 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9159 N000.getOperand(0)), 9160 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9161 N000.getOperand(1)), 9162 N1)); 9163 } 9164 } 9165 } 9166 9167 // fold (fsub (fneg (fpext (fmul, x, y))), z) 9168 // -> (fneg (fma (fpext x)), (fpext y), z) 9169 // Note: This could be removed with appropriate canonicalization of the 9170 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9171 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9172 // from implementing the canonicalization in visitFSUB. 9173 if (N0.getOpcode() == ISD::FNEG) { 9174 SDValue N00 = N0.getOperand(0); 9175 if (N00.getOpcode() == ISD::FP_EXTEND) { 9176 SDValue N000 = N00.getOperand(0); 9177 if (isContractableFMUL(N000)) { 9178 return DAG.getNode(ISD::FNEG, SL, VT, 9179 DAG.getNode(PreferredFusedOpcode, SL, VT, 9180 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9181 N000.getOperand(0)), 9182 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9183 N000.getOperand(1)), 9184 N1)); 9185 } 9186 } 9187 } 9188 9189 } 9190 9191 // More folding opportunities when target permits. 9192 if (Aggressive) { 9193 // fold (fsub (fma x, y, (fmul u, v)), z) 9194 // -> (fma x, y (fma u, v, (fneg z))) 9195 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9196 // are currently only supported on binary nodes. 9197 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode && 9198 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 9199 N0.getOperand(2)->hasOneUse()) { 9200 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9201 N0.getOperand(0), N0.getOperand(1), 9202 DAG.getNode(PreferredFusedOpcode, SL, VT, 9203 N0.getOperand(2).getOperand(0), 9204 N0.getOperand(2).getOperand(1), 9205 DAG.getNode(ISD::FNEG, SL, VT, 9206 N1))); 9207 } 9208 9209 // fold (fsub x, (fma y, z, (fmul u, v))) 9210 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 9211 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9212 // are currently only supported on binary nodes. 9213 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode && 9214 isContractableFMUL(N1.getOperand(2))) { 9215 SDValue N20 = N1.getOperand(2).getOperand(0); 9216 SDValue N21 = N1.getOperand(2).getOperand(1); 9217 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9218 DAG.getNode(ISD::FNEG, SL, VT, 9219 N1.getOperand(0)), 9220 N1.getOperand(1), 9221 DAG.getNode(PreferredFusedOpcode, SL, VT, 9222 DAG.getNode(ISD::FNEG, SL, VT, N20), 9223 9224 N21, N0)); 9225 } 9226 9227 if (LookThroughFPExt) { 9228 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 9229 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 9230 if (N0.getOpcode() == PreferredFusedOpcode) { 9231 SDValue N02 = N0.getOperand(2); 9232 if (N02.getOpcode() == ISD::FP_EXTEND) { 9233 SDValue N020 = N02.getOperand(0); 9234 if (isContractableFMUL(N020)) 9235 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9236 N0.getOperand(0), N0.getOperand(1), 9237 DAG.getNode(PreferredFusedOpcode, SL, VT, 9238 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9239 N020.getOperand(0)), 9240 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9241 N020.getOperand(1)), 9242 DAG.getNode(ISD::FNEG, SL, VT, 9243 N1))); 9244 } 9245 } 9246 9247 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 9248 // -> (fma (fpext x), (fpext y), 9249 // (fma (fpext u), (fpext v), (fneg z))) 9250 // FIXME: This turns two single-precision and one double-precision 9251 // operation into two double-precision operations, which might not be 9252 // interesting for all targets, especially GPUs. 9253 if (N0.getOpcode() == ISD::FP_EXTEND) { 9254 SDValue N00 = N0.getOperand(0); 9255 if (N00.getOpcode() == PreferredFusedOpcode) { 9256 SDValue N002 = N00.getOperand(2); 9257 if (isContractableFMUL(N002)) 9258 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9259 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9260 N00.getOperand(0)), 9261 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9262 N00.getOperand(1)), 9263 DAG.getNode(PreferredFusedOpcode, SL, VT, 9264 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9265 N002.getOperand(0)), 9266 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9267 N002.getOperand(1)), 9268 DAG.getNode(ISD::FNEG, SL, VT, 9269 N1))); 9270 } 9271 } 9272 9273 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 9274 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 9275 if (N1.getOpcode() == PreferredFusedOpcode && 9276 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 9277 SDValue N120 = N1.getOperand(2).getOperand(0); 9278 if (isContractableFMUL(N120)) { 9279 SDValue N1200 = N120.getOperand(0); 9280 SDValue N1201 = N120.getOperand(1); 9281 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9282 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 9283 N1.getOperand(1), 9284 DAG.getNode(PreferredFusedOpcode, SL, VT, 9285 DAG.getNode(ISD::FNEG, SL, VT, 9286 DAG.getNode(ISD::FP_EXTEND, SL, 9287 VT, N1200)), 9288 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9289 N1201), 9290 N0)); 9291 } 9292 } 9293 9294 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 9295 // -> (fma (fneg (fpext y)), (fpext z), 9296 // (fma (fneg (fpext u)), (fpext v), x)) 9297 // FIXME: This turns two single-precision and one double-precision 9298 // operation into two double-precision operations, which might not be 9299 // interesting for all targets, especially GPUs. 9300 if (N1.getOpcode() == ISD::FP_EXTEND && 9301 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 9302 SDValue N100 = N1.getOperand(0).getOperand(0); 9303 SDValue N101 = N1.getOperand(0).getOperand(1); 9304 SDValue N102 = N1.getOperand(0).getOperand(2); 9305 if (isContractableFMUL(N102)) { 9306 SDValue N1020 = N102.getOperand(0); 9307 SDValue N1021 = N102.getOperand(1); 9308 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9309 DAG.getNode(ISD::FNEG, SL, VT, 9310 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9311 N100)), 9312 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 9313 DAG.getNode(PreferredFusedOpcode, SL, VT, 9314 DAG.getNode(ISD::FNEG, SL, VT, 9315 DAG.getNode(ISD::FP_EXTEND, SL, 9316 VT, N1020)), 9317 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9318 N1021), 9319 N0)); 9320 } 9321 } 9322 } 9323 } 9324 9325 return SDValue(); 9326 } 9327 9328 /// Try to perform FMA combining on a given FMUL node based on the distributive 9329 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 9330 /// subtraction instead of addition). 9331 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 9332 SDValue N0 = N->getOperand(0); 9333 SDValue N1 = N->getOperand(1); 9334 EVT VT = N->getValueType(0); 9335 SDLoc SL(N); 9336 9337 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 9338 9339 const TargetOptions &Options = DAG.getTarget().Options; 9340 9341 // The transforms below are incorrect when x == 0 and y == inf, because the 9342 // intermediate multiplication produces a nan. 9343 if (!Options.NoInfsFPMath) 9344 return SDValue(); 9345 9346 // Floating-point multiply-add without intermediate rounding. 9347 bool HasFMA = 9348 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 9349 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9350 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9351 9352 // Floating-point multiply-add with intermediate rounding. This can result 9353 // in a less precise result due to the changed rounding order. 9354 bool HasFMAD = Options.UnsafeFPMath && 9355 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9356 9357 // No valid opcode, do not combine. 9358 if (!HasFMAD && !HasFMA) 9359 return SDValue(); 9360 9361 // Always prefer FMAD to FMA for precision. 9362 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9363 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9364 9365 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 9366 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 9367 auto FuseFADD = [&](SDValue X, SDValue Y) { 9368 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 9369 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9370 if (XC1 && XC1->isExactlyValue(+1.0)) 9371 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9372 if (XC1 && XC1->isExactlyValue(-1.0)) 9373 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9374 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9375 } 9376 return SDValue(); 9377 }; 9378 9379 if (SDValue FMA = FuseFADD(N0, N1)) 9380 return FMA; 9381 if (SDValue FMA = FuseFADD(N1, N0)) 9382 return FMA; 9383 9384 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 9385 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 9386 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 9387 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 9388 auto FuseFSUB = [&](SDValue X, SDValue Y) { 9389 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 9390 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 9391 if (XC0 && XC0->isExactlyValue(+1.0)) 9392 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9393 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9394 Y); 9395 if (XC0 && XC0->isExactlyValue(-1.0)) 9396 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9397 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9398 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9399 9400 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9401 if (XC1 && XC1->isExactlyValue(+1.0)) 9402 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9403 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9404 if (XC1 && XC1->isExactlyValue(-1.0)) 9405 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9406 } 9407 return SDValue(); 9408 }; 9409 9410 if (SDValue FMA = FuseFSUB(N0, N1)) 9411 return FMA; 9412 if (SDValue FMA = FuseFSUB(N1, N0)) 9413 return FMA; 9414 9415 return SDValue(); 9416 } 9417 9418 static bool isFMulNegTwo(SDValue &N) { 9419 if (N.getOpcode() != ISD::FMUL) 9420 return false; 9421 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1))) 9422 return CFP->isExactlyValue(-2.0); 9423 return false; 9424 } 9425 9426 SDValue DAGCombiner::visitFADD(SDNode *N) { 9427 SDValue N0 = N->getOperand(0); 9428 SDValue N1 = N->getOperand(1); 9429 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 9430 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 9431 EVT VT = N->getValueType(0); 9432 SDLoc DL(N); 9433 const TargetOptions &Options = DAG.getTarget().Options; 9434 const SDNodeFlags Flags = N->getFlags(); 9435 9436 // fold vector ops 9437 if (VT.isVector()) 9438 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9439 return FoldedVOp; 9440 9441 // fold (fadd c1, c2) -> c1 + c2 9442 if (N0CFP && N1CFP) 9443 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 9444 9445 // canonicalize constant to RHS 9446 if (N0CFP && !N1CFP) 9447 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 9448 9449 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9450 return NewSel; 9451 9452 // fold (fadd A, (fneg B)) -> (fsub A, B) 9453 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9454 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 9455 return DAG.getNode(ISD::FSUB, DL, VT, N0, 9456 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9457 9458 // fold (fadd (fneg A), B) -> (fsub B, A) 9459 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9460 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 9461 return DAG.getNode(ISD::FSUB, DL, VT, N1, 9462 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 9463 9464 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B)) 9465 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B)) 9466 if ((isFMulNegTwo(N0) && N0.hasOneUse()) || 9467 (isFMulNegTwo(N1) && N1.hasOneUse())) { 9468 bool N1IsFMul = isFMulNegTwo(N1); 9469 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0); 9470 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags); 9471 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags); 9472 } 9473 9474 // FIXME: Auto-upgrade the target/function-level option. 9475 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9476 // fold (fadd A, 0) -> A 9477 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 9478 if (N1C->isZero()) 9479 return N0; 9480 } 9481 9482 // If 'unsafe math' is enabled, fold lots of things. 9483 if (Options.UnsafeFPMath) { 9484 // No FP constant should be created after legalization as Instruction 9485 // Selection pass has a hard time dealing with FP constants. 9486 bool AllowNewConst = (Level < AfterLegalizeDAG); 9487 9488 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9489 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9490 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9491 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9492 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9493 Flags), 9494 Flags); 9495 9496 // If allowed, fold (fadd (fneg x), x) -> 0.0 9497 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 9498 return DAG.getConstantFP(0.0, DL, VT); 9499 9500 // If allowed, fold (fadd x, (fneg x)) -> 0.0 9501 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 9502 return DAG.getConstantFP(0.0, DL, VT); 9503 9504 // We can fold chains of FADD's of the same value into multiplications. 9505 // This transform is not safe in general because we are reducing the number 9506 // of rounding steps. 9507 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 9508 if (N0.getOpcode() == ISD::FMUL) { 9509 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9510 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 9511 9512 // (fadd (fmul x, c), x) -> (fmul x, c+1) 9513 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 9514 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9515 DAG.getConstantFP(1.0, DL, VT), Flags); 9516 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 9517 } 9518 9519 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 9520 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 9521 N1.getOperand(0) == N1.getOperand(1) && 9522 N0.getOperand(0) == N1.getOperand(0)) { 9523 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9524 DAG.getConstantFP(2.0, DL, VT), Flags); 9525 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 9526 } 9527 } 9528 9529 if (N1.getOpcode() == ISD::FMUL) { 9530 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9531 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 9532 9533 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 9534 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 9535 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9536 DAG.getConstantFP(1.0, DL, VT), Flags); 9537 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 9538 } 9539 9540 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 9541 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 9542 N0.getOperand(0) == N0.getOperand(1) && 9543 N1.getOperand(0) == N0.getOperand(0)) { 9544 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9545 DAG.getConstantFP(2.0, DL, VT), Flags); 9546 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 9547 } 9548 } 9549 9550 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 9551 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9552 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 9553 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 9554 (N0.getOperand(0) == N1)) { 9555 return DAG.getNode(ISD::FMUL, DL, VT, 9556 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 9557 } 9558 } 9559 9560 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 9561 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9562 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 9563 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 9564 N1.getOperand(0) == N0) { 9565 return DAG.getNode(ISD::FMUL, DL, VT, 9566 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 9567 } 9568 } 9569 9570 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 9571 if (AllowNewConst && 9572 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 9573 N0.getOperand(0) == N0.getOperand(1) && 9574 N1.getOperand(0) == N1.getOperand(1) && 9575 N0.getOperand(0) == N1.getOperand(0)) { 9576 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 9577 DAG.getConstantFP(4.0, DL, VT), Flags); 9578 } 9579 } 9580 } // enable-unsafe-fp-math 9581 9582 // FADD -> FMA combines: 9583 if (SDValue Fused = visitFADDForFMACombine(N)) { 9584 AddToWorklist(Fused.getNode()); 9585 return Fused; 9586 } 9587 return SDValue(); 9588 } 9589 9590 SDValue DAGCombiner::visitFSUB(SDNode *N) { 9591 SDValue N0 = N->getOperand(0); 9592 SDValue N1 = N->getOperand(1); 9593 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9594 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9595 EVT VT = N->getValueType(0); 9596 SDLoc DL(N); 9597 const TargetOptions &Options = DAG.getTarget().Options; 9598 const SDNodeFlags Flags = N->getFlags(); 9599 9600 // fold vector ops 9601 if (VT.isVector()) 9602 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9603 return FoldedVOp; 9604 9605 // fold (fsub c1, c2) -> c1-c2 9606 if (N0CFP && N1CFP) 9607 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 9608 9609 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9610 return NewSel; 9611 9612 // fold (fsub A, (fneg B)) -> (fadd A, B) 9613 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9614 return DAG.getNode(ISD::FADD, DL, VT, N0, 9615 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9616 9617 // FIXME: Auto-upgrade the target/function-level option. 9618 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9619 // (fsub 0, B) -> -B 9620 if (N0CFP && N0CFP->isZero()) { 9621 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9622 return GetNegatedExpression(N1, DAG, LegalOperations); 9623 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9624 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 9625 } 9626 } 9627 9628 // If 'unsafe math' is enabled, fold lots of things. 9629 if (Options.UnsafeFPMath) { 9630 // (fsub A, 0) -> A 9631 if (N1CFP && N1CFP->isZero()) 9632 return N0; 9633 9634 // (fsub x, x) -> 0.0 9635 if (N0 == N1) 9636 return DAG.getConstantFP(0.0f, DL, VT); 9637 9638 // (fsub x, (fadd x, y)) -> (fneg y) 9639 // (fsub x, (fadd y, x)) -> (fneg y) 9640 if (N1.getOpcode() == ISD::FADD) { 9641 SDValue N10 = N1->getOperand(0); 9642 SDValue N11 = N1->getOperand(1); 9643 9644 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 9645 return GetNegatedExpression(N11, DAG, LegalOperations); 9646 9647 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 9648 return GetNegatedExpression(N10, DAG, LegalOperations); 9649 } 9650 } 9651 9652 // FSUB -> FMA combines: 9653 if (SDValue Fused = visitFSUBForFMACombine(N)) { 9654 AddToWorklist(Fused.getNode()); 9655 return Fused; 9656 } 9657 9658 return SDValue(); 9659 } 9660 9661 SDValue DAGCombiner::visitFMUL(SDNode *N) { 9662 SDValue N0 = N->getOperand(0); 9663 SDValue N1 = N->getOperand(1); 9664 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9665 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9666 EVT VT = N->getValueType(0); 9667 SDLoc DL(N); 9668 const TargetOptions &Options = DAG.getTarget().Options; 9669 const SDNodeFlags Flags = N->getFlags(); 9670 9671 // fold vector ops 9672 if (VT.isVector()) { 9673 // This just handles C1 * C2 for vectors. Other vector folds are below. 9674 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9675 return FoldedVOp; 9676 } 9677 9678 // fold (fmul c1, c2) -> c1*c2 9679 if (N0CFP && N1CFP) 9680 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 9681 9682 // canonicalize constant to RHS 9683 if (isConstantFPBuildVectorOrConstantFP(N0) && 9684 !isConstantFPBuildVectorOrConstantFP(N1)) 9685 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 9686 9687 // fold (fmul A, 1.0) -> A 9688 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9689 return N0; 9690 9691 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9692 return NewSel; 9693 9694 if (Options.UnsafeFPMath) { 9695 // fold (fmul A, 0) -> 0 9696 if (N1CFP && N1CFP->isZero()) 9697 return N1; 9698 9699 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 9700 if (N0.getOpcode() == ISD::FMUL) { 9701 // Fold scalars or any vector constants (not just splats). 9702 // This fold is done in general by InstCombine, but extra fmul insts 9703 // may have been generated during lowering. 9704 SDValue N00 = N0.getOperand(0); 9705 SDValue N01 = N0.getOperand(1); 9706 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 9707 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 9708 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 9709 9710 // Check 1: Make sure that the first operand of the inner multiply is NOT 9711 // a constant. Otherwise, we may induce infinite looping. 9712 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 9713 // Check 2: Make sure that the second operand of the inner multiply and 9714 // the second operand of the outer multiply are constants. 9715 if ((N1CFP && isConstOrConstSplatFP(N01)) || 9716 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 9717 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 9718 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 9719 } 9720 } 9721 } 9722 9723 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 9724 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 9725 // during an early run of DAGCombiner can prevent folding with fmuls 9726 // inserted during lowering. 9727 if (N0.getOpcode() == ISD::FADD && 9728 (N0.getOperand(0) == N0.getOperand(1)) && 9729 N0.hasOneUse()) { 9730 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 9731 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 9732 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 9733 } 9734 } 9735 9736 // fold (fmul X, 2.0) -> (fadd X, X) 9737 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 9738 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 9739 9740 // fold (fmul X, -1.0) -> (fneg X) 9741 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 9742 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9743 return DAG.getNode(ISD::FNEG, DL, VT, N0); 9744 9745 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 9746 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9747 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9748 // Both can be negated for free, check to see if at least one is cheaper 9749 // negated. 9750 if (LHSNeg == 2 || RHSNeg == 2) 9751 return DAG.getNode(ISD::FMUL, DL, VT, 9752 GetNegatedExpression(N0, DAG, LegalOperations), 9753 GetNegatedExpression(N1, DAG, LegalOperations), 9754 Flags); 9755 } 9756 } 9757 9758 // FMUL -> FMA combines: 9759 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 9760 AddToWorklist(Fused.getNode()); 9761 return Fused; 9762 } 9763 9764 return SDValue(); 9765 } 9766 9767 SDValue DAGCombiner::visitFMA(SDNode *N) { 9768 SDValue N0 = N->getOperand(0); 9769 SDValue N1 = N->getOperand(1); 9770 SDValue N2 = N->getOperand(2); 9771 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9772 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9773 EVT VT = N->getValueType(0); 9774 SDLoc DL(N); 9775 const TargetOptions &Options = DAG.getTarget().Options; 9776 9777 // Constant fold FMA. 9778 if (isa<ConstantFPSDNode>(N0) && 9779 isa<ConstantFPSDNode>(N1) && 9780 isa<ConstantFPSDNode>(N2)) { 9781 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 9782 } 9783 9784 if (Options.UnsafeFPMath) { 9785 if (N0CFP && N0CFP->isZero()) 9786 return N2; 9787 if (N1CFP && N1CFP->isZero()) 9788 return N2; 9789 } 9790 // TODO: The FMA node should have flags that propagate to these nodes. 9791 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9792 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 9793 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9794 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 9795 9796 // Canonicalize (fma c, x, y) -> (fma x, c, y) 9797 if (isConstantFPBuildVectorOrConstantFP(N0) && 9798 !isConstantFPBuildVectorOrConstantFP(N1)) 9799 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 9800 9801 // TODO: FMA nodes should have flags that propagate to the created nodes. 9802 // For now, create a Flags object for use with all unsafe math transforms. 9803 SDNodeFlags Flags; 9804 Flags.setUnsafeAlgebra(true); 9805 9806 if (Options.UnsafeFPMath) { 9807 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 9808 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 9809 isConstantFPBuildVectorOrConstantFP(N1) && 9810 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 9811 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9812 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 9813 Flags), Flags); 9814 } 9815 9816 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 9817 if (N0.getOpcode() == ISD::FMUL && 9818 isConstantFPBuildVectorOrConstantFP(N1) && 9819 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 9820 return DAG.getNode(ISD::FMA, DL, VT, 9821 N0.getOperand(0), 9822 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 9823 Flags), 9824 N2); 9825 } 9826 } 9827 9828 // (fma x, 1, y) -> (fadd x, y) 9829 // (fma x, -1, y) -> (fadd (fneg x), y) 9830 if (N1CFP) { 9831 if (N1CFP->isExactlyValue(1.0)) 9832 // TODO: The FMA node should have flags that propagate to this node. 9833 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 9834 9835 if (N1CFP->isExactlyValue(-1.0) && 9836 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 9837 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 9838 AddToWorklist(RHSNeg.getNode()); 9839 // TODO: The FMA node should have flags that propagate to this node. 9840 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 9841 } 9842 } 9843 9844 if (Options.UnsafeFPMath) { 9845 // (fma x, c, x) -> (fmul x, (c+1)) 9846 if (N1CFP && N0 == N2) { 9847 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9848 DAG.getNode(ISD::FADD, DL, VT, N1, 9849 DAG.getConstantFP(1.0, DL, VT), Flags), 9850 Flags); 9851 } 9852 9853 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 9854 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 9855 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9856 DAG.getNode(ISD::FADD, DL, VT, N1, 9857 DAG.getConstantFP(-1.0, DL, VT), Flags), 9858 Flags); 9859 } 9860 } 9861 9862 return SDValue(); 9863 } 9864 9865 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 9866 // reciprocal. 9867 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 9868 // Notice that this is not always beneficial. One reason is different targets 9869 // may have different costs for FDIV and FMUL, so sometimes the cost of two 9870 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 9871 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 9872 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 9873 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 9874 const SDNodeFlags Flags = N->getFlags(); 9875 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 9876 return SDValue(); 9877 9878 // Skip if current node is a reciprocal. 9879 SDValue N0 = N->getOperand(0); 9880 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9881 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9882 return SDValue(); 9883 9884 // Exit early if the target does not want this transform or if there can't 9885 // possibly be enough uses of the divisor to make the transform worthwhile. 9886 SDValue N1 = N->getOperand(1); 9887 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 9888 if (!MinUses || N1->use_size() < MinUses) 9889 return SDValue(); 9890 9891 // Find all FDIV users of the same divisor. 9892 // Use a set because duplicates may be present in the user list. 9893 SetVector<SDNode *> Users; 9894 for (auto *U : N1->uses()) { 9895 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 9896 // This division is eligible for optimization only if global unsafe math 9897 // is enabled or if this division allows reciprocal formation. 9898 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 9899 Users.insert(U); 9900 } 9901 } 9902 9903 // Now that we have the actual number of divisor uses, make sure it meets 9904 // the minimum threshold specified by the target. 9905 if (Users.size() < MinUses) 9906 return SDValue(); 9907 9908 EVT VT = N->getValueType(0); 9909 SDLoc DL(N); 9910 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 9911 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 9912 9913 // Dividend / Divisor -> Dividend * Reciprocal 9914 for (auto *U : Users) { 9915 SDValue Dividend = U->getOperand(0); 9916 if (Dividend != FPOne) { 9917 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 9918 Reciprocal, Flags); 9919 CombineTo(U, NewNode); 9920 } else if (U != Reciprocal.getNode()) { 9921 // In the absence of fast-math-flags, this user node is always the 9922 // same node as Reciprocal, but with FMF they may be different nodes. 9923 CombineTo(U, Reciprocal); 9924 } 9925 } 9926 return SDValue(N, 0); // N was replaced. 9927 } 9928 9929 SDValue DAGCombiner::visitFDIV(SDNode *N) { 9930 SDValue N0 = N->getOperand(0); 9931 SDValue N1 = N->getOperand(1); 9932 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9933 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9934 EVT VT = N->getValueType(0); 9935 SDLoc DL(N); 9936 const TargetOptions &Options = DAG.getTarget().Options; 9937 SDNodeFlags Flags = N->getFlags(); 9938 9939 // fold vector ops 9940 if (VT.isVector()) 9941 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9942 return FoldedVOp; 9943 9944 // fold (fdiv c1, c2) -> c1/c2 9945 if (N0CFP && N1CFP) 9946 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 9947 9948 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9949 return NewSel; 9950 9951 if (Options.UnsafeFPMath) { 9952 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 9953 if (N1CFP) { 9954 // Compute the reciprocal 1.0 / c2. 9955 const APFloat &N1APF = N1CFP->getValueAPF(); 9956 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 9957 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 9958 // Only do the transform if the reciprocal is a legal fp immediate that 9959 // isn't too nasty (eg NaN, denormal, ...). 9960 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 9961 (!LegalOperations || 9962 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 9963 // backend)... we should handle this gracefully after Legalize. 9964 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 9965 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 9966 TLI.isFPImmLegal(Recip, VT))) 9967 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9968 DAG.getConstantFP(Recip, DL, VT), Flags); 9969 } 9970 9971 // If this FDIV is part of a reciprocal square root, it may be folded 9972 // into a target-specific square root estimate instruction. 9973 if (N1.getOpcode() == ISD::FSQRT) { 9974 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 9975 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9976 } 9977 } else if (N1.getOpcode() == ISD::FP_EXTEND && 9978 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9979 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 9980 Flags)) { 9981 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 9982 AddToWorklist(RV.getNode()); 9983 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9984 } 9985 } else if (N1.getOpcode() == ISD::FP_ROUND && 9986 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9987 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 9988 Flags)) { 9989 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 9990 AddToWorklist(RV.getNode()); 9991 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 9992 } 9993 } else if (N1.getOpcode() == ISD::FMUL) { 9994 // Look through an FMUL. Even though this won't remove the FDIV directly, 9995 // it's still worthwhile to get rid of the FSQRT if possible. 9996 SDValue SqrtOp; 9997 SDValue OtherOp; 9998 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 9999 SqrtOp = N1.getOperand(0); 10000 OtherOp = N1.getOperand(1); 10001 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 10002 SqrtOp = N1.getOperand(1); 10003 OtherOp = N1.getOperand(0); 10004 } 10005 if (SqrtOp.getNode()) { 10006 // We found a FSQRT, so try to make this fold: 10007 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 10008 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 10009 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 10010 AddToWorklist(RV.getNode()); 10011 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10012 } 10013 } 10014 } 10015 10016 // Fold into a reciprocal estimate and multiply instead of a real divide. 10017 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 10018 AddToWorklist(RV.getNode()); 10019 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10020 } 10021 } 10022 10023 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 10024 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10025 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10026 // Both can be negated for free, check to see if at least one is cheaper 10027 // negated. 10028 if (LHSNeg == 2 || RHSNeg == 2) 10029 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 10030 GetNegatedExpression(N0, DAG, LegalOperations), 10031 GetNegatedExpression(N1, DAG, LegalOperations), 10032 Flags); 10033 } 10034 } 10035 10036 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 10037 return CombineRepeatedDivisors; 10038 10039 return SDValue(); 10040 } 10041 10042 SDValue DAGCombiner::visitFREM(SDNode *N) { 10043 SDValue N0 = N->getOperand(0); 10044 SDValue N1 = N->getOperand(1); 10045 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10046 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10047 EVT VT = N->getValueType(0); 10048 10049 // fold (frem c1, c2) -> fmod(c1,c2) 10050 if (N0CFP && N1CFP) 10051 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 10052 10053 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10054 return NewSel; 10055 10056 return SDValue(); 10057 } 10058 10059 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 10060 if (!DAG.getTarget().Options.UnsafeFPMath) 10061 return SDValue(); 10062 10063 SDValue N0 = N->getOperand(0); 10064 if (TLI.isFsqrtCheap(N0, DAG)) 10065 return SDValue(); 10066 10067 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 10068 // For now, create a Flags object for use with all unsafe math transforms. 10069 SDNodeFlags Flags; 10070 Flags.setUnsafeAlgebra(true); 10071 return buildSqrtEstimate(N0, Flags); 10072 } 10073 10074 /// copysign(x, fp_extend(y)) -> copysign(x, y) 10075 /// copysign(x, fp_round(y)) -> copysign(x, y) 10076 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 10077 SDValue N1 = N->getOperand(1); 10078 if ((N1.getOpcode() == ISD::FP_EXTEND || 10079 N1.getOpcode() == ISD::FP_ROUND)) { 10080 // Do not optimize out type conversion of f128 type yet. 10081 // For some targets like x86_64, configuration is changed to keep one f128 10082 // value in one SSE register, but instruction selection cannot handle 10083 // FCOPYSIGN on SSE registers yet. 10084 EVT N1VT = N1->getValueType(0); 10085 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 10086 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 10087 } 10088 return false; 10089 } 10090 10091 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 10092 SDValue N0 = N->getOperand(0); 10093 SDValue N1 = N->getOperand(1); 10094 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10095 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10096 EVT VT = N->getValueType(0); 10097 10098 if (N0CFP && N1CFP) // Constant fold 10099 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 10100 10101 if (N1CFP) { 10102 const APFloat &V = N1CFP->getValueAPF(); 10103 // copysign(x, c1) -> fabs(x) iff ispos(c1) 10104 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 10105 if (!V.isNegative()) { 10106 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 10107 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10108 } else { 10109 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10110 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10111 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 10112 } 10113 } 10114 10115 // copysign(fabs(x), y) -> copysign(x, y) 10116 // copysign(fneg(x), y) -> copysign(x, y) 10117 // copysign(copysign(x,z), y) -> copysign(x, y) 10118 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 10119 N0.getOpcode() == ISD::FCOPYSIGN) 10120 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 10121 10122 // copysign(x, abs(y)) -> abs(x) 10123 if (N1.getOpcode() == ISD::FABS) 10124 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10125 10126 // copysign(x, copysign(y,z)) -> copysign(x, z) 10127 if (N1.getOpcode() == ISD::FCOPYSIGN) 10128 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 10129 10130 // copysign(x, fp_extend(y)) -> copysign(x, y) 10131 // copysign(x, fp_round(y)) -> copysign(x, y) 10132 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 10133 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 10134 10135 return SDValue(); 10136 } 10137 10138 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 10139 SDValue N0 = N->getOperand(0); 10140 EVT VT = N->getValueType(0); 10141 EVT OpVT = N0.getValueType(); 10142 10143 // fold (sint_to_fp c1) -> c1fp 10144 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10145 // ...but only if the target supports immediate floating-point values 10146 (!LegalOperations || 10147 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 10148 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10149 10150 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 10151 // but UINT_TO_FP is legal on this target, try to convert. 10152 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 10153 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 10154 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 10155 if (DAG.SignBitIsZero(N0)) 10156 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10157 } 10158 10159 // The next optimizations are desirable only if SELECT_CC can be lowered. 10160 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10161 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10162 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 10163 !VT.isVector() && 10164 (!LegalOperations || 10165 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10166 SDLoc DL(N); 10167 SDValue Ops[] = 10168 { N0.getOperand(0), N0.getOperand(1), 10169 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10170 N0.getOperand(2) }; 10171 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10172 } 10173 10174 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 10175 // (select_cc x, y, 1.0, 0.0,, cc) 10176 if (N0.getOpcode() == ISD::ZERO_EXTEND && 10177 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 10178 (!LegalOperations || 10179 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10180 SDLoc DL(N); 10181 SDValue Ops[] = 10182 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 10183 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10184 N0.getOperand(0).getOperand(2) }; 10185 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10186 } 10187 } 10188 10189 return SDValue(); 10190 } 10191 10192 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 10193 SDValue N0 = N->getOperand(0); 10194 EVT VT = N->getValueType(0); 10195 EVT OpVT = N0.getValueType(); 10196 10197 // fold (uint_to_fp c1) -> c1fp 10198 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10199 // ...but only if the target supports immediate floating-point values 10200 (!LegalOperations || 10201 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 10202 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10203 10204 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 10205 // but SINT_TO_FP is legal on this target, try to convert. 10206 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 10207 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 10208 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 10209 if (DAG.SignBitIsZero(N0)) 10210 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10211 } 10212 10213 // The next optimizations are desirable only if SELECT_CC can be lowered. 10214 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10215 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10216 10217 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 10218 (!LegalOperations || 10219 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10220 SDLoc DL(N); 10221 SDValue Ops[] = 10222 { N0.getOperand(0), N0.getOperand(1), 10223 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10224 N0.getOperand(2) }; 10225 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10226 } 10227 } 10228 10229 return SDValue(); 10230 } 10231 10232 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 10233 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 10234 SDValue N0 = N->getOperand(0); 10235 EVT VT = N->getValueType(0); 10236 10237 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 10238 return SDValue(); 10239 10240 SDValue Src = N0.getOperand(0); 10241 EVT SrcVT = Src.getValueType(); 10242 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 10243 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 10244 10245 // We can safely assume the conversion won't overflow the output range, 10246 // because (for example) (uint8_t)18293.f is undefined behavior. 10247 10248 // Since we can assume the conversion won't overflow, our decision as to 10249 // whether the input will fit in the float should depend on the minimum 10250 // of the input range and output range. 10251 10252 // This means this is also safe for a signed input and unsigned output, since 10253 // a negative input would lead to undefined behavior. 10254 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 10255 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 10256 unsigned ActualSize = std::min(InputSize, OutputSize); 10257 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 10258 10259 // We can only fold away the float conversion if the input range can be 10260 // represented exactly in the float range. 10261 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 10262 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 10263 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 10264 : ISD::ZERO_EXTEND; 10265 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 10266 } 10267 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 10268 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 10269 return DAG.getBitcast(VT, Src); 10270 } 10271 return SDValue(); 10272 } 10273 10274 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 10275 SDValue N0 = N->getOperand(0); 10276 EVT VT = N->getValueType(0); 10277 10278 // fold (fp_to_sint c1fp) -> c1 10279 if (isConstantFPBuildVectorOrConstantFP(N0)) 10280 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 10281 10282 return FoldIntToFPToInt(N, DAG); 10283 } 10284 10285 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 10286 SDValue N0 = N->getOperand(0); 10287 EVT VT = N->getValueType(0); 10288 10289 // fold (fp_to_uint c1fp) -> c1 10290 if (isConstantFPBuildVectorOrConstantFP(N0)) 10291 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 10292 10293 return FoldIntToFPToInt(N, DAG); 10294 } 10295 10296 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 10297 SDValue N0 = N->getOperand(0); 10298 SDValue N1 = N->getOperand(1); 10299 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10300 EVT VT = N->getValueType(0); 10301 10302 // fold (fp_round c1fp) -> c1fp 10303 if (N0CFP) 10304 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 10305 10306 // fold (fp_round (fp_extend x)) -> x 10307 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 10308 return N0.getOperand(0); 10309 10310 // fold (fp_round (fp_round x)) -> (fp_round x) 10311 if (N0.getOpcode() == ISD::FP_ROUND) { 10312 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 10313 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 10314 10315 // Skip this folding if it results in an fp_round from f80 to f16. 10316 // 10317 // f80 to f16 always generates an expensive (and as yet, unimplemented) 10318 // libcall to __truncxfhf2 instead of selecting native f16 conversion 10319 // instructions from f32 or f64. Moreover, the first (value-preserving) 10320 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 10321 // x86. 10322 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 10323 return SDValue(); 10324 10325 // If the first fp_round isn't a value preserving truncation, it might 10326 // introduce a tie in the second fp_round, that wouldn't occur in the 10327 // single-step fp_round we want to fold to. 10328 // In other words, double rounding isn't the same as rounding. 10329 // Also, this is a value preserving truncation iff both fp_round's are. 10330 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 10331 SDLoc DL(N); 10332 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 10333 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 10334 } 10335 } 10336 10337 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 10338 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 10339 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 10340 N0.getOperand(0), N1); 10341 AddToWorklist(Tmp.getNode()); 10342 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 10343 Tmp, N0.getOperand(1)); 10344 } 10345 10346 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10347 return NewVSel; 10348 10349 return SDValue(); 10350 } 10351 10352 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 10353 SDValue N0 = N->getOperand(0); 10354 EVT VT = N->getValueType(0); 10355 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 10356 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10357 10358 // fold (fp_round_inreg c1fp) -> c1fp 10359 if (N0CFP && isTypeLegal(EVT)) { 10360 SDLoc DL(N); 10361 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 10362 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 10363 } 10364 10365 return SDValue(); 10366 } 10367 10368 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 10369 SDValue N0 = N->getOperand(0); 10370 EVT VT = N->getValueType(0); 10371 10372 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 10373 if (N->hasOneUse() && 10374 N->use_begin()->getOpcode() == ISD::FP_ROUND) 10375 return SDValue(); 10376 10377 // fold (fp_extend c1fp) -> c1fp 10378 if (isConstantFPBuildVectorOrConstantFP(N0)) 10379 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 10380 10381 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 10382 if (N0.getOpcode() == ISD::FP16_TO_FP && 10383 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 10384 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 10385 10386 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 10387 // value of X. 10388 if (N0.getOpcode() == ISD::FP_ROUND 10389 && N0.getConstantOperandVal(1) == 1) { 10390 SDValue In = N0.getOperand(0); 10391 if (In.getValueType() == VT) return In; 10392 if (VT.bitsLT(In.getValueType())) 10393 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 10394 In, N0.getOperand(1)); 10395 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 10396 } 10397 10398 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 10399 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10400 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 10401 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10402 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 10403 LN0->getChain(), 10404 LN0->getBasePtr(), N0.getValueType(), 10405 LN0->getMemOperand()); 10406 CombineTo(N, ExtLoad); 10407 CombineTo(N0.getNode(), 10408 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 10409 N0.getValueType(), ExtLoad, 10410 DAG.getIntPtrConstant(1, SDLoc(N0))), 10411 ExtLoad.getValue(1)); 10412 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10413 } 10414 10415 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10416 return NewVSel; 10417 10418 return SDValue(); 10419 } 10420 10421 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 10422 SDValue N0 = N->getOperand(0); 10423 EVT VT = N->getValueType(0); 10424 10425 // fold (fceil c1) -> fceil(c1) 10426 if (isConstantFPBuildVectorOrConstantFP(N0)) 10427 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 10428 10429 return SDValue(); 10430 } 10431 10432 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 10433 SDValue N0 = N->getOperand(0); 10434 EVT VT = N->getValueType(0); 10435 10436 // fold (ftrunc c1) -> ftrunc(c1) 10437 if (isConstantFPBuildVectorOrConstantFP(N0)) 10438 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 10439 10440 return SDValue(); 10441 } 10442 10443 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 10444 SDValue N0 = N->getOperand(0); 10445 EVT VT = N->getValueType(0); 10446 10447 // fold (ffloor c1) -> ffloor(c1) 10448 if (isConstantFPBuildVectorOrConstantFP(N0)) 10449 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 10450 10451 return SDValue(); 10452 } 10453 10454 // FIXME: FNEG and FABS have a lot in common; refactor. 10455 SDValue DAGCombiner::visitFNEG(SDNode *N) { 10456 SDValue N0 = N->getOperand(0); 10457 EVT VT = N->getValueType(0); 10458 10459 // Constant fold FNEG. 10460 if (isConstantFPBuildVectorOrConstantFP(N0)) 10461 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 10462 10463 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 10464 &DAG.getTarget().Options)) 10465 return GetNegatedExpression(N0, DAG, LegalOperations); 10466 10467 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 10468 // constant pool values. 10469 if (!TLI.isFNegFree(VT) && 10470 N0.getOpcode() == ISD::BITCAST && 10471 N0.getNode()->hasOneUse()) { 10472 SDValue Int = N0.getOperand(0); 10473 EVT IntVT = Int.getValueType(); 10474 if (IntVT.isInteger() && !IntVT.isVector()) { 10475 APInt SignMask; 10476 if (N0.getValueType().isVector()) { 10477 // For a vector, get a mask such as 0x80... per scalar element 10478 // and splat it. 10479 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 10480 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10481 } else { 10482 // For a scalar, just generate 0x80... 10483 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 10484 } 10485 SDLoc DL0(N0); 10486 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 10487 DAG.getConstant(SignMask, DL0, IntVT)); 10488 AddToWorklist(Int.getNode()); 10489 return DAG.getBitcast(VT, Int); 10490 } 10491 } 10492 10493 // (fneg (fmul c, x)) -> (fmul -c, x) 10494 if (N0.getOpcode() == ISD::FMUL && 10495 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 10496 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10497 if (CFP1) { 10498 APFloat CVal = CFP1->getValueAPF(); 10499 CVal.changeSign(); 10500 if (Level >= AfterLegalizeDAG && 10501 (TLI.isFPImmLegal(CVal, VT) || 10502 TLI.isOperationLegal(ISD::ConstantFP, VT))) 10503 return DAG.getNode( 10504 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 10505 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 10506 N0->getFlags()); 10507 } 10508 } 10509 10510 return SDValue(); 10511 } 10512 10513 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 10514 SDValue N0 = N->getOperand(0); 10515 SDValue N1 = N->getOperand(1); 10516 EVT VT = N->getValueType(0); 10517 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10518 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10519 10520 if (N0CFP && N1CFP) { 10521 const APFloat &C0 = N0CFP->getValueAPF(); 10522 const APFloat &C1 = N1CFP->getValueAPF(); 10523 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 10524 } 10525 10526 // Canonicalize to constant on RHS. 10527 if (isConstantFPBuildVectorOrConstantFP(N0) && 10528 !isConstantFPBuildVectorOrConstantFP(N1)) 10529 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 10530 10531 return SDValue(); 10532 } 10533 10534 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 10535 SDValue N0 = N->getOperand(0); 10536 SDValue N1 = N->getOperand(1); 10537 EVT VT = N->getValueType(0); 10538 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10539 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10540 10541 if (N0CFP && N1CFP) { 10542 const APFloat &C0 = N0CFP->getValueAPF(); 10543 const APFloat &C1 = N1CFP->getValueAPF(); 10544 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 10545 } 10546 10547 // Canonicalize to constant on RHS. 10548 if (isConstantFPBuildVectorOrConstantFP(N0) && 10549 !isConstantFPBuildVectorOrConstantFP(N1)) 10550 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 10551 10552 return SDValue(); 10553 } 10554 10555 SDValue DAGCombiner::visitFABS(SDNode *N) { 10556 SDValue N0 = N->getOperand(0); 10557 EVT VT = N->getValueType(0); 10558 10559 // fold (fabs c1) -> fabs(c1) 10560 if (isConstantFPBuildVectorOrConstantFP(N0)) 10561 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10562 10563 // fold (fabs (fabs x)) -> (fabs x) 10564 if (N0.getOpcode() == ISD::FABS) 10565 return N->getOperand(0); 10566 10567 // fold (fabs (fneg x)) -> (fabs x) 10568 // fold (fabs (fcopysign x, y)) -> (fabs x) 10569 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 10570 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 10571 10572 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 10573 // constant pool values. 10574 if (!TLI.isFAbsFree(VT) && 10575 N0.getOpcode() == ISD::BITCAST && 10576 N0.getNode()->hasOneUse()) { 10577 SDValue Int = N0.getOperand(0); 10578 EVT IntVT = Int.getValueType(); 10579 if (IntVT.isInteger() && !IntVT.isVector()) { 10580 APInt SignMask; 10581 if (N0.getValueType().isVector()) { 10582 // For a vector, get a mask such as 0x7f... per scalar element 10583 // and splat it. 10584 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 10585 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10586 } else { 10587 // For a scalar, just generate 0x7f... 10588 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 10589 } 10590 SDLoc DL(N0); 10591 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 10592 DAG.getConstant(SignMask, DL, IntVT)); 10593 AddToWorklist(Int.getNode()); 10594 return DAG.getBitcast(N->getValueType(0), Int); 10595 } 10596 } 10597 10598 return SDValue(); 10599 } 10600 10601 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 10602 SDValue Chain = N->getOperand(0); 10603 SDValue N1 = N->getOperand(1); 10604 SDValue N2 = N->getOperand(2); 10605 10606 // If N is a constant we could fold this into a fallthrough or unconditional 10607 // branch. However that doesn't happen very often in normal code, because 10608 // Instcombine/SimplifyCFG should have handled the available opportunities. 10609 // If we did this folding here, it would be necessary to update the 10610 // MachineBasicBlock CFG, which is awkward. 10611 10612 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 10613 // on the target. 10614 if (N1.getOpcode() == ISD::SETCC && 10615 TLI.isOperationLegalOrCustom(ISD::BR_CC, 10616 N1.getOperand(0).getValueType())) { 10617 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10618 Chain, N1.getOperand(2), 10619 N1.getOperand(0), N1.getOperand(1), N2); 10620 } 10621 10622 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 10623 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 10624 (N1.getOperand(0).hasOneUse() && 10625 N1.getOperand(0).getOpcode() == ISD::SRL))) { 10626 SDNode *Trunc = nullptr; 10627 if (N1.getOpcode() == ISD::TRUNCATE) { 10628 // Look pass the truncate. 10629 Trunc = N1.getNode(); 10630 N1 = N1.getOperand(0); 10631 } 10632 10633 // Match this pattern so that we can generate simpler code: 10634 // 10635 // %a = ... 10636 // %b = and i32 %a, 2 10637 // %c = srl i32 %b, 1 10638 // brcond i32 %c ... 10639 // 10640 // into 10641 // 10642 // %a = ... 10643 // %b = and i32 %a, 2 10644 // %c = setcc eq %b, 0 10645 // brcond %c ... 10646 // 10647 // This applies only when the AND constant value has one bit set and the 10648 // SRL constant is equal to the log2 of the AND constant. The back-end is 10649 // smart enough to convert the result into a TEST/JMP sequence. 10650 SDValue Op0 = N1.getOperand(0); 10651 SDValue Op1 = N1.getOperand(1); 10652 10653 if (Op0.getOpcode() == ISD::AND && 10654 Op1.getOpcode() == ISD::Constant) { 10655 SDValue AndOp1 = Op0.getOperand(1); 10656 10657 if (AndOp1.getOpcode() == ISD::Constant) { 10658 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 10659 10660 if (AndConst.isPowerOf2() && 10661 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 10662 SDLoc DL(N); 10663 SDValue SetCC = 10664 DAG.getSetCC(DL, 10665 getSetCCResultType(Op0.getValueType()), 10666 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 10667 ISD::SETNE); 10668 10669 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 10670 MVT::Other, Chain, SetCC, N2); 10671 // Don't add the new BRCond into the worklist or else SimplifySelectCC 10672 // will convert it back to (X & C1) >> C2. 10673 CombineTo(N, NewBRCond, false); 10674 // Truncate is dead. 10675 if (Trunc) 10676 deleteAndRecombine(Trunc); 10677 // Replace the uses of SRL with SETCC 10678 WorklistRemover DeadNodes(*this); 10679 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10680 deleteAndRecombine(N1.getNode()); 10681 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10682 } 10683 } 10684 } 10685 10686 if (Trunc) 10687 // Restore N1 if the above transformation doesn't match. 10688 N1 = N->getOperand(1); 10689 } 10690 10691 // Transform br(xor(x, y)) -> br(x != y) 10692 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 10693 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 10694 SDNode *TheXor = N1.getNode(); 10695 SDValue Op0 = TheXor->getOperand(0); 10696 SDValue Op1 = TheXor->getOperand(1); 10697 if (Op0.getOpcode() == Op1.getOpcode()) { 10698 // Avoid missing important xor optimizations. 10699 if (SDValue Tmp = visitXOR(TheXor)) { 10700 if (Tmp.getNode() != TheXor) { 10701 DEBUG(dbgs() << "\nReplacing.8 "; 10702 TheXor->dump(&DAG); 10703 dbgs() << "\nWith: "; 10704 Tmp.getNode()->dump(&DAG); 10705 dbgs() << '\n'); 10706 WorklistRemover DeadNodes(*this); 10707 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 10708 deleteAndRecombine(TheXor); 10709 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10710 MVT::Other, Chain, Tmp, N2); 10711 } 10712 10713 // visitXOR has changed XOR's operands or replaced the XOR completely, 10714 // bail out. 10715 return SDValue(N, 0); 10716 } 10717 } 10718 10719 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 10720 bool Equal = false; 10721 if (isOneConstant(Op0) && Op0.hasOneUse() && 10722 Op0.getOpcode() == ISD::XOR) { 10723 TheXor = Op0.getNode(); 10724 Equal = true; 10725 } 10726 10727 EVT SetCCVT = N1.getValueType(); 10728 if (LegalTypes) 10729 SetCCVT = getSetCCResultType(SetCCVT); 10730 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 10731 SetCCVT, 10732 Op0, Op1, 10733 Equal ? ISD::SETEQ : ISD::SETNE); 10734 // Replace the uses of XOR with SETCC 10735 WorklistRemover DeadNodes(*this); 10736 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10737 deleteAndRecombine(N1.getNode()); 10738 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10739 MVT::Other, Chain, SetCC, N2); 10740 } 10741 } 10742 10743 return SDValue(); 10744 } 10745 10746 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 10747 // 10748 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 10749 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 10750 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 10751 10752 // If N is a constant we could fold this into a fallthrough or unconditional 10753 // branch. However that doesn't happen very often in normal code, because 10754 // Instcombine/SimplifyCFG should have handled the available opportunities. 10755 // If we did this folding here, it would be necessary to update the 10756 // MachineBasicBlock CFG, which is awkward. 10757 10758 // Use SimplifySetCC to simplify SETCC's. 10759 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 10760 CondLHS, CondRHS, CC->get(), SDLoc(N), 10761 false); 10762 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 10763 10764 // fold to a simpler setcc 10765 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 10766 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10767 N->getOperand(0), Simp.getOperand(2), 10768 Simp.getOperand(0), Simp.getOperand(1), 10769 N->getOperand(4)); 10770 10771 return SDValue(); 10772 } 10773 10774 /// Return true if 'Use' is a load or a store that uses N as its base pointer 10775 /// and that N may be folded in the load / store addressing mode. 10776 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 10777 SelectionDAG &DAG, 10778 const TargetLowering &TLI) { 10779 EVT VT; 10780 unsigned AS; 10781 10782 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 10783 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 10784 return false; 10785 VT = LD->getMemoryVT(); 10786 AS = LD->getAddressSpace(); 10787 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 10788 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 10789 return false; 10790 VT = ST->getMemoryVT(); 10791 AS = ST->getAddressSpace(); 10792 } else 10793 return false; 10794 10795 TargetLowering::AddrMode AM; 10796 if (N->getOpcode() == ISD::ADD) { 10797 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10798 if (Offset) 10799 // [reg +/- imm] 10800 AM.BaseOffs = Offset->getSExtValue(); 10801 else 10802 // [reg +/- reg] 10803 AM.Scale = 1; 10804 } else if (N->getOpcode() == ISD::SUB) { 10805 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10806 if (Offset) 10807 // [reg +/- imm] 10808 AM.BaseOffs = -Offset->getSExtValue(); 10809 else 10810 // [reg +/- reg] 10811 AM.Scale = 1; 10812 } else 10813 return false; 10814 10815 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 10816 VT.getTypeForEVT(*DAG.getContext()), AS); 10817 } 10818 10819 /// Try turning a load/store into a pre-indexed load/store when the base 10820 /// pointer is an add or subtract and it has other uses besides the load/store. 10821 /// After the transformation, the new indexed load/store has effectively folded 10822 /// the add/subtract in and all of its other uses are redirected to the 10823 /// new load/store. 10824 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 10825 if (Level < AfterLegalizeDAG) 10826 return false; 10827 10828 bool isLoad = true; 10829 SDValue Ptr; 10830 EVT VT; 10831 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10832 if (LD->isIndexed()) 10833 return false; 10834 VT = LD->getMemoryVT(); 10835 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 10836 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 10837 return false; 10838 Ptr = LD->getBasePtr(); 10839 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10840 if (ST->isIndexed()) 10841 return false; 10842 VT = ST->getMemoryVT(); 10843 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 10844 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 10845 return false; 10846 Ptr = ST->getBasePtr(); 10847 isLoad = false; 10848 } else { 10849 return false; 10850 } 10851 10852 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 10853 // out. There is no reason to make this a preinc/predec. 10854 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 10855 Ptr.getNode()->hasOneUse()) 10856 return false; 10857 10858 // Ask the target to do addressing mode selection. 10859 SDValue BasePtr; 10860 SDValue Offset; 10861 ISD::MemIndexedMode AM = ISD::UNINDEXED; 10862 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 10863 return false; 10864 10865 // Backends without true r+i pre-indexed forms may need to pass a 10866 // constant base with a variable offset so that constant coercion 10867 // will work with the patterns in canonical form. 10868 bool Swapped = false; 10869 if (isa<ConstantSDNode>(BasePtr)) { 10870 std::swap(BasePtr, Offset); 10871 Swapped = true; 10872 } 10873 10874 // Don't create a indexed load / store with zero offset. 10875 if (isNullConstant(Offset)) 10876 return false; 10877 10878 // Try turning it into a pre-indexed load / store except when: 10879 // 1) The new base ptr is a frame index. 10880 // 2) If N is a store and the new base ptr is either the same as or is a 10881 // predecessor of the value being stored. 10882 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 10883 // that would create a cycle. 10884 // 4) All uses are load / store ops that use it as old base ptr. 10885 10886 // Check #1. Preinc'ing a frame index would require copying the stack pointer 10887 // (plus the implicit offset) to a register to preinc anyway. 10888 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 10889 return false; 10890 10891 // Check #2. 10892 if (!isLoad) { 10893 SDValue Val = cast<StoreSDNode>(N)->getValue(); 10894 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 10895 return false; 10896 } 10897 10898 // Caches for hasPredecessorHelper. 10899 SmallPtrSet<const SDNode *, 32> Visited; 10900 SmallVector<const SDNode *, 16> Worklist; 10901 Worklist.push_back(N); 10902 10903 // If the offset is a constant, there may be other adds of constants that 10904 // can be folded with this one. We should do this to avoid having to keep 10905 // a copy of the original base pointer. 10906 SmallVector<SDNode *, 16> OtherUses; 10907 if (isa<ConstantSDNode>(Offset)) 10908 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 10909 UE = BasePtr.getNode()->use_end(); 10910 UI != UE; ++UI) { 10911 SDUse &Use = UI.getUse(); 10912 // Skip the use that is Ptr and uses of other results from BasePtr's 10913 // node (important for nodes that return multiple results). 10914 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 10915 continue; 10916 10917 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 10918 continue; 10919 10920 if (Use.getUser()->getOpcode() != ISD::ADD && 10921 Use.getUser()->getOpcode() != ISD::SUB) { 10922 OtherUses.clear(); 10923 break; 10924 } 10925 10926 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 10927 if (!isa<ConstantSDNode>(Op1)) { 10928 OtherUses.clear(); 10929 break; 10930 } 10931 10932 // FIXME: In some cases, we can be smarter about this. 10933 if (Op1.getValueType() != Offset.getValueType()) { 10934 OtherUses.clear(); 10935 break; 10936 } 10937 10938 OtherUses.push_back(Use.getUser()); 10939 } 10940 10941 if (Swapped) 10942 std::swap(BasePtr, Offset); 10943 10944 // Now check for #3 and #4. 10945 bool RealUse = false; 10946 10947 for (SDNode *Use : Ptr.getNode()->uses()) { 10948 if (Use == N) 10949 continue; 10950 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 10951 return false; 10952 10953 // If Ptr may be folded in addressing mode of other use, then it's 10954 // not profitable to do this transformation. 10955 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 10956 RealUse = true; 10957 } 10958 10959 if (!RealUse) 10960 return false; 10961 10962 SDValue Result; 10963 if (isLoad) 10964 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 10965 BasePtr, Offset, AM); 10966 else 10967 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 10968 BasePtr, Offset, AM); 10969 ++PreIndexedNodes; 10970 ++NodesCombined; 10971 DEBUG(dbgs() << "\nReplacing.4 "; 10972 N->dump(&DAG); 10973 dbgs() << "\nWith: "; 10974 Result.getNode()->dump(&DAG); 10975 dbgs() << '\n'); 10976 WorklistRemover DeadNodes(*this); 10977 if (isLoad) { 10978 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10979 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10980 } else { 10981 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10982 } 10983 10984 // Finally, since the node is now dead, remove it from the graph. 10985 deleteAndRecombine(N); 10986 10987 if (Swapped) 10988 std::swap(BasePtr, Offset); 10989 10990 // Replace other uses of BasePtr that can be updated to use Ptr 10991 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 10992 unsigned OffsetIdx = 1; 10993 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 10994 OffsetIdx = 0; 10995 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 10996 BasePtr.getNode() && "Expected BasePtr operand"); 10997 10998 // We need to replace ptr0 in the following expression: 10999 // x0 * offset0 + y0 * ptr0 = t0 11000 // knowing that 11001 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 11002 // 11003 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 11004 // indexed load/store and the expresion that needs to be re-written. 11005 // 11006 // Therefore, we have: 11007 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 11008 11009 ConstantSDNode *CN = 11010 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 11011 int X0, X1, Y0, Y1; 11012 const APInt &Offset0 = CN->getAPIntValue(); 11013 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 11014 11015 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 11016 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 11017 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 11018 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 11019 11020 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 11021 11022 APInt CNV = Offset0; 11023 if (X0 < 0) CNV = -CNV; 11024 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 11025 else CNV = CNV - Offset1; 11026 11027 SDLoc DL(OtherUses[i]); 11028 11029 // We can now generate the new expression. 11030 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 11031 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 11032 11033 SDValue NewUse = DAG.getNode(Opcode, 11034 DL, 11035 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 11036 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 11037 deleteAndRecombine(OtherUses[i]); 11038 } 11039 11040 // Replace the uses of Ptr with uses of the updated base value. 11041 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 11042 deleteAndRecombine(Ptr.getNode()); 11043 11044 return true; 11045 } 11046 11047 /// Try to combine a load/store with a add/sub of the base pointer node into a 11048 /// post-indexed load/store. The transformation folded the add/subtract into the 11049 /// new indexed load/store effectively and all of its uses are redirected to the 11050 /// new load/store. 11051 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 11052 if (Level < AfterLegalizeDAG) 11053 return false; 11054 11055 bool isLoad = true; 11056 SDValue Ptr; 11057 EVT VT; 11058 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11059 if (LD->isIndexed()) 11060 return false; 11061 VT = LD->getMemoryVT(); 11062 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 11063 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 11064 return false; 11065 Ptr = LD->getBasePtr(); 11066 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11067 if (ST->isIndexed()) 11068 return false; 11069 VT = ST->getMemoryVT(); 11070 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 11071 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 11072 return false; 11073 Ptr = ST->getBasePtr(); 11074 isLoad = false; 11075 } else { 11076 return false; 11077 } 11078 11079 if (Ptr.getNode()->hasOneUse()) 11080 return false; 11081 11082 for (SDNode *Op : Ptr.getNode()->uses()) { 11083 if (Op == N || 11084 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 11085 continue; 11086 11087 SDValue BasePtr; 11088 SDValue Offset; 11089 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11090 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 11091 // Don't create a indexed load / store with zero offset. 11092 if (isNullConstant(Offset)) 11093 continue; 11094 11095 // Try turning it into a post-indexed load / store except when 11096 // 1) All uses are load / store ops that use it as base ptr (and 11097 // it may be folded as addressing mmode). 11098 // 2) Op must be independent of N, i.e. Op is neither a predecessor 11099 // nor a successor of N. Otherwise, if Op is folded that would 11100 // create a cycle. 11101 11102 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11103 continue; 11104 11105 // Check for #1. 11106 bool TryNext = false; 11107 for (SDNode *Use : BasePtr.getNode()->uses()) { 11108 if (Use == Ptr.getNode()) 11109 continue; 11110 11111 // If all the uses are load / store addresses, then don't do the 11112 // transformation. 11113 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 11114 bool RealUse = false; 11115 for (SDNode *UseUse : Use->uses()) { 11116 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 11117 RealUse = true; 11118 } 11119 11120 if (!RealUse) { 11121 TryNext = true; 11122 break; 11123 } 11124 } 11125 } 11126 11127 if (TryNext) 11128 continue; 11129 11130 // Check for #2 11131 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 11132 SDValue Result = isLoad 11133 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11134 BasePtr, Offset, AM) 11135 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11136 BasePtr, Offset, AM); 11137 ++PostIndexedNodes; 11138 ++NodesCombined; 11139 DEBUG(dbgs() << "\nReplacing.5 "; 11140 N->dump(&DAG); 11141 dbgs() << "\nWith: "; 11142 Result.getNode()->dump(&DAG); 11143 dbgs() << '\n'); 11144 WorklistRemover DeadNodes(*this); 11145 if (isLoad) { 11146 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11147 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11148 } else { 11149 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11150 } 11151 11152 // Finally, since the node is now dead, remove it from the graph. 11153 deleteAndRecombine(N); 11154 11155 // Replace the uses of Use with uses of the updated base value. 11156 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 11157 Result.getValue(isLoad ? 1 : 0)); 11158 deleteAndRecombine(Op); 11159 return true; 11160 } 11161 } 11162 } 11163 11164 return false; 11165 } 11166 11167 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 11168 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 11169 ISD::MemIndexedMode AM = LD->getAddressingMode(); 11170 assert(AM != ISD::UNINDEXED); 11171 SDValue BP = LD->getOperand(1); 11172 SDValue Inc = LD->getOperand(2); 11173 11174 // Some backends use TargetConstants for load offsets, but don't expect 11175 // TargetConstants in general ADD nodes. We can convert these constants into 11176 // regular Constants (if the constant is not opaque). 11177 assert((Inc.getOpcode() != ISD::TargetConstant || 11178 !cast<ConstantSDNode>(Inc)->isOpaque()) && 11179 "Cannot split out indexing using opaque target constants"); 11180 if (Inc.getOpcode() == ISD::TargetConstant) { 11181 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 11182 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 11183 ConstInc->getValueType(0)); 11184 } 11185 11186 unsigned Opc = 11187 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 11188 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 11189 } 11190 11191 SDValue DAGCombiner::visitLOAD(SDNode *N) { 11192 LoadSDNode *LD = cast<LoadSDNode>(N); 11193 SDValue Chain = LD->getChain(); 11194 SDValue Ptr = LD->getBasePtr(); 11195 11196 // If load is not volatile and there are no uses of the loaded value (and 11197 // the updated indexed value in case of indexed loads), change uses of the 11198 // chain value into uses of the chain input (i.e. delete the dead load). 11199 if (!LD->isVolatile()) { 11200 if (N->getValueType(1) == MVT::Other) { 11201 // Unindexed loads. 11202 if (!N->hasAnyUseOfValue(0)) { 11203 // It's not safe to use the two value CombineTo variant here. e.g. 11204 // v1, chain2 = load chain1, loc 11205 // v2, chain3 = load chain2, loc 11206 // v3 = add v2, c 11207 // Now we replace use of chain2 with chain1. This makes the second load 11208 // isomorphic to the one we are deleting, and thus makes this load live. 11209 DEBUG(dbgs() << "\nReplacing.6 "; 11210 N->dump(&DAG); 11211 dbgs() << "\nWith chain: "; 11212 Chain.getNode()->dump(&DAG); 11213 dbgs() << "\n"); 11214 WorklistRemover DeadNodes(*this); 11215 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11216 AddUsersToWorklist(Chain.getNode()); 11217 if (N->use_empty()) 11218 deleteAndRecombine(N); 11219 11220 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11221 } 11222 } else { 11223 // Indexed loads. 11224 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 11225 11226 // If this load has an opaque TargetConstant offset, then we cannot split 11227 // the indexing into an add/sub directly (that TargetConstant may not be 11228 // valid for a different type of node, and we cannot convert an opaque 11229 // target constant into a regular constant). 11230 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 11231 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 11232 11233 if (!N->hasAnyUseOfValue(0) && 11234 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 11235 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 11236 SDValue Index; 11237 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 11238 Index = SplitIndexingFromLoad(LD); 11239 // Try to fold the base pointer arithmetic into subsequent loads and 11240 // stores. 11241 AddUsersToWorklist(N); 11242 } else 11243 Index = DAG.getUNDEF(N->getValueType(1)); 11244 DEBUG(dbgs() << "\nReplacing.7 "; 11245 N->dump(&DAG); 11246 dbgs() << "\nWith: "; 11247 Undef.getNode()->dump(&DAG); 11248 dbgs() << " and 2 other values\n"); 11249 WorklistRemover DeadNodes(*this); 11250 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 11251 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 11252 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 11253 deleteAndRecombine(N); 11254 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11255 } 11256 } 11257 } 11258 11259 // If this load is directly stored, replace the load value with the stored 11260 // value. 11261 // TODO: Handle store large -> read small portion. 11262 // TODO: Handle TRUNCSTORE/LOADEXT 11263 if (OptLevel != CodeGenOpt::None && 11264 ISD::isNormalLoad(N) && !LD->isVolatile()) { 11265 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 11266 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 11267 if (PrevST->getBasePtr() == Ptr && 11268 PrevST->getValue().getValueType() == N->getValueType(0)) 11269 return CombineTo(N, PrevST->getOperand(1), Chain); 11270 } 11271 } 11272 11273 // Try to infer better alignment information than the load already has. 11274 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 11275 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11276 if (Align > LD->getMemOperand()->getBaseAlignment()) { 11277 SDValue NewLoad = DAG.getExtLoad( 11278 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 11279 LD->getPointerInfo(), LD->getMemoryVT(), Align, 11280 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11281 if (NewLoad.getNode() != N) 11282 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 11283 } 11284 } 11285 } 11286 11287 if (LD->isUnindexed()) { 11288 // Walk up chain skipping non-aliasing memory nodes. 11289 SDValue BetterChain = FindBetterChain(N, Chain); 11290 11291 // If there is a better chain. 11292 if (Chain != BetterChain) { 11293 SDValue ReplLoad; 11294 11295 // Replace the chain to void dependency. 11296 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 11297 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 11298 BetterChain, Ptr, LD->getMemOperand()); 11299 } else { 11300 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 11301 LD->getValueType(0), 11302 BetterChain, Ptr, LD->getMemoryVT(), 11303 LD->getMemOperand()); 11304 } 11305 11306 // Create token factor to keep old chain connected. 11307 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11308 MVT::Other, Chain, ReplLoad.getValue(1)); 11309 11310 // Make sure the new and old chains are cleaned up. 11311 AddToWorklist(Token.getNode()); 11312 11313 // Replace uses with load result and token factor. Don't add users 11314 // to work list. 11315 return CombineTo(N, ReplLoad.getValue(0), Token, false); 11316 } 11317 } 11318 11319 // Try transforming N to an indexed load. 11320 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11321 return SDValue(N, 0); 11322 11323 // Try to slice up N to more direct loads if the slices are mapped to 11324 // different register banks or pairing can take place. 11325 if (SliceUpLoad(N)) 11326 return SDValue(N, 0); 11327 11328 return SDValue(); 11329 } 11330 11331 namespace { 11332 /// \brief Helper structure used to slice a load in smaller loads. 11333 /// Basically a slice is obtained from the following sequence: 11334 /// Origin = load Ty1, Base 11335 /// Shift = srl Ty1 Origin, CstTy Amount 11336 /// Inst = trunc Shift to Ty2 11337 /// 11338 /// Then, it will be rewriten into: 11339 /// Slice = load SliceTy, Base + SliceOffset 11340 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 11341 /// 11342 /// SliceTy is deduced from the number of bits that are actually used to 11343 /// build Inst. 11344 struct LoadedSlice { 11345 /// \brief Helper structure used to compute the cost of a slice. 11346 struct Cost { 11347 /// Are we optimizing for code size. 11348 bool ForCodeSize; 11349 /// Various cost. 11350 unsigned Loads; 11351 unsigned Truncates; 11352 unsigned CrossRegisterBanksCopies; 11353 unsigned ZExts; 11354 unsigned Shift; 11355 11356 Cost(bool ForCodeSize = false) 11357 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 11358 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 11359 11360 /// \brief Get the cost of one isolated slice. 11361 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 11362 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 11363 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 11364 EVT TruncType = LS.Inst->getValueType(0); 11365 EVT LoadedType = LS.getLoadedType(); 11366 if (TruncType != LoadedType && 11367 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 11368 ZExts = 1; 11369 } 11370 11371 /// \brief Account for slicing gain in the current cost. 11372 /// Slicing provide a few gains like removing a shift or a 11373 /// truncate. This method allows to grow the cost of the original 11374 /// load with the gain from this slice. 11375 void addSliceGain(const LoadedSlice &LS) { 11376 // Each slice saves a truncate. 11377 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 11378 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 11379 LS.Inst->getValueType(0))) 11380 ++Truncates; 11381 // If there is a shift amount, this slice gets rid of it. 11382 if (LS.Shift) 11383 ++Shift; 11384 // If this slice can merge a cross register bank copy, account for it. 11385 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 11386 ++CrossRegisterBanksCopies; 11387 } 11388 11389 Cost &operator+=(const Cost &RHS) { 11390 Loads += RHS.Loads; 11391 Truncates += RHS.Truncates; 11392 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 11393 ZExts += RHS.ZExts; 11394 Shift += RHS.Shift; 11395 return *this; 11396 } 11397 11398 bool operator==(const Cost &RHS) const { 11399 return Loads == RHS.Loads && Truncates == RHS.Truncates && 11400 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 11401 ZExts == RHS.ZExts && Shift == RHS.Shift; 11402 } 11403 11404 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 11405 11406 bool operator<(const Cost &RHS) const { 11407 // Assume cross register banks copies are as expensive as loads. 11408 // FIXME: Do we want some more target hooks? 11409 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 11410 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 11411 // Unless we are optimizing for code size, consider the 11412 // expensive operation first. 11413 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 11414 return ExpensiveOpsLHS < ExpensiveOpsRHS; 11415 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 11416 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 11417 } 11418 11419 bool operator>(const Cost &RHS) const { return RHS < *this; } 11420 11421 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 11422 11423 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 11424 }; 11425 // The last instruction that represent the slice. This should be a 11426 // truncate instruction. 11427 SDNode *Inst; 11428 // The original load instruction. 11429 LoadSDNode *Origin; 11430 // The right shift amount in bits from the original load. 11431 unsigned Shift; 11432 // The DAG from which Origin came from. 11433 // This is used to get some contextual information about legal types, etc. 11434 SelectionDAG *DAG; 11435 11436 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 11437 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 11438 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 11439 11440 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 11441 /// \return Result is \p BitWidth and has used bits set to 1 and 11442 /// not used bits set to 0. 11443 APInt getUsedBits() const { 11444 // Reproduce the trunc(lshr) sequence: 11445 // - Start from the truncated value. 11446 // - Zero extend to the desired bit width. 11447 // - Shift left. 11448 assert(Origin && "No original load to compare against."); 11449 unsigned BitWidth = Origin->getValueSizeInBits(0); 11450 assert(Inst && "This slice is not bound to an instruction"); 11451 assert(Inst->getValueSizeInBits(0) <= BitWidth && 11452 "Extracted slice is bigger than the whole type!"); 11453 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 11454 UsedBits.setAllBits(); 11455 UsedBits = UsedBits.zext(BitWidth); 11456 UsedBits <<= Shift; 11457 return UsedBits; 11458 } 11459 11460 /// \brief Get the size of the slice to be loaded in bytes. 11461 unsigned getLoadedSize() const { 11462 unsigned SliceSize = getUsedBits().countPopulation(); 11463 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 11464 return SliceSize / 8; 11465 } 11466 11467 /// \brief Get the type that will be loaded for this slice. 11468 /// Note: This may not be the final type for the slice. 11469 EVT getLoadedType() const { 11470 assert(DAG && "Missing context"); 11471 LLVMContext &Ctxt = *DAG->getContext(); 11472 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 11473 } 11474 11475 /// \brief Get the alignment of the load used for this slice. 11476 unsigned getAlignment() const { 11477 unsigned Alignment = Origin->getAlignment(); 11478 unsigned Offset = getOffsetFromBase(); 11479 if (Offset != 0) 11480 Alignment = MinAlign(Alignment, Alignment + Offset); 11481 return Alignment; 11482 } 11483 11484 /// \brief Check if this slice can be rewritten with legal operations. 11485 bool isLegal() const { 11486 // An invalid slice is not legal. 11487 if (!Origin || !Inst || !DAG) 11488 return false; 11489 11490 // Offsets are for indexed load only, we do not handle that. 11491 if (!Origin->getOffset().isUndef()) 11492 return false; 11493 11494 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11495 11496 // Check that the type is legal. 11497 EVT SliceType = getLoadedType(); 11498 if (!TLI.isTypeLegal(SliceType)) 11499 return false; 11500 11501 // Check that the load is legal for this type. 11502 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 11503 return false; 11504 11505 // Check that the offset can be computed. 11506 // 1. Check its type. 11507 EVT PtrType = Origin->getBasePtr().getValueType(); 11508 if (PtrType == MVT::Untyped || PtrType.isExtended()) 11509 return false; 11510 11511 // 2. Check that it fits in the immediate. 11512 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 11513 return false; 11514 11515 // 3. Check that the computation is legal. 11516 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 11517 return false; 11518 11519 // Check that the zext is legal if it needs one. 11520 EVT TruncateType = Inst->getValueType(0); 11521 if (TruncateType != SliceType && 11522 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 11523 return false; 11524 11525 return true; 11526 } 11527 11528 /// \brief Get the offset in bytes of this slice in the original chunk of 11529 /// bits. 11530 /// \pre DAG != nullptr. 11531 uint64_t getOffsetFromBase() const { 11532 assert(DAG && "Missing context."); 11533 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 11534 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 11535 uint64_t Offset = Shift / 8; 11536 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 11537 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 11538 "The size of the original loaded type is not a multiple of a" 11539 " byte."); 11540 // If Offset is bigger than TySizeInBytes, it means we are loading all 11541 // zeros. This should have been optimized before in the process. 11542 assert(TySizeInBytes > Offset && 11543 "Invalid shift amount for given loaded size"); 11544 if (IsBigEndian) 11545 Offset = TySizeInBytes - Offset - getLoadedSize(); 11546 return Offset; 11547 } 11548 11549 /// \brief Generate the sequence of instructions to load the slice 11550 /// represented by this object and redirect the uses of this slice to 11551 /// this new sequence of instructions. 11552 /// \pre this->Inst && this->Origin are valid Instructions and this 11553 /// object passed the legal check: LoadedSlice::isLegal returned true. 11554 /// \return The last instruction of the sequence used to load the slice. 11555 SDValue loadSlice() const { 11556 assert(Inst && Origin && "Unable to replace a non-existing slice."); 11557 const SDValue &OldBaseAddr = Origin->getBasePtr(); 11558 SDValue BaseAddr = OldBaseAddr; 11559 // Get the offset in that chunk of bytes w.r.t. the endianness. 11560 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 11561 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 11562 if (Offset) { 11563 // BaseAddr = BaseAddr + Offset. 11564 EVT ArithType = BaseAddr.getValueType(); 11565 SDLoc DL(Origin); 11566 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 11567 DAG->getConstant(Offset, DL, ArithType)); 11568 } 11569 11570 // Create the type of the loaded slice according to its size. 11571 EVT SliceType = getLoadedType(); 11572 11573 // Create the load for the slice. 11574 SDValue LastInst = 11575 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 11576 Origin->getPointerInfo().getWithOffset(Offset), 11577 getAlignment(), Origin->getMemOperand()->getFlags()); 11578 // If the final type is not the same as the loaded type, this means that 11579 // we have to pad with zero. Create a zero extend for that. 11580 EVT FinalType = Inst->getValueType(0); 11581 if (SliceType != FinalType) 11582 LastInst = 11583 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 11584 return LastInst; 11585 } 11586 11587 /// \brief Check if this slice can be merged with an expensive cross register 11588 /// bank copy. E.g., 11589 /// i = load i32 11590 /// f = bitcast i32 i to float 11591 bool canMergeExpensiveCrossRegisterBankCopy() const { 11592 if (!Inst || !Inst->hasOneUse()) 11593 return false; 11594 SDNode *Use = *Inst->use_begin(); 11595 if (Use->getOpcode() != ISD::BITCAST) 11596 return false; 11597 assert(DAG && "Missing context"); 11598 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11599 EVT ResVT = Use->getValueType(0); 11600 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 11601 const TargetRegisterClass *ArgRC = 11602 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 11603 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 11604 return false; 11605 11606 // At this point, we know that we perform a cross-register-bank copy. 11607 // Check if it is expensive. 11608 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 11609 // Assume bitcasts are cheap, unless both register classes do not 11610 // explicitly share a common sub class. 11611 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 11612 return false; 11613 11614 // Check if it will be merged with the load. 11615 // 1. Check the alignment constraint. 11616 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 11617 ResVT.getTypeForEVT(*DAG->getContext())); 11618 11619 if (RequiredAlignment > getAlignment()) 11620 return false; 11621 11622 // 2. Check that the load is a legal operation for that type. 11623 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 11624 return false; 11625 11626 // 3. Check that we do not have a zext in the way. 11627 if (Inst->getValueType(0) != getLoadedType()) 11628 return false; 11629 11630 return true; 11631 } 11632 }; 11633 } 11634 11635 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 11636 /// \p UsedBits looks like 0..0 1..1 0..0. 11637 static bool areUsedBitsDense(const APInt &UsedBits) { 11638 // If all the bits are one, this is dense! 11639 if (UsedBits.isAllOnesValue()) 11640 return true; 11641 11642 // Get rid of the unused bits on the right. 11643 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 11644 // Get rid of the unused bits on the left. 11645 if (NarrowedUsedBits.countLeadingZeros()) 11646 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 11647 // Check that the chunk of bits is completely used. 11648 return NarrowedUsedBits.isAllOnesValue(); 11649 } 11650 11651 /// \brief Check whether or not \p First and \p Second are next to each other 11652 /// in memory. This means that there is no hole between the bits loaded 11653 /// by \p First and the bits loaded by \p Second. 11654 static bool areSlicesNextToEachOther(const LoadedSlice &First, 11655 const LoadedSlice &Second) { 11656 assert(First.Origin == Second.Origin && First.Origin && 11657 "Unable to match different memory origins."); 11658 APInt UsedBits = First.getUsedBits(); 11659 assert((UsedBits & Second.getUsedBits()) == 0 && 11660 "Slices are not supposed to overlap."); 11661 UsedBits |= Second.getUsedBits(); 11662 return areUsedBitsDense(UsedBits); 11663 } 11664 11665 /// \brief Adjust the \p GlobalLSCost according to the target 11666 /// paring capabilities and the layout of the slices. 11667 /// \pre \p GlobalLSCost should account for at least as many loads as 11668 /// there is in the slices in \p LoadedSlices. 11669 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11670 LoadedSlice::Cost &GlobalLSCost) { 11671 unsigned NumberOfSlices = LoadedSlices.size(); 11672 // If there is less than 2 elements, no pairing is possible. 11673 if (NumberOfSlices < 2) 11674 return; 11675 11676 // Sort the slices so that elements that are likely to be next to each 11677 // other in memory are next to each other in the list. 11678 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 11679 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 11680 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 11681 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 11682 }); 11683 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 11684 // First (resp. Second) is the first (resp. Second) potentially candidate 11685 // to be placed in a paired load. 11686 const LoadedSlice *First = nullptr; 11687 const LoadedSlice *Second = nullptr; 11688 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 11689 // Set the beginning of the pair. 11690 First = Second) { 11691 11692 Second = &LoadedSlices[CurrSlice]; 11693 11694 // If First is NULL, it means we start a new pair. 11695 // Get to the next slice. 11696 if (!First) 11697 continue; 11698 11699 EVT LoadedType = First->getLoadedType(); 11700 11701 // If the types of the slices are different, we cannot pair them. 11702 if (LoadedType != Second->getLoadedType()) 11703 continue; 11704 11705 // Check if the target supplies paired loads for this type. 11706 unsigned RequiredAlignment = 0; 11707 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 11708 // move to the next pair, this type is hopeless. 11709 Second = nullptr; 11710 continue; 11711 } 11712 // Check if we meet the alignment requirement. 11713 if (RequiredAlignment > First->getAlignment()) 11714 continue; 11715 11716 // Check that both loads are next to each other in memory. 11717 if (!areSlicesNextToEachOther(*First, *Second)) 11718 continue; 11719 11720 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 11721 --GlobalLSCost.Loads; 11722 // Move to the next pair. 11723 Second = nullptr; 11724 } 11725 } 11726 11727 /// \brief Check the profitability of all involved LoadedSlice. 11728 /// Currently, it is considered profitable if there is exactly two 11729 /// involved slices (1) which are (2) next to each other in memory, and 11730 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 11731 /// 11732 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 11733 /// the elements themselves. 11734 /// 11735 /// FIXME: When the cost model will be mature enough, we can relax 11736 /// constraints (1) and (2). 11737 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11738 const APInt &UsedBits, bool ForCodeSize) { 11739 unsigned NumberOfSlices = LoadedSlices.size(); 11740 if (StressLoadSlicing) 11741 return NumberOfSlices > 1; 11742 11743 // Check (1). 11744 if (NumberOfSlices != 2) 11745 return false; 11746 11747 // Check (2). 11748 if (!areUsedBitsDense(UsedBits)) 11749 return false; 11750 11751 // Check (3). 11752 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 11753 // The original code has one big load. 11754 OrigCost.Loads = 1; 11755 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 11756 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 11757 // Accumulate the cost of all the slices. 11758 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 11759 GlobalSlicingCost += SliceCost; 11760 11761 // Account as cost in the original configuration the gain obtained 11762 // with the current slices. 11763 OrigCost.addSliceGain(LS); 11764 } 11765 11766 // If the target supports paired load, adjust the cost accordingly. 11767 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 11768 return OrigCost > GlobalSlicingCost; 11769 } 11770 11771 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 11772 /// operations, split it in the various pieces being extracted. 11773 /// 11774 /// This sort of thing is introduced by SROA. 11775 /// This slicing takes care not to insert overlapping loads. 11776 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 11777 bool DAGCombiner::SliceUpLoad(SDNode *N) { 11778 if (Level < AfterLegalizeDAG) 11779 return false; 11780 11781 LoadSDNode *LD = cast<LoadSDNode>(N); 11782 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 11783 !LD->getValueType(0).isInteger()) 11784 return false; 11785 11786 // Keep track of already used bits to detect overlapping values. 11787 // In that case, we will just abort the transformation. 11788 APInt UsedBits(LD->getValueSizeInBits(0), 0); 11789 11790 SmallVector<LoadedSlice, 4> LoadedSlices; 11791 11792 // Check if this load is used as several smaller chunks of bits. 11793 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 11794 // of computation for each trunc. 11795 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 11796 UI != UIEnd; ++UI) { 11797 // Skip the uses of the chain. 11798 if (UI.getUse().getResNo() != 0) 11799 continue; 11800 11801 SDNode *User = *UI; 11802 unsigned Shift = 0; 11803 11804 // Check if this is a trunc(lshr). 11805 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 11806 isa<ConstantSDNode>(User->getOperand(1))) { 11807 Shift = User->getConstantOperandVal(1); 11808 User = *User->use_begin(); 11809 } 11810 11811 // At this point, User is a Truncate, iff we encountered, trunc or 11812 // trunc(lshr). 11813 if (User->getOpcode() != ISD::TRUNCATE) 11814 return false; 11815 11816 // The width of the type must be a power of 2 and greater than 8-bits. 11817 // Otherwise the load cannot be represented in LLVM IR. 11818 // Moreover, if we shifted with a non-8-bits multiple, the slice 11819 // will be across several bytes. We do not support that. 11820 unsigned Width = User->getValueSizeInBits(0); 11821 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 11822 return 0; 11823 11824 // Build the slice for this chain of computations. 11825 LoadedSlice LS(User, LD, Shift, &DAG); 11826 APInt CurrentUsedBits = LS.getUsedBits(); 11827 11828 // Check if this slice overlaps with another. 11829 if ((CurrentUsedBits & UsedBits) != 0) 11830 return false; 11831 // Update the bits used globally. 11832 UsedBits |= CurrentUsedBits; 11833 11834 // Check if the new slice would be legal. 11835 if (!LS.isLegal()) 11836 return false; 11837 11838 // Record the slice. 11839 LoadedSlices.push_back(LS); 11840 } 11841 11842 // Abort slicing if it does not seem to be profitable. 11843 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 11844 return false; 11845 11846 ++SlicedLoads; 11847 11848 // Rewrite each chain to use an independent load. 11849 // By construction, each chain can be represented by a unique load. 11850 11851 // Prepare the argument for the new token factor for all the slices. 11852 SmallVector<SDValue, 8> ArgChains; 11853 for (SmallVectorImpl<LoadedSlice>::const_iterator 11854 LSIt = LoadedSlices.begin(), 11855 LSItEnd = LoadedSlices.end(); 11856 LSIt != LSItEnd; ++LSIt) { 11857 SDValue SliceInst = LSIt->loadSlice(); 11858 CombineTo(LSIt->Inst, SliceInst, true); 11859 if (SliceInst.getOpcode() != ISD::LOAD) 11860 SliceInst = SliceInst.getOperand(0); 11861 assert(SliceInst->getOpcode() == ISD::LOAD && 11862 "It takes more than a zext to get to the loaded slice!!"); 11863 ArgChains.push_back(SliceInst.getValue(1)); 11864 } 11865 11866 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 11867 ArgChains); 11868 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11869 AddToWorklist(Chain.getNode()); 11870 return true; 11871 } 11872 11873 /// Check to see if V is (and load (ptr), imm), where the load is having 11874 /// specific bytes cleared out. If so, return the byte size being masked out 11875 /// and the shift amount. 11876 static std::pair<unsigned, unsigned> 11877 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 11878 std::pair<unsigned, unsigned> Result(0, 0); 11879 11880 // Check for the structure we're looking for. 11881 if (V->getOpcode() != ISD::AND || 11882 !isa<ConstantSDNode>(V->getOperand(1)) || 11883 !ISD::isNormalLoad(V->getOperand(0).getNode())) 11884 return Result; 11885 11886 // Check the chain and pointer. 11887 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 11888 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 11889 11890 // The store should be chained directly to the load or be an operand of a 11891 // tokenfactor. 11892 if (LD == Chain.getNode()) 11893 ; // ok. 11894 else if (Chain->getOpcode() != ISD::TokenFactor) 11895 return Result; // Fail. 11896 else { 11897 bool isOk = false; 11898 for (const SDValue &ChainOp : Chain->op_values()) 11899 if (ChainOp.getNode() == LD) { 11900 isOk = true; 11901 break; 11902 } 11903 if (!isOk) return Result; 11904 } 11905 11906 // This only handles simple types. 11907 if (V.getValueType() != MVT::i16 && 11908 V.getValueType() != MVT::i32 && 11909 V.getValueType() != MVT::i64) 11910 return Result; 11911 11912 // Check the constant mask. Invert it so that the bits being masked out are 11913 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 11914 // follow the sign bit for uniformity. 11915 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 11916 unsigned NotMaskLZ = countLeadingZeros(NotMask); 11917 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 11918 unsigned NotMaskTZ = countTrailingZeros(NotMask); 11919 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 11920 if (NotMaskLZ == 64) return Result; // All zero mask. 11921 11922 // See if we have a continuous run of bits. If so, we have 0*1+0* 11923 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 11924 return Result; 11925 11926 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 11927 if (V.getValueType() != MVT::i64 && NotMaskLZ) 11928 NotMaskLZ -= 64-V.getValueSizeInBits(); 11929 11930 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 11931 switch (MaskedBytes) { 11932 case 1: 11933 case 2: 11934 case 4: break; 11935 default: return Result; // All one mask, or 5-byte mask. 11936 } 11937 11938 // Verify that the first bit starts at a multiple of mask so that the access 11939 // is aligned the same as the access width. 11940 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 11941 11942 Result.first = MaskedBytes; 11943 Result.second = NotMaskTZ/8; 11944 return Result; 11945 } 11946 11947 11948 /// Check to see if IVal is something that provides a value as specified by 11949 /// MaskInfo. If so, replace the specified store with a narrower store of 11950 /// truncated IVal. 11951 static SDNode * 11952 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 11953 SDValue IVal, StoreSDNode *St, 11954 DAGCombiner *DC) { 11955 unsigned NumBytes = MaskInfo.first; 11956 unsigned ByteShift = MaskInfo.second; 11957 SelectionDAG &DAG = DC->getDAG(); 11958 11959 // Check to see if IVal is all zeros in the part being masked in by the 'or' 11960 // that uses this. If not, this is not a replacement. 11961 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 11962 ByteShift*8, (ByteShift+NumBytes)*8); 11963 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 11964 11965 // Check that it is legal on the target to do this. It is legal if the new 11966 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 11967 // legalization. 11968 MVT VT = MVT::getIntegerVT(NumBytes*8); 11969 if (!DC->isTypeLegal(VT)) 11970 return nullptr; 11971 11972 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 11973 // shifted by ByteShift and truncated down to NumBytes. 11974 if (ByteShift) { 11975 SDLoc DL(IVal); 11976 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 11977 DAG.getConstant(ByteShift*8, DL, 11978 DC->getShiftAmountTy(IVal.getValueType()))); 11979 } 11980 11981 // Figure out the offset for the store and the alignment of the access. 11982 unsigned StOffset; 11983 unsigned NewAlign = St->getAlignment(); 11984 11985 if (DAG.getDataLayout().isLittleEndian()) 11986 StOffset = ByteShift; 11987 else 11988 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 11989 11990 SDValue Ptr = St->getBasePtr(); 11991 if (StOffset) { 11992 SDLoc DL(IVal); 11993 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 11994 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 11995 NewAlign = MinAlign(NewAlign, StOffset); 11996 } 11997 11998 // Truncate down to the new size. 11999 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 12000 12001 ++OpsNarrowed; 12002 return DAG 12003 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 12004 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 12005 .getNode(); 12006 } 12007 12008 12009 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 12010 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 12011 /// narrowing the load and store if it would end up being a win for performance 12012 /// or code size. 12013 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 12014 StoreSDNode *ST = cast<StoreSDNode>(N); 12015 if (ST->isVolatile()) 12016 return SDValue(); 12017 12018 SDValue Chain = ST->getChain(); 12019 SDValue Value = ST->getValue(); 12020 SDValue Ptr = ST->getBasePtr(); 12021 EVT VT = Value.getValueType(); 12022 12023 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 12024 return SDValue(); 12025 12026 unsigned Opc = Value.getOpcode(); 12027 12028 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 12029 // is a byte mask indicating a consecutive number of bytes, check to see if 12030 // Y is known to provide just those bytes. If so, we try to replace the 12031 // load + replace + store sequence with a single (narrower) store, which makes 12032 // the load dead. 12033 if (Opc == ISD::OR) { 12034 std::pair<unsigned, unsigned> MaskedLoad; 12035 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 12036 if (MaskedLoad.first) 12037 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12038 Value.getOperand(1), ST,this)) 12039 return SDValue(NewST, 0); 12040 12041 // Or is commutative, so try swapping X and Y. 12042 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 12043 if (MaskedLoad.first) 12044 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12045 Value.getOperand(0), ST,this)) 12046 return SDValue(NewST, 0); 12047 } 12048 12049 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 12050 Value.getOperand(1).getOpcode() != ISD::Constant) 12051 return SDValue(); 12052 12053 SDValue N0 = Value.getOperand(0); 12054 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12055 Chain == SDValue(N0.getNode(), 1)) { 12056 LoadSDNode *LD = cast<LoadSDNode>(N0); 12057 if (LD->getBasePtr() != Ptr || 12058 LD->getPointerInfo().getAddrSpace() != 12059 ST->getPointerInfo().getAddrSpace()) 12060 return SDValue(); 12061 12062 // Find the type to narrow it the load / op / store to. 12063 SDValue N1 = Value.getOperand(1); 12064 unsigned BitWidth = N1.getValueSizeInBits(); 12065 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 12066 if (Opc == ISD::AND) 12067 Imm ^= APInt::getAllOnesValue(BitWidth); 12068 if (Imm == 0 || Imm.isAllOnesValue()) 12069 return SDValue(); 12070 unsigned ShAmt = Imm.countTrailingZeros(); 12071 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 12072 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 12073 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12074 // The narrowing should be profitable, the load/store operation should be 12075 // legal (or custom) and the store size should be equal to the NewVT width. 12076 while (NewBW < BitWidth && 12077 (NewVT.getStoreSizeInBits() != NewBW || 12078 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 12079 !TLI.isNarrowingProfitable(VT, NewVT))) { 12080 NewBW = NextPowerOf2(NewBW); 12081 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12082 } 12083 if (NewBW >= BitWidth) 12084 return SDValue(); 12085 12086 // If the lsb changed does not start at the type bitwidth boundary, 12087 // start at the previous one. 12088 if (ShAmt % NewBW) 12089 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 12090 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 12091 std::min(BitWidth, ShAmt + NewBW)); 12092 if ((Imm & Mask) == Imm) { 12093 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 12094 if (Opc == ISD::AND) 12095 NewImm ^= APInt::getAllOnesValue(NewBW); 12096 uint64_t PtrOff = ShAmt / 8; 12097 // For big endian targets, we need to adjust the offset to the pointer to 12098 // load the correct bytes. 12099 if (DAG.getDataLayout().isBigEndian()) 12100 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 12101 12102 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 12103 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 12104 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 12105 return SDValue(); 12106 12107 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 12108 Ptr.getValueType(), Ptr, 12109 DAG.getConstant(PtrOff, SDLoc(LD), 12110 Ptr.getValueType())); 12111 SDValue NewLD = 12112 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 12113 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 12114 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12115 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 12116 DAG.getConstant(NewImm, SDLoc(Value), 12117 NewVT)); 12118 SDValue NewST = 12119 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 12120 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 12121 12122 AddToWorklist(NewPtr.getNode()); 12123 AddToWorklist(NewLD.getNode()); 12124 AddToWorklist(NewVal.getNode()); 12125 WorklistRemover DeadNodes(*this); 12126 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 12127 ++OpsNarrowed; 12128 return NewST; 12129 } 12130 } 12131 12132 return SDValue(); 12133 } 12134 12135 /// For a given floating point load / store pair, if the load value isn't used 12136 /// by any other operations, then consider transforming the pair to integer 12137 /// load / store operations if the target deems the transformation profitable. 12138 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 12139 StoreSDNode *ST = cast<StoreSDNode>(N); 12140 SDValue Chain = ST->getChain(); 12141 SDValue Value = ST->getValue(); 12142 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 12143 Value.hasOneUse() && 12144 Chain == SDValue(Value.getNode(), 1)) { 12145 LoadSDNode *LD = cast<LoadSDNode>(Value); 12146 EVT VT = LD->getMemoryVT(); 12147 if (!VT.isFloatingPoint() || 12148 VT != ST->getMemoryVT() || 12149 LD->isNonTemporal() || 12150 ST->isNonTemporal() || 12151 LD->getPointerInfo().getAddrSpace() != 0 || 12152 ST->getPointerInfo().getAddrSpace() != 0) 12153 return SDValue(); 12154 12155 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 12156 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 12157 !TLI.isOperationLegal(ISD::STORE, IntVT) || 12158 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 12159 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 12160 return SDValue(); 12161 12162 unsigned LDAlign = LD->getAlignment(); 12163 unsigned STAlign = ST->getAlignment(); 12164 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 12165 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 12166 if (LDAlign < ABIAlign || STAlign < ABIAlign) 12167 return SDValue(); 12168 12169 SDValue NewLD = 12170 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 12171 LD->getPointerInfo(), LDAlign); 12172 12173 SDValue NewST = 12174 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 12175 ST->getPointerInfo(), STAlign); 12176 12177 AddToWorklist(NewLD.getNode()); 12178 AddToWorklist(NewST.getNode()); 12179 WorklistRemover DeadNodes(*this); 12180 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 12181 ++LdStFP2Int; 12182 return NewST; 12183 } 12184 12185 return SDValue(); 12186 } 12187 12188 // This is a helper function for visitMUL to check the profitability 12189 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 12190 // MulNode is the original multiply, AddNode is (add x, c1), 12191 // and ConstNode is c2. 12192 // 12193 // If the (add x, c1) has multiple uses, we could increase 12194 // the number of adds if we make this transformation. 12195 // It would only be worth doing this if we can remove a 12196 // multiply in the process. Check for that here. 12197 // To illustrate: 12198 // (A + c1) * c3 12199 // (A + c2) * c3 12200 // We're checking for cases where we have common "c3 * A" expressions. 12201 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 12202 SDValue &AddNode, 12203 SDValue &ConstNode) { 12204 APInt Val; 12205 12206 // If the add only has one use, this would be OK to do. 12207 if (AddNode.getNode()->hasOneUse()) 12208 return true; 12209 12210 // Walk all the users of the constant with which we're multiplying. 12211 for (SDNode *Use : ConstNode->uses()) { 12212 12213 if (Use == MulNode) // This use is the one we're on right now. Skip it. 12214 continue; 12215 12216 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 12217 SDNode *OtherOp; 12218 SDNode *MulVar = AddNode.getOperand(0).getNode(); 12219 12220 // OtherOp is what we're multiplying against the constant. 12221 if (Use->getOperand(0) == ConstNode) 12222 OtherOp = Use->getOperand(1).getNode(); 12223 else 12224 OtherOp = Use->getOperand(0).getNode(); 12225 12226 // Check to see if multiply is with the same operand of our "add". 12227 // 12228 // ConstNode = CONST 12229 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 12230 // ... 12231 // AddNode = (A + c1) <-- MulVar is A. 12232 // = AddNode * ConstNode <-- current visiting instruction. 12233 // 12234 // If we make this transformation, we will have a common 12235 // multiply (ConstNode * A) that we can save. 12236 if (OtherOp == MulVar) 12237 return true; 12238 12239 // Now check to see if a future expansion will give us a common 12240 // multiply. 12241 // 12242 // ConstNode = CONST 12243 // AddNode = (A + c1) 12244 // ... = AddNode * ConstNode <-- current visiting instruction. 12245 // ... 12246 // OtherOp = (A + c2) 12247 // Use = OtherOp * ConstNode <-- visiting Use. 12248 // 12249 // If we make this transformation, we will have a common 12250 // multiply (CONST * A) after we also do the same transformation 12251 // to the "t2" instruction. 12252 if (OtherOp->getOpcode() == ISD::ADD && 12253 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 12254 OtherOp->getOperand(0).getNode() == MulVar) 12255 return true; 12256 } 12257 } 12258 12259 // Didn't find a case where this would be profitable. 12260 return false; 12261 } 12262 12263 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 12264 unsigned NumStores) { 12265 SmallVector<SDValue, 8> Chains; 12266 SmallPtrSet<const SDNode *, 8> Visited; 12267 SDLoc StoreDL(StoreNodes[0].MemNode); 12268 12269 for (unsigned i = 0; i < NumStores; ++i) { 12270 Visited.insert(StoreNodes[i].MemNode); 12271 } 12272 12273 // don't include nodes that are children 12274 for (unsigned i = 0; i < NumStores; ++i) { 12275 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 12276 Chains.push_back(StoreNodes[i].MemNode->getChain()); 12277 } 12278 12279 assert(Chains.size() > 0 && "Chain should have generated a chain"); 12280 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 12281 } 12282 12283 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 12284 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 12285 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 12286 // Make sure we have something to merge. 12287 if (NumStores < 2) 12288 return false; 12289 12290 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12291 12292 // The latest Node in the DAG. 12293 SDLoc DL(StoreNodes[0].MemNode); 12294 12295 SDValue StoredVal; 12296 if (UseVector) { 12297 bool IsVec = MemVT.isVector(); 12298 unsigned Elts = NumStores; 12299 if (IsVec) { 12300 // When merging vector stores, get the total number of elements. 12301 Elts *= MemVT.getVectorNumElements(); 12302 } 12303 // Get the type for the merged vector store. 12304 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12305 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 12306 12307 if (IsConstantSrc) { 12308 SmallVector<SDValue, 8> BuildVector; 12309 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 12310 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 12311 SDValue Val = St->getValue(); 12312 if (MemVT.getScalarType().isInteger()) 12313 if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue())) 12314 Val = DAG.getConstant( 12315 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(), 12316 SDLoc(CFP), MemVT); 12317 BuildVector.push_back(Val); 12318 } 12319 StoredVal = DAG.getBuildVector(Ty, DL, BuildVector); 12320 } else { 12321 SmallVector<SDValue, 8> Ops; 12322 for (unsigned i = 0; i < NumStores; ++i) { 12323 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12324 SDValue Val = St->getValue(); 12325 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 12326 if (Val.getValueType() != MemVT) 12327 return false; 12328 Ops.push_back(Val); 12329 } 12330 12331 // Build the extracted vector elements back into a vector. 12332 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 12333 DL, Ty, Ops); } 12334 } else { 12335 // We should always use a vector store when merging extracted vector 12336 // elements, so this path implies a store of constants. 12337 assert(IsConstantSrc && "Merged vector elements should use vector store"); 12338 12339 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 12340 APInt StoreInt(SizeInBits, 0); 12341 12342 // Construct a single integer constant which is made of the smaller 12343 // constant inputs. 12344 bool IsLE = DAG.getDataLayout().isLittleEndian(); 12345 for (unsigned i = 0; i < NumStores; ++i) { 12346 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 12347 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 12348 12349 SDValue Val = St->getValue(); 12350 StoreInt <<= ElementSizeBytes * 8; 12351 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 12352 StoreInt |= C->getAPIntValue().zextOrTrunc(SizeInBits); 12353 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 12354 StoreInt |= C->getValueAPF().bitcastToAPInt().zextOrTrunc(SizeInBits); 12355 } else { 12356 llvm_unreachable("Invalid constant element type"); 12357 } 12358 } 12359 12360 // Create the new Load and Store operations. 12361 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 12362 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 12363 } 12364 12365 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12366 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 12367 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 12368 FirstInChain->getBasePtr(), 12369 FirstInChain->getPointerInfo(), 12370 FirstInChain->getAlignment()); 12371 12372 // Replace all merged stores with the new store. 12373 for (unsigned i = 0; i < NumStores; ++i) 12374 CombineTo(StoreNodes[i].MemNode, NewStore); 12375 12376 AddToWorklist(NewChain.getNode()); 12377 return true; 12378 } 12379 12380 void DAGCombiner::getStoreMergeCandidates( 12381 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12382 // This holds the base pointer, index, and the offset in bytes from the base 12383 // pointer. 12384 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 12385 EVT MemVT = St->getMemoryVT(); 12386 12387 // We must have a base and an offset. 12388 if (!BasePtr.Base.getNode()) 12389 return; 12390 12391 // Do not handle stores to undef base pointers. 12392 if (BasePtr.Base.isUndef()) 12393 return; 12394 12395 bool IsLoadSrc = isa<LoadSDNode>(St->getValue()); 12396 bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) || 12397 isa<ConstantFPSDNode>(St->getValue()); 12398 bool IsExtractVecSrc = 12399 (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12400 St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR); 12401 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool { 12402 if (Other->isVolatile() || Other->isIndexed()) 12403 return false; 12404 // We can merge constant floats to equivalent integers 12405 if (Other->getMemoryVT() != MemVT) 12406 if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) && 12407 isa<ConstantFPSDNode>(Other->getValue()))) 12408 return false; 12409 if (IsLoadSrc) 12410 if (!isa<LoadSDNode>(Other->getValue())) 12411 return false; 12412 if (IsConstantSrc) 12413 if (!(isa<ConstantSDNode>(Other->getValue()) || 12414 isa<ConstantFPSDNode>(Other->getValue()))) 12415 return false; 12416 if (IsExtractVecSrc) 12417 if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12418 Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR)) 12419 return false; 12420 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG); 12421 return (Ptr.equalBaseIndex(BasePtr)); 12422 }; 12423 // We looking for a root node which is an ancestor to all mergable 12424 // stores. We search up through a load, to our root and then down 12425 // through all children. For instance we will find Store{1,2,3} if 12426 // St is Store1, Store2. or Store3 where the root is not a load 12427 // which always true for nonvolatile ops. TODO: Expand 12428 // the search to find all valid candidates through multiple layers of loads. 12429 // 12430 // Root 12431 // |-------|-------| 12432 // Load Load Store3 12433 // | | 12434 // Store1 Store2 12435 // 12436 // FIXME: We should be able to climb and 12437 // descend TokenFactors to find candidates as well. 12438 12439 SDNode *RootNode = (St->getChain()).getNode(); 12440 12441 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 12442 RootNode = Ldn->getChain().getNode(); 12443 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12444 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 12445 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 12446 if (I2.getOperandNo() == 0) 12447 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 12448 BaseIndexOffset Ptr; 12449 if (CandidateMatch(OtherST, Ptr)) 12450 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset)); 12451 } 12452 } else 12453 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12454 if (I.getOperandNo() == 0) 12455 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 12456 BaseIndexOffset Ptr; 12457 if (CandidateMatch(OtherST, Ptr)) 12458 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset)); 12459 } 12460 } 12461 12462 // We need to check that merging these stores does not cause a loop 12463 // in the DAG. Any store candidate may depend on another candidate 12464 // indirectly through its operand (we already consider dependencies 12465 // through the chain). Check in parallel by searching up from 12466 // non-chain operands of candidates. 12467 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 12468 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) { 12469 SmallPtrSet<const SDNode *, 16> Visited; 12470 SmallVector<const SDNode *, 8> Worklist; 12471 // search ops of store candidates 12472 for (unsigned i = 0; i < NumStores; ++i) { 12473 SDNode *n = StoreNodes[i].MemNode; 12474 // Potential loops may happen only through non-chain operands 12475 for (unsigned j = 1; j < n->getNumOperands(); ++j) 12476 Worklist.push_back(n->getOperand(j).getNode()); 12477 } 12478 // search through DAG. We can stop early if we find a storenode 12479 for (unsigned i = 0; i < NumStores; ++i) { 12480 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 12481 return false; 12482 } 12483 return true; 12484 } 12485 12486 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 12487 if (OptLevel == CodeGenOpt::None) 12488 return false; 12489 12490 EVT MemVT = St->getMemoryVT(); 12491 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12492 12493 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 12494 return false; 12495 12496 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 12497 Attribute::NoImplicitFloat); 12498 12499 // This function cannot currently deal with non-byte-sized memory sizes. 12500 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 12501 return false; 12502 12503 if (!MemVT.isSimple()) 12504 return false; 12505 12506 // Perform an early exit check. Do not bother looking at stored values that 12507 // are not constants, loads, or extracted vector elements. 12508 SDValue StoredVal = St->getValue(); 12509 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 12510 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 12511 isa<ConstantFPSDNode>(StoredVal); 12512 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12513 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12514 12515 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 12516 return false; 12517 12518 // Don't merge vectors into wider vectors if the source data comes from loads. 12519 // TODO: This restriction can be lifted by using logic similar to the 12520 // ExtractVecSrc case. 12521 if (MemVT.isVector() && IsLoadSrc) 12522 return false; 12523 12524 SmallVector<MemOpLink, 8> StoreNodes; 12525 // Find potential store merge candidates by searching through chain sub-DAG 12526 getStoreMergeCandidates(St, StoreNodes); 12527 12528 // Check if there is anything to merge. 12529 if (StoreNodes.size() < 2) 12530 return false; 12531 12532 // Sort the memory operands according to their distance from the 12533 // base pointer. 12534 std::sort(StoreNodes.begin(), StoreNodes.end(), 12535 [](MemOpLink LHS, MemOpLink RHS) { 12536 return LHS.OffsetFromBase < RHS.OffsetFromBase; 12537 }); 12538 12539 // Store Merge attempts to merge the lowest stores. This generally 12540 // works out as if successful, as the remaining stores are checked 12541 // after the first collection of stores is merged. However, in the 12542 // case that a non-mergeable store is found first, e.g., {p[-2], 12543 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 12544 // mergeable cases. To prevent this, we prune such stores from the 12545 // front of StoreNodes here. 12546 12547 bool RV = false; 12548 while (StoreNodes.size() > 1) { 12549 unsigned StartIdx = 0; 12550 while ((StartIdx + 1 < StoreNodes.size()) && 12551 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 12552 StoreNodes[StartIdx + 1].OffsetFromBase) 12553 ++StartIdx; 12554 12555 // Bail if we don't have enough candidates to merge. 12556 if (StartIdx + 1 >= StoreNodes.size()) 12557 return RV; 12558 12559 if (StartIdx) 12560 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 12561 12562 // Scan the memory operations on the chain and find the first 12563 // non-consecutive store memory address. 12564 unsigned NumConsecutiveStores = 1; 12565 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 12566 // Check that the addresses are consecutive starting from the second 12567 // element in the list of stores. 12568 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 12569 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 12570 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12571 break; 12572 NumConsecutiveStores = i + 1; 12573 } 12574 12575 if (NumConsecutiveStores < 2) { 12576 StoreNodes.erase(StoreNodes.begin(), 12577 StoreNodes.begin() + NumConsecutiveStores); 12578 continue; 12579 } 12580 12581 // Check that we can merge these candidates without causing a cycle 12582 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, 12583 NumConsecutiveStores)) { 12584 StoreNodes.erase(StoreNodes.begin(), 12585 StoreNodes.begin() + NumConsecutiveStores); 12586 continue; 12587 } 12588 12589 // The node with the lowest store address. 12590 LLVMContext &Context = *DAG.getContext(); 12591 const DataLayout &DL = DAG.getDataLayout(); 12592 12593 // Store the constants into memory as one consecutive store. 12594 if (IsConstantSrc) { 12595 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12596 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12597 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12598 unsigned LastLegalType = 0; 12599 unsigned LastLegalVectorType = 0; 12600 bool NonZero = false; 12601 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12602 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 12603 SDValue StoredVal = ST->getValue(); 12604 12605 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 12606 NonZero |= !C->isNullValue(); 12607 } else if (ConstantFPSDNode *C = 12608 dyn_cast<ConstantFPSDNode>(StoredVal)) { 12609 NonZero |= !C->getConstantFPValue()->isNullValue(); 12610 } else { 12611 // Non-constant. 12612 break; 12613 } 12614 12615 // Find a legal type for the constant store. 12616 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 12617 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12618 bool IsFast = false; 12619 if (TLI.isTypeLegal(StoreTy) && 12620 TLI.canMergeStoresTo(FirstStoreAS, StoreTy) && 12621 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12622 FirstStoreAlign, &IsFast) && 12623 IsFast) { 12624 LastLegalType = i + 1; 12625 // Or check whether a truncstore is legal. 12626 } else if (TLI.getTypeAction(Context, StoreTy) == 12627 TargetLowering::TypePromoteInteger) { 12628 EVT LegalizedStoredValueTy = 12629 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 12630 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12631 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy) && 12632 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12633 FirstStoreAS, FirstStoreAlign, &IsFast) && 12634 IsFast) { 12635 LastLegalType = i + 1; 12636 } 12637 } 12638 12639 // We only use vectors if the constant is known to be zero or the target 12640 // allows it and the function is not marked with the noimplicitfloat 12641 // attribute. 12642 if ((!NonZero || 12643 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 12644 !NoVectors) { 12645 // Find a legal type for the vector store. 12646 EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1); 12647 if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty) && 12648 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12649 FirstStoreAlign, &IsFast) && 12650 IsFast) 12651 LastLegalVectorType = i + 1; 12652 } 12653 } 12654 12655 // Check if we found a legal integer type that creates a meaningful merge. 12656 if (LastLegalType < 2 && LastLegalVectorType < 2) { 12657 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 12658 continue; 12659 } 12660 12661 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 12662 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 12663 12664 bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 12665 true, UseVector); 12666 if (!Merged) { 12667 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 12668 continue; 12669 } 12670 // Remove merged stores for next iteration. 12671 RV = true; 12672 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 12673 continue; 12674 } 12675 12676 // When extracting multiple vector elements, try to store them 12677 // in one vector store rather than a sequence of scalar stores. 12678 if (IsExtractVecSrc) { 12679 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12680 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12681 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12682 unsigned NumStoresToMerge = 1; 12683 bool IsVec = MemVT.isVector(); 12684 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12685 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12686 unsigned StoreValOpcode = St->getValue().getOpcode(); 12687 // This restriction could be loosened. 12688 // Bail out if any stored values are not elements extracted from a 12689 // vector. It should be possible to handle mixed sources, but load 12690 // sources need more careful handling (see the block of code below that 12691 // handles consecutive loads). 12692 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 12693 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 12694 return RV; 12695 12696 // Find a legal type for the vector store. 12697 unsigned Elts = i + 1; 12698 if (IsVec) { 12699 // When merging vector stores, get the total number of elements. 12700 Elts *= MemVT.getVectorNumElements(); 12701 } 12702 EVT Ty = 12703 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12704 bool IsFast; 12705 if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(FirstStoreAS, Ty) && 12706 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12707 FirstStoreAlign, &IsFast) && 12708 IsFast) 12709 NumStoresToMerge = i + 1; 12710 } 12711 12712 bool Merged = MergeStoresOfConstantsOrVecElts( 12713 StoreNodes, MemVT, NumStoresToMerge, false, true); 12714 if (!Merged) { 12715 StoreNodes.erase(StoreNodes.begin(), 12716 StoreNodes.begin() + NumStoresToMerge); 12717 continue; 12718 } 12719 // Remove merged stores for next iteration. 12720 StoreNodes.erase(StoreNodes.begin(), 12721 StoreNodes.begin() + NumStoresToMerge); 12722 RV = true; 12723 continue; 12724 } 12725 12726 // Below we handle the case of multiple consecutive stores that 12727 // come from multiple consecutive loads. We merge them into a single 12728 // wide load and a single wide store. 12729 12730 // Look for load nodes which are used by the stored values. 12731 SmallVector<MemOpLink, 8> LoadNodes; 12732 12733 // Find acceptable loads. Loads need to have the same chain (token factor), 12734 // must not be zext, volatile, indexed, and they must be consecutive. 12735 BaseIndexOffset LdBasePtr; 12736 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12737 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12738 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 12739 if (!Ld) 12740 break; 12741 12742 // Loads must only have one use. 12743 if (!Ld->hasNUsesOfValue(1, 0)) 12744 break; 12745 12746 // The memory operands must not be volatile. 12747 if (Ld->isVolatile() || Ld->isIndexed()) 12748 break; 12749 12750 // We do not accept ext loads. 12751 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 12752 break; 12753 12754 // The stored memory type must be the same. 12755 if (Ld->getMemoryVT() != MemVT) 12756 break; 12757 12758 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 12759 // If this is not the first ptr that we check. 12760 if (LdBasePtr.Base.getNode()) { 12761 // The base ptr must be the same. 12762 if (!LdPtr.equalBaseIndex(LdBasePtr)) 12763 break; 12764 } else { 12765 // Check that all other base pointers are the same as this one. 12766 LdBasePtr = LdPtr; 12767 } 12768 12769 // We found a potential memory operand to merge. 12770 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset)); 12771 } 12772 12773 if (LoadNodes.size() < 2) { 12774 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 12775 continue; 12776 } 12777 12778 // If we have load/store pair instructions and we only have two values, 12779 // don't bother. 12780 unsigned RequiredAlignment; 12781 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 12782 St->getAlignment() >= RequiredAlignment) { 12783 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 12784 continue; 12785 } 12786 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12787 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12788 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12789 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 12790 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 12791 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 12792 12793 // Scan the memory operations on the chain and find the first 12794 // non-consecutive load memory address. These variables hold the index in 12795 // the store node array. 12796 unsigned LastConsecutiveLoad = 0; 12797 // This variable refers to the size and not index in the array. 12798 unsigned LastLegalVectorType = 0; 12799 unsigned LastLegalIntegerType = 0; 12800 StartAddress = LoadNodes[0].OffsetFromBase; 12801 SDValue FirstChain = FirstLoad->getChain(); 12802 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 12803 // All loads must share the same chain. 12804 if (LoadNodes[i].MemNode->getChain() != FirstChain) 12805 break; 12806 12807 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 12808 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12809 break; 12810 LastConsecutiveLoad = i; 12811 // Find a legal type for the vector store. 12812 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i + 1); 12813 bool IsFastSt, IsFastLd; 12814 if (TLI.isTypeLegal(StoreTy) && 12815 TLI.canMergeStoresTo(FirstStoreAS, StoreTy) && 12816 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12817 FirstStoreAlign, &IsFastSt) && 12818 IsFastSt && 12819 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12820 FirstLoadAlign, &IsFastLd) && 12821 IsFastLd) { 12822 LastLegalVectorType = i + 1; 12823 } 12824 12825 // Find a legal type for the integer store. 12826 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 12827 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12828 if (TLI.isTypeLegal(StoreTy) && 12829 TLI.canMergeStoresTo(FirstStoreAS, StoreTy) && 12830 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12831 FirstStoreAlign, &IsFastSt) && 12832 IsFastSt && 12833 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12834 FirstLoadAlign, &IsFastLd) && 12835 IsFastLd) 12836 LastLegalIntegerType = i + 1; 12837 // Or check whether a truncstore and extload is legal. 12838 else if (TLI.getTypeAction(Context, StoreTy) == 12839 TargetLowering::TypePromoteInteger) { 12840 EVT LegalizedStoredValueTy = TLI.getTypeToTransformTo(Context, StoreTy); 12841 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12842 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValueTy) && 12843 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, 12844 StoreTy) && 12845 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, 12846 StoreTy) && 12847 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 12848 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12849 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 12850 IsFastSt && 12851 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12852 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 12853 IsFastLd) 12854 LastLegalIntegerType = i + 1; 12855 } 12856 } 12857 12858 // Only use vector types if the vector type is larger than the integer type. 12859 // If they are the same, use integers. 12860 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 12861 unsigned LastLegalType = 12862 std::max(LastLegalVectorType, LastLegalIntegerType); 12863 12864 // We add +1 here because the LastXXX variables refer to location while 12865 // the NumElem refers to array/index size. 12866 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 12867 NumElem = std::min(LastLegalType, NumElem); 12868 12869 if (NumElem < 2) { 12870 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 12871 continue; 12872 } 12873 12874 // Find if it is better to use vectors or integers to load and store 12875 // to memory. 12876 EVT JointMemOpVT; 12877 if (UseVectorTy) { 12878 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 12879 } else { 12880 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 12881 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 12882 } 12883 12884 SDLoc LoadDL(LoadNodes[0].MemNode); 12885 SDLoc StoreDL(StoreNodes[0].MemNode); 12886 12887 // The merged loads are required to have the same incoming chain, so 12888 // using the first's chain is acceptable. 12889 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 12890 FirstLoad->getBasePtr(), 12891 FirstLoad->getPointerInfo(), FirstLoadAlign); 12892 12893 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 12894 12895 AddToWorklist(NewStoreChain.getNode()); 12896 12897 SDValue NewStore = DAG.getStore( 12898 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 12899 FirstInChain->getPointerInfo(), FirstStoreAlign); 12900 12901 // Transfer chain users from old loads to the new load. 12902 for (unsigned i = 0; i < NumElem; ++i) { 12903 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 12904 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 12905 SDValue(NewLoad.getNode(), 1)); 12906 } 12907 12908 // Replace the all stores with the new store. 12909 for (unsigned i = 0; i < NumElem; ++i) 12910 CombineTo(StoreNodes[i].MemNode, NewStore); 12911 RV = true; 12912 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 12913 continue; 12914 } 12915 return RV; 12916 } 12917 12918 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 12919 SDLoc SL(ST); 12920 SDValue ReplStore; 12921 12922 // Replace the chain to avoid dependency. 12923 if (ST->isTruncatingStore()) { 12924 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 12925 ST->getBasePtr(), ST->getMemoryVT(), 12926 ST->getMemOperand()); 12927 } else { 12928 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 12929 ST->getMemOperand()); 12930 } 12931 12932 // Create token to keep both nodes around. 12933 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 12934 MVT::Other, ST->getChain(), ReplStore); 12935 12936 // Make sure the new and old chains are cleaned up. 12937 AddToWorklist(Token.getNode()); 12938 12939 // Don't add users to work list. 12940 return CombineTo(ST, Token, false); 12941 } 12942 12943 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 12944 SDValue Value = ST->getValue(); 12945 if (Value.getOpcode() == ISD::TargetConstantFP) 12946 return SDValue(); 12947 12948 SDLoc DL(ST); 12949 12950 SDValue Chain = ST->getChain(); 12951 SDValue Ptr = ST->getBasePtr(); 12952 12953 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 12954 12955 // NOTE: If the original store is volatile, this transform must not increase 12956 // the number of stores. For example, on x86-32 an f64 can be stored in one 12957 // processor operation but an i64 (which is not legal) requires two. So the 12958 // transform should not be done in this case. 12959 12960 SDValue Tmp; 12961 switch (CFP->getSimpleValueType(0).SimpleTy) { 12962 default: 12963 llvm_unreachable("Unknown FP type"); 12964 case MVT::f16: // We don't do this for these yet. 12965 case MVT::f80: 12966 case MVT::f128: 12967 case MVT::ppcf128: 12968 return SDValue(); 12969 case MVT::f32: 12970 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 12971 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12972 ; 12973 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 12974 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 12975 MVT::i32); 12976 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 12977 } 12978 12979 return SDValue(); 12980 case MVT::f64: 12981 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 12982 !ST->isVolatile()) || 12983 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 12984 ; 12985 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 12986 getZExtValue(), SDLoc(CFP), MVT::i64); 12987 return DAG.getStore(Chain, DL, Tmp, 12988 Ptr, ST->getMemOperand()); 12989 } 12990 12991 if (!ST->isVolatile() && 12992 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12993 // Many FP stores are not made apparent until after legalize, e.g. for 12994 // argument passing. Since this is so common, custom legalize the 12995 // 64-bit integer store into two 32-bit stores. 12996 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 12997 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 12998 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 12999 if (DAG.getDataLayout().isBigEndian()) 13000 std::swap(Lo, Hi); 13001 13002 unsigned Alignment = ST->getAlignment(); 13003 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13004 AAMDNodes AAInfo = ST->getAAInfo(); 13005 13006 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13007 ST->getAlignment(), MMOFlags, AAInfo); 13008 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13009 DAG.getConstant(4, DL, Ptr.getValueType())); 13010 Alignment = MinAlign(Alignment, 4U); 13011 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 13012 ST->getPointerInfo().getWithOffset(4), 13013 Alignment, MMOFlags, AAInfo); 13014 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 13015 St0, St1); 13016 } 13017 13018 return SDValue(); 13019 } 13020 } 13021 13022 SDValue DAGCombiner::visitSTORE(SDNode *N) { 13023 StoreSDNode *ST = cast<StoreSDNode>(N); 13024 SDValue Chain = ST->getChain(); 13025 SDValue Value = ST->getValue(); 13026 SDValue Ptr = ST->getBasePtr(); 13027 13028 // If this is a store of a bit convert, store the input value if the 13029 // resultant store does not need a higher alignment than the original. 13030 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 13031 ST->isUnindexed()) { 13032 EVT SVT = Value.getOperand(0).getValueType(); 13033 if (((!LegalOperations && !ST->isVolatile()) || 13034 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 13035 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 13036 unsigned OrigAlign = ST->getAlignment(); 13037 bool Fast = false; 13038 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 13039 ST->getAddressSpace(), OrigAlign, &Fast) && 13040 Fast) { 13041 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 13042 ST->getPointerInfo(), OrigAlign, 13043 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13044 } 13045 } 13046 } 13047 13048 // Turn 'store undef, Ptr' -> nothing. 13049 if (Value.isUndef() && ST->isUnindexed()) 13050 return Chain; 13051 13052 // Try to infer better alignment information than the store already has. 13053 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 13054 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 13055 if (Align > ST->getAlignment()) { 13056 SDValue NewStore = 13057 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 13058 ST->getMemoryVT(), Align, 13059 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13060 if (NewStore.getNode() != N) 13061 return CombineTo(ST, NewStore, true); 13062 } 13063 } 13064 } 13065 13066 // Try transforming a pair floating point load / store ops to integer 13067 // load / store ops. 13068 if (SDValue NewST = TransformFPLoadStorePair(N)) 13069 return NewST; 13070 13071 if (ST->isUnindexed()) { 13072 // Walk up chain skipping non-aliasing memory nodes, on this store and any 13073 // adjacent stores. 13074 if (findBetterNeighborChains(ST)) { 13075 // replaceStoreChain uses CombineTo, which handled all of the worklist 13076 // manipulation. Return the original node to not do anything else. 13077 return SDValue(ST, 0); 13078 } 13079 Chain = ST->getChain(); 13080 } 13081 13082 // Try transforming N to an indexed store. 13083 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 13084 return SDValue(N, 0); 13085 13086 // FIXME: is there such a thing as a truncating indexed store? 13087 if (ST->isTruncatingStore() && ST->isUnindexed() && 13088 Value.getValueType().isInteger()) { 13089 // See if we can simplify the input to this truncstore with knowledge that 13090 // only the low bits are being used. For example: 13091 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 13092 SDValue Shorter = GetDemandedBits( 13093 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13094 ST->getMemoryVT().getScalarSizeInBits())); 13095 AddToWorklist(Value.getNode()); 13096 if (Shorter.getNode()) 13097 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 13098 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13099 13100 // Otherwise, see if we can simplify the operation with 13101 // SimplifyDemandedBits, which only works if the value has a single use. 13102 if (SimplifyDemandedBits( 13103 Value, 13104 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13105 ST->getMemoryVT().getScalarSizeInBits()))) { 13106 // Re-visit the store if anything changed and the store hasn't been merged 13107 // with another node (N is deleted) SimplifyDemandedBits will add Value's 13108 // node back to the worklist if necessary, but we also need to re-visit 13109 // the Store node itself. 13110 if (N->getOpcode() != ISD::DELETED_NODE) 13111 AddToWorklist(N); 13112 return SDValue(N, 0); 13113 } 13114 } 13115 13116 // If this is a load followed by a store to the same location, then the store 13117 // is dead/noop. 13118 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 13119 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 13120 ST->isUnindexed() && !ST->isVolatile() && 13121 // There can't be any side effects between the load and store, such as 13122 // a call or store. 13123 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 13124 // The store is dead, remove it. 13125 return Chain; 13126 } 13127 } 13128 13129 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 13130 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 13131 !ST1->isVolatile() && ST1->getBasePtr() == Ptr && 13132 ST->getMemoryVT() == ST1->getMemoryVT()) { 13133 // If this is a store followed by a store with the same value to the same 13134 // location, then the store is dead/noop. 13135 if (ST1->getValue() == Value) { 13136 // The store is dead, remove it. 13137 return Chain; 13138 } 13139 13140 // If this is a store who's preceeding store to the same location 13141 // and no one other node is chained to that store we can effectively 13142 // drop the store. Do not remove stores to undef as they may be used as 13143 // data sinks. 13144 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 13145 !ST1->getBasePtr().isUndef()) { 13146 // ST1 is fully overwritten and can be elided. Combine with it's chain 13147 // value. 13148 CombineTo(ST1, ST1->getChain()); 13149 return SDValue(); 13150 } 13151 } 13152 } 13153 13154 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 13155 // truncating store. We can do this even if this is already a truncstore. 13156 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 13157 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 13158 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 13159 ST->getMemoryVT())) { 13160 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 13161 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13162 } 13163 13164 // Only perform this optimization before the types are legal, because we 13165 // don't want to perform this optimization on every DAGCombine invocation. 13166 if (!LegalTypes) { 13167 for (;;) { 13168 // There can be multiple store sequences on the same chain. 13169 // Keep trying to merge store sequences until we are unable to do so 13170 // or until we merge the last store on the chain. 13171 bool Changed = MergeConsecutiveStores(ST); 13172 if (!Changed) break; 13173 // Return N as merge only uses CombineTo and no worklist clean 13174 // up is necessary. 13175 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 13176 return SDValue(N, 0); 13177 } 13178 } 13179 13180 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 13181 // 13182 // Make sure to do this only after attempting to merge stores in order to 13183 // avoid changing the types of some subset of stores due to visit order, 13184 // preventing their merging. 13185 if (isa<ConstantFPSDNode>(ST->getValue())) { 13186 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 13187 return NewSt; 13188 } 13189 13190 if (SDValue NewSt = splitMergedValStore(ST)) 13191 return NewSt; 13192 13193 return ReduceLoadOpStoreWidth(N); 13194 } 13195 13196 /// For the instruction sequence of store below, F and I values 13197 /// are bundled together as an i64 value before being stored into memory. 13198 /// Sometimes it is more efficent to generate separate stores for F and I, 13199 /// which can remove the bitwise instructions or sink them to colder places. 13200 /// 13201 /// (store (or (zext (bitcast F to i32) to i64), 13202 /// (shl (zext I to i64), 32)), addr) --> 13203 /// (store F, addr) and (store I, addr+4) 13204 /// 13205 /// Similarly, splitting for other merged store can also be beneficial, like: 13206 /// For pair of {i32, i32}, i64 store --> two i32 stores. 13207 /// For pair of {i32, i16}, i64 store --> two i32 stores. 13208 /// For pair of {i16, i16}, i32 store --> two i16 stores. 13209 /// For pair of {i16, i8}, i32 store --> two i16 stores. 13210 /// For pair of {i8, i8}, i16 store --> two i8 stores. 13211 /// 13212 /// We allow each target to determine specifically which kind of splitting is 13213 /// supported. 13214 /// 13215 /// The store patterns are commonly seen from the simple code snippet below 13216 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 13217 /// void goo(const std::pair<int, float> &); 13218 /// hoo() { 13219 /// ... 13220 /// goo(std::make_pair(tmp, ftmp)); 13221 /// ... 13222 /// } 13223 /// 13224 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 13225 if (OptLevel == CodeGenOpt::None) 13226 return SDValue(); 13227 13228 SDValue Val = ST->getValue(); 13229 SDLoc DL(ST); 13230 13231 // Match OR operand. 13232 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 13233 return SDValue(); 13234 13235 // Match SHL operand and get Lower and Higher parts of Val. 13236 SDValue Op1 = Val.getOperand(0); 13237 SDValue Op2 = Val.getOperand(1); 13238 SDValue Lo, Hi; 13239 if (Op1.getOpcode() != ISD::SHL) { 13240 std::swap(Op1, Op2); 13241 if (Op1.getOpcode() != ISD::SHL) 13242 return SDValue(); 13243 } 13244 Lo = Op2; 13245 Hi = Op1.getOperand(0); 13246 if (!Op1.hasOneUse()) 13247 return SDValue(); 13248 13249 // Match shift amount to HalfValBitSize. 13250 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 13251 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 13252 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 13253 return SDValue(); 13254 13255 // Lo and Hi are zero-extended from int with size less equal than 32 13256 // to i64. 13257 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 13258 !Lo.getOperand(0).getValueType().isScalarInteger() || 13259 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 13260 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 13261 !Hi.getOperand(0).getValueType().isScalarInteger() || 13262 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 13263 return SDValue(); 13264 13265 // Use the EVT of low and high parts before bitcast as the input 13266 // of target query. 13267 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 13268 ? Lo.getOperand(0).getValueType() 13269 : Lo.getValueType(); 13270 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 13271 ? Hi.getOperand(0).getValueType() 13272 : Hi.getValueType(); 13273 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 13274 return SDValue(); 13275 13276 // Start to split store. 13277 unsigned Alignment = ST->getAlignment(); 13278 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13279 AAMDNodes AAInfo = ST->getAAInfo(); 13280 13281 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 13282 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 13283 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 13284 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 13285 13286 SDValue Chain = ST->getChain(); 13287 SDValue Ptr = ST->getBasePtr(); 13288 // Lower value store. 13289 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13290 ST->getAlignment(), MMOFlags, AAInfo); 13291 Ptr = 13292 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13293 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 13294 // Higher value store. 13295 SDValue St1 = 13296 DAG.getStore(St0, DL, Hi, Ptr, 13297 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 13298 Alignment / 2, MMOFlags, AAInfo); 13299 return St1; 13300 } 13301 13302 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 13303 SDValue InVec = N->getOperand(0); 13304 SDValue InVal = N->getOperand(1); 13305 SDValue EltNo = N->getOperand(2); 13306 SDLoc DL(N); 13307 13308 // If the inserted element is an UNDEF, just use the input vector. 13309 if (InVal.isUndef()) 13310 return InVec; 13311 13312 EVT VT = InVec.getValueType(); 13313 13314 // Check that we know which element is being inserted 13315 if (!isa<ConstantSDNode>(EltNo)) 13316 return SDValue(); 13317 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13318 13319 // Canonicalize insert_vector_elt dag nodes. 13320 // Example: 13321 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 13322 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 13323 // 13324 // Do this only if the child insert_vector node has one use; also 13325 // do this only if indices are both constants and Idx1 < Idx0. 13326 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 13327 && isa<ConstantSDNode>(InVec.getOperand(2))) { 13328 unsigned OtherElt = InVec.getConstantOperandVal(2); 13329 if (Elt < OtherElt) { 13330 // Swap nodes. 13331 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 13332 InVec.getOperand(0), InVal, EltNo); 13333 AddToWorklist(NewOp.getNode()); 13334 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 13335 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 13336 } 13337 } 13338 13339 // If we can't generate a legal BUILD_VECTOR, exit 13340 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 13341 return SDValue(); 13342 13343 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 13344 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 13345 // vector elements. 13346 SmallVector<SDValue, 8> Ops; 13347 // Do not combine these two vectors if the output vector will not replace 13348 // the input vector. 13349 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 13350 Ops.append(InVec.getNode()->op_begin(), 13351 InVec.getNode()->op_end()); 13352 } else if (InVec.isUndef()) { 13353 unsigned NElts = VT.getVectorNumElements(); 13354 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 13355 } else { 13356 return SDValue(); 13357 } 13358 13359 // Insert the element 13360 if (Elt < Ops.size()) { 13361 // All the operands of BUILD_VECTOR must have the same type; 13362 // we enforce that here. 13363 EVT OpVT = Ops[0].getValueType(); 13364 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 13365 } 13366 13367 // Return the new vector 13368 return DAG.getBuildVector(VT, DL, Ops); 13369 } 13370 13371 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 13372 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 13373 assert(!OriginalLoad->isVolatile()); 13374 13375 EVT ResultVT = EVE->getValueType(0); 13376 EVT VecEltVT = InVecVT.getVectorElementType(); 13377 unsigned Align = OriginalLoad->getAlignment(); 13378 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 13379 VecEltVT.getTypeForEVT(*DAG.getContext())); 13380 13381 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 13382 return SDValue(); 13383 13384 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 13385 ISD::NON_EXTLOAD : ISD::EXTLOAD; 13386 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 13387 return SDValue(); 13388 13389 Align = NewAlign; 13390 13391 SDValue NewPtr = OriginalLoad->getBasePtr(); 13392 SDValue Offset; 13393 EVT PtrType = NewPtr.getValueType(); 13394 MachinePointerInfo MPI; 13395 SDLoc DL(EVE); 13396 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 13397 int Elt = ConstEltNo->getZExtValue(); 13398 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 13399 Offset = DAG.getConstant(PtrOff, DL, PtrType); 13400 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 13401 } else { 13402 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 13403 Offset = DAG.getNode( 13404 ISD::MUL, DL, PtrType, Offset, 13405 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 13406 MPI = OriginalLoad->getPointerInfo(); 13407 } 13408 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 13409 13410 // The replacement we need to do here is a little tricky: we need to 13411 // replace an extractelement of a load with a load. 13412 // Use ReplaceAllUsesOfValuesWith to do the replacement. 13413 // Note that this replacement assumes that the extractvalue is the only 13414 // use of the load; that's okay because we don't want to perform this 13415 // transformation in other cases anyway. 13416 SDValue Load; 13417 SDValue Chain; 13418 if (ResultVT.bitsGT(VecEltVT)) { 13419 // If the result type of vextract is wider than the load, then issue an 13420 // extending load instead. 13421 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 13422 VecEltVT) 13423 ? ISD::ZEXTLOAD 13424 : ISD::EXTLOAD; 13425 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 13426 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 13427 Align, OriginalLoad->getMemOperand()->getFlags(), 13428 OriginalLoad->getAAInfo()); 13429 Chain = Load.getValue(1); 13430 } else { 13431 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 13432 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 13433 OriginalLoad->getAAInfo()); 13434 Chain = Load.getValue(1); 13435 if (ResultVT.bitsLT(VecEltVT)) 13436 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 13437 else 13438 Load = DAG.getBitcast(ResultVT, Load); 13439 } 13440 WorklistRemover DeadNodes(*this); 13441 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 13442 SDValue To[] = { Load, Chain }; 13443 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 13444 // Since we're explicitly calling ReplaceAllUses, add the new node to the 13445 // worklist explicitly as well. 13446 AddToWorklist(Load.getNode()); 13447 AddUsersToWorklist(Load.getNode()); // Add users too 13448 // Make sure to revisit this node to clean it up; it will usually be dead. 13449 AddToWorklist(EVE); 13450 ++OpsNarrowed; 13451 return SDValue(EVE, 0); 13452 } 13453 13454 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 13455 // (vextract (scalar_to_vector val, 0) -> val 13456 SDValue InVec = N->getOperand(0); 13457 EVT VT = InVec.getValueType(); 13458 EVT NVT = N->getValueType(0); 13459 13460 if (InVec.isUndef()) 13461 return DAG.getUNDEF(NVT); 13462 13463 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 13464 // Check if the result type doesn't match the inserted element type. A 13465 // SCALAR_TO_VECTOR may truncate the inserted element and the 13466 // EXTRACT_VECTOR_ELT may widen the extracted vector. 13467 SDValue InOp = InVec.getOperand(0); 13468 if (InOp.getValueType() != NVT) { 13469 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13470 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 13471 } 13472 return InOp; 13473 } 13474 13475 SDValue EltNo = N->getOperand(1); 13476 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 13477 13478 // extract_vector_elt (build_vector x, y), 1 -> y 13479 if (ConstEltNo && 13480 InVec.getOpcode() == ISD::BUILD_VECTOR && 13481 TLI.isTypeLegal(VT) && 13482 (InVec.hasOneUse() || 13483 TLI.aggressivelyPreferBuildVectorSources(VT))) { 13484 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 13485 EVT InEltVT = Elt.getValueType(); 13486 13487 // Sometimes build_vector's scalar input types do not match result type. 13488 if (NVT == InEltVT) 13489 return Elt; 13490 13491 // TODO: It may be useful to truncate if free if the build_vector implicitly 13492 // converts. 13493 } 13494 13495 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 13496 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 13497 ConstEltNo->isNullValue() && VT.isInteger()) { 13498 SDValue BCSrc = InVec.getOperand(0); 13499 if (BCSrc.getValueType().isScalarInteger()) 13500 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 13501 } 13502 13503 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 13504 // 13505 // This only really matters if the index is non-constant since other combines 13506 // on the constant elements already work. 13507 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 13508 EltNo == InVec.getOperand(2)) { 13509 SDValue Elt = InVec.getOperand(1); 13510 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 13511 } 13512 13513 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 13514 // We only perform this optimization before the op legalization phase because 13515 // we may introduce new vector instructions which are not backed by TD 13516 // patterns. For example on AVX, extracting elements from a wide vector 13517 // without using extract_subvector. However, if we can find an underlying 13518 // scalar value, then we can always use that. 13519 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 13520 int NumElem = VT.getVectorNumElements(); 13521 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 13522 // Find the new index to extract from. 13523 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 13524 13525 // Extracting an undef index is undef. 13526 if (OrigElt == -1) 13527 return DAG.getUNDEF(NVT); 13528 13529 // Select the right vector half to extract from. 13530 SDValue SVInVec; 13531 if (OrigElt < NumElem) { 13532 SVInVec = InVec->getOperand(0); 13533 } else { 13534 SVInVec = InVec->getOperand(1); 13535 OrigElt -= NumElem; 13536 } 13537 13538 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 13539 SDValue InOp = SVInVec.getOperand(OrigElt); 13540 if (InOp.getValueType() != NVT) { 13541 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13542 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 13543 } 13544 13545 return InOp; 13546 } 13547 13548 // FIXME: We should handle recursing on other vector shuffles and 13549 // scalar_to_vector here as well. 13550 13551 if (!LegalOperations) { 13552 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13553 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 13554 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 13555 } 13556 } 13557 13558 bool BCNumEltsChanged = false; 13559 EVT ExtVT = VT.getVectorElementType(); 13560 EVT LVT = ExtVT; 13561 13562 // If the result of load has to be truncated, then it's not necessarily 13563 // profitable. 13564 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 13565 return SDValue(); 13566 13567 if (InVec.getOpcode() == ISD::BITCAST) { 13568 // Don't duplicate a load with other uses. 13569 if (!InVec.hasOneUse()) 13570 return SDValue(); 13571 13572 EVT BCVT = InVec.getOperand(0).getValueType(); 13573 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 13574 return SDValue(); 13575 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 13576 BCNumEltsChanged = true; 13577 InVec = InVec.getOperand(0); 13578 ExtVT = BCVT.getVectorElementType(); 13579 } 13580 13581 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 13582 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 13583 ISD::isNormalLoad(InVec.getNode()) && 13584 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 13585 SDValue Index = N->getOperand(1); 13586 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 13587 if (!OrigLoad->isVolatile()) { 13588 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 13589 OrigLoad); 13590 } 13591 } 13592 } 13593 13594 // Perform only after legalization to ensure build_vector / vector_shuffle 13595 // optimizations have already been done. 13596 if (!LegalOperations) return SDValue(); 13597 13598 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 13599 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 13600 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 13601 13602 if (ConstEltNo) { 13603 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13604 13605 LoadSDNode *LN0 = nullptr; 13606 const ShuffleVectorSDNode *SVN = nullptr; 13607 if (ISD::isNormalLoad(InVec.getNode())) { 13608 LN0 = cast<LoadSDNode>(InVec); 13609 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 13610 InVec.getOperand(0).getValueType() == ExtVT && 13611 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 13612 // Don't duplicate a load with other uses. 13613 if (!InVec.hasOneUse()) 13614 return SDValue(); 13615 13616 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 13617 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 13618 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 13619 // => 13620 // (load $addr+1*size) 13621 13622 // Don't duplicate a load with other uses. 13623 if (!InVec.hasOneUse()) 13624 return SDValue(); 13625 13626 // If the bit convert changed the number of elements, it is unsafe 13627 // to examine the mask. 13628 if (BCNumEltsChanged) 13629 return SDValue(); 13630 13631 // Select the input vector, guarding against out of range extract vector. 13632 unsigned NumElems = VT.getVectorNumElements(); 13633 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 13634 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 13635 13636 if (InVec.getOpcode() == ISD::BITCAST) { 13637 // Don't duplicate a load with other uses. 13638 if (!InVec.hasOneUse()) 13639 return SDValue(); 13640 13641 InVec = InVec.getOperand(0); 13642 } 13643 if (ISD::isNormalLoad(InVec.getNode())) { 13644 LN0 = cast<LoadSDNode>(InVec); 13645 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 13646 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 13647 } 13648 } 13649 13650 // Make sure we found a non-volatile load and the extractelement is 13651 // the only use. 13652 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 13653 return SDValue(); 13654 13655 // If Idx was -1 above, Elt is going to be -1, so just return undef. 13656 if (Elt == -1) 13657 return DAG.getUNDEF(LVT); 13658 13659 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 13660 } 13661 13662 return SDValue(); 13663 } 13664 13665 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 13666 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 13667 // We perform this optimization post type-legalization because 13668 // the type-legalizer often scalarizes integer-promoted vectors. 13669 // Performing this optimization before may create bit-casts which 13670 // will be type-legalized to complex code sequences. 13671 // We perform this optimization only before the operation legalizer because we 13672 // may introduce illegal operations. 13673 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 13674 return SDValue(); 13675 13676 unsigned NumInScalars = N->getNumOperands(); 13677 SDLoc DL(N); 13678 EVT VT = N->getValueType(0); 13679 13680 // Check to see if this is a BUILD_VECTOR of a bunch of values 13681 // which come from any_extend or zero_extend nodes. If so, we can create 13682 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 13683 // optimizations. We do not handle sign-extend because we can't fill the sign 13684 // using shuffles. 13685 EVT SourceType = MVT::Other; 13686 bool AllAnyExt = true; 13687 13688 for (unsigned i = 0; i != NumInScalars; ++i) { 13689 SDValue In = N->getOperand(i); 13690 // Ignore undef inputs. 13691 if (In.isUndef()) continue; 13692 13693 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 13694 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 13695 13696 // Abort if the element is not an extension. 13697 if (!ZeroExt && !AnyExt) { 13698 SourceType = MVT::Other; 13699 break; 13700 } 13701 13702 // The input is a ZeroExt or AnyExt. Check the original type. 13703 EVT InTy = In.getOperand(0).getValueType(); 13704 13705 // Check that all of the widened source types are the same. 13706 if (SourceType == MVT::Other) 13707 // First time. 13708 SourceType = InTy; 13709 else if (InTy != SourceType) { 13710 // Multiple income types. Abort. 13711 SourceType = MVT::Other; 13712 break; 13713 } 13714 13715 // Check if all of the extends are ANY_EXTENDs. 13716 AllAnyExt &= AnyExt; 13717 } 13718 13719 // In order to have valid types, all of the inputs must be extended from the 13720 // same source type and all of the inputs must be any or zero extend. 13721 // Scalar sizes must be a power of two. 13722 EVT OutScalarTy = VT.getScalarType(); 13723 bool ValidTypes = SourceType != MVT::Other && 13724 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 13725 isPowerOf2_32(SourceType.getSizeInBits()); 13726 13727 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 13728 // turn into a single shuffle instruction. 13729 if (!ValidTypes) 13730 return SDValue(); 13731 13732 bool isLE = DAG.getDataLayout().isLittleEndian(); 13733 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 13734 assert(ElemRatio > 1 && "Invalid element size ratio"); 13735 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 13736 DAG.getConstant(0, DL, SourceType); 13737 13738 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 13739 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 13740 13741 // Populate the new build_vector 13742 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13743 SDValue Cast = N->getOperand(i); 13744 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 13745 Cast.getOpcode() == ISD::ZERO_EXTEND || 13746 Cast.isUndef()) && "Invalid cast opcode"); 13747 SDValue In; 13748 if (Cast.isUndef()) 13749 In = DAG.getUNDEF(SourceType); 13750 else 13751 In = Cast->getOperand(0); 13752 unsigned Index = isLE ? (i * ElemRatio) : 13753 (i * ElemRatio + (ElemRatio - 1)); 13754 13755 assert(Index < Ops.size() && "Invalid index"); 13756 Ops[Index] = In; 13757 } 13758 13759 // The type of the new BUILD_VECTOR node. 13760 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 13761 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 13762 "Invalid vector size"); 13763 // Check if the new vector type is legal. 13764 if (!isTypeLegal(VecVT)) return SDValue(); 13765 13766 // Make the new BUILD_VECTOR. 13767 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 13768 13769 // The new BUILD_VECTOR node has the potential to be further optimized. 13770 AddToWorklist(BV.getNode()); 13771 // Bitcast to the desired type. 13772 return DAG.getBitcast(VT, BV); 13773 } 13774 13775 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 13776 EVT VT = N->getValueType(0); 13777 13778 unsigned NumInScalars = N->getNumOperands(); 13779 SDLoc DL(N); 13780 13781 EVT SrcVT = MVT::Other; 13782 unsigned Opcode = ISD::DELETED_NODE; 13783 unsigned NumDefs = 0; 13784 13785 for (unsigned i = 0; i != NumInScalars; ++i) { 13786 SDValue In = N->getOperand(i); 13787 unsigned Opc = In.getOpcode(); 13788 13789 if (Opc == ISD::UNDEF) 13790 continue; 13791 13792 // If all scalar values are floats and converted from integers. 13793 if (Opcode == ISD::DELETED_NODE && 13794 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 13795 Opcode = Opc; 13796 } 13797 13798 if (Opc != Opcode) 13799 return SDValue(); 13800 13801 EVT InVT = In.getOperand(0).getValueType(); 13802 13803 // If all scalar values are typed differently, bail out. It's chosen to 13804 // simplify BUILD_VECTOR of integer types. 13805 if (SrcVT == MVT::Other) 13806 SrcVT = InVT; 13807 if (SrcVT != InVT) 13808 return SDValue(); 13809 NumDefs++; 13810 } 13811 13812 // If the vector has just one element defined, it's not worth to fold it into 13813 // a vectorized one. 13814 if (NumDefs < 2) 13815 return SDValue(); 13816 13817 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 13818 && "Should only handle conversion from integer to float."); 13819 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 13820 13821 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 13822 13823 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 13824 return SDValue(); 13825 13826 // Just because the floating-point vector type is legal does not necessarily 13827 // mean that the corresponding integer vector type is. 13828 if (!isTypeLegal(NVT)) 13829 return SDValue(); 13830 13831 SmallVector<SDValue, 8> Opnds; 13832 for (unsigned i = 0; i != NumInScalars; ++i) { 13833 SDValue In = N->getOperand(i); 13834 13835 if (In.isUndef()) 13836 Opnds.push_back(DAG.getUNDEF(SrcVT)); 13837 else 13838 Opnds.push_back(In.getOperand(0)); 13839 } 13840 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 13841 AddToWorklist(BV.getNode()); 13842 13843 return DAG.getNode(Opcode, DL, VT, BV); 13844 } 13845 13846 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 13847 ArrayRef<int> VectorMask, 13848 SDValue VecIn1, SDValue VecIn2, 13849 unsigned LeftIdx) { 13850 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13851 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 13852 13853 EVT VT = N->getValueType(0); 13854 EVT InVT1 = VecIn1.getValueType(); 13855 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 13856 13857 unsigned Vec2Offset = InVT1.getVectorNumElements(); 13858 unsigned NumElems = VT.getVectorNumElements(); 13859 unsigned ShuffleNumElems = NumElems; 13860 13861 // We can't generate a shuffle node with mismatched input and output types. 13862 // Try to make the types match the type of the output. 13863 if (InVT1 != VT || InVT2 != VT) { 13864 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 13865 // If the output vector length is a multiple of both input lengths, 13866 // we can concatenate them and pad the rest with undefs. 13867 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 13868 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 13869 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 13870 ConcatOps[0] = VecIn1; 13871 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 13872 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 13873 VecIn2 = SDValue(); 13874 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 13875 if (!TLI.isExtractSubvectorCheap(VT, NumElems)) 13876 return SDValue(); 13877 13878 if (!VecIn2.getNode()) { 13879 // If we only have one input vector, and it's twice the size of the 13880 // output, split it in two. 13881 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 13882 DAG.getConstant(NumElems, DL, IdxTy)); 13883 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 13884 // Since we now have shorter input vectors, adjust the offset of the 13885 // second vector's start. 13886 Vec2Offset = NumElems; 13887 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 13888 // VecIn1 is wider than the output, and we have another, possibly 13889 // smaller input. Pad the smaller input with undefs, shuffle at the 13890 // input vector width, and extract the output. 13891 // The shuffle type is different than VT, so check legality again. 13892 if (LegalOperations && 13893 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 13894 return SDValue(); 13895 13896 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 13897 // lower it back into a BUILD_VECTOR. So if the inserted type is 13898 // illegal, don't even try. 13899 if (InVT1 != InVT2) { 13900 if (!TLI.isTypeLegal(InVT2)) 13901 return SDValue(); 13902 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 13903 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 13904 } 13905 ShuffleNumElems = NumElems * 2; 13906 } else { 13907 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 13908 // than VecIn1. We can't handle this for now - this case will disappear 13909 // when we start sorting the vectors by type. 13910 return SDValue(); 13911 } 13912 } else { 13913 // TODO: Support cases where the length mismatch isn't exactly by a 13914 // factor of 2. 13915 // TODO: Move this check upwards, so that if we have bad type 13916 // mismatches, we don't create any DAG nodes. 13917 return SDValue(); 13918 } 13919 } 13920 13921 // Initialize mask to undef. 13922 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 13923 13924 // Only need to run up to the number of elements actually used, not the 13925 // total number of elements in the shuffle - if we are shuffling a wider 13926 // vector, the high lanes should be set to undef. 13927 for (unsigned i = 0; i != NumElems; ++i) { 13928 if (VectorMask[i] <= 0) 13929 continue; 13930 13931 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 13932 if (VectorMask[i] == (int)LeftIdx) { 13933 Mask[i] = ExtIndex; 13934 } else if (VectorMask[i] == (int)LeftIdx + 1) { 13935 Mask[i] = Vec2Offset + ExtIndex; 13936 } 13937 } 13938 13939 // The type the input vectors may have changed above. 13940 InVT1 = VecIn1.getValueType(); 13941 13942 // If we already have a VecIn2, it should have the same type as VecIn1. 13943 // If we don't, get an undef/zero vector of the appropriate type. 13944 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 13945 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 13946 13947 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 13948 if (ShuffleNumElems > NumElems) 13949 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 13950 13951 return Shuffle; 13952 } 13953 13954 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 13955 // operations. If the types of the vectors we're extracting from allow it, 13956 // turn this into a vector_shuffle node. 13957 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 13958 SDLoc DL(N); 13959 EVT VT = N->getValueType(0); 13960 13961 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 13962 if (!isTypeLegal(VT)) 13963 return SDValue(); 13964 13965 // May only combine to shuffle after legalize if shuffle is legal. 13966 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 13967 return SDValue(); 13968 13969 bool UsesZeroVector = false; 13970 unsigned NumElems = N->getNumOperands(); 13971 13972 // Record, for each element of the newly built vector, which input vector 13973 // that element comes from. -1 stands for undef, 0 for the zero vector, 13974 // and positive values for the input vectors. 13975 // VectorMask maps each element to its vector number, and VecIn maps vector 13976 // numbers to their initial SDValues. 13977 13978 SmallVector<int, 8> VectorMask(NumElems, -1); 13979 SmallVector<SDValue, 8> VecIn; 13980 VecIn.push_back(SDValue()); 13981 13982 for (unsigned i = 0; i != NumElems; ++i) { 13983 SDValue Op = N->getOperand(i); 13984 13985 if (Op.isUndef()) 13986 continue; 13987 13988 // See if we can use a blend with a zero vector. 13989 // TODO: Should we generalize this to a blend with an arbitrary constant 13990 // vector? 13991 if (isNullConstant(Op) || isNullFPConstant(Op)) { 13992 UsesZeroVector = true; 13993 VectorMask[i] = 0; 13994 continue; 13995 } 13996 13997 // Not an undef or zero. If the input is something other than an 13998 // EXTRACT_VECTOR_ELT with a constant index, bail out. 13999 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14000 !isa<ConstantSDNode>(Op.getOperand(1))) 14001 return SDValue(); 14002 14003 SDValue ExtractedFromVec = Op.getOperand(0); 14004 14005 // All inputs must have the same element type as the output. 14006 if (VT.getVectorElementType() != 14007 ExtractedFromVec.getValueType().getVectorElementType()) 14008 return SDValue(); 14009 14010 // Have we seen this input vector before? 14011 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 14012 // a map back from SDValues to numbers isn't worth it. 14013 unsigned Idx = std::distance( 14014 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 14015 if (Idx == VecIn.size()) 14016 VecIn.push_back(ExtractedFromVec); 14017 14018 VectorMask[i] = Idx; 14019 } 14020 14021 // If we didn't find at least one input vector, bail out. 14022 if (VecIn.size() < 2) 14023 return SDValue(); 14024 14025 // TODO: We want to sort the vectors by descending length, so that adjacent 14026 // pairs have similar length, and the longer vector is always first in the 14027 // pair. 14028 14029 // TODO: Should this fire if some of the input vectors has illegal type (like 14030 // it does now), or should we let legalization run its course first? 14031 14032 // Shuffle phase: 14033 // Take pairs of vectors, and shuffle them so that the result has elements 14034 // from these vectors in the correct places. 14035 // For example, given: 14036 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 14037 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 14038 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 14039 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 14040 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 14041 // We will generate: 14042 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 14043 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 14044 SmallVector<SDValue, 4> Shuffles; 14045 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 14046 unsigned LeftIdx = 2 * In + 1; 14047 SDValue VecLeft = VecIn[LeftIdx]; 14048 SDValue VecRight = 14049 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 14050 14051 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 14052 VecRight, LeftIdx)) 14053 Shuffles.push_back(Shuffle); 14054 else 14055 return SDValue(); 14056 } 14057 14058 // If we need the zero vector as an "ingredient" in the blend tree, add it 14059 // to the list of shuffles. 14060 if (UsesZeroVector) 14061 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 14062 : DAG.getConstantFP(0.0, DL, VT)); 14063 14064 // If we only have one shuffle, we're done. 14065 if (Shuffles.size() == 1) 14066 return Shuffles[0]; 14067 14068 // Update the vector mask to point to the post-shuffle vectors. 14069 for (int &Vec : VectorMask) 14070 if (Vec == 0) 14071 Vec = Shuffles.size() - 1; 14072 else 14073 Vec = (Vec - 1) / 2; 14074 14075 // More than one shuffle. Generate a binary tree of blends, e.g. if from 14076 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 14077 // generate: 14078 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 14079 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 14080 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 14081 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 14082 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 14083 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 14084 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 14085 14086 // Make sure the initial size of the shuffle list is even. 14087 if (Shuffles.size() % 2) 14088 Shuffles.push_back(DAG.getUNDEF(VT)); 14089 14090 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 14091 if (CurSize % 2) { 14092 Shuffles[CurSize] = DAG.getUNDEF(VT); 14093 CurSize++; 14094 } 14095 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 14096 int Left = 2 * In; 14097 int Right = 2 * In + 1; 14098 SmallVector<int, 8> Mask(NumElems, -1); 14099 for (unsigned i = 0; i != NumElems; ++i) { 14100 if (VectorMask[i] == Left) { 14101 Mask[i] = i; 14102 VectorMask[i] = In; 14103 } else if (VectorMask[i] == Right) { 14104 Mask[i] = i + NumElems; 14105 VectorMask[i] = In; 14106 } 14107 } 14108 14109 Shuffles[In] = 14110 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 14111 } 14112 } 14113 14114 return Shuffles[0]; 14115 } 14116 14117 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 14118 EVT VT = N->getValueType(0); 14119 14120 // A vector built entirely of undefs is undef. 14121 if (ISD::allOperandsUndef(N)) 14122 return DAG.getUNDEF(VT); 14123 14124 // Check if we can express BUILD VECTOR via subvector extract. 14125 if (!LegalTypes && (N->getNumOperands() > 1)) { 14126 SDValue Op0 = N->getOperand(0); 14127 auto checkElem = [&](SDValue Op) -> uint64_t { 14128 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 14129 (Op0.getOperand(0) == Op.getOperand(0))) 14130 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 14131 return CNode->getZExtValue(); 14132 return -1; 14133 }; 14134 14135 int Offset = checkElem(Op0); 14136 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 14137 if (Offset + i != checkElem(N->getOperand(i))) { 14138 Offset = -1; 14139 break; 14140 } 14141 } 14142 14143 if ((Offset == 0) && 14144 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 14145 return Op0.getOperand(0); 14146 if ((Offset != -1) && 14147 ((Offset % N->getValueType(0).getVectorNumElements()) == 14148 0)) // IDX must be multiple of output size. 14149 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 14150 Op0.getOperand(0), Op0.getOperand(1)); 14151 } 14152 14153 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 14154 return V; 14155 14156 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 14157 return V; 14158 14159 if (SDValue V = reduceBuildVecToShuffle(N)) 14160 return V; 14161 14162 return SDValue(); 14163 } 14164 14165 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 14166 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14167 EVT OpVT = N->getOperand(0).getValueType(); 14168 14169 // If the operands are legal vectors, leave them alone. 14170 if (TLI.isTypeLegal(OpVT)) 14171 return SDValue(); 14172 14173 SDLoc DL(N); 14174 EVT VT = N->getValueType(0); 14175 SmallVector<SDValue, 8> Ops; 14176 14177 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 14178 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14179 14180 // Keep track of what we encounter. 14181 bool AnyInteger = false; 14182 bool AnyFP = false; 14183 for (const SDValue &Op : N->ops()) { 14184 if (ISD::BITCAST == Op.getOpcode() && 14185 !Op.getOperand(0).getValueType().isVector()) 14186 Ops.push_back(Op.getOperand(0)); 14187 else if (ISD::UNDEF == Op.getOpcode()) 14188 Ops.push_back(ScalarUndef); 14189 else 14190 return SDValue(); 14191 14192 // Note whether we encounter an integer or floating point scalar. 14193 // If it's neither, bail out, it could be something weird like x86mmx. 14194 EVT LastOpVT = Ops.back().getValueType(); 14195 if (LastOpVT.isFloatingPoint()) 14196 AnyFP = true; 14197 else if (LastOpVT.isInteger()) 14198 AnyInteger = true; 14199 else 14200 return SDValue(); 14201 } 14202 14203 // If any of the operands is a floating point scalar bitcast to a vector, 14204 // use floating point types throughout, and bitcast everything. 14205 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 14206 if (AnyFP) { 14207 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 14208 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14209 if (AnyInteger) { 14210 for (SDValue &Op : Ops) { 14211 if (Op.getValueType() == SVT) 14212 continue; 14213 if (Op.isUndef()) 14214 Op = ScalarUndef; 14215 else 14216 Op = DAG.getBitcast(SVT, Op); 14217 } 14218 } 14219 } 14220 14221 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 14222 VT.getSizeInBits() / SVT.getSizeInBits()); 14223 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 14224 } 14225 14226 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 14227 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 14228 // most two distinct vectors the same size as the result, attempt to turn this 14229 // into a legal shuffle. 14230 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 14231 EVT VT = N->getValueType(0); 14232 EVT OpVT = N->getOperand(0).getValueType(); 14233 int NumElts = VT.getVectorNumElements(); 14234 int NumOpElts = OpVT.getVectorNumElements(); 14235 14236 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 14237 SmallVector<int, 8> Mask; 14238 14239 for (SDValue Op : N->ops()) { 14240 // Peek through any bitcast. 14241 while (Op.getOpcode() == ISD::BITCAST) 14242 Op = Op.getOperand(0); 14243 14244 // UNDEF nodes convert to UNDEF shuffle mask values. 14245 if (Op.isUndef()) { 14246 Mask.append((unsigned)NumOpElts, -1); 14247 continue; 14248 } 14249 14250 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14251 return SDValue(); 14252 14253 // What vector are we extracting the subvector from and at what index? 14254 SDValue ExtVec = Op.getOperand(0); 14255 14256 // We want the EVT of the original extraction to correctly scale the 14257 // extraction index. 14258 EVT ExtVT = ExtVec.getValueType(); 14259 14260 // Peek through any bitcast. 14261 while (ExtVec.getOpcode() == ISD::BITCAST) 14262 ExtVec = ExtVec.getOperand(0); 14263 14264 // UNDEF nodes convert to UNDEF shuffle mask values. 14265 if (ExtVec.isUndef()) { 14266 Mask.append((unsigned)NumOpElts, -1); 14267 continue; 14268 } 14269 14270 if (!isa<ConstantSDNode>(Op.getOperand(1))) 14271 return SDValue(); 14272 int ExtIdx = Op.getConstantOperandVal(1); 14273 14274 // Ensure that we are extracting a subvector from a vector the same 14275 // size as the result. 14276 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 14277 return SDValue(); 14278 14279 // Scale the subvector index to account for any bitcast. 14280 int NumExtElts = ExtVT.getVectorNumElements(); 14281 if (0 == (NumExtElts % NumElts)) 14282 ExtIdx /= (NumExtElts / NumElts); 14283 else if (0 == (NumElts % NumExtElts)) 14284 ExtIdx *= (NumElts / NumExtElts); 14285 else 14286 return SDValue(); 14287 14288 // At most we can reference 2 inputs in the final shuffle. 14289 if (SV0.isUndef() || SV0 == ExtVec) { 14290 SV0 = ExtVec; 14291 for (int i = 0; i != NumOpElts; ++i) 14292 Mask.push_back(i + ExtIdx); 14293 } else if (SV1.isUndef() || SV1 == ExtVec) { 14294 SV1 = ExtVec; 14295 for (int i = 0; i != NumOpElts; ++i) 14296 Mask.push_back(i + ExtIdx + NumElts); 14297 } else { 14298 return SDValue(); 14299 } 14300 } 14301 14302 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 14303 return SDValue(); 14304 14305 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 14306 DAG.getBitcast(VT, SV1), Mask); 14307 } 14308 14309 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 14310 // If we only have one input vector, we don't need to do any concatenation. 14311 if (N->getNumOperands() == 1) 14312 return N->getOperand(0); 14313 14314 // Check if all of the operands are undefs. 14315 EVT VT = N->getValueType(0); 14316 if (ISD::allOperandsUndef(N)) 14317 return DAG.getUNDEF(VT); 14318 14319 // Optimize concat_vectors where all but the first of the vectors are undef. 14320 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 14321 return Op.isUndef(); 14322 })) { 14323 SDValue In = N->getOperand(0); 14324 assert(In.getValueType().isVector() && "Must concat vectors"); 14325 14326 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 14327 if (In->getOpcode() == ISD::BITCAST && 14328 !In->getOperand(0)->getValueType(0).isVector()) { 14329 SDValue Scalar = In->getOperand(0); 14330 14331 // If the bitcast type isn't legal, it might be a trunc of a legal type; 14332 // look through the trunc so we can still do the transform: 14333 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 14334 if (Scalar->getOpcode() == ISD::TRUNCATE && 14335 !TLI.isTypeLegal(Scalar.getValueType()) && 14336 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 14337 Scalar = Scalar->getOperand(0); 14338 14339 EVT SclTy = Scalar->getValueType(0); 14340 14341 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 14342 return SDValue(); 14343 14344 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 14345 if (VNTNumElms < 2) 14346 return SDValue(); 14347 14348 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 14349 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 14350 return SDValue(); 14351 14352 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 14353 return DAG.getBitcast(VT, Res); 14354 } 14355 } 14356 14357 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 14358 // We have already tested above for an UNDEF only concatenation. 14359 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 14360 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 14361 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 14362 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 14363 }; 14364 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 14365 SmallVector<SDValue, 8> Opnds; 14366 EVT SVT = VT.getScalarType(); 14367 14368 EVT MinVT = SVT; 14369 if (!SVT.isFloatingPoint()) { 14370 // If BUILD_VECTOR are from built from integer, they may have different 14371 // operand types. Get the smallest type and truncate all operands to it. 14372 bool FoundMinVT = false; 14373 for (const SDValue &Op : N->ops()) 14374 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14375 EVT OpSVT = Op.getOperand(0)->getValueType(0); 14376 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 14377 FoundMinVT = true; 14378 } 14379 assert(FoundMinVT && "Concat vector type mismatch"); 14380 } 14381 14382 for (const SDValue &Op : N->ops()) { 14383 EVT OpVT = Op.getValueType(); 14384 unsigned NumElts = OpVT.getVectorNumElements(); 14385 14386 if (ISD::UNDEF == Op.getOpcode()) 14387 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 14388 14389 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14390 if (SVT.isFloatingPoint()) { 14391 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 14392 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 14393 } else { 14394 for (unsigned i = 0; i != NumElts; ++i) 14395 Opnds.push_back( 14396 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 14397 } 14398 } 14399 } 14400 14401 assert(VT.getVectorNumElements() == Opnds.size() && 14402 "Concat vector type mismatch"); 14403 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 14404 } 14405 14406 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 14407 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 14408 return V; 14409 14410 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 14411 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 14412 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 14413 return V; 14414 14415 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 14416 // nodes often generate nop CONCAT_VECTOR nodes. 14417 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 14418 // place the incoming vectors at the exact same location. 14419 SDValue SingleSource = SDValue(); 14420 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 14421 14422 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14423 SDValue Op = N->getOperand(i); 14424 14425 if (Op.isUndef()) 14426 continue; 14427 14428 // Check if this is the identity extract: 14429 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14430 return SDValue(); 14431 14432 // Find the single incoming vector for the extract_subvector. 14433 if (SingleSource.getNode()) { 14434 if (Op.getOperand(0) != SingleSource) 14435 return SDValue(); 14436 } else { 14437 SingleSource = Op.getOperand(0); 14438 14439 // Check the source type is the same as the type of the result. 14440 // If not, this concat may extend the vector, so we can not 14441 // optimize it away. 14442 if (SingleSource.getValueType() != N->getValueType(0)) 14443 return SDValue(); 14444 } 14445 14446 unsigned IdentityIndex = i * PartNumElem; 14447 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14448 // The extract index must be constant. 14449 if (!CS) 14450 return SDValue(); 14451 14452 // Check that we are reading from the identity index. 14453 if (CS->getZExtValue() != IdentityIndex) 14454 return SDValue(); 14455 } 14456 14457 if (SingleSource.getNode()) 14458 return SingleSource; 14459 14460 return SDValue(); 14461 } 14462 14463 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 14464 EVT NVT = N->getValueType(0); 14465 SDValue V = N->getOperand(0); 14466 14467 // Extract from UNDEF is UNDEF. 14468 if (V.isUndef()) 14469 return DAG.getUNDEF(NVT); 14470 14471 // Combine: 14472 // (extract_subvec (concat V1, V2, ...), i) 14473 // Into: 14474 // Vi if possible 14475 // Only operand 0 is checked as 'concat' assumes all inputs of the same 14476 // type. 14477 if (V->getOpcode() == ISD::CONCAT_VECTORS && 14478 isa<ConstantSDNode>(N->getOperand(1)) && 14479 V->getOperand(0).getValueType() == NVT) { 14480 unsigned Idx = N->getConstantOperandVal(1); 14481 unsigned NumElems = NVT.getVectorNumElements(); 14482 assert((Idx % NumElems) == 0 && 14483 "IDX in concat is not a multiple of the result vector length."); 14484 return V->getOperand(Idx / NumElems); 14485 } 14486 14487 // Skip bitcasting 14488 if (V->getOpcode() == ISD::BITCAST) 14489 V = V.getOperand(0); 14490 14491 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 14492 // Handle only simple case where vector being inserted and vector 14493 // being extracted are of same size. 14494 EVT SmallVT = V->getOperand(1).getValueType(); 14495 if (!NVT.bitsEq(SmallVT)) 14496 return SDValue(); 14497 14498 // Only handle cases where both indexes are constants. 14499 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14500 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14501 14502 if (InsIdx && ExtIdx) { 14503 // Combine: 14504 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 14505 // Into: 14506 // indices are equal or bit offsets are equal => V1 14507 // otherwise => (extract_subvec V1, ExtIdx) 14508 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 14509 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 14510 return DAG.getBitcast(NVT, V->getOperand(1)); 14511 return DAG.getNode( 14512 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 14513 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 14514 N->getOperand(1)); 14515 } 14516 } 14517 14518 return SDValue(); 14519 } 14520 14521 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 14522 SDValue V, SelectionDAG &DAG) { 14523 SDLoc DL(V); 14524 EVT VT = V.getValueType(); 14525 14526 switch (V.getOpcode()) { 14527 default: 14528 return V; 14529 14530 case ISD::CONCAT_VECTORS: { 14531 EVT OpVT = V->getOperand(0).getValueType(); 14532 int OpSize = OpVT.getVectorNumElements(); 14533 SmallBitVector OpUsedElements(OpSize, false); 14534 bool FoundSimplification = false; 14535 SmallVector<SDValue, 4> NewOps; 14536 NewOps.reserve(V->getNumOperands()); 14537 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 14538 SDValue Op = V->getOperand(i); 14539 bool OpUsed = false; 14540 for (int j = 0; j < OpSize; ++j) 14541 if (UsedElements[i * OpSize + j]) { 14542 OpUsedElements[j] = true; 14543 OpUsed = true; 14544 } 14545 NewOps.push_back( 14546 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 14547 : DAG.getUNDEF(OpVT)); 14548 FoundSimplification |= Op == NewOps.back(); 14549 OpUsedElements.reset(); 14550 } 14551 if (FoundSimplification) 14552 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 14553 return V; 14554 } 14555 14556 case ISD::INSERT_SUBVECTOR: { 14557 SDValue BaseV = V->getOperand(0); 14558 SDValue SubV = V->getOperand(1); 14559 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14560 if (!IdxN) 14561 return V; 14562 14563 int SubSize = SubV.getValueType().getVectorNumElements(); 14564 int Idx = IdxN->getZExtValue(); 14565 bool SubVectorUsed = false; 14566 SmallBitVector SubUsedElements(SubSize, false); 14567 for (int i = 0; i < SubSize; ++i) 14568 if (UsedElements[i + Idx]) { 14569 SubVectorUsed = true; 14570 SubUsedElements[i] = true; 14571 UsedElements[i + Idx] = false; 14572 } 14573 14574 // Now recurse on both the base and sub vectors. 14575 SDValue SimplifiedSubV = 14576 SubVectorUsed 14577 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 14578 : DAG.getUNDEF(SubV.getValueType()); 14579 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 14580 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 14581 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 14582 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 14583 return V; 14584 } 14585 } 14586 } 14587 14588 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 14589 SDValue N1, SelectionDAG &DAG) { 14590 EVT VT = SVN->getValueType(0); 14591 int NumElts = VT.getVectorNumElements(); 14592 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 14593 for (int M : SVN->getMask()) 14594 if (M >= 0 && M < NumElts) 14595 N0UsedElements[M] = true; 14596 else if (M >= NumElts) 14597 N1UsedElements[M - NumElts] = true; 14598 14599 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 14600 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 14601 if (S0 == N0 && S1 == N1) 14602 return SDValue(); 14603 14604 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 14605 } 14606 14607 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 14608 // or turn a shuffle of a single concat into simpler shuffle then concat. 14609 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 14610 EVT VT = N->getValueType(0); 14611 unsigned NumElts = VT.getVectorNumElements(); 14612 14613 SDValue N0 = N->getOperand(0); 14614 SDValue N1 = N->getOperand(1); 14615 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14616 14617 SmallVector<SDValue, 4> Ops; 14618 EVT ConcatVT = N0.getOperand(0).getValueType(); 14619 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 14620 unsigned NumConcats = NumElts / NumElemsPerConcat; 14621 14622 // Special case: shuffle(concat(A,B)) can be more efficiently represented 14623 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 14624 // half vector elements. 14625 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 14626 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 14627 SVN->getMask().end(), [](int i) { return i == -1; })) { 14628 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 14629 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 14630 N1 = DAG.getUNDEF(ConcatVT); 14631 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 14632 } 14633 14634 // Look at every vector that's inserted. We're looking for exact 14635 // subvector-sized copies from a concatenated vector 14636 for (unsigned I = 0; I != NumConcats; ++I) { 14637 // Make sure we're dealing with a copy. 14638 unsigned Begin = I * NumElemsPerConcat; 14639 bool AllUndef = true, NoUndef = true; 14640 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 14641 if (SVN->getMaskElt(J) >= 0) 14642 AllUndef = false; 14643 else 14644 NoUndef = false; 14645 } 14646 14647 if (NoUndef) { 14648 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 14649 return SDValue(); 14650 14651 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 14652 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 14653 return SDValue(); 14654 14655 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 14656 if (FirstElt < N0.getNumOperands()) 14657 Ops.push_back(N0.getOperand(FirstElt)); 14658 else 14659 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 14660 14661 } else if (AllUndef) { 14662 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 14663 } else { // Mixed with general masks and undefs, can't do optimization. 14664 return SDValue(); 14665 } 14666 } 14667 14668 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 14669 } 14670 14671 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 14672 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 14673 // 14674 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 14675 // a simplification in some sense, but it isn't appropriate in general: some 14676 // BUILD_VECTORs are substantially cheaper than others. The general case 14677 // of a BUILD_VECTOR requires inserting each element individually (or 14678 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 14679 // all constants is a single constant pool load. A BUILD_VECTOR where each 14680 // element is identical is a splat. A BUILD_VECTOR where most of the operands 14681 // are undef lowers to a small number of element insertions. 14682 // 14683 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 14684 // We don't fold shuffles where one side is a non-zero constant, and we don't 14685 // fold shuffles if the resulting BUILD_VECTOR would have duplicate 14686 // non-constant operands. This seems to work out reasonably well in practice. 14687 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 14688 SelectionDAG &DAG, 14689 const TargetLowering &TLI) { 14690 EVT VT = SVN->getValueType(0); 14691 unsigned NumElts = VT.getVectorNumElements(); 14692 SDValue N0 = SVN->getOperand(0); 14693 SDValue N1 = SVN->getOperand(1); 14694 14695 if (!N0->hasOneUse() || !N1->hasOneUse()) 14696 return SDValue(); 14697 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 14698 // discussed above. 14699 if (!N1.isUndef()) { 14700 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 14701 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 14702 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 14703 return SDValue(); 14704 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 14705 return SDValue(); 14706 } 14707 14708 SmallVector<SDValue, 8> Ops; 14709 SmallSet<SDValue, 16> DuplicateOps; 14710 for (int M : SVN->getMask()) { 14711 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 14712 if (M >= 0) { 14713 int Idx = M < (int)NumElts ? M : M - NumElts; 14714 SDValue &S = (M < (int)NumElts ? N0 : N1); 14715 if (S.getOpcode() == ISD::BUILD_VECTOR) { 14716 Op = S.getOperand(Idx); 14717 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 14718 if (Idx == 0) 14719 Op = S.getOperand(0); 14720 } else { 14721 // Operand can't be combined - bail out. 14722 return SDValue(); 14723 } 14724 } 14725 14726 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is 14727 // fine, but it's likely to generate low-quality code if the target can't 14728 // reconstruct an appropriate shuffle. 14729 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 14730 if (!DuplicateOps.insert(Op).second) 14731 return SDValue(); 14732 14733 Ops.push_back(Op); 14734 } 14735 // BUILD_VECTOR requires all inputs to be of the same type, find the 14736 // maximum type and extend them all. 14737 EVT SVT = VT.getScalarType(); 14738 if (SVT.isInteger()) 14739 for (SDValue &Op : Ops) 14740 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 14741 if (SVT != VT.getScalarType()) 14742 for (SDValue &Op : Ops) 14743 Op = TLI.isZExtFree(Op.getValueType(), SVT) 14744 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 14745 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 14746 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 14747 } 14748 14749 // Match shuffles that can be converted to any_vector_extend_in_reg. 14750 // This is often generated during legalization. 14751 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 14752 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 14753 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 14754 SelectionDAG &DAG, 14755 const TargetLowering &TLI, 14756 bool LegalOperations) { 14757 EVT VT = SVN->getValueType(0); 14758 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 14759 14760 // TODO Add support for big-endian when we have a test case. 14761 if (!VT.isInteger() || IsBigEndian) 14762 return SDValue(); 14763 14764 unsigned NumElts = VT.getVectorNumElements(); 14765 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 14766 ArrayRef<int> Mask = SVN->getMask(); 14767 SDValue N0 = SVN->getOperand(0); 14768 14769 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 14770 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 14771 for (unsigned i = 0; i != NumElts; ++i) { 14772 if (Mask[i] < 0) 14773 continue; 14774 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 14775 continue; 14776 return false; 14777 } 14778 return true; 14779 }; 14780 14781 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 14782 // power-of-2 extensions as they are the most likely. 14783 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 14784 if (!isAnyExtend(Scale)) 14785 continue; 14786 14787 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 14788 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 14789 if (!LegalOperations || 14790 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 14791 return DAG.getBitcast(VT, 14792 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 14793 } 14794 14795 return SDValue(); 14796 } 14797 14798 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 14799 // each source element of a large type into the lowest elements of a smaller 14800 // destination type. This is often generated during legalization. 14801 // If the source node itself was a '*_extend_vector_inreg' node then we should 14802 // then be able to remove it. 14803 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) { 14804 EVT VT = SVN->getValueType(0); 14805 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 14806 14807 // TODO Add support for big-endian when we have a test case. 14808 if (!VT.isInteger() || IsBigEndian) 14809 return SDValue(); 14810 14811 SDValue N0 = SVN->getOperand(0); 14812 while (N0.getOpcode() == ISD::BITCAST) 14813 N0 = N0.getOperand(0); 14814 14815 unsigned Opcode = N0.getOpcode(); 14816 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 14817 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 14818 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 14819 return SDValue(); 14820 14821 SDValue N00 = N0.getOperand(0); 14822 ArrayRef<int> Mask = SVN->getMask(); 14823 unsigned NumElts = VT.getVectorNumElements(); 14824 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 14825 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 14826 14827 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 14828 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 14829 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 14830 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 14831 for (unsigned i = 0; i != NumElts; ++i) { 14832 if (Mask[i] < 0) 14833 continue; 14834 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 14835 continue; 14836 return false; 14837 } 14838 return true; 14839 }; 14840 14841 // At the moment we just handle the case where we've truncated back to the 14842 // same size as before the extension. 14843 // TODO: handle more extension/truncation cases as cases arise. 14844 if (EltSizeInBits != ExtSrcSizeInBits) 14845 return SDValue(); 14846 14847 // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for 14848 // power-of-2 truncations as they are the most likely. 14849 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) 14850 if (isTruncate(Scale)) 14851 return DAG.getBitcast(VT, N00); 14852 14853 return SDValue(); 14854 } 14855 14856 // Combine shuffles of splat-shuffles of the form: 14857 // shuffle (shuffle V, undef, splat-mask), undef, M 14858 // If splat-mask contains undef elements, we need to be careful about 14859 // introducing undef's in the folded mask which are not the result of composing 14860 // the masks of the shuffles. 14861 static SDValue combineShuffleOfSplat(ArrayRef<int> UserMask, 14862 ShuffleVectorSDNode *Splat, 14863 SelectionDAG &DAG) { 14864 ArrayRef<int> SplatMask = Splat->getMask(); 14865 assert(UserMask.size() == SplatMask.size() && "Mask length mismatch"); 14866 14867 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 14868 // every undef mask element in the splat-shuffle has a corresponding undef 14869 // element in the user-shuffle's mask or if the composition of mask elements 14870 // would result in undef. 14871 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 14872 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 14873 // In this case it is not legal to simplify to the splat-shuffle because we 14874 // may be exposing the users of the shuffle an undef element at index 1 14875 // which was not there before the combine. 14876 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 14877 // In this case the composition of masks yields SplatMask, so it's ok to 14878 // simplify to the splat-shuffle. 14879 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 14880 // In this case the composed mask includes all undef elements of SplatMask 14881 // and in addition sets element zero to undef. It is safe to simplify to 14882 // the splat-shuffle. 14883 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 14884 ArrayRef<int> SplatMask) { 14885 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 14886 if (UserMask[i] != -1 && SplatMask[i] == -1 && 14887 SplatMask[UserMask[i]] != -1) 14888 return false; 14889 return true; 14890 }; 14891 if (CanSimplifyToExistingSplat(UserMask, SplatMask)) 14892 return SDValue(Splat, 0); 14893 14894 // Create a new shuffle with a mask that is composed of the two shuffles' 14895 // masks. 14896 SmallVector<int, 32> NewMask; 14897 for (int Idx : UserMask) 14898 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 14899 14900 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 14901 Splat->getOperand(0), Splat->getOperand(1), 14902 NewMask); 14903 } 14904 14905 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 14906 EVT VT = N->getValueType(0); 14907 unsigned NumElts = VT.getVectorNumElements(); 14908 14909 SDValue N0 = N->getOperand(0); 14910 SDValue N1 = N->getOperand(1); 14911 14912 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 14913 14914 // Canonicalize shuffle undef, undef -> undef 14915 if (N0.isUndef() && N1.isUndef()) 14916 return DAG.getUNDEF(VT); 14917 14918 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14919 14920 // Canonicalize shuffle v, v -> v, undef 14921 if (N0 == N1) { 14922 SmallVector<int, 8> NewMask; 14923 for (unsigned i = 0; i != NumElts; ++i) { 14924 int Idx = SVN->getMaskElt(i); 14925 if (Idx >= (int)NumElts) Idx -= NumElts; 14926 NewMask.push_back(Idx); 14927 } 14928 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 14929 } 14930 14931 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 14932 if (N0.isUndef()) 14933 return DAG.getCommutedVectorShuffle(*SVN); 14934 14935 // Remove references to rhs if it is undef 14936 if (N1.isUndef()) { 14937 bool Changed = false; 14938 SmallVector<int, 8> NewMask; 14939 for (unsigned i = 0; i != NumElts; ++i) { 14940 int Idx = SVN->getMaskElt(i); 14941 if (Idx >= (int)NumElts) { 14942 Idx = -1; 14943 Changed = true; 14944 } 14945 NewMask.push_back(Idx); 14946 } 14947 if (Changed) 14948 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 14949 } 14950 14951 // A shuffle of a single vector that is a splat can always be folded. 14952 if (auto *N0Shuf = dyn_cast<ShuffleVectorSDNode>(N0)) 14953 if (N1->isUndef() && N0Shuf->isSplat()) 14954 return combineShuffleOfSplat(SVN->getMask(), N0Shuf, DAG); 14955 14956 // If it is a splat, check if the argument vector is another splat or a 14957 // build_vector. 14958 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 14959 SDNode *V = N0.getNode(); 14960 14961 // If this is a bit convert that changes the element type of the vector but 14962 // not the number of vector elements, look through it. Be careful not to 14963 // look though conversions that change things like v4f32 to v2f64. 14964 if (V->getOpcode() == ISD::BITCAST) { 14965 SDValue ConvInput = V->getOperand(0); 14966 if (ConvInput.getValueType().isVector() && 14967 ConvInput.getValueType().getVectorNumElements() == NumElts) 14968 V = ConvInput.getNode(); 14969 } 14970 14971 if (V->getOpcode() == ISD::BUILD_VECTOR) { 14972 assert(V->getNumOperands() == NumElts && 14973 "BUILD_VECTOR has wrong number of operands"); 14974 SDValue Base; 14975 bool AllSame = true; 14976 for (unsigned i = 0; i != NumElts; ++i) { 14977 if (!V->getOperand(i).isUndef()) { 14978 Base = V->getOperand(i); 14979 break; 14980 } 14981 } 14982 // Splat of <u, u, u, u>, return <u, u, u, u> 14983 if (!Base.getNode()) 14984 return N0; 14985 for (unsigned i = 0; i != NumElts; ++i) { 14986 if (V->getOperand(i) != Base) { 14987 AllSame = false; 14988 break; 14989 } 14990 } 14991 // Splat of <x, x, x, x>, return <x, x, x, x> 14992 if (AllSame) 14993 return N0; 14994 14995 // Canonicalize any other splat as a build_vector. 14996 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 14997 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 14998 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 14999 15000 // We may have jumped through bitcasts, so the type of the 15001 // BUILD_VECTOR may not match the type of the shuffle. 15002 if (V->getValueType(0) != VT) 15003 NewBV = DAG.getBitcast(VT, NewBV); 15004 return NewBV; 15005 } 15006 } 15007 15008 // There are various patterns used to build up a vector from smaller vectors, 15009 // subvectors, or elements. Scan chains of these and replace unused insertions 15010 // or components with undef. 15011 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 15012 return S; 15013 15014 // Match shuffles that can be converted to any_vector_extend_in_reg. 15015 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) 15016 return V; 15017 15018 // Combine "truncate_vector_in_reg" style shuffles. 15019 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 15020 return V; 15021 15022 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 15023 Level < AfterLegalizeVectorOps && 15024 (N1.isUndef() || 15025 (N1.getOpcode() == ISD::CONCAT_VECTORS && 15026 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 15027 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 15028 return V; 15029 } 15030 15031 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 15032 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 15033 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 15034 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 15035 return Res; 15036 15037 // If this shuffle only has a single input that is a bitcasted shuffle, 15038 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 15039 // back to their original types. 15040 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 15041 N1.isUndef() && Level < AfterLegalizeVectorOps && 15042 TLI.isTypeLegal(VT)) { 15043 15044 // Peek through the bitcast only if there is one user. 15045 SDValue BC0 = N0; 15046 while (BC0.getOpcode() == ISD::BITCAST) { 15047 if (!BC0.hasOneUse()) 15048 break; 15049 BC0 = BC0.getOperand(0); 15050 } 15051 15052 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 15053 if (Scale == 1) 15054 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 15055 15056 SmallVector<int, 8> NewMask; 15057 for (int M : Mask) 15058 for (int s = 0; s != Scale; ++s) 15059 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 15060 return NewMask; 15061 }; 15062 15063 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 15064 EVT SVT = VT.getScalarType(); 15065 EVT InnerVT = BC0->getValueType(0); 15066 EVT InnerSVT = InnerVT.getScalarType(); 15067 15068 // Determine which shuffle works with the smaller scalar type. 15069 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 15070 EVT ScaleSVT = ScaleVT.getScalarType(); 15071 15072 if (TLI.isTypeLegal(ScaleVT) && 15073 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 15074 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 15075 15076 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 15077 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 15078 15079 // Scale the shuffle masks to the smaller scalar type. 15080 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 15081 SmallVector<int, 8> InnerMask = 15082 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 15083 SmallVector<int, 8> OuterMask = 15084 ScaleShuffleMask(SVN->getMask(), OuterScale); 15085 15086 // Merge the shuffle masks. 15087 SmallVector<int, 8> NewMask; 15088 for (int M : OuterMask) 15089 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 15090 15091 // Test for shuffle mask legality over both commutations. 15092 SDValue SV0 = BC0->getOperand(0); 15093 SDValue SV1 = BC0->getOperand(1); 15094 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 15095 if (!LegalMask) { 15096 std::swap(SV0, SV1); 15097 ShuffleVectorSDNode::commuteMask(NewMask); 15098 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 15099 } 15100 15101 if (LegalMask) { 15102 SV0 = DAG.getBitcast(ScaleVT, SV0); 15103 SV1 = DAG.getBitcast(ScaleVT, SV1); 15104 return DAG.getBitcast( 15105 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 15106 } 15107 } 15108 } 15109 } 15110 15111 // Canonicalize shuffles according to rules: 15112 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 15113 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 15114 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 15115 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 15116 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 15117 TLI.isTypeLegal(VT)) { 15118 // The incoming shuffle must be of the same type as the result of the 15119 // current shuffle. 15120 assert(N1->getOperand(0).getValueType() == VT && 15121 "Shuffle types don't match"); 15122 15123 SDValue SV0 = N1->getOperand(0); 15124 SDValue SV1 = N1->getOperand(1); 15125 bool HasSameOp0 = N0 == SV0; 15126 bool IsSV1Undef = SV1.isUndef(); 15127 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 15128 // Commute the operands of this shuffle so that next rule 15129 // will trigger. 15130 return DAG.getCommutedVectorShuffle(*SVN); 15131 } 15132 15133 // Try to fold according to rules: 15134 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 15135 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 15136 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 15137 // Don't try to fold shuffles with illegal type. 15138 // Only fold if this shuffle is the only user of the other shuffle. 15139 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 15140 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 15141 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 15142 15143 // Don't try to fold splats; they're likely to simplify somehow, or they 15144 // might be free. 15145 if (OtherSV->isSplat()) 15146 return SDValue(); 15147 15148 // The incoming shuffle must be of the same type as the result of the 15149 // current shuffle. 15150 assert(OtherSV->getOperand(0).getValueType() == VT && 15151 "Shuffle types don't match"); 15152 15153 SDValue SV0, SV1; 15154 SmallVector<int, 4> Mask; 15155 // Compute the combined shuffle mask for a shuffle with SV0 as the first 15156 // operand, and SV1 as the second operand. 15157 for (unsigned i = 0; i != NumElts; ++i) { 15158 int Idx = SVN->getMaskElt(i); 15159 if (Idx < 0) { 15160 // Propagate Undef. 15161 Mask.push_back(Idx); 15162 continue; 15163 } 15164 15165 SDValue CurrentVec; 15166 if (Idx < (int)NumElts) { 15167 // This shuffle index refers to the inner shuffle N0. Lookup the inner 15168 // shuffle mask to identify which vector is actually referenced. 15169 Idx = OtherSV->getMaskElt(Idx); 15170 if (Idx < 0) { 15171 // Propagate Undef. 15172 Mask.push_back(Idx); 15173 continue; 15174 } 15175 15176 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 15177 : OtherSV->getOperand(1); 15178 } else { 15179 // This shuffle index references an element within N1. 15180 CurrentVec = N1; 15181 } 15182 15183 // Simple case where 'CurrentVec' is UNDEF. 15184 if (CurrentVec.isUndef()) { 15185 Mask.push_back(-1); 15186 continue; 15187 } 15188 15189 // Canonicalize the shuffle index. We don't know yet if CurrentVec 15190 // will be the first or second operand of the combined shuffle. 15191 Idx = Idx % NumElts; 15192 if (!SV0.getNode() || SV0 == CurrentVec) { 15193 // Ok. CurrentVec is the left hand side. 15194 // Update the mask accordingly. 15195 SV0 = CurrentVec; 15196 Mask.push_back(Idx); 15197 continue; 15198 } 15199 15200 // Bail out if we cannot convert the shuffle pair into a single shuffle. 15201 if (SV1.getNode() && SV1 != CurrentVec) 15202 return SDValue(); 15203 15204 // Ok. CurrentVec is the right hand side. 15205 // Update the mask accordingly. 15206 SV1 = CurrentVec; 15207 Mask.push_back(Idx + NumElts); 15208 } 15209 15210 // Check if all indices in Mask are Undef. In case, propagate Undef. 15211 bool isUndefMask = true; 15212 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 15213 isUndefMask &= Mask[i] < 0; 15214 15215 if (isUndefMask) 15216 return DAG.getUNDEF(VT); 15217 15218 if (!SV0.getNode()) 15219 SV0 = DAG.getUNDEF(VT); 15220 if (!SV1.getNode()) 15221 SV1 = DAG.getUNDEF(VT); 15222 15223 // Avoid introducing shuffles with illegal mask. 15224 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 15225 ShuffleVectorSDNode::commuteMask(Mask); 15226 15227 if (!TLI.isShuffleMaskLegal(Mask, VT)) 15228 return SDValue(); 15229 15230 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 15231 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 15232 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 15233 std::swap(SV0, SV1); 15234 } 15235 15236 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 15237 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 15238 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 15239 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 15240 } 15241 15242 return SDValue(); 15243 } 15244 15245 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 15246 SDValue InVal = N->getOperand(0); 15247 EVT VT = N->getValueType(0); 15248 15249 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 15250 // with a VECTOR_SHUFFLE. 15251 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 15252 SDValue InVec = InVal->getOperand(0); 15253 SDValue EltNo = InVal->getOperand(1); 15254 15255 // FIXME: We could support implicit truncation if the shuffle can be 15256 // scaled to a smaller vector scalar type. 15257 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 15258 if (C0 && VT == InVec.getValueType() && 15259 VT.getScalarType() == InVal.getValueType()) { 15260 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 15261 int Elt = C0->getZExtValue(); 15262 NewMask[0] = Elt; 15263 15264 if (TLI.isShuffleMaskLegal(NewMask, VT)) 15265 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 15266 NewMask); 15267 } 15268 } 15269 15270 return SDValue(); 15271 } 15272 15273 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 15274 EVT VT = N->getValueType(0); 15275 SDValue N0 = N->getOperand(0); 15276 SDValue N1 = N->getOperand(1); 15277 SDValue N2 = N->getOperand(2); 15278 15279 // If inserting an UNDEF, just return the original vector. 15280 if (N1.isUndef()) 15281 return N0; 15282 15283 // If this is an insert of an extracted vector into an undef vector, we can 15284 // just use the input to the extract. 15285 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 15286 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 15287 return N1.getOperand(0); 15288 15289 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 15290 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 15291 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 15292 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 15293 N0.getOperand(1).getValueType() == N1.getValueType() && 15294 N0.getOperand(2) == N2) 15295 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 15296 N1, N2); 15297 15298 if (!isa<ConstantSDNode>(N2)) 15299 return SDValue(); 15300 15301 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 15302 15303 // Canonicalize insert_subvector dag nodes. 15304 // Example: 15305 // (insert_subvector (insert_subvector A, Idx0), Idx1) 15306 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 15307 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 15308 N1.getValueType() == N0.getOperand(1).getValueType() && 15309 isa<ConstantSDNode>(N0.getOperand(2))) { 15310 unsigned OtherIdx = N0.getConstantOperandVal(2); 15311 if (InsIdx < OtherIdx) { 15312 // Swap nodes. 15313 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 15314 N0.getOperand(0), N1, N2); 15315 AddToWorklist(NewOp.getNode()); 15316 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 15317 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 15318 } 15319 } 15320 15321 // If the input vector is a concatenation, and the insert replaces 15322 // one of the pieces, we can optimize into a single concat_vectors. 15323 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 15324 N0.getOperand(0).getValueType() == N1.getValueType()) { 15325 unsigned Factor = N1.getValueType().getVectorNumElements(); 15326 15327 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 15328 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 15329 15330 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 15331 } 15332 15333 return SDValue(); 15334 } 15335 15336 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 15337 SDValue N0 = N->getOperand(0); 15338 15339 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 15340 if (N0->getOpcode() == ISD::FP16_TO_FP) 15341 return N0->getOperand(0); 15342 15343 return SDValue(); 15344 } 15345 15346 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 15347 SDValue N0 = N->getOperand(0); 15348 15349 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 15350 if (N0->getOpcode() == ISD::AND) { 15351 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 15352 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 15353 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 15354 N0.getOperand(0)); 15355 } 15356 } 15357 15358 return SDValue(); 15359 } 15360 15361 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 15362 /// with the destination vector and a zero vector. 15363 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 15364 /// vector_shuffle V, Zero, <0, 4, 2, 4> 15365 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 15366 EVT VT = N->getValueType(0); 15367 SDValue LHS = N->getOperand(0); 15368 SDValue RHS = N->getOperand(1); 15369 SDLoc DL(N); 15370 15371 // Make sure we're not running after operation legalization where it 15372 // may have custom lowered the vector shuffles. 15373 if (LegalOperations) 15374 return SDValue(); 15375 15376 if (N->getOpcode() != ISD::AND) 15377 return SDValue(); 15378 15379 if (RHS.getOpcode() == ISD::BITCAST) 15380 RHS = RHS.getOperand(0); 15381 15382 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 15383 return SDValue(); 15384 15385 EVT RVT = RHS.getValueType(); 15386 unsigned NumElts = RHS.getNumOperands(); 15387 15388 // Attempt to create a valid clear mask, splitting the mask into 15389 // sub elements and checking to see if each is 15390 // all zeros or all ones - suitable for shuffle masking. 15391 auto BuildClearMask = [&](int Split) { 15392 int NumSubElts = NumElts * Split; 15393 int NumSubBits = RVT.getScalarSizeInBits() / Split; 15394 15395 SmallVector<int, 8> Indices; 15396 for (int i = 0; i != NumSubElts; ++i) { 15397 int EltIdx = i / Split; 15398 int SubIdx = i % Split; 15399 SDValue Elt = RHS.getOperand(EltIdx); 15400 if (Elt.isUndef()) { 15401 Indices.push_back(-1); 15402 continue; 15403 } 15404 15405 APInt Bits; 15406 if (isa<ConstantSDNode>(Elt)) 15407 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 15408 else if (isa<ConstantFPSDNode>(Elt)) 15409 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 15410 else 15411 return SDValue(); 15412 15413 // Extract the sub element from the constant bit mask. 15414 if (DAG.getDataLayout().isBigEndian()) { 15415 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 15416 } else { 15417 Bits.lshrInPlace(SubIdx * NumSubBits); 15418 } 15419 15420 if (Split > 1) 15421 Bits = Bits.trunc(NumSubBits); 15422 15423 if (Bits.isAllOnesValue()) 15424 Indices.push_back(i); 15425 else if (Bits == 0) 15426 Indices.push_back(i + NumSubElts); 15427 else 15428 return SDValue(); 15429 } 15430 15431 // Let's see if the target supports this vector_shuffle. 15432 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 15433 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 15434 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 15435 return SDValue(); 15436 15437 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 15438 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 15439 DAG.getBitcast(ClearVT, LHS), 15440 Zero, Indices)); 15441 }; 15442 15443 // Determine maximum split level (byte level masking). 15444 int MaxSplit = 1; 15445 if (RVT.getScalarSizeInBits() % 8 == 0) 15446 MaxSplit = RVT.getScalarSizeInBits() / 8; 15447 15448 for (int Split = 1; Split <= MaxSplit; ++Split) 15449 if (RVT.getScalarSizeInBits() % Split == 0) 15450 if (SDValue S = BuildClearMask(Split)) 15451 return S; 15452 15453 return SDValue(); 15454 } 15455 15456 /// Visit a binary vector operation, like ADD. 15457 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 15458 assert(N->getValueType(0).isVector() && 15459 "SimplifyVBinOp only works on vectors!"); 15460 15461 SDValue LHS = N->getOperand(0); 15462 SDValue RHS = N->getOperand(1); 15463 SDValue Ops[] = {LHS, RHS}; 15464 15465 // See if we can constant fold the vector operation. 15466 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 15467 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 15468 return Fold; 15469 15470 // Try to convert a constant mask AND into a shuffle clear mask. 15471 if (SDValue Shuffle = XformToShuffleWithZero(N)) 15472 return Shuffle; 15473 15474 // Type legalization might introduce new shuffles in the DAG. 15475 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 15476 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 15477 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 15478 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 15479 LHS.getOperand(1).isUndef() && 15480 RHS.getOperand(1).isUndef()) { 15481 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 15482 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 15483 15484 if (SVN0->getMask().equals(SVN1->getMask())) { 15485 EVT VT = N->getValueType(0); 15486 SDValue UndefVector = LHS.getOperand(1); 15487 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 15488 LHS.getOperand(0), RHS.getOperand(0), 15489 N->getFlags()); 15490 AddUsersToWorklist(N); 15491 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 15492 SVN0->getMask()); 15493 } 15494 } 15495 15496 return SDValue(); 15497 } 15498 15499 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 15500 SDValue N2) { 15501 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 15502 15503 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 15504 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 15505 15506 // If we got a simplified select_cc node back from SimplifySelectCC, then 15507 // break it down into a new SETCC node, and a new SELECT node, and then return 15508 // the SELECT node, since we were called with a SELECT node. 15509 if (SCC.getNode()) { 15510 // Check to see if we got a select_cc back (to turn into setcc/select). 15511 // Otherwise, just return whatever node we got back, like fabs. 15512 if (SCC.getOpcode() == ISD::SELECT_CC) { 15513 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 15514 N0.getValueType(), 15515 SCC.getOperand(0), SCC.getOperand(1), 15516 SCC.getOperand(4)); 15517 AddToWorklist(SETCC.getNode()); 15518 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 15519 SCC.getOperand(2), SCC.getOperand(3)); 15520 } 15521 15522 return SCC; 15523 } 15524 return SDValue(); 15525 } 15526 15527 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 15528 /// being selected between, see if we can simplify the select. Callers of this 15529 /// should assume that TheSelect is deleted if this returns true. As such, they 15530 /// should return the appropriate thing (e.g. the node) back to the top-level of 15531 /// the DAG combiner loop to avoid it being looked at. 15532 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 15533 SDValue RHS) { 15534 15535 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15536 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 15537 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 15538 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 15539 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 15540 SDValue Sqrt = RHS; 15541 ISD::CondCode CC; 15542 SDValue CmpLHS; 15543 const ConstantFPSDNode *Zero = nullptr; 15544 15545 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 15546 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 15547 CmpLHS = TheSelect->getOperand(0); 15548 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 15549 } else { 15550 // SELECT or VSELECT 15551 SDValue Cmp = TheSelect->getOperand(0); 15552 if (Cmp.getOpcode() == ISD::SETCC) { 15553 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 15554 CmpLHS = Cmp.getOperand(0); 15555 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 15556 } 15557 } 15558 if (Zero && Zero->isZero() && 15559 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 15560 CC == ISD::SETULT || CC == ISD::SETLT)) { 15561 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15562 CombineTo(TheSelect, Sqrt); 15563 return true; 15564 } 15565 } 15566 } 15567 // Cannot simplify select with vector condition 15568 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 15569 15570 // If this is a select from two identical things, try to pull the operation 15571 // through the select. 15572 if (LHS.getOpcode() != RHS.getOpcode() || 15573 !LHS.hasOneUse() || !RHS.hasOneUse()) 15574 return false; 15575 15576 // If this is a load and the token chain is identical, replace the select 15577 // of two loads with a load through a select of the address to load from. 15578 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 15579 // constants have been dropped into the constant pool. 15580 if (LHS.getOpcode() == ISD::LOAD) { 15581 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 15582 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 15583 15584 // Token chains must be identical. 15585 if (LHS.getOperand(0) != RHS.getOperand(0) || 15586 // Do not let this transformation reduce the number of volatile loads. 15587 LLD->isVolatile() || RLD->isVolatile() || 15588 // FIXME: If either is a pre/post inc/dec load, 15589 // we'd need to split out the address adjustment. 15590 LLD->isIndexed() || RLD->isIndexed() || 15591 // If this is an EXTLOAD, the VT's must match. 15592 LLD->getMemoryVT() != RLD->getMemoryVT() || 15593 // If this is an EXTLOAD, the kind of extension must match. 15594 (LLD->getExtensionType() != RLD->getExtensionType() && 15595 // The only exception is if one of the extensions is anyext. 15596 LLD->getExtensionType() != ISD::EXTLOAD && 15597 RLD->getExtensionType() != ISD::EXTLOAD) || 15598 // FIXME: this discards src value information. This is 15599 // over-conservative. It would be beneficial to be able to remember 15600 // both potential memory locations. Since we are discarding 15601 // src value info, don't do the transformation if the memory 15602 // locations are not in the default address space. 15603 LLD->getPointerInfo().getAddrSpace() != 0 || 15604 RLD->getPointerInfo().getAddrSpace() != 0 || 15605 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 15606 LLD->getBasePtr().getValueType())) 15607 return false; 15608 15609 // Check that the select condition doesn't reach either load. If so, 15610 // folding this will induce a cycle into the DAG. If not, this is safe to 15611 // xform, so create a select of the addresses. 15612 SDValue Addr; 15613 if (TheSelect->getOpcode() == ISD::SELECT) { 15614 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 15615 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 15616 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 15617 return false; 15618 // The loads must not depend on one another. 15619 if (LLD->isPredecessorOf(RLD) || 15620 RLD->isPredecessorOf(LLD)) 15621 return false; 15622 Addr = DAG.getSelect(SDLoc(TheSelect), 15623 LLD->getBasePtr().getValueType(), 15624 TheSelect->getOperand(0), LLD->getBasePtr(), 15625 RLD->getBasePtr()); 15626 } else { // Otherwise SELECT_CC 15627 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 15628 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 15629 15630 if ((LLD->hasAnyUseOfValue(1) && 15631 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 15632 (RLD->hasAnyUseOfValue(1) && 15633 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 15634 return false; 15635 15636 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 15637 LLD->getBasePtr().getValueType(), 15638 TheSelect->getOperand(0), 15639 TheSelect->getOperand(1), 15640 LLD->getBasePtr(), RLD->getBasePtr(), 15641 TheSelect->getOperand(4)); 15642 } 15643 15644 SDValue Load; 15645 // It is safe to replace the two loads if they have different alignments, 15646 // but the new load must be the minimum (most restrictive) alignment of the 15647 // inputs. 15648 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 15649 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 15650 if (!RLD->isInvariant()) 15651 MMOFlags &= ~MachineMemOperand::MOInvariant; 15652 if (!RLD->isDereferenceable()) 15653 MMOFlags &= ~MachineMemOperand::MODereferenceable; 15654 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 15655 // FIXME: Discards pointer and AA info. 15656 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 15657 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 15658 MMOFlags); 15659 } else { 15660 // FIXME: Discards pointer and AA info. 15661 Load = DAG.getExtLoad( 15662 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 15663 : LLD->getExtensionType(), 15664 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 15665 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 15666 } 15667 15668 // Users of the select now use the result of the load. 15669 CombineTo(TheSelect, Load); 15670 15671 // Users of the old loads now use the new load's chain. We know the 15672 // old-load value is dead now. 15673 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 15674 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 15675 return true; 15676 } 15677 15678 return false; 15679 } 15680 15681 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 15682 /// bitwise 'and'. 15683 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 15684 SDValue N1, SDValue N2, SDValue N3, 15685 ISD::CondCode CC) { 15686 // If this is a select where the false operand is zero and the compare is a 15687 // check of the sign bit, see if we can perform the "gzip trick": 15688 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 15689 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 15690 EVT XType = N0.getValueType(); 15691 EVT AType = N2.getValueType(); 15692 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 15693 return SDValue(); 15694 15695 // If the comparison is testing for a positive value, we have to invert 15696 // the sign bit mask, so only do that transform if the target has a bitwise 15697 // 'and not' instruction (the invert is free). 15698 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 15699 // (X > -1) ? A : 0 15700 // (X > 0) ? X : 0 <-- This is canonical signed max. 15701 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 15702 return SDValue(); 15703 } else if (CC == ISD::SETLT) { 15704 // (X < 0) ? A : 0 15705 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 15706 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 15707 return SDValue(); 15708 } else { 15709 return SDValue(); 15710 } 15711 15712 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 15713 // constant. 15714 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 15715 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15716 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 15717 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 15718 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 15719 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 15720 AddToWorklist(Shift.getNode()); 15721 15722 if (XType.bitsGT(AType)) { 15723 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 15724 AddToWorklist(Shift.getNode()); 15725 } 15726 15727 if (CC == ISD::SETGT) 15728 Shift = DAG.getNOT(DL, Shift, AType); 15729 15730 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 15731 } 15732 15733 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 15734 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 15735 AddToWorklist(Shift.getNode()); 15736 15737 if (XType.bitsGT(AType)) { 15738 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 15739 AddToWorklist(Shift.getNode()); 15740 } 15741 15742 if (CC == ISD::SETGT) 15743 Shift = DAG.getNOT(DL, Shift, AType); 15744 15745 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 15746 } 15747 15748 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 15749 /// where 'cond' is the comparison specified by CC. 15750 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 15751 SDValue N2, SDValue N3, ISD::CondCode CC, 15752 bool NotExtCompare) { 15753 // (x ? y : y) -> y. 15754 if (N2 == N3) return N2; 15755 15756 EVT VT = N2.getValueType(); 15757 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 15758 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15759 15760 // Determine if the condition we're dealing with is constant 15761 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 15762 N0, N1, CC, DL, false); 15763 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 15764 15765 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 15766 // fold select_cc true, x, y -> x 15767 // fold select_cc false, x, y -> y 15768 return !SCCC->isNullValue() ? N2 : N3; 15769 } 15770 15771 // Check to see if we can simplify the select into an fabs node 15772 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 15773 // Allow either -0.0 or 0.0 15774 if (CFP->isZero()) { 15775 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 15776 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 15777 N0 == N2 && N3.getOpcode() == ISD::FNEG && 15778 N2 == N3.getOperand(0)) 15779 return DAG.getNode(ISD::FABS, DL, VT, N0); 15780 15781 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 15782 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 15783 N0 == N3 && N2.getOpcode() == ISD::FNEG && 15784 N2.getOperand(0) == N3) 15785 return DAG.getNode(ISD::FABS, DL, VT, N3); 15786 } 15787 } 15788 15789 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 15790 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 15791 // in it. This is a win when the constant is not otherwise available because 15792 // it replaces two constant pool loads with one. We only do this if the FP 15793 // type is known to be legal, because if it isn't, then we are before legalize 15794 // types an we want the other legalization to happen first (e.g. to avoid 15795 // messing with soft float) and if the ConstantFP is not legal, because if 15796 // it is legal, we may not need to store the FP constant in a constant pool. 15797 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 15798 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 15799 if (TLI.isTypeLegal(N2.getValueType()) && 15800 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 15801 TargetLowering::Legal && 15802 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 15803 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 15804 // If both constants have multiple uses, then we won't need to do an 15805 // extra load, they are likely around in registers for other users. 15806 (TV->hasOneUse() || FV->hasOneUse())) { 15807 Constant *Elts[] = { 15808 const_cast<ConstantFP*>(FV->getConstantFPValue()), 15809 const_cast<ConstantFP*>(TV->getConstantFPValue()) 15810 }; 15811 Type *FPTy = Elts[0]->getType(); 15812 const DataLayout &TD = DAG.getDataLayout(); 15813 15814 // Create a ConstantArray of the two constants. 15815 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 15816 SDValue CPIdx = 15817 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 15818 TD.getPrefTypeAlignment(FPTy)); 15819 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 15820 15821 // Get the offsets to the 0 and 1 element of the array so that we can 15822 // select between them. 15823 SDValue Zero = DAG.getIntPtrConstant(0, DL); 15824 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 15825 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 15826 15827 SDValue Cond = DAG.getSetCC(DL, 15828 getSetCCResultType(N0.getValueType()), 15829 N0, N1, CC); 15830 AddToWorklist(Cond.getNode()); 15831 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 15832 Cond, One, Zero); 15833 AddToWorklist(CstOffset.getNode()); 15834 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 15835 CstOffset); 15836 AddToWorklist(CPIdx.getNode()); 15837 return DAG.getLoad( 15838 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 15839 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 15840 Alignment); 15841 } 15842 } 15843 15844 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 15845 return V; 15846 15847 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 15848 // where y is has a single bit set. 15849 // A plaintext description would be, we can turn the SELECT_CC into an AND 15850 // when the condition can be materialized as an all-ones register. Any 15851 // single bit-test can be materialized as an all-ones register with 15852 // shift-left and shift-right-arith. 15853 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 15854 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 15855 SDValue AndLHS = N0->getOperand(0); 15856 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 15857 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 15858 // Shift the tested bit over the sign bit. 15859 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 15860 SDValue ShlAmt = 15861 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 15862 getShiftAmountTy(AndLHS.getValueType())); 15863 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 15864 15865 // Now arithmetic right shift it all the way over, so the result is either 15866 // all-ones, or zero. 15867 SDValue ShrAmt = 15868 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 15869 getShiftAmountTy(Shl.getValueType())); 15870 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 15871 15872 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 15873 } 15874 } 15875 15876 // fold select C, 16, 0 -> shl C, 4 15877 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 15878 TLI.getBooleanContents(N0.getValueType()) == 15879 TargetLowering::ZeroOrOneBooleanContent) { 15880 15881 // If the caller doesn't want us to simplify this into a zext of a compare, 15882 // don't do it. 15883 if (NotExtCompare && N2C->isOne()) 15884 return SDValue(); 15885 15886 // Get a SetCC of the condition 15887 // NOTE: Don't create a SETCC if it's not legal on this target. 15888 if (!LegalOperations || 15889 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 15890 SDValue Temp, SCC; 15891 // cast from setcc result type to select result type 15892 if (LegalTypes) { 15893 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 15894 N0, N1, CC); 15895 if (N2.getValueType().bitsLT(SCC.getValueType())) 15896 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 15897 N2.getValueType()); 15898 else 15899 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 15900 N2.getValueType(), SCC); 15901 } else { 15902 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 15903 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 15904 N2.getValueType(), SCC); 15905 } 15906 15907 AddToWorklist(SCC.getNode()); 15908 AddToWorklist(Temp.getNode()); 15909 15910 if (N2C->isOne()) 15911 return Temp; 15912 15913 // shl setcc result by log2 n2c 15914 return DAG.getNode( 15915 ISD::SHL, DL, N2.getValueType(), Temp, 15916 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 15917 getShiftAmountTy(Temp.getValueType()))); 15918 } 15919 } 15920 15921 // Check to see if this is an integer abs. 15922 // select_cc setg[te] X, 0, X, -X -> 15923 // select_cc setgt X, -1, X, -X -> 15924 // select_cc setl[te] X, 0, -X, X -> 15925 // select_cc setlt X, 1, -X, X -> 15926 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 15927 if (N1C) { 15928 ConstantSDNode *SubC = nullptr; 15929 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 15930 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 15931 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 15932 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 15933 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 15934 (N1C->isOne() && CC == ISD::SETLT)) && 15935 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 15936 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 15937 15938 EVT XType = N0.getValueType(); 15939 if (SubC && SubC->isNullValue() && XType.isInteger()) { 15940 SDLoc DL(N0); 15941 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 15942 N0, 15943 DAG.getConstant(XType.getSizeInBits() - 1, DL, 15944 getShiftAmountTy(N0.getValueType()))); 15945 SDValue Add = DAG.getNode(ISD::ADD, DL, 15946 XType, N0, Shift); 15947 AddToWorklist(Shift.getNode()); 15948 AddToWorklist(Add.getNode()); 15949 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 15950 } 15951 } 15952 15953 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 15954 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 15955 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 15956 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 15957 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 15958 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 15959 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 15960 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 15961 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 15962 SDValue ValueOnZero = N2; 15963 SDValue Count = N3; 15964 // If the condition is NE instead of E, swap the operands. 15965 if (CC == ISD::SETNE) 15966 std::swap(ValueOnZero, Count); 15967 // Check if the value on zero is a constant equal to the bits in the type. 15968 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 15969 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 15970 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 15971 // legal, combine to just cttz. 15972 if ((Count.getOpcode() == ISD::CTTZ || 15973 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 15974 N0 == Count.getOperand(0) && 15975 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 15976 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 15977 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 15978 // legal, combine to just ctlz. 15979 if ((Count.getOpcode() == ISD::CTLZ || 15980 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 15981 N0 == Count.getOperand(0) && 15982 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 15983 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 15984 } 15985 } 15986 } 15987 15988 return SDValue(); 15989 } 15990 15991 /// This is a stub for TargetLowering::SimplifySetCC. 15992 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 15993 ISD::CondCode Cond, const SDLoc &DL, 15994 bool foldBooleans) { 15995 TargetLowering::DAGCombinerInfo 15996 DagCombineInfo(DAG, Level, false, this); 15997 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 15998 } 15999 16000 /// Given an ISD::SDIV node expressing a divide by constant, return 16001 /// a DAG expression to select that will generate the same value by multiplying 16002 /// by a magic number. 16003 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 16004 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 16005 // when optimising for minimum size, we don't want to expand a div to a mul 16006 // and a shift. 16007 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 16008 return SDValue(); 16009 16010 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16011 if (!C) 16012 return SDValue(); 16013 16014 // Avoid division by zero. 16015 if (C->isNullValue()) 16016 return SDValue(); 16017 16018 std::vector<SDNode*> Built; 16019 SDValue S = 16020 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 16021 16022 for (SDNode *N : Built) 16023 AddToWorklist(N); 16024 return S; 16025 } 16026 16027 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 16028 /// DAG expression that will generate the same value by right shifting. 16029 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 16030 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16031 if (!C) 16032 return SDValue(); 16033 16034 // Avoid division by zero. 16035 if (C->isNullValue()) 16036 return SDValue(); 16037 16038 std::vector<SDNode *> Built; 16039 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 16040 16041 for (SDNode *N : Built) 16042 AddToWorklist(N); 16043 return S; 16044 } 16045 16046 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 16047 /// expression that will generate the same value by multiplying by a magic 16048 /// number. 16049 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 16050 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 16051 // when optimising for minimum size, we don't want to expand a div to a mul 16052 // and a shift. 16053 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 16054 return SDValue(); 16055 16056 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16057 if (!C) 16058 return SDValue(); 16059 16060 // Avoid division by zero. 16061 if (C->isNullValue()) 16062 return SDValue(); 16063 16064 std::vector<SDNode*> Built; 16065 SDValue S = 16066 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 16067 16068 for (SDNode *N : Built) 16069 AddToWorklist(N); 16070 return S; 16071 } 16072 16073 /// Determines the LogBase2 value for a non-null input value using the 16074 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 16075 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 16076 EVT VT = V.getValueType(); 16077 unsigned EltBits = VT.getScalarSizeInBits(); 16078 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 16079 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 16080 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 16081 return LogBase2; 16082 } 16083 16084 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16085 /// For the reciprocal, we need to find the zero of the function: 16086 /// F(X) = A X - 1 [which has a zero at X = 1/A] 16087 /// => 16088 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 16089 /// does not require additional intermediate precision] 16090 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 16091 if (Level >= AfterLegalizeDAG) 16092 return SDValue(); 16093 16094 // TODO: Handle half and/or extended types? 16095 EVT VT = Op.getValueType(); 16096 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 16097 return SDValue(); 16098 16099 // If estimates are explicitly disabled for this function, we're done. 16100 MachineFunction &MF = DAG.getMachineFunction(); 16101 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 16102 if (Enabled == TLI.ReciprocalEstimate::Disabled) 16103 return SDValue(); 16104 16105 // Estimates may be explicitly enabled for this type with a custom number of 16106 // refinement steps. 16107 int Iterations = TLI.getDivRefinementSteps(VT, MF); 16108 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 16109 AddToWorklist(Est.getNode()); 16110 16111 if (Iterations) { 16112 EVT VT = Op.getValueType(); 16113 SDLoc DL(Op); 16114 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 16115 16116 // Newton iterations: Est = Est + Est (1 - Arg * Est) 16117 for (int i = 0; i < Iterations; ++i) { 16118 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 16119 AddToWorklist(NewEst.getNode()); 16120 16121 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 16122 AddToWorklist(NewEst.getNode()); 16123 16124 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 16125 AddToWorklist(NewEst.getNode()); 16126 16127 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 16128 AddToWorklist(Est.getNode()); 16129 } 16130 } 16131 return Est; 16132 } 16133 16134 return SDValue(); 16135 } 16136 16137 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16138 /// For the reciprocal sqrt, we need to find the zero of the function: 16139 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 16140 /// => 16141 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 16142 /// As a result, we precompute A/2 prior to the iteration loop. 16143 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 16144 unsigned Iterations, 16145 SDNodeFlags Flags, bool Reciprocal) { 16146 EVT VT = Arg.getValueType(); 16147 SDLoc DL(Arg); 16148 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 16149 16150 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 16151 // this entire sequence requires only one FP constant. 16152 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 16153 AddToWorklist(HalfArg.getNode()); 16154 16155 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 16156 AddToWorklist(HalfArg.getNode()); 16157 16158 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 16159 for (unsigned i = 0; i < Iterations; ++i) { 16160 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 16161 AddToWorklist(NewEst.getNode()); 16162 16163 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 16164 AddToWorklist(NewEst.getNode()); 16165 16166 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 16167 AddToWorklist(NewEst.getNode()); 16168 16169 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 16170 AddToWorklist(Est.getNode()); 16171 } 16172 16173 // If non-reciprocal square root is requested, multiply the result by Arg. 16174 if (!Reciprocal) { 16175 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 16176 AddToWorklist(Est.getNode()); 16177 } 16178 16179 return Est; 16180 } 16181 16182 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16183 /// For the reciprocal sqrt, we need to find the zero of the function: 16184 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 16185 /// => 16186 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 16187 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 16188 unsigned Iterations, 16189 SDNodeFlags Flags, bool Reciprocal) { 16190 EVT VT = Arg.getValueType(); 16191 SDLoc DL(Arg); 16192 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 16193 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 16194 16195 // This routine must enter the loop below to work correctly 16196 // when (Reciprocal == false). 16197 assert(Iterations > 0); 16198 16199 // Newton iterations for reciprocal square root: 16200 // E = (E * -0.5) * ((A * E) * E + -3.0) 16201 for (unsigned i = 0; i < Iterations; ++i) { 16202 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 16203 AddToWorklist(AE.getNode()); 16204 16205 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 16206 AddToWorklist(AEE.getNode()); 16207 16208 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 16209 AddToWorklist(RHS.getNode()); 16210 16211 // When calculating a square root at the last iteration build: 16212 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 16213 // (notice a common subexpression) 16214 SDValue LHS; 16215 if (Reciprocal || (i + 1) < Iterations) { 16216 // RSQRT: LHS = (E * -0.5) 16217 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 16218 } else { 16219 // SQRT: LHS = (A * E) * -0.5 16220 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 16221 } 16222 AddToWorklist(LHS.getNode()); 16223 16224 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 16225 AddToWorklist(Est.getNode()); 16226 } 16227 16228 return Est; 16229 } 16230 16231 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 16232 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 16233 /// Op can be zero. 16234 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 16235 bool Reciprocal) { 16236 if (Level >= AfterLegalizeDAG) 16237 return SDValue(); 16238 16239 // TODO: Handle half and/or extended types? 16240 EVT VT = Op.getValueType(); 16241 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 16242 return SDValue(); 16243 16244 // If estimates are explicitly disabled for this function, we're done. 16245 MachineFunction &MF = DAG.getMachineFunction(); 16246 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 16247 if (Enabled == TLI.ReciprocalEstimate::Disabled) 16248 return SDValue(); 16249 16250 // Estimates may be explicitly enabled for this type with a custom number of 16251 // refinement steps. 16252 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 16253 16254 bool UseOneConstNR = false; 16255 if (SDValue Est = 16256 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 16257 Reciprocal)) { 16258 AddToWorklist(Est.getNode()); 16259 16260 if (Iterations) { 16261 Est = UseOneConstNR 16262 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 16263 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 16264 16265 if (!Reciprocal) { 16266 // Unfortunately, Est is now NaN if the input was exactly 0.0. 16267 // Select out this case and force the answer to 0.0. 16268 EVT VT = Op.getValueType(); 16269 SDLoc DL(Op); 16270 16271 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 16272 EVT CCVT = getSetCCResultType(VT); 16273 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 16274 AddToWorklist(ZeroCmp.getNode()); 16275 16276 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 16277 ZeroCmp, FPZero, Est); 16278 AddToWorklist(Est.getNode()); 16279 } 16280 } 16281 return Est; 16282 } 16283 16284 return SDValue(); 16285 } 16286 16287 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 16288 return buildSqrtEstimateImpl(Op, Flags, true); 16289 } 16290 16291 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 16292 return buildSqrtEstimateImpl(Op, Flags, false); 16293 } 16294 16295 /// Return true if base is a frame index, which is known not to alias with 16296 /// anything but itself. Provides base object and offset as results. 16297 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 16298 const GlobalValue *&GV, const void *&CV) { 16299 // Assume it is a primitive operation. 16300 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 16301 16302 // If it's an adding a simple constant then integrate the offset. 16303 if (Base.getOpcode() == ISD::ADD) { 16304 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 16305 Base = Base.getOperand(0); 16306 Offset += C->getSExtValue(); 16307 } 16308 } 16309 16310 // Return the underlying GlobalValue, and update the Offset. Return false 16311 // for GlobalAddressSDNode since the same GlobalAddress may be represented 16312 // by multiple nodes with different offsets. 16313 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 16314 GV = G->getGlobal(); 16315 Offset += G->getOffset(); 16316 return false; 16317 } 16318 16319 // Return the underlying Constant value, and update the Offset. Return false 16320 // for ConstantSDNodes since the same constant pool entry may be represented 16321 // by multiple nodes with different offsets. 16322 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 16323 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 16324 : (const void *)C->getConstVal(); 16325 Offset += C->getOffset(); 16326 return false; 16327 } 16328 // If it's any of the following then it can't alias with anything but itself. 16329 return isa<FrameIndexSDNode>(Base); 16330 } 16331 16332 /// Return true if there is any possibility that the two addresses overlap. 16333 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 16334 // If they are the same then they must be aliases. 16335 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 16336 16337 // If they are both volatile then they cannot be reordered. 16338 if (Op0->isVolatile() && Op1->isVolatile()) return true; 16339 16340 // If one operation reads from invariant memory, and the other may store, they 16341 // cannot alias. These should really be checking the equivalent of mayWrite, 16342 // but it only matters for memory nodes other than load /store. 16343 if (Op0->isInvariant() && Op1->writeMem()) 16344 return false; 16345 16346 if (Op1->isInvariant() && Op0->writeMem()) 16347 return false; 16348 16349 unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3; 16350 unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3; 16351 16352 // Check for BaseIndexOffset matching. 16353 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG); 16354 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG); 16355 if (BasePtr0.equalBaseIndex(BasePtr1)) 16356 return !((BasePtr0.Offset + NumBytes0 <= BasePtr1.Offset) || 16357 (BasePtr1.Offset + NumBytes1 <= BasePtr0.Offset)); 16358 16359 // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis 16360 // modified to use BaseIndexOffset. 16361 16362 // Gather base node and offset information. 16363 SDValue Base0, Base1; 16364 int64_t Offset0, Offset1; 16365 const GlobalValue *GV0, *GV1; 16366 const void *CV0, *CV1; 16367 bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(), 16368 Base0, Offset0, GV0, CV0); 16369 bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(), 16370 Base1, Offset1, GV1, CV1); 16371 16372 // If they have the same base address, then check to see if they overlap. 16373 if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1))) 16374 return !((Offset0 + NumBytes0) <= Offset1 || 16375 (Offset1 + NumBytes1) <= Offset0); 16376 16377 // It is possible for different frame indices to alias each other, mostly 16378 // when tail call optimization reuses return address slots for arguments. 16379 // To catch this case, look up the actual index of frame indices to compute 16380 // the real alias relationship. 16381 if (IsFrameIndex0 && IsFrameIndex1) { 16382 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 16383 Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex()); 16384 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 16385 return !((Offset0 + NumBytes0) <= Offset1 || 16386 (Offset1 + NumBytes1) <= Offset0); 16387 } 16388 16389 // Otherwise, if we know what the bases are, and they aren't identical, then 16390 // we know they cannot alias. 16391 if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1)) 16392 return false; 16393 16394 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 16395 // compared to the size and offset of the access, we may be able to prove they 16396 // do not alias. This check is conservative for now to catch cases created by 16397 // splitting vector types. 16398 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 16399 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 16400 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 16401 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 16402 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 16403 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 16404 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 16405 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 16406 16407 // There is no overlap between these relatively aligned accesses of similar 16408 // size. Return no alias. 16409 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 16410 (OffAlign1 + NumBytes1) <= OffAlign0) 16411 return false; 16412 } 16413 16414 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 16415 ? CombinerGlobalAA 16416 : DAG.getSubtarget().useAA(); 16417 #ifndef NDEBUG 16418 if (CombinerAAOnlyFunc.getNumOccurrences() && 16419 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 16420 UseAA = false; 16421 #endif 16422 16423 if (UseAA && AA && 16424 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 16425 // Use alias analysis information. 16426 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 16427 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 16428 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 16429 AliasResult AAResult = 16430 AA->alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 16431 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 16432 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 16433 UseTBAA ? Op1->getAAInfo() : AAMDNodes()) ); 16434 if (AAResult == NoAlias) 16435 return false; 16436 } 16437 16438 // Otherwise we have to assume they alias. 16439 return true; 16440 } 16441 16442 /// Walk up chain skipping non-aliasing memory nodes, 16443 /// looking for aliasing nodes and adding them to the Aliases vector. 16444 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 16445 SmallVectorImpl<SDValue> &Aliases) { 16446 SmallVector<SDValue, 8> Chains; // List of chains to visit. 16447 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 16448 16449 // Get alias information for node. 16450 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 16451 16452 // Starting off. 16453 Chains.push_back(OriginalChain); 16454 unsigned Depth = 0; 16455 16456 // Look at each chain and determine if it is an alias. If so, add it to the 16457 // aliases list. If not, then continue up the chain looking for the next 16458 // candidate. 16459 while (!Chains.empty()) { 16460 SDValue Chain = Chains.pop_back_val(); 16461 16462 // For TokenFactor nodes, look at each operand and only continue up the 16463 // chain until we reach the depth limit. 16464 // 16465 // FIXME: The depth check could be made to return the last non-aliasing 16466 // chain we found before we hit a tokenfactor rather than the original 16467 // chain. 16468 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 16469 Aliases.clear(); 16470 Aliases.push_back(OriginalChain); 16471 return; 16472 } 16473 16474 // Don't bother if we've been before. 16475 if (!Visited.insert(Chain.getNode()).second) 16476 continue; 16477 16478 switch (Chain.getOpcode()) { 16479 case ISD::EntryToken: 16480 // Entry token is ideal chain operand, but handled in FindBetterChain. 16481 break; 16482 16483 case ISD::LOAD: 16484 case ISD::STORE: { 16485 // Get alias information for Chain. 16486 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 16487 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 16488 16489 // If chain is alias then stop here. 16490 if (!(IsLoad && IsOpLoad) && 16491 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 16492 Aliases.push_back(Chain); 16493 } else { 16494 // Look further up the chain. 16495 Chains.push_back(Chain.getOperand(0)); 16496 ++Depth; 16497 } 16498 break; 16499 } 16500 16501 case ISD::TokenFactor: 16502 // We have to check each of the operands of the token factor for "small" 16503 // token factors, so we queue them up. Adding the operands to the queue 16504 // (stack) in reverse order maintains the original order and increases the 16505 // likelihood that getNode will find a matching token factor (CSE.) 16506 if (Chain.getNumOperands() > 16) { 16507 Aliases.push_back(Chain); 16508 break; 16509 } 16510 for (unsigned n = Chain.getNumOperands(); n;) 16511 Chains.push_back(Chain.getOperand(--n)); 16512 ++Depth; 16513 break; 16514 16515 case ISD::CopyFromReg: 16516 // Forward past CopyFromReg. 16517 Chains.push_back(Chain.getOperand(0)); 16518 ++Depth; 16519 break; 16520 16521 default: 16522 // For all other instructions we will just have to take what we can get. 16523 Aliases.push_back(Chain); 16524 break; 16525 } 16526 } 16527 } 16528 16529 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 16530 /// (aliasing node.) 16531 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 16532 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 16533 16534 // Accumulate all the aliases to this node. 16535 GatherAllAliases(N, OldChain, Aliases); 16536 16537 // If no operands then chain to entry token. 16538 if (Aliases.size() == 0) 16539 return DAG.getEntryNode(); 16540 16541 // If a single operand then chain to it. We don't need to revisit it. 16542 if (Aliases.size() == 1) 16543 return Aliases[0]; 16544 16545 // Construct a custom tailored token factor. 16546 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 16547 } 16548 16549 // This function tries to collect a bunch of potentially interesting 16550 // nodes to improve the chains of, all at once. This might seem 16551 // redundant, as this function gets called when visiting every store 16552 // node, so why not let the work be done on each store as it's visited? 16553 // 16554 // I believe this is mainly important because MergeConsecutiveStores 16555 // is unable to deal with merging stores of different sizes, so unless 16556 // we improve the chains of all the potential candidates up-front 16557 // before running MergeConsecutiveStores, it might only see some of 16558 // the nodes that will eventually be candidates, and then not be able 16559 // to go from a partially-merged state to the desired final 16560 // fully-merged state. 16561 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 16562 // This holds the base pointer, index, and the offset in bytes from the base 16563 // pointer. 16564 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 16565 16566 // We must have a base and an offset. 16567 if (!BasePtr.Base.getNode()) 16568 return false; 16569 16570 // Do not handle stores to undef base pointers. 16571 if (BasePtr.Base.isUndef()) 16572 return false; 16573 16574 SmallVector<StoreSDNode *, 8> ChainedStores; 16575 ChainedStores.push_back(St); 16576 16577 // Walk up the chain and look for nodes with offsets from the same 16578 // base pointer. Stop when reaching an instruction with a different kind 16579 // or instruction which has a different base pointer. 16580 StoreSDNode *Index = St; 16581 while (Index) { 16582 // If the chain has more than one use, then we can't reorder the mem ops. 16583 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 16584 break; 16585 16586 if (Index->isVolatile() || Index->isIndexed()) 16587 break; 16588 16589 // Find the base pointer and offset for this memory node. 16590 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 16591 16592 // Check that the base pointer is the same as the original one. 16593 if (!Ptr.equalBaseIndex(BasePtr)) 16594 break; 16595 16596 // Walk up the chain to find the next store node, ignoring any 16597 // intermediate loads. Any other kind of node will halt the loop. 16598 SDNode *NextInChain = Index->getChain().getNode(); 16599 while (true) { 16600 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 16601 // We found a store node. Use it for the next iteration. 16602 if (STn->isVolatile() || STn->isIndexed()) { 16603 Index = nullptr; 16604 break; 16605 } 16606 ChainedStores.push_back(STn); 16607 Index = STn; 16608 break; 16609 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 16610 NextInChain = Ldn->getChain().getNode(); 16611 continue; 16612 } else { 16613 Index = nullptr; 16614 break; 16615 } 16616 } // end while 16617 } 16618 16619 // At this point, ChainedStores lists all of the Store nodes 16620 // reachable by iterating up through chain nodes matching the above 16621 // conditions. For each such store identified, try to find an 16622 // earlier chain to attach the store to which won't violate the 16623 // required ordering. 16624 bool MadeChangeToSt = false; 16625 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 16626 16627 for (StoreSDNode *ChainedStore : ChainedStores) { 16628 SDValue Chain = ChainedStore->getChain(); 16629 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 16630 16631 if (Chain != BetterChain) { 16632 if (ChainedStore == St) 16633 MadeChangeToSt = true; 16634 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 16635 } 16636 } 16637 16638 // Do all replacements after finding the replacements to make to avoid making 16639 // the chains more complicated by introducing new TokenFactors. 16640 for (auto Replacement : BetterChains) 16641 replaceStoreChain(Replacement.first, Replacement.second); 16642 16643 return MadeChangeToSt; 16644 } 16645 16646 /// This is the entry point for the file. 16647 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 16648 CodeGenOpt::Level OptLevel) { 16649 /// This is the main entry point to this class. 16650 DAGCombiner(*this, AA, OptLevel).Run(Level); 16651 } 16652