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 &A, CodeGenOpt::Level OL) 500 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 501 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 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 SDValue Result; 1733 1734 // If we've changed things around then replace token factor. 1735 if (Changed) { 1736 if (Ops.empty()) { 1737 // The entry token is the only possible outcome. 1738 Result = DAG.getEntryNode(); 1739 } else { 1740 if (DidPruneOps) { 1741 SmallVector<SDValue, 8> PrunedOps; 1742 // 1743 for (const SDValue &Op : Ops) { 1744 if (SeenChains.count(Op.getNode()) == 0) 1745 PrunedOps.push_back(Op); 1746 } 1747 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps); 1748 } else { 1749 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1750 } 1751 } 1752 1753 // Add users to worklist, since we may introduce a lot of new 1754 // chained token factors while removing memory deps. 1755 return CombineTo(N, Result, true /*add to worklist*/); 1756 } 1757 1758 return Result; 1759 } 1760 1761 /// MERGE_VALUES can always be eliminated. 1762 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1763 WorklistRemover DeadNodes(*this); 1764 // Replacing results may cause a different MERGE_VALUES to suddenly 1765 // be CSE'd with N, and carry its uses with it. Iterate until no 1766 // uses remain, to ensure that the node can be safely deleted. 1767 // First add the users of this node to the work list so that they 1768 // can be tried again once they have new operands. 1769 AddUsersToWorklist(N); 1770 do { 1771 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1772 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1773 } while (!N->use_empty()); 1774 deleteAndRecombine(N); 1775 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1776 } 1777 1778 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1779 /// ConstantSDNode pointer else nullptr. 1780 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1781 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1782 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1783 } 1784 1785 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1786 auto BinOpcode = BO->getOpcode(); 1787 assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB || 1788 BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV || 1789 BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM || 1790 BinOpcode == ISD::UREM || BinOpcode == ISD::AND || 1791 BinOpcode == ISD::OR || BinOpcode == ISD::XOR || 1792 BinOpcode == ISD::SHL || BinOpcode == ISD::SRL || 1793 BinOpcode == ISD::SRA || BinOpcode == ISD::FADD || 1794 BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL || 1795 BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) && 1796 "Unexpected binary operator"); 1797 1798 // Bail out if any constants are opaque because we can't constant fold those. 1799 SDValue C1 = BO->getOperand(1); 1800 if (!isConstantOrConstantVector(C1, true) && 1801 !isConstantFPBuildVectorOrConstantFP(C1)) 1802 return SDValue(); 1803 1804 // Don't do this unless the old select is going away. We want to eliminate the 1805 // binary operator, not replace a binop with a select. 1806 // TODO: Handle ISD::SELECT_CC. 1807 SDValue Sel = BO->getOperand(0); 1808 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1809 return SDValue(); 1810 1811 SDValue CT = Sel.getOperand(1); 1812 if (!isConstantOrConstantVector(CT, true) && 1813 !isConstantFPBuildVectorOrConstantFP(CT)) 1814 return SDValue(); 1815 1816 SDValue CF = Sel.getOperand(2); 1817 if (!isConstantOrConstantVector(CF, true) && 1818 !isConstantFPBuildVectorOrConstantFP(CF)) 1819 return SDValue(); 1820 1821 // We have a select-of-constants followed by a binary operator with a 1822 // constant. Eliminate the binop by pulling the constant math into the select. 1823 // Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1 1824 EVT VT = Sel.getValueType(); 1825 SDLoc DL(Sel); 1826 SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1); 1827 assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) || 1828 isConstantFPBuildVectorOrConstantFP(NewCT)) && 1829 "Failed to constant fold a binop with constant operands"); 1830 1831 SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1); 1832 assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) || 1833 isConstantFPBuildVectorOrConstantFP(NewCF)) && 1834 "Failed to constant fold a binop with constant operands"); 1835 1836 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 1837 } 1838 1839 SDValue DAGCombiner::visitADD(SDNode *N) { 1840 SDValue N0 = N->getOperand(0); 1841 SDValue N1 = N->getOperand(1); 1842 EVT VT = N0.getValueType(); 1843 SDLoc DL(N); 1844 1845 // fold vector ops 1846 if (VT.isVector()) { 1847 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1848 return FoldedVOp; 1849 1850 // fold (add x, 0) -> x, vector edition 1851 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1852 return N0; 1853 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1854 return N1; 1855 } 1856 1857 // fold (add x, undef) -> undef 1858 if (N0.isUndef()) 1859 return N0; 1860 1861 if (N1.isUndef()) 1862 return N1; 1863 1864 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1865 // canonicalize constant to RHS 1866 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1867 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 1868 // fold (add c1, c2) -> c1+c2 1869 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 1870 N1.getNode()); 1871 } 1872 1873 // fold (add x, 0) -> x 1874 if (isNullConstant(N1)) 1875 return N0; 1876 1877 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 1878 // fold ((c1-A)+c2) -> (c1+c2)-A 1879 if (N0.getOpcode() == ISD::SUB && 1880 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 1881 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 1882 return DAG.getNode(ISD::SUB, DL, VT, 1883 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 1884 N0.getOperand(1)); 1885 } 1886 1887 // add (sext i1 X), 1 -> zext (not i1 X) 1888 // We don't transform this pattern: 1889 // add (zext i1 X), -1 -> sext (not i1 X) 1890 // because most (?) targets generate better code for the zext form. 1891 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 1892 isOneConstantOrOneSplatConstant(N1)) { 1893 SDValue X = N0.getOperand(0); 1894 if ((!LegalOperations || 1895 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 1896 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 1897 X.getScalarValueSizeInBits() == 1) { 1898 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 1899 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 1900 } 1901 } 1902 } 1903 1904 if (SDValue NewSel = foldBinOpIntoSelect(N)) 1905 return NewSel; 1906 1907 // reassociate add 1908 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1)) 1909 return RADD; 1910 1911 // fold ((0-A) + B) -> B-A 1912 if (N0.getOpcode() == ISD::SUB && 1913 isNullConstantOrNullSplatConstant(N0.getOperand(0))) 1914 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 1915 1916 // fold (A + (0-B)) -> A-B 1917 if (N1.getOpcode() == ISD::SUB && 1918 isNullConstantOrNullSplatConstant(N1.getOperand(0))) 1919 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 1920 1921 // fold (A+(B-A)) -> B 1922 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1923 return N1.getOperand(0); 1924 1925 // fold ((B-A)+A) -> B 1926 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1927 return N0.getOperand(0); 1928 1929 // fold (A+(B-(A+C))) to (B-C) 1930 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1931 N0 == N1.getOperand(1).getOperand(0)) 1932 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1933 N1.getOperand(1).getOperand(1)); 1934 1935 // fold (A+(B-(C+A))) to (B-C) 1936 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1937 N0 == N1.getOperand(1).getOperand(1)) 1938 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 1939 N1.getOperand(1).getOperand(0)); 1940 1941 // fold (A+((B-A)+or-C)) to (B+or-C) 1942 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1943 N1.getOperand(0).getOpcode() == ISD::SUB && 1944 N0 == N1.getOperand(0).getOperand(1)) 1945 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 1946 N1.getOperand(1)); 1947 1948 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1949 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1950 SDValue N00 = N0.getOperand(0); 1951 SDValue N01 = N0.getOperand(1); 1952 SDValue N10 = N1.getOperand(0); 1953 SDValue N11 = N1.getOperand(1); 1954 1955 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 1956 return DAG.getNode(ISD::SUB, DL, VT, 1957 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1958 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1959 } 1960 1961 if (SimplifyDemandedBits(SDValue(N, 0))) 1962 return SDValue(N, 0); 1963 1964 // fold (a+b) -> (a|b) iff a and b share no bits. 1965 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1966 VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1)) 1967 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 1968 1969 if (SDValue Combined = visitADDLike(N0, N1, N)) 1970 return Combined; 1971 1972 if (SDValue Combined = visitADDLike(N1, N0, N)) 1973 return Combined; 1974 1975 return SDValue(); 1976 } 1977 1978 SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) { 1979 EVT VT = N0.getValueType(); 1980 SDLoc DL(LocReference); 1981 1982 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1983 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1984 isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0))) 1985 return DAG.getNode(ISD::SUB, DL, VT, N0, 1986 DAG.getNode(ISD::SHL, DL, VT, 1987 N1.getOperand(0).getOperand(1), 1988 N1.getOperand(1))); 1989 1990 if (N1.getOpcode() == ISD::AND) { 1991 SDValue AndOp0 = N1.getOperand(0); 1992 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1993 unsigned DestBits = VT.getScalarSizeInBits(); 1994 1995 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1996 // and similar xforms where the inner op is either ~0 or 0. 1997 if (NumSignBits == DestBits && 1998 isOneConstantOrOneSplatConstant(N1->getOperand(1))) 1999 return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0); 2000 } 2001 2002 // add (sext i1), X -> sub X, (zext i1) 2003 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2004 N0.getOperand(0).getValueType() == MVT::i1 && 2005 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 2006 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2007 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2008 } 2009 2010 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2011 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2012 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2013 if (TN->getVT() == MVT::i1) { 2014 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2015 DAG.getConstant(1, DL, VT)); 2016 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2017 } 2018 } 2019 2020 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2021 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) 2022 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2023 N0, N1.getOperand(0), N1.getOperand(2)); 2024 2025 return SDValue(); 2026 } 2027 2028 SDValue DAGCombiner::visitADDC(SDNode *N) { 2029 SDValue N0 = N->getOperand(0); 2030 SDValue N1 = N->getOperand(1); 2031 EVT VT = N0.getValueType(); 2032 SDLoc DL(N); 2033 2034 // If the flag result is dead, turn this into an ADD. 2035 if (!N->hasAnyUseOfValue(1)) 2036 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2037 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2038 2039 // canonicalize constant to RHS. 2040 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2041 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2042 if (N0C && !N1C) 2043 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2044 2045 // fold (addc x, 0) -> x + no carry out 2046 if (isNullConstant(N1)) 2047 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2048 DL, MVT::Glue)); 2049 2050 // If it cannot overflow, transform into an add. 2051 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2052 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2053 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2054 2055 return SDValue(); 2056 } 2057 2058 SDValue DAGCombiner::visitUADDO(SDNode *N) { 2059 SDValue N0 = N->getOperand(0); 2060 SDValue N1 = N->getOperand(1); 2061 EVT VT = N0.getValueType(); 2062 if (VT.isVector()) 2063 return SDValue(); 2064 2065 EVT CarryVT = N->getValueType(1); 2066 SDLoc DL(N); 2067 2068 // If the flag result is dead, turn this into an ADD. 2069 if (!N->hasAnyUseOfValue(1)) 2070 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2071 DAG.getUNDEF(CarryVT)); 2072 2073 // canonicalize constant to RHS. 2074 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2075 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2076 if (N0C && !N1C) 2077 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0); 2078 2079 // fold (uaddo x, 0) -> x + no carry out 2080 if (isNullConstant(N1)) 2081 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2082 2083 // If it cannot overflow, transform into an add. 2084 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2085 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2086 DAG.getConstant(0, DL, CarryVT)); 2087 2088 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2089 return Combined; 2090 2091 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2092 return Combined; 2093 2094 return SDValue(); 2095 } 2096 2097 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2098 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2099 // If Y + 1 cannot overflow. 2100 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2101 SDValue Y = N1.getOperand(0); 2102 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2103 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2104 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2105 N1.getOperand(2)); 2106 } 2107 2108 return SDValue(); 2109 } 2110 2111 SDValue DAGCombiner::visitADDE(SDNode *N) { 2112 SDValue N0 = N->getOperand(0); 2113 SDValue N1 = N->getOperand(1); 2114 SDValue CarryIn = N->getOperand(2); 2115 2116 // canonicalize constant to RHS 2117 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2118 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2119 if (N0C && !N1C) 2120 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2121 N1, N0, CarryIn); 2122 2123 // fold (adde x, y, false) -> (addc x, y) 2124 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2125 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2126 2127 return SDValue(); 2128 } 2129 2130 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2131 SDValue N0 = N->getOperand(0); 2132 SDValue N1 = N->getOperand(1); 2133 SDValue CarryIn = N->getOperand(2); 2134 2135 // canonicalize constant to RHS 2136 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2137 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2138 if (N0C && !N1C) 2139 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2140 N1, N0, CarryIn); 2141 2142 // fold (addcarry x, y, false) -> (uaddo x, y) 2143 if (isNullConstant(CarryIn)) 2144 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), N0, N1); 2145 2146 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2147 return Combined; 2148 2149 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2150 return Combined; 2151 2152 return SDValue(); 2153 } 2154 2155 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2156 SDNode *N) { 2157 // Iff the flag result is dead: 2158 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2159 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::UADDO) && 2160 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2161 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2162 N0.getOperand(0), N0.getOperand(1), CarryIn); 2163 2164 return SDValue(); 2165 } 2166 2167 // Since it may not be valid to emit a fold to zero for vector initializers 2168 // check if we can before folding. 2169 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2170 SelectionDAG &DAG, bool LegalOperations, 2171 bool LegalTypes) { 2172 if (!VT.isVector()) 2173 return DAG.getConstant(0, DL, VT); 2174 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2175 return DAG.getConstant(0, DL, VT); 2176 return SDValue(); 2177 } 2178 2179 SDValue DAGCombiner::visitSUB(SDNode *N) { 2180 SDValue N0 = N->getOperand(0); 2181 SDValue N1 = N->getOperand(1); 2182 EVT VT = N0.getValueType(); 2183 SDLoc DL(N); 2184 2185 // fold vector ops 2186 if (VT.isVector()) { 2187 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2188 return FoldedVOp; 2189 2190 // fold (sub x, 0) -> x, vector edition 2191 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2192 return N0; 2193 } 2194 2195 // fold (sub x, x) -> 0 2196 // FIXME: Refactor this and xor and other similar operations together. 2197 if (N0 == N1) 2198 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes); 2199 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2200 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2201 // fold (sub c1, c2) -> c1-c2 2202 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2203 N1.getNode()); 2204 } 2205 2206 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2207 return NewSel; 2208 2209 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2210 2211 // fold (sub x, c) -> (add x, -c) 2212 if (N1C) { 2213 return DAG.getNode(ISD::ADD, DL, VT, N0, 2214 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2215 } 2216 2217 if (isNullConstantOrNullSplatConstant(N0)) { 2218 unsigned BitWidth = VT.getScalarSizeInBits(); 2219 // Right-shifting everything out but the sign bit followed by negation is 2220 // the same as flipping arithmetic/logical shift type without the negation: 2221 // -(X >>u 31) -> (X >>s 31) 2222 // -(X >>s 31) -> (X >>u 31) 2223 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2224 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2225 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2226 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2227 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2228 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2229 } 2230 } 2231 2232 // 0 - X --> 0 if the sub is NUW. 2233 if (N->getFlags().hasNoUnsignedWrap()) 2234 return N0; 2235 2236 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2237 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2238 // N1 must be 0 because negating the minimum signed value is undefined. 2239 if (N->getFlags().hasNoSignedWrap()) 2240 return N0; 2241 2242 // 0 - X --> X if X is 0 or the minimum signed value. 2243 return N1; 2244 } 2245 } 2246 2247 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2248 if (isAllOnesConstantOrAllOnesSplatConstant(N0)) 2249 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2250 2251 // fold A-(A-B) -> B 2252 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2253 return N1.getOperand(1); 2254 2255 // fold (A+B)-A -> B 2256 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2257 return N0.getOperand(1); 2258 2259 // fold (A+B)-B -> A 2260 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2261 return N0.getOperand(0); 2262 2263 // fold C2-(A+C1) -> (C2-C1)-A 2264 if (N1.getOpcode() == ISD::ADD) { 2265 SDValue N11 = N1.getOperand(1); 2266 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2267 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2268 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2269 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2270 } 2271 } 2272 2273 // fold ((A+(B+or-C))-B) -> A+or-C 2274 if (N0.getOpcode() == ISD::ADD && 2275 (N0.getOperand(1).getOpcode() == ISD::SUB || 2276 N0.getOperand(1).getOpcode() == ISD::ADD) && 2277 N0.getOperand(1).getOperand(0) == N1) 2278 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2279 N0.getOperand(1).getOperand(1)); 2280 2281 // fold ((A+(C+B))-B) -> A+C 2282 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2283 N0.getOperand(1).getOperand(1) == N1) 2284 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2285 N0.getOperand(1).getOperand(0)); 2286 2287 // fold ((A-(B-C))-C) -> A-B 2288 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2289 N0.getOperand(1).getOperand(1) == N1) 2290 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2291 N0.getOperand(1).getOperand(0)); 2292 2293 // If either operand of a sub is undef, the result is undef 2294 if (N0.isUndef()) 2295 return N0; 2296 if (N1.isUndef()) 2297 return N1; 2298 2299 // If the relocation model supports it, consider symbol offsets. 2300 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2301 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2302 // fold (sub Sym, c) -> Sym-c 2303 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2304 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2305 GA->getOffset() - 2306 (uint64_t)N1C->getSExtValue()); 2307 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2308 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2309 if (GA->getGlobal() == GB->getGlobal()) 2310 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2311 DL, VT); 2312 } 2313 2314 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2315 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2316 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2317 if (TN->getVT() == MVT::i1) { 2318 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2319 DAG.getConstant(1, DL, VT)); 2320 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2321 } 2322 } 2323 2324 return SDValue(); 2325 } 2326 2327 SDValue DAGCombiner::visitSUBC(SDNode *N) { 2328 SDValue N0 = N->getOperand(0); 2329 SDValue N1 = N->getOperand(1); 2330 EVT VT = N0.getValueType(); 2331 SDLoc DL(N); 2332 2333 // If the flag result is dead, turn this into an SUB. 2334 if (!N->hasAnyUseOfValue(1)) 2335 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2336 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2337 2338 // fold (subc x, x) -> 0 + no borrow 2339 if (N0 == N1) 2340 return CombineTo(N, DAG.getConstant(0, DL, VT), 2341 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2342 2343 // fold (subc x, 0) -> x + no borrow 2344 if (isNullConstant(N1)) 2345 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2346 2347 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2348 if (isAllOnesConstant(N0)) 2349 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2350 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2351 2352 return SDValue(); 2353 } 2354 2355 SDValue DAGCombiner::visitUSUBO(SDNode *N) { 2356 SDValue N0 = N->getOperand(0); 2357 SDValue N1 = N->getOperand(1); 2358 EVT VT = N0.getValueType(); 2359 if (VT.isVector()) 2360 return SDValue(); 2361 2362 EVT CarryVT = N->getValueType(1); 2363 SDLoc DL(N); 2364 2365 // If the flag result is dead, turn this into an SUB. 2366 if (!N->hasAnyUseOfValue(1)) 2367 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2368 DAG.getUNDEF(CarryVT)); 2369 2370 // fold (usubo x, x) -> 0 + no borrow 2371 if (N0 == N1) 2372 return CombineTo(N, DAG.getConstant(0, DL, VT), 2373 DAG.getConstant(0, DL, CarryVT)); 2374 2375 // fold (usubo x, 0) -> x + no borrow 2376 if (isNullConstant(N1)) 2377 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2378 2379 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2380 if (isAllOnesConstant(N0)) 2381 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2382 DAG.getConstant(0, DL, CarryVT)); 2383 2384 return SDValue(); 2385 } 2386 2387 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2388 SDValue N0 = N->getOperand(0); 2389 SDValue N1 = N->getOperand(1); 2390 SDValue CarryIn = N->getOperand(2); 2391 2392 // fold (sube x, y, false) -> (subc x, y) 2393 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2394 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2395 2396 return SDValue(); 2397 } 2398 2399 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 2400 SDValue N0 = N->getOperand(0); 2401 SDValue N1 = N->getOperand(1); 2402 SDValue CarryIn = N->getOperand(2); 2403 2404 // fold (subcarry x, y, false) -> (usubo x, y) 2405 if (isNullConstant(CarryIn)) 2406 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 2407 2408 return SDValue(); 2409 } 2410 2411 SDValue DAGCombiner::visitMUL(SDNode *N) { 2412 SDValue N0 = N->getOperand(0); 2413 SDValue N1 = N->getOperand(1); 2414 EVT VT = N0.getValueType(); 2415 2416 // fold (mul x, undef) -> 0 2417 if (N0.isUndef() || N1.isUndef()) 2418 return DAG.getConstant(0, SDLoc(N), VT); 2419 2420 bool N0IsConst = false; 2421 bool N1IsConst = false; 2422 bool N1IsOpaqueConst = false; 2423 bool N0IsOpaqueConst = false; 2424 APInt ConstValue0, ConstValue1; 2425 // fold vector ops 2426 if (VT.isVector()) { 2427 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2428 return FoldedVOp; 2429 2430 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2431 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2432 } else { 2433 N0IsConst = isa<ConstantSDNode>(N0); 2434 if (N0IsConst) { 2435 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2436 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2437 } 2438 N1IsConst = isa<ConstantSDNode>(N1); 2439 if (N1IsConst) { 2440 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2441 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2442 } 2443 } 2444 2445 // fold (mul c1, c2) -> c1*c2 2446 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2447 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2448 N0.getNode(), N1.getNode()); 2449 2450 // canonicalize constant to RHS (vector doesn't have to splat) 2451 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2452 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2453 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2454 // fold (mul x, 0) -> 0 2455 if (N1IsConst && ConstValue1 == 0) 2456 return N1; 2457 // We require a splat of the entire scalar bit width for non-contiguous 2458 // bit patterns. 2459 bool IsFullSplat = 2460 ConstValue1.getBitWidth() == VT.getScalarSizeInBits(); 2461 // fold (mul x, 1) -> x 2462 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2463 return N0; 2464 2465 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2466 return NewSel; 2467 2468 // fold (mul x, -1) -> 0-x 2469 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2470 SDLoc DL(N); 2471 return DAG.getNode(ISD::SUB, DL, VT, 2472 DAG.getConstant(0, DL, VT), N0); 2473 } 2474 // fold (mul x, (1 << c)) -> x << c 2475 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2476 IsFullSplat) { 2477 SDLoc DL(N); 2478 return DAG.getNode(ISD::SHL, DL, VT, N0, 2479 DAG.getConstant(ConstValue1.logBase2(), DL, 2480 getShiftAmountTy(N0.getValueType()))); 2481 } 2482 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2483 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2484 IsFullSplat) { 2485 unsigned Log2Val = (-ConstValue1).logBase2(); 2486 SDLoc DL(N); 2487 // FIXME: If the input is something that is easily negated (e.g. a 2488 // single-use add), we should put the negate there. 2489 return DAG.getNode(ISD::SUB, DL, VT, 2490 DAG.getConstant(0, DL, VT), 2491 DAG.getNode(ISD::SHL, DL, VT, N0, 2492 DAG.getConstant(Log2Val, DL, 2493 getShiftAmountTy(N0.getValueType())))); 2494 } 2495 2496 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2497 if (N0.getOpcode() == ISD::SHL && 2498 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 2499 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 2500 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2501 if (isConstantOrConstantVector(C3)) 2502 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2503 } 2504 2505 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2506 // use. 2507 { 2508 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2509 2510 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2511 if (N0.getOpcode() == ISD::SHL && 2512 isConstantOrConstantVector(N0.getOperand(1)) && 2513 N0.getNode()->hasOneUse()) { 2514 Sh = N0; Y = N1; 2515 } else if (N1.getOpcode() == ISD::SHL && 2516 isConstantOrConstantVector(N1.getOperand(1)) && 2517 N1.getNode()->hasOneUse()) { 2518 Sh = N1; Y = N0; 2519 } 2520 2521 if (Sh.getNode()) { 2522 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2523 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2524 } 2525 } 2526 2527 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2528 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2529 N0.getOpcode() == ISD::ADD && 2530 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2531 isMulAddWithConstProfitable(N, N0, N1)) 2532 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2533 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2534 N0.getOperand(0), N1), 2535 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2536 N0.getOperand(1), N1)); 2537 2538 // reassociate mul 2539 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2540 return RMUL; 2541 2542 return SDValue(); 2543 } 2544 2545 /// Return true if divmod libcall is available. 2546 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2547 const TargetLowering &TLI) { 2548 RTLIB::Libcall LC; 2549 EVT NodeType = Node->getValueType(0); 2550 if (!NodeType.isSimple()) 2551 return false; 2552 switch (NodeType.getSimpleVT().SimpleTy) { 2553 default: return false; // No libcall for vector types. 2554 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2555 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2556 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2557 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2558 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2559 } 2560 2561 return TLI.getLibcallName(LC) != nullptr; 2562 } 2563 2564 /// Issue divrem if both quotient and remainder are needed. 2565 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2566 if (Node->use_empty()) 2567 return SDValue(); // This is a dead node, leave it alone. 2568 2569 unsigned Opcode = Node->getOpcode(); 2570 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2571 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2572 2573 // DivMod lib calls can still work on non-legal types if using lib-calls. 2574 EVT VT = Node->getValueType(0); 2575 if (VT.isVector() || !VT.isInteger()) 2576 return SDValue(); 2577 2578 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2579 return SDValue(); 2580 2581 // If DIVREM is going to get expanded into a libcall, 2582 // but there is no libcall available, then don't combine. 2583 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2584 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2585 return SDValue(); 2586 2587 // If div is legal, it's better to do the normal expansion 2588 unsigned OtherOpcode = 0; 2589 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2590 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2591 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2592 return SDValue(); 2593 } else { 2594 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2595 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2596 return SDValue(); 2597 } 2598 2599 SDValue Op0 = Node->getOperand(0); 2600 SDValue Op1 = Node->getOperand(1); 2601 SDValue combined; 2602 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2603 UE = Op0.getNode()->use_end(); UI != UE;) { 2604 SDNode *User = *UI++; 2605 if (User == Node || User->use_empty()) 2606 continue; 2607 // Convert the other matching node(s), too; 2608 // otherwise, the DIVREM may get target-legalized into something 2609 // target-specific that we won't be able to recognize. 2610 unsigned UserOpc = User->getOpcode(); 2611 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2612 User->getOperand(0) == Op0 && 2613 User->getOperand(1) == Op1) { 2614 if (!combined) { 2615 if (UserOpc == OtherOpcode) { 2616 SDVTList VTs = DAG.getVTList(VT, VT); 2617 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2618 } else if (UserOpc == DivRemOpc) { 2619 combined = SDValue(User, 0); 2620 } else { 2621 assert(UserOpc == Opcode); 2622 continue; 2623 } 2624 } 2625 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2626 CombineTo(User, combined); 2627 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2628 CombineTo(User, combined.getValue(1)); 2629 } 2630 } 2631 return combined; 2632 } 2633 2634 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 2635 SDValue N0 = N->getOperand(0); 2636 SDValue N1 = N->getOperand(1); 2637 EVT VT = N->getValueType(0); 2638 SDLoc DL(N); 2639 2640 if (DAG.isUndef(N->getOpcode(), {N0, N1})) 2641 return DAG.getUNDEF(VT); 2642 2643 // undef / X -> 0 2644 // undef % X -> 0 2645 if (N0.isUndef()) 2646 return DAG.getConstant(0, DL, VT); 2647 2648 return SDValue(); 2649 } 2650 2651 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2652 SDValue N0 = N->getOperand(0); 2653 SDValue N1 = N->getOperand(1); 2654 EVT VT = N->getValueType(0); 2655 2656 // fold vector ops 2657 if (VT.isVector()) 2658 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2659 return FoldedVOp; 2660 2661 SDLoc DL(N); 2662 2663 // fold (sdiv c1, c2) -> c1/c2 2664 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2665 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2666 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2667 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2668 // fold (sdiv X, 1) -> X 2669 if (N1C && N1C->isOne()) 2670 return N0; 2671 // fold (sdiv X, -1) -> 0-X 2672 if (N1C && N1C->isAllOnesValue()) 2673 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 2674 2675 if (SDValue V = simplifyDivRem(N, DAG)) 2676 return V; 2677 2678 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2679 return NewSel; 2680 2681 // If we know the sign bits of both operands are zero, strength reduce to a 2682 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2683 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2684 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2685 2686 // fold (sdiv X, pow2) -> simple ops after legalize 2687 // FIXME: We check for the exact bit here because the generic lowering gives 2688 // better results in that case. The target-specific lowering should learn how 2689 // to handle exact sdivs efficiently. 2690 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2691 !N->getFlags().hasExact() && (N1C->getAPIntValue().isPowerOf2() || 2692 (-N1C->getAPIntValue()).isPowerOf2())) { 2693 // Target-specific implementation of sdiv x, pow2. 2694 if (SDValue Res = BuildSDIVPow2(N)) 2695 return Res; 2696 2697 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2698 2699 // Splat the sign bit into the register 2700 SDValue SGN = 2701 DAG.getNode(ISD::SRA, DL, VT, N0, 2702 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2703 getShiftAmountTy(N0.getValueType()))); 2704 AddToWorklist(SGN.getNode()); 2705 2706 // Add (N0 < 0) ? abs2 - 1 : 0; 2707 SDValue SRL = 2708 DAG.getNode(ISD::SRL, DL, VT, SGN, 2709 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2710 getShiftAmountTy(SGN.getValueType()))); 2711 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2712 AddToWorklist(SRL.getNode()); 2713 AddToWorklist(ADD.getNode()); // Divide by pow2 2714 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2715 DAG.getConstant(lg2, DL, 2716 getShiftAmountTy(ADD.getValueType()))); 2717 2718 // If we're dividing by a positive value, we're done. Otherwise, we must 2719 // negate the result. 2720 if (N1C->getAPIntValue().isNonNegative()) 2721 return SRA; 2722 2723 AddToWorklist(SRA.getNode()); 2724 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2725 } 2726 2727 // If integer divide is expensive and we satisfy the requirements, emit an 2728 // alternate sequence. Targets may check function attributes for size/speed 2729 // trade-offs. 2730 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2731 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2732 if (SDValue Op = BuildSDIV(N)) 2733 return Op; 2734 2735 // sdiv, srem -> sdivrem 2736 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2737 // true. Otherwise, we break the simplification logic in visitREM(). 2738 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2739 if (SDValue DivRem = useDivRem(N)) 2740 return DivRem; 2741 2742 return SDValue(); 2743 } 2744 2745 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2746 SDValue N0 = N->getOperand(0); 2747 SDValue N1 = N->getOperand(1); 2748 EVT VT = N->getValueType(0); 2749 2750 // fold vector ops 2751 if (VT.isVector()) 2752 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2753 return FoldedVOp; 2754 2755 SDLoc DL(N); 2756 2757 // fold (udiv c1, c2) -> c1/c2 2758 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2759 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2760 if (N0C && N1C) 2761 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2762 N0C, N1C)) 2763 return Folded; 2764 2765 if (SDValue V = simplifyDivRem(N, DAG)) 2766 return V; 2767 2768 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2769 return NewSel; 2770 2771 // fold (udiv x, (1 << c)) -> x >>u c 2772 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 2773 DAG.isKnownToBeAPowerOfTwo(N1)) { 2774 SDValue LogBase2 = BuildLogBase2(N1, DL); 2775 AddToWorklist(LogBase2.getNode()); 2776 2777 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 2778 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 2779 AddToWorklist(Trunc.getNode()); 2780 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 2781 } 2782 2783 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2784 if (N1.getOpcode() == ISD::SHL) { 2785 SDValue N10 = N1.getOperand(0); 2786 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 2787 DAG.isKnownToBeAPowerOfTwo(N10)) { 2788 SDValue LogBase2 = BuildLogBase2(N10, DL); 2789 AddToWorklist(LogBase2.getNode()); 2790 2791 EVT ADDVT = N1.getOperand(1).getValueType(); 2792 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 2793 AddToWorklist(Trunc.getNode()); 2794 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 2795 AddToWorklist(Add.getNode()); 2796 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2797 } 2798 } 2799 2800 // fold (udiv x, c) -> alternate 2801 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2802 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2803 if (SDValue Op = BuildUDIV(N)) 2804 return Op; 2805 2806 // sdiv, srem -> sdivrem 2807 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 2808 // true. Otherwise, we break the simplification logic in visitREM(). 2809 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2810 if (SDValue DivRem = useDivRem(N)) 2811 return DivRem; 2812 2813 return SDValue(); 2814 } 2815 2816 // handles ISD::SREM and ISD::UREM 2817 SDValue DAGCombiner::visitREM(SDNode *N) { 2818 unsigned Opcode = N->getOpcode(); 2819 SDValue N0 = N->getOperand(0); 2820 SDValue N1 = N->getOperand(1); 2821 EVT VT = N->getValueType(0); 2822 bool isSigned = (Opcode == ISD::SREM); 2823 SDLoc DL(N); 2824 2825 // fold (rem c1, c2) -> c1%c2 2826 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2827 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2828 if (N0C && N1C) 2829 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2830 return Folded; 2831 2832 if (SDValue V = simplifyDivRem(N, DAG)) 2833 return V; 2834 2835 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2836 return NewSel; 2837 2838 if (isSigned) { 2839 // If we know the sign bits of both operands are zero, strength reduce to a 2840 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2841 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2842 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2843 } else { 2844 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 2845 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 2846 // fold (urem x, pow2) -> (and x, pow2-1) 2847 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2848 AddToWorklist(Add.getNode()); 2849 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2850 } 2851 if (N1.getOpcode() == ISD::SHL && 2852 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 2853 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2854 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 2855 AddToWorklist(Add.getNode()); 2856 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2857 } 2858 } 2859 2860 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2861 2862 // If X/C can be simplified by the division-by-constant logic, lower 2863 // X%C to the equivalent of X-X/C*C. 2864 // To avoid mangling nodes, this simplification requires that the combine() 2865 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2866 // against this by skipping the simplification if isIntDivCheap(). When 2867 // div is not cheap, combine will not return a DIVREM. Regardless, 2868 // checking cheapness here makes sense since the simplification results in 2869 // fatter code. 2870 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2871 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2872 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2873 AddToWorklist(Div.getNode()); 2874 SDValue OptimizedDiv = combine(Div.getNode()); 2875 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2876 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2877 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2878 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2879 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2880 AddToWorklist(Mul.getNode()); 2881 return Sub; 2882 } 2883 } 2884 2885 // sdiv, srem -> sdivrem 2886 if (SDValue DivRem = useDivRem(N)) 2887 return DivRem.getValue(1); 2888 2889 return SDValue(); 2890 } 2891 2892 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2893 SDValue N0 = N->getOperand(0); 2894 SDValue N1 = N->getOperand(1); 2895 EVT VT = N->getValueType(0); 2896 SDLoc DL(N); 2897 2898 // fold (mulhs x, 0) -> 0 2899 if (isNullConstant(N1)) 2900 return N1; 2901 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2902 if (isOneConstant(N1)) { 2903 SDLoc DL(N); 2904 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2905 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 2906 getShiftAmountTy(N0.getValueType()))); 2907 } 2908 // fold (mulhs x, undef) -> 0 2909 if (N0.isUndef() || N1.isUndef()) 2910 return DAG.getConstant(0, SDLoc(N), VT); 2911 2912 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2913 // plus a shift. 2914 if (VT.isSimple() && !VT.isVector()) { 2915 MVT Simple = VT.getSimpleVT(); 2916 unsigned SimpleSize = Simple.getSizeInBits(); 2917 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2918 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2919 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2920 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2921 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2922 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2923 DAG.getConstant(SimpleSize, DL, 2924 getShiftAmountTy(N1.getValueType()))); 2925 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2926 } 2927 } 2928 2929 return SDValue(); 2930 } 2931 2932 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2933 SDValue N0 = N->getOperand(0); 2934 SDValue N1 = N->getOperand(1); 2935 EVT VT = N->getValueType(0); 2936 SDLoc DL(N); 2937 2938 // fold (mulhu x, 0) -> 0 2939 if (isNullConstant(N1)) 2940 return N1; 2941 // fold (mulhu x, 1) -> 0 2942 if (isOneConstant(N1)) 2943 return DAG.getConstant(0, DL, N0.getValueType()); 2944 // fold (mulhu x, undef) -> 0 2945 if (N0.isUndef() || N1.isUndef()) 2946 return DAG.getConstant(0, DL, VT); 2947 2948 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2949 // plus a shift. 2950 if (VT.isSimple() && !VT.isVector()) { 2951 MVT Simple = VT.getSimpleVT(); 2952 unsigned SimpleSize = Simple.getSizeInBits(); 2953 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2954 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2955 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2956 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2957 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2958 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2959 DAG.getConstant(SimpleSize, DL, 2960 getShiftAmountTy(N1.getValueType()))); 2961 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2962 } 2963 } 2964 2965 return SDValue(); 2966 } 2967 2968 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2969 /// give the opcodes for the two computations that are being performed. Return 2970 /// true if a simplification was made. 2971 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2972 unsigned HiOp) { 2973 // If the high half is not needed, just compute the low half. 2974 bool HiExists = N->hasAnyUseOfValue(1); 2975 if (!HiExists && 2976 (!LegalOperations || 2977 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2978 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2979 return CombineTo(N, Res, Res); 2980 } 2981 2982 // If the low half is not needed, just compute the high half. 2983 bool LoExists = N->hasAnyUseOfValue(0); 2984 if (!LoExists && 2985 (!LegalOperations || 2986 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2987 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2988 return CombineTo(N, Res, Res); 2989 } 2990 2991 // If both halves are used, return as it is. 2992 if (LoExists && HiExists) 2993 return SDValue(); 2994 2995 // If the two computed results can be simplified separately, separate them. 2996 if (LoExists) { 2997 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2998 AddToWorklist(Lo.getNode()); 2999 SDValue LoOpt = combine(Lo.getNode()); 3000 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3001 (!LegalOperations || 3002 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 3003 return CombineTo(N, LoOpt, LoOpt); 3004 } 3005 3006 if (HiExists) { 3007 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3008 AddToWorklist(Hi.getNode()); 3009 SDValue HiOpt = combine(Hi.getNode()); 3010 if (HiOpt.getNode() && HiOpt != Hi && 3011 (!LegalOperations || 3012 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 3013 return CombineTo(N, HiOpt, HiOpt); 3014 } 3015 3016 return SDValue(); 3017 } 3018 3019 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3020 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3021 return Res; 3022 3023 EVT VT = N->getValueType(0); 3024 SDLoc DL(N); 3025 3026 // If the type is twice as wide is legal, transform the mulhu to a wider 3027 // multiply plus a shift. 3028 if (VT.isSimple() && !VT.isVector()) { 3029 MVT Simple = VT.getSimpleVT(); 3030 unsigned SimpleSize = Simple.getSizeInBits(); 3031 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3032 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3033 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3034 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3035 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3036 // Compute the high part as N1. 3037 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3038 DAG.getConstant(SimpleSize, DL, 3039 getShiftAmountTy(Lo.getValueType()))); 3040 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3041 // Compute the low part as N0. 3042 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3043 return CombineTo(N, Lo, Hi); 3044 } 3045 } 3046 3047 return SDValue(); 3048 } 3049 3050 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3051 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3052 return Res; 3053 3054 EVT VT = N->getValueType(0); 3055 SDLoc DL(N); 3056 3057 // If the type is twice as wide is legal, transform the mulhu to a wider 3058 // multiply plus a shift. 3059 if (VT.isSimple() && !VT.isVector()) { 3060 MVT Simple = VT.getSimpleVT(); 3061 unsigned SimpleSize = Simple.getSizeInBits(); 3062 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3063 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3064 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3065 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3066 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3067 // Compute the high part as N1. 3068 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3069 DAG.getConstant(SimpleSize, DL, 3070 getShiftAmountTy(Lo.getValueType()))); 3071 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3072 // Compute the low part as N0. 3073 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3074 return CombineTo(N, Lo, Hi); 3075 } 3076 } 3077 3078 return SDValue(); 3079 } 3080 3081 SDValue DAGCombiner::visitSMULO(SDNode *N) { 3082 // (smulo x, 2) -> (saddo x, x) 3083 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3084 if (C2->getAPIntValue() == 2) 3085 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 3086 N->getOperand(0), N->getOperand(0)); 3087 3088 return SDValue(); 3089 } 3090 3091 SDValue DAGCombiner::visitUMULO(SDNode *N) { 3092 // (umulo x, 2) -> (uaddo x, x) 3093 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 3094 if (C2->getAPIntValue() == 2) 3095 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 3096 N->getOperand(0), N->getOperand(0)); 3097 3098 return SDValue(); 3099 } 3100 3101 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3102 SDValue N0 = N->getOperand(0); 3103 SDValue N1 = N->getOperand(1); 3104 EVT VT = N0.getValueType(); 3105 3106 // fold vector ops 3107 if (VT.isVector()) 3108 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3109 return FoldedVOp; 3110 3111 // fold (add c1, c2) -> c1+c2 3112 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3113 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3114 if (N0C && N1C) 3115 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3116 3117 // canonicalize constant to RHS 3118 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3119 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3120 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3121 3122 return SDValue(); 3123 } 3124 3125 /// If this is a binary operator with two operands of the same opcode, try to 3126 /// simplify it. 3127 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 3128 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 3129 EVT VT = N0.getValueType(); 3130 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 3131 3132 // Bail early if none of these transforms apply. 3133 if (N0.getNumOperands() == 0) return SDValue(); 3134 3135 // For each of OP in AND/OR/XOR: 3136 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 3137 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 3138 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 3139 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 3140 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 3141 // 3142 // do not sink logical op inside of a vector extend, since it may combine 3143 // into a vsetcc. 3144 EVT Op0VT = N0.getOperand(0).getValueType(); 3145 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 3146 N0.getOpcode() == ISD::SIGN_EXTEND || 3147 N0.getOpcode() == ISD::BSWAP || 3148 // Avoid infinite looping with PromoteIntBinOp. 3149 (N0.getOpcode() == ISD::ANY_EXTEND && 3150 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 3151 (N0.getOpcode() == ISD::TRUNCATE && 3152 (!TLI.isZExtFree(VT, Op0VT) || 3153 !TLI.isTruncateFree(Op0VT, VT)) && 3154 TLI.isTypeLegal(Op0VT))) && 3155 !VT.isVector() && 3156 Op0VT == N1.getOperand(0).getValueType() && 3157 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 3158 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3159 N0.getOperand(0).getValueType(), 3160 N0.getOperand(0), N1.getOperand(0)); 3161 AddToWorklist(ORNode.getNode()); 3162 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 3163 } 3164 3165 // For each of OP in SHL/SRL/SRA/AND... 3166 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 3167 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 3168 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 3169 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 3170 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 3171 N0.getOperand(1) == N1.getOperand(1)) { 3172 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 3173 N0.getOperand(0).getValueType(), 3174 N0.getOperand(0), N1.getOperand(0)); 3175 AddToWorklist(ORNode.getNode()); 3176 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 3177 ORNode, N0.getOperand(1)); 3178 } 3179 3180 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 3181 // Only perform this optimization up until type legalization, before 3182 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 3183 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 3184 // we don't want to undo this promotion. 3185 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 3186 // on scalars. 3187 if ((N0.getOpcode() == ISD::BITCAST || 3188 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 3189 Level <= AfterLegalizeTypes) { 3190 SDValue In0 = N0.getOperand(0); 3191 SDValue In1 = N1.getOperand(0); 3192 EVT In0Ty = In0.getValueType(); 3193 EVT In1Ty = In1.getValueType(); 3194 SDLoc DL(N); 3195 // If both incoming values are integers, and the original types are the 3196 // same. 3197 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 3198 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 3199 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 3200 AddToWorklist(Op.getNode()); 3201 return BC; 3202 } 3203 } 3204 3205 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 3206 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 3207 // If both shuffles use the same mask, and both shuffle within a single 3208 // vector, then it is worthwhile to move the swizzle after the operation. 3209 // The type-legalizer generates this pattern when loading illegal 3210 // vector types from memory. In many cases this allows additional shuffle 3211 // optimizations. 3212 // There are other cases where moving the shuffle after the xor/and/or 3213 // is profitable even if shuffles don't perform a swizzle. 3214 // If both shuffles use the same mask, and both shuffles have the same first 3215 // or second operand, then it might still be profitable to move the shuffle 3216 // after the xor/and/or operation. 3217 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 3218 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 3219 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 3220 3221 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 3222 "Inputs to shuffles are not the same type"); 3223 3224 // Check that both shuffles use the same mask. The masks are known to be of 3225 // the same length because the result vector type is the same. 3226 // Check also that shuffles have only one use to avoid introducing extra 3227 // instructions. 3228 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 3229 SVN0->getMask().equals(SVN1->getMask())) { 3230 SDValue ShOp = N0->getOperand(1); 3231 3232 // Don't try to fold this node if it requires introducing a 3233 // build vector of all zeros that might be illegal at this stage. 3234 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3235 if (!LegalTypes) 3236 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3237 else 3238 ShOp = SDValue(); 3239 } 3240 3241 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 3242 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 3243 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 3244 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 3245 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3246 N0->getOperand(0), N1->getOperand(0)); 3247 AddToWorklist(NewNode.getNode()); 3248 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 3249 SVN0->getMask()); 3250 } 3251 3252 // Don't try to fold this node if it requires introducing a 3253 // build vector of all zeros that might be illegal at this stage. 3254 ShOp = N0->getOperand(0); 3255 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 3256 if (!LegalTypes) 3257 ShOp = DAG.getConstant(0, SDLoc(N), VT); 3258 else 3259 ShOp = SDValue(); 3260 } 3261 3262 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 3263 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 3264 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 3265 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 3266 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 3267 N0->getOperand(1), N1->getOperand(1)); 3268 AddToWorklist(NewNode.getNode()); 3269 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 3270 SVN0->getMask()); 3271 } 3272 } 3273 } 3274 3275 return SDValue(); 3276 } 3277 3278 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 3279 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 3280 const SDLoc &DL) { 3281 SDValue LL, LR, RL, RR, N0CC, N1CC; 3282 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 3283 !isSetCCEquivalent(N1, RL, RR, N1CC)) 3284 return SDValue(); 3285 3286 assert(N0.getValueType() == N1.getValueType() && 3287 "Unexpected operand types for bitwise logic op"); 3288 assert(LL.getValueType() == LR.getValueType() && 3289 RL.getValueType() == RR.getValueType() && 3290 "Unexpected operand types for setcc"); 3291 3292 // If we're here post-legalization or the logic op type is not i1, the logic 3293 // op type must match a setcc result type. Also, all folds require new 3294 // operations on the left and right operands, so those types must match. 3295 EVT VT = N0.getValueType(); 3296 EVT OpVT = LL.getValueType(); 3297 if (LegalOperations || VT != MVT::i1) 3298 if (VT != getSetCCResultType(OpVT)) 3299 return SDValue(); 3300 if (OpVT != RL.getValueType()) 3301 return SDValue(); 3302 3303 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 3304 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 3305 bool IsInteger = OpVT.isInteger(); 3306 if (LR == RR && CC0 == CC1 && IsInteger) { 3307 bool IsZero = isNullConstantOrNullSplatConstant(LR); 3308 bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR); 3309 3310 // All bits clear? 3311 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 3312 // All sign bits clear? 3313 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 3314 // Any bits set? 3315 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 3316 // Any sign bits set? 3317 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 3318 3319 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 3320 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 3321 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 3322 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 3323 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 3324 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 3325 AddToWorklist(Or.getNode()); 3326 return DAG.getSetCC(DL, VT, Or, LR, CC1); 3327 } 3328 3329 // All bits set? 3330 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 3331 // All sign bits set? 3332 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 3333 // Any bits clear? 3334 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 3335 // Any sign bits clear? 3336 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 3337 3338 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 3339 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 3340 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 3341 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 3342 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 3343 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 3344 AddToWorklist(And.getNode()); 3345 return DAG.getSetCC(DL, VT, And, LR, CC1); 3346 } 3347 } 3348 3349 // TODO: What is the 'or' equivalent of this fold? 3350 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 3351 if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE && 3352 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 3353 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 3354 SDValue One = DAG.getConstant(1, DL, OpVT); 3355 SDValue Two = DAG.getConstant(2, DL, OpVT); 3356 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 3357 AddToWorklist(Add.getNode()); 3358 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 3359 } 3360 3361 // Try more general transforms if the predicates match and the only user of 3362 // the compares is the 'and' or 'or'. 3363 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 3364 N0.hasOneUse() && N1.hasOneUse()) { 3365 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 3366 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 3367 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 3368 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 3369 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 3370 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 3371 SDValue Zero = DAG.getConstant(0, DL, OpVT); 3372 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 3373 } 3374 } 3375 3376 // Canonicalize equivalent operands to LL == RL. 3377 if (LL == RR && LR == RL) { 3378 CC1 = ISD::getSetCCSwappedOperands(CC1); 3379 std::swap(RL, RR); 3380 } 3381 3382 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3383 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 3384 if (LL == RL && LR == RR) { 3385 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 3386 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 3387 if (NewCC != ISD::SETCC_INVALID && 3388 (!LegalOperations || 3389 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 3390 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 3391 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 3392 } 3393 3394 return SDValue(); 3395 } 3396 3397 /// This contains all DAGCombine rules which reduce two values combined by 3398 /// an And operation to a single value. This makes them reusable in the context 3399 /// of visitSELECT(). Rules involving constants are not included as 3400 /// visitSELECT() already handles those cases. 3401 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 3402 EVT VT = N1.getValueType(); 3403 SDLoc DL(N); 3404 3405 // fold (and x, undef) -> 0 3406 if (N0.isUndef() || N1.isUndef()) 3407 return DAG.getConstant(0, DL, VT); 3408 3409 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 3410 return V; 3411 3412 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3413 VT.getSizeInBits() <= 64) { 3414 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3415 APInt ADDC = ADDI->getAPIntValue(); 3416 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3417 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3418 // immediate for an add, but it is legal if its top c2 bits are set, 3419 // transform the ADD so the immediate doesn't need to be materialized 3420 // in a register. 3421 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3422 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3423 SRLI->getZExtValue()); 3424 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3425 ADDC |= Mask; 3426 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3427 SDLoc DL0(N0); 3428 SDValue NewAdd = 3429 DAG.getNode(ISD::ADD, DL0, VT, 3430 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 3431 CombineTo(N0.getNode(), NewAdd); 3432 // Return N so it doesn't get rechecked! 3433 return SDValue(N, 0); 3434 } 3435 } 3436 } 3437 } 3438 } 3439 } 3440 3441 // Reduce bit extract of low half of an integer to the narrower type. 3442 // (and (srl i64:x, K), KMask) -> 3443 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 3444 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 3445 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 3446 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3447 unsigned Size = VT.getSizeInBits(); 3448 const APInt &AndMask = CAnd->getAPIntValue(); 3449 unsigned ShiftBits = CShift->getZExtValue(); 3450 3451 // Bail out, this node will probably disappear anyway. 3452 if (ShiftBits == 0) 3453 return SDValue(); 3454 3455 unsigned MaskBits = AndMask.countTrailingOnes(); 3456 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 3457 3458 if (AndMask.isMask() && 3459 // Required bits must not span the two halves of the integer and 3460 // must fit in the half size type. 3461 (ShiftBits + MaskBits <= Size / 2) && 3462 TLI.isNarrowingProfitable(VT, HalfVT) && 3463 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3464 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3465 TLI.isTruncateFree(VT, HalfVT) && 3466 TLI.isZExtFree(HalfVT, VT)) { 3467 // The isNarrowingProfitable is to avoid regressions on PPC and 3468 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3469 // on downstream users of this. Those patterns could probably be 3470 // extended to handle extensions mixed in. 3471 3472 SDValue SL(N0); 3473 assert(MaskBits <= Size); 3474 3475 // Extracting the highest bit of the low half. 3476 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3477 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3478 N0.getOperand(0)); 3479 3480 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3481 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3482 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3483 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3484 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3485 } 3486 } 3487 } 3488 } 3489 3490 return SDValue(); 3491 } 3492 3493 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3494 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3495 bool &NarrowLoad) { 3496 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3497 3498 if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits)) 3499 return false; 3500 3501 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3502 LoadedVT = LoadN->getMemoryVT(); 3503 3504 if (ExtVT == LoadedVT && 3505 (!LegalOperations || 3506 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3507 // ZEXTLOAD will match without needing to change the size of the value being 3508 // loaded. 3509 NarrowLoad = false; 3510 return true; 3511 } 3512 3513 // Do not change the width of a volatile load. 3514 if (LoadN->isVolatile()) 3515 return false; 3516 3517 // Do not generate loads of non-round integer types since these can 3518 // be expensive (and would be wrong if the type is not byte sized). 3519 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3520 return false; 3521 3522 if (LegalOperations && 3523 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3524 return false; 3525 3526 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3527 return false; 3528 3529 NarrowLoad = true; 3530 return true; 3531 } 3532 3533 SDValue DAGCombiner::visitAND(SDNode *N) { 3534 SDValue N0 = N->getOperand(0); 3535 SDValue N1 = N->getOperand(1); 3536 EVT VT = N1.getValueType(); 3537 3538 // x & x --> x 3539 if (N0 == N1) 3540 return N0; 3541 3542 // fold vector ops 3543 if (VT.isVector()) { 3544 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3545 return FoldedVOp; 3546 3547 // fold (and x, 0) -> 0, vector edition 3548 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3549 // do not return N0, because undef node may exist in N0 3550 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 3551 SDLoc(N), N0.getValueType()); 3552 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3553 // do not return N1, because undef node may exist in N1 3554 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 3555 SDLoc(N), N1.getValueType()); 3556 3557 // fold (and x, -1) -> x, vector edition 3558 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3559 return N1; 3560 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3561 return N0; 3562 } 3563 3564 // fold (and c1, c2) -> c1&c2 3565 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3566 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3567 if (N0C && N1C && !N1C->isOpaque()) 3568 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3569 // canonicalize constant to RHS 3570 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3571 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3572 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3573 // fold (and x, -1) -> x 3574 if (isAllOnesConstant(N1)) 3575 return N0; 3576 // if (and x, c) is known to be zero, return 0 3577 unsigned BitWidth = VT.getScalarSizeInBits(); 3578 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3579 APInt::getAllOnesValue(BitWidth))) 3580 return DAG.getConstant(0, SDLoc(N), VT); 3581 3582 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3583 return NewSel; 3584 3585 // reassociate and 3586 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3587 return RAND; 3588 // fold (and (or x, C), D) -> D if (C & D) == D 3589 if (N1C && N0.getOpcode() == ISD::OR) 3590 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1))) 3591 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3592 return N1; 3593 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3594 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3595 SDValue N0Op0 = N0.getOperand(0); 3596 APInt Mask = ~N1C->getAPIntValue(); 3597 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 3598 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3599 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3600 N0.getValueType(), N0Op0); 3601 3602 // Replace uses of the AND with uses of the Zero extend node. 3603 CombineTo(N, Zext); 3604 3605 // We actually want to replace all uses of the any_extend with the 3606 // zero_extend, to avoid duplicating things. This will later cause this 3607 // AND to be folded. 3608 CombineTo(N0.getNode(), Zext); 3609 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3610 } 3611 } 3612 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3613 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3614 // already be zero by virtue of the width of the base type of the load. 3615 // 3616 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3617 // more cases. 3618 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3619 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3620 N0.getOperand(0).getOpcode() == ISD::LOAD && 3621 N0.getOperand(0).getResNo() == 0) || 3622 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3623 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3624 N0 : N0.getOperand(0) ); 3625 3626 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3627 // This can be a pure constant or a vector splat, in which case we treat the 3628 // vector as a scalar and use the splat value. 3629 APInt Constant = APInt::getNullValue(1); 3630 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3631 Constant = C->getAPIntValue(); 3632 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3633 APInt SplatValue, SplatUndef; 3634 unsigned SplatBitSize; 3635 bool HasAnyUndefs; 3636 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3637 SplatBitSize, HasAnyUndefs); 3638 if (IsSplat) { 3639 // Undef bits can contribute to a possible optimisation if set, so 3640 // set them. 3641 SplatValue |= SplatUndef; 3642 3643 // The splat value may be something like "0x00FFFFFF", which means 0 for 3644 // the first vector value and FF for the rest, repeating. We need a mask 3645 // that will apply equally to all members of the vector, so AND all the 3646 // lanes of the constant together. 3647 EVT VT = Vector->getValueType(0); 3648 unsigned BitWidth = VT.getScalarSizeInBits(); 3649 3650 // If the splat value has been compressed to a bitlength lower 3651 // than the size of the vector lane, we need to re-expand it to 3652 // the lane size. 3653 if (BitWidth > SplatBitSize) 3654 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3655 SplatBitSize < BitWidth; 3656 SplatBitSize = SplatBitSize * 2) 3657 SplatValue |= SplatValue.shl(SplatBitSize); 3658 3659 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3660 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3661 if (SplatBitSize % BitWidth == 0) { 3662 Constant = APInt::getAllOnesValue(BitWidth); 3663 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3664 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3665 } 3666 } 3667 } 3668 3669 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3670 // actually legal and isn't going to get expanded, else this is a false 3671 // optimisation. 3672 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3673 Load->getValueType(0), 3674 Load->getMemoryVT()); 3675 3676 // Resize the constant to the same size as the original memory access before 3677 // extension. If it is still the AllOnesValue then this AND is completely 3678 // unneeded. 3679 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 3680 3681 bool B; 3682 switch (Load->getExtensionType()) { 3683 default: B = false; break; 3684 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3685 case ISD::ZEXTLOAD: 3686 case ISD::NON_EXTLOAD: B = true; break; 3687 } 3688 3689 if (B && Constant.isAllOnesValue()) { 3690 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3691 // preserve semantics once we get rid of the AND. 3692 SDValue NewLoad(Load, 0); 3693 3694 // Fold the AND away. NewLoad may get replaced immediately. 3695 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3696 3697 if (Load->getExtensionType() == ISD::EXTLOAD) { 3698 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3699 Load->getValueType(0), SDLoc(Load), 3700 Load->getChain(), Load->getBasePtr(), 3701 Load->getOffset(), Load->getMemoryVT(), 3702 Load->getMemOperand()); 3703 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3704 if (Load->getNumValues() == 3) { 3705 // PRE/POST_INC loads have 3 values. 3706 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3707 NewLoad.getValue(2) }; 3708 CombineTo(Load, To, 3, true); 3709 } else { 3710 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3711 } 3712 } 3713 3714 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3715 } 3716 } 3717 3718 // fold (and (load x), 255) -> (zextload x, i8) 3719 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3720 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3721 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 3722 (N0.getOpcode() == ISD::ANY_EXTEND && 3723 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3724 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3725 LoadSDNode *LN0 = HasAnyExt 3726 ? cast<LoadSDNode>(N0.getOperand(0)) 3727 : cast<LoadSDNode>(N0); 3728 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3729 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3730 auto NarrowLoad = false; 3731 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3732 EVT ExtVT, LoadedVT; 3733 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3734 NarrowLoad)) { 3735 if (!NarrowLoad) { 3736 SDValue NewLoad = 3737 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3738 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3739 LN0->getMemOperand()); 3740 AddToWorklist(N); 3741 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3742 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3743 } else { 3744 EVT PtrType = LN0->getOperand(1).getValueType(); 3745 3746 unsigned Alignment = LN0->getAlignment(); 3747 SDValue NewPtr = LN0->getBasePtr(); 3748 3749 // For big endian targets, we need to add an offset to the pointer 3750 // to load the correct bytes. For little endian systems, we merely 3751 // need to read fewer bytes from the same pointer. 3752 if (DAG.getDataLayout().isBigEndian()) { 3753 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3754 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3755 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3756 SDLoc DL(LN0); 3757 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3758 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3759 Alignment = MinAlign(Alignment, PtrOff); 3760 } 3761 3762 AddToWorklist(NewPtr.getNode()); 3763 3764 SDValue Load = DAG.getExtLoad( 3765 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3766 LN0->getPointerInfo(), ExtVT, Alignment, 3767 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3768 AddToWorklist(N); 3769 CombineTo(LN0, Load, Load.getValue(1)); 3770 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3771 } 3772 } 3773 } 3774 } 3775 3776 if (SDValue Combined = visitANDLike(N0, N1, N)) 3777 return Combined; 3778 3779 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3780 if (N0.getOpcode() == N1.getOpcode()) 3781 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3782 return Tmp; 3783 3784 // Masking the negated extension of a boolean is just the zero-extended 3785 // boolean: 3786 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 3787 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 3788 // 3789 // Note: the SimplifyDemandedBits fold below can make an information-losing 3790 // transform, and then we have no way to find this better fold. 3791 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 3792 ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0)); 3793 SDValue SubRHS = N0.getOperand(1); 3794 if (SubLHS && SubLHS->isNullValue()) { 3795 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 3796 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3797 return SubRHS; 3798 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 3799 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 3800 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 3801 } 3802 } 3803 3804 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3805 // fold (and (sra)) -> (and (srl)) when possible. 3806 if (SimplifyDemandedBits(SDValue(N, 0))) 3807 return SDValue(N, 0); 3808 3809 // fold (zext_inreg (extload x)) -> (zextload x) 3810 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3811 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3812 EVT MemVT = LN0->getMemoryVT(); 3813 // If we zero all the possible extended bits, then we can turn this into 3814 // a zextload if we are running before legalize or the operation is legal. 3815 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3816 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3817 BitWidth - MemVT.getScalarSizeInBits())) && 3818 ((!LegalOperations && !LN0->isVolatile()) || 3819 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3820 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3821 LN0->getChain(), LN0->getBasePtr(), 3822 MemVT, LN0->getMemOperand()); 3823 AddToWorklist(N); 3824 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3825 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3826 } 3827 } 3828 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3829 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3830 N0.hasOneUse()) { 3831 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3832 EVT MemVT = LN0->getMemoryVT(); 3833 // If we zero all the possible extended bits, then we can turn this into 3834 // a zextload if we are running before legalize or the operation is legal. 3835 unsigned BitWidth = N1.getScalarValueSizeInBits(); 3836 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3837 BitWidth - MemVT.getScalarSizeInBits())) && 3838 ((!LegalOperations && !LN0->isVolatile()) || 3839 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3840 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3841 LN0->getChain(), LN0->getBasePtr(), 3842 MemVT, LN0->getMemOperand()); 3843 AddToWorklist(N); 3844 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3845 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3846 } 3847 } 3848 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3849 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3850 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3851 N0.getOperand(1), false)) 3852 return BSwap; 3853 } 3854 3855 return SDValue(); 3856 } 3857 3858 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3859 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3860 bool DemandHighBits) { 3861 if (!LegalOperations) 3862 return SDValue(); 3863 3864 EVT VT = N->getValueType(0); 3865 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3866 return SDValue(); 3867 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 3868 return SDValue(); 3869 3870 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3871 bool LookPassAnd0 = false; 3872 bool LookPassAnd1 = false; 3873 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3874 std::swap(N0, N1); 3875 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3876 std::swap(N0, N1); 3877 if (N0.getOpcode() == ISD::AND) { 3878 if (!N0.getNode()->hasOneUse()) 3879 return SDValue(); 3880 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3881 if (!N01C || N01C->getZExtValue() != 0xFF00) 3882 return SDValue(); 3883 N0 = N0.getOperand(0); 3884 LookPassAnd0 = true; 3885 } 3886 3887 if (N1.getOpcode() == ISD::AND) { 3888 if (!N1.getNode()->hasOneUse()) 3889 return SDValue(); 3890 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3891 if (!N11C || N11C->getZExtValue() != 0xFF) 3892 return SDValue(); 3893 N1 = N1.getOperand(0); 3894 LookPassAnd1 = true; 3895 } 3896 3897 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3898 std::swap(N0, N1); 3899 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3900 return SDValue(); 3901 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 3902 return SDValue(); 3903 3904 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3905 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3906 if (!N01C || !N11C) 3907 return SDValue(); 3908 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3909 return SDValue(); 3910 3911 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3912 SDValue N00 = N0->getOperand(0); 3913 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3914 if (!N00.getNode()->hasOneUse()) 3915 return SDValue(); 3916 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3917 if (!N001C || N001C->getZExtValue() != 0xFF) 3918 return SDValue(); 3919 N00 = N00.getOperand(0); 3920 LookPassAnd0 = true; 3921 } 3922 3923 SDValue N10 = N1->getOperand(0); 3924 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3925 if (!N10.getNode()->hasOneUse()) 3926 return SDValue(); 3927 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3928 if (!N101C || N101C->getZExtValue() != 0xFF00) 3929 return SDValue(); 3930 N10 = N10.getOperand(0); 3931 LookPassAnd1 = true; 3932 } 3933 3934 if (N00 != N10) 3935 return SDValue(); 3936 3937 // Make sure everything beyond the low halfword gets set to zero since the SRL 3938 // 16 will clear the top bits. 3939 unsigned OpSizeInBits = VT.getSizeInBits(); 3940 if (DemandHighBits && OpSizeInBits > 16) { 3941 // If the left-shift isn't masked out then the only way this is a bswap is 3942 // if all bits beyond the low 8 are 0. In that case the entire pattern 3943 // reduces to a left shift anyway: leave it for other parts of the combiner. 3944 if (!LookPassAnd0) 3945 return SDValue(); 3946 3947 // However, if the right shift isn't masked out then it might be because 3948 // it's not needed. See if we can spot that too. 3949 if (!LookPassAnd1 && 3950 !DAG.MaskedValueIsZero( 3951 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3952 return SDValue(); 3953 } 3954 3955 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3956 if (OpSizeInBits > 16) { 3957 SDLoc DL(N); 3958 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3959 DAG.getConstant(OpSizeInBits - 16, DL, 3960 getShiftAmountTy(VT))); 3961 } 3962 return Res; 3963 } 3964 3965 /// Return true if the specified node is an element that makes up a 32-bit 3966 /// packed halfword byteswap. 3967 /// ((x & 0x000000ff) << 8) | 3968 /// ((x & 0x0000ff00) >> 8) | 3969 /// ((x & 0x00ff0000) << 8) | 3970 /// ((x & 0xff000000) >> 8) 3971 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3972 if (!N.getNode()->hasOneUse()) 3973 return false; 3974 3975 unsigned Opc = N.getOpcode(); 3976 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3977 return false; 3978 3979 SDValue N0 = N.getOperand(0); 3980 unsigned Opc0 = N0.getOpcode(); 3981 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 3982 return false; 3983 3984 ConstantSDNode *N1C = nullptr; 3985 // SHL or SRL: look upstream for AND mask operand 3986 if (Opc == ISD::AND) 3987 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3988 else if (Opc0 == ISD::AND) 3989 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3990 if (!N1C) 3991 return false; 3992 3993 unsigned MaskByteOffset; 3994 switch (N1C->getZExtValue()) { 3995 default: 3996 return false; 3997 case 0xFF: MaskByteOffset = 0; break; 3998 case 0xFF00: MaskByteOffset = 1; break; 3999 case 0xFF0000: MaskByteOffset = 2; break; 4000 case 0xFF000000: MaskByteOffset = 3; break; 4001 } 4002 4003 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 4004 if (Opc == ISD::AND) { 4005 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 4006 // (x >> 8) & 0xff 4007 // (x >> 8) & 0xff0000 4008 if (Opc0 != ISD::SRL) 4009 return false; 4010 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4011 if (!C || C->getZExtValue() != 8) 4012 return false; 4013 } else { 4014 // (x << 8) & 0xff00 4015 // (x << 8) & 0xff000000 4016 if (Opc0 != ISD::SHL) 4017 return false; 4018 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4019 if (!C || C->getZExtValue() != 8) 4020 return false; 4021 } 4022 } else if (Opc == ISD::SHL) { 4023 // (x & 0xff) << 8 4024 // (x & 0xff0000) << 8 4025 if (MaskByteOffset != 0 && MaskByteOffset != 2) 4026 return false; 4027 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4028 if (!C || C->getZExtValue() != 8) 4029 return false; 4030 } else { // Opc == ISD::SRL 4031 // (x & 0xff00) >> 8 4032 // (x & 0xff000000) >> 8 4033 if (MaskByteOffset != 1 && MaskByteOffset != 3) 4034 return false; 4035 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 4036 if (!C || C->getZExtValue() != 8) 4037 return false; 4038 } 4039 4040 if (Parts[MaskByteOffset]) 4041 return false; 4042 4043 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 4044 return true; 4045 } 4046 4047 /// Match a 32-bit packed halfword bswap. That is 4048 /// ((x & 0x000000ff) << 8) | 4049 /// ((x & 0x0000ff00) >> 8) | 4050 /// ((x & 0x00ff0000) << 8) | 4051 /// ((x & 0xff000000) >> 8) 4052 /// => (rotl (bswap x), 16) 4053 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 4054 if (!LegalOperations) 4055 return SDValue(); 4056 4057 EVT VT = N->getValueType(0); 4058 if (VT != MVT::i32) 4059 return SDValue(); 4060 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 4061 return SDValue(); 4062 4063 // Look for either 4064 // (or (or (and), (and)), (or (and), (and))) 4065 // (or (or (or (and), (and)), (and)), (and)) 4066 if (N0.getOpcode() != ISD::OR) 4067 return SDValue(); 4068 SDValue N00 = N0.getOperand(0); 4069 SDValue N01 = N0.getOperand(1); 4070 SDNode *Parts[4] = {}; 4071 4072 if (N1.getOpcode() == ISD::OR && 4073 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 4074 // (or (or (and), (and)), (or (and), (and))) 4075 if (!isBSwapHWordElement(N00, Parts)) 4076 return SDValue(); 4077 4078 if (!isBSwapHWordElement(N01, Parts)) 4079 return SDValue(); 4080 SDValue N10 = N1.getOperand(0); 4081 if (!isBSwapHWordElement(N10, Parts)) 4082 return SDValue(); 4083 SDValue N11 = N1.getOperand(1); 4084 if (!isBSwapHWordElement(N11, Parts)) 4085 return SDValue(); 4086 } else { 4087 // (or (or (or (and), (and)), (and)), (and)) 4088 if (!isBSwapHWordElement(N1, Parts)) 4089 return SDValue(); 4090 if (!isBSwapHWordElement(N01, Parts)) 4091 return SDValue(); 4092 if (N00.getOpcode() != ISD::OR) 4093 return SDValue(); 4094 SDValue N000 = N00.getOperand(0); 4095 if (!isBSwapHWordElement(N000, Parts)) 4096 return SDValue(); 4097 SDValue N001 = N00.getOperand(1); 4098 if (!isBSwapHWordElement(N001, Parts)) 4099 return SDValue(); 4100 } 4101 4102 // Make sure the parts are all coming from the same node. 4103 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 4104 return SDValue(); 4105 4106 SDLoc DL(N); 4107 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 4108 SDValue(Parts[0], 0)); 4109 4110 // Result of the bswap should be rotated by 16. If it's not legal, then 4111 // do (x << 16) | (x >> 16). 4112 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 4113 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4114 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 4115 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 4116 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 4117 return DAG.getNode(ISD::OR, DL, VT, 4118 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 4119 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 4120 } 4121 4122 /// This contains all DAGCombine rules which reduce two values combined by 4123 /// an Or operation to a single value \see visitANDLike(). 4124 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 4125 EVT VT = N1.getValueType(); 4126 SDLoc DL(N); 4127 4128 // fold (or x, undef) -> -1 4129 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 4130 return DAG.getAllOnesConstant(DL, VT); 4131 4132 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 4133 return V; 4134 4135 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 4136 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 4137 // Don't increase # computations. 4138 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4139 // We can only do this xform if we know that bits from X that are set in C2 4140 // but not in C1 are already zero. Likewise for Y. 4141 if (const ConstantSDNode *N0O1C = 4142 getAsNonOpaqueConstant(N0.getOperand(1))) { 4143 if (const ConstantSDNode *N1O1C = 4144 getAsNonOpaqueConstant(N1.getOperand(1))) { 4145 // We can only do this xform if we know that bits from X that are set in 4146 // C2 but not in C1 are already zero. Likewise for Y. 4147 const APInt &LHSMask = N0O1C->getAPIntValue(); 4148 const APInt &RHSMask = N1O1C->getAPIntValue(); 4149 4150 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 4151 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 4152 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4153 N0.getOperand(0), N1.getOperand(0)); 4154 return DAG.getNode(ISD::AND, DL, VT, X, 4155 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 4156 } 4157 } 4158 } 4159 } 4160 4161 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 4162 if (N0.getOpcode() == ISD::AND && 4163 N1.getOpcode() == ISD::AND && 4164 N0.getOperand(0) == N1.getOperand(0) && 4165 // Don't increase # computations. 4166 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 4167 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 4168 N0.getOperand(1), N1.getOperand(1)); 4169 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 4170 } 4171 4172 return SDValue(); 4173 } 4174 4175 SDValue DAGCombiner::visitOR(SDNode *N) { 4176 SDValue N0 = N->getOperand(0); 4177 SDValue N1 = N->getOperand(1); 4178 EVT VT = N1.getValueType(); 4179 4180 // x | x --> x 4181 if (N0 == N1) 4182 return N0; 4183 4184 // fold vector ops 4185 if (VT.isVector()) { 4186 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4187 return FoldedVOp; 4188 4189 // fold (or x, 0) -> x, vector edition 4190 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4191 return N1; 4192 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4193 return N0; 4194 4195 // fold (or x, -1) -> -1, vector edition 4196 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4197 // do not return N0, because undef node may exist in N0 4198 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 4199 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4200 // do not return N1, because undef node may exist in N1 4201 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 4202 4203 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 4204 // Do this only if the resulting shuffle is legal. 4205 if (isa<ShuffleVectorSDNode>(N0) && 4206 isa<ShuffleVectorSDNode>(N1) && 4207 // Avoid folding a node with illegal type. 4208 TLI.isTypeLegal(VT)) { 4209 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 4210 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 4211 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 4212 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 4213 // Ensure both shuffles have a zero input. 4214 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 4215 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 4216 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 4217 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 4218 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 4219 bool CanFold = true; 4220 int NumElts = VT.getVectorNumElements(); 4221 SmallVector<int, 4> Mask(NumElts); 4222 4223 for (int i = 0; i != NumElts; ++i) { 4224 int M0 = SV0->getMaskElt(i); 4225 int M1 = SV1->getMaskElt(i); 4226 4227 // Determine if either index is pointing to a zero vector. 4228 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 4229 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 4230 4231 // If one element is zero and the otherside is undef, keep undef. 4232 // This also handles the case that both are undef. 4233 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 4234 Mask[i] = -1; 4235 continue; 4236 } 4237 4238 // Make sure only one of the elements is zero. 4239 if (M0Zero == M1Zero) { 4240 CanFold = false; 4241 break; 4242 } 4243 4244 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 4245 4246 // We have a zero and non-zero element. If the non-zero came from 4247 // SV0 make the index a LHS index. If it came from SV1, make it 4248 // a RHS index. We need to mod by NumElts because we don't care 4249 // which operand it came from in the original shuffles. 4250 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 4251 } 4252 4253 if (CanFold) { 4254 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 4255 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 4256 4257 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4258 if (!LegalMask) { 4259 std::swap(NewLHS, NewRHS); 4260 ShuffleVectorSDNode::commuteMask(Mask); 4261 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 4262 } 4263 4264 if (LegalMask) 4265 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 4266 } 4267 } 4268 } 4269 } 4270 4271 // fold (or c1, c2) -> c1|c2 4272 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4273 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4274 if (N0C && N1C && !N1C->isOpaque()) 4275 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 4276 // canonicalize constant to RHS 4277 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4278 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4279 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 4280 // fold (or x, 0) -> x 4281 if (isNullConstant(N1)) 4282 return N0; 4283 // fold (or x, -1) -> -1 4284 if (isAllOnesConstant(N1)) 4285 return N1; 4286 4287 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4288 return NewSel; 4289 4290 // fold (or x, c) -> c iff (x & ~c) == 0 4291 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 4292 return N1; 4293 4294 if (SDValue Combined = visitORLike(N0, N1, N)) 4295 return Combined; 4296 4297 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 4298 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 4299 return BSwap; 4300 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 4301 return BSwap; 4302 4303 // reassociate or 4304 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 4305 return ROR; 4306 4307 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 4308 // iff (c1 & c2) != 0. 4309 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse()) { 4310 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4311 if (C1->getAPIntValue().intersects(N1C->getAPIntValue())) { 4312 if (SDValue COR = 4313 DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, N1C, C1)) 4314 return DAG.getNode( 4315 ISD::AND, SDLoc(N), VT, 4316 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 4317 return SDValue(); 4318 } 4319 } 4320 } 4321 4322 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 4323 if (N0.getOpcode() == N1.getOpcode()) 4324 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4325 return Tmp; 4326 4327 // See if this is some rotate idiom. 4328 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 4329 return SDValue(Rot, 0); 4330 4331 if (SDValue Load = MatchLoadCombine(N)) 4332 return Load; 4333 4334 // Simplify the operands using demanded-bits information. 4335 if (SimplifyDemandedBits(SDValue(N, 0))) 4336 return SDValue(N, 0); 4337 4338 return SDValue(); 4339 } 4340 4341 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 4342 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 4343 if (Op.getOpcode() == ISD::AND) { 4344 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 4345 Mask = Op.getOperand(1); 4346 Op = Op.getOperand(0); 4347 } else { 4348 return false; 4349 } 4350 } 4351 4352 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 4353 Shift = Op; 4354 return true; 4355 } 4356 4357 return false; 4358 } 4359 4360 // Return true if we can prove that, whenever Neg and Pos are both in the 4361 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 4362 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 4363 // 4364 // (or (shift1 X, Neg), (shift2 X, Pos)) 4365 // 4366 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 4367 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 4368 // to consider shift amounts with defined behavior. 4369 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 4370 // If EltSize is a power of 2 then: 4371 // 4372 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 4373 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 4374 // 4375 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 4376 // for the stronger condition: 4377 // 4378 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 4379 // 4380 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 4381 // we can just replace Neg with Neg' for the rest of the function. 4382 // 4383 // In other cases we check for the even stronger condition: 4384 // 4385 // Neg == EltSize - Pos [B] 4386 // 4387 // for all Neg and Pos. Note that the (or ...) then invokes undefined 4388 // behavior if Pos == 0 (and consequently Neg == EltSize). 4389 // 4390 // We could actually use [A] whenever EltSize is a power of 2, but the 4391 // only extra cases that it would match are those uninteresting ones 4392 // where Neg and Pos are never in range at the same time. E.g. for 4393 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 4394 // as well as (sub 32, Pos), but: 4395 // 4396 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 4397 // 4398 // always invokes undefined behavior for 32-bit X. 4399 // 4400 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 4401 unsigned MaskLoBits = 0; 4402 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 4403 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 4404 if (NegC->getAPIntValue() == EltSize - 1) { 4405 Neg = Neg.getOperand(0); 4406 MaskLoBits = Log2_64(EltSize); 4407 } 4408 } 4409 } 4410 4411 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 4412 if (Neg.getOpcode() != ISD::SUB) 4413 return false; 4414 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 4415 if (!NegC) 4416 return false; 4417 SDValue NegOp1 = Neg.getOperand(1); 4418 4419 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 4420 // Pos'. The truncation is redundant for the purpose of the equality. 4421 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 4422 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4423 if (PosC->getAPIntValue() == EltSize - 1) 4424 Pos = Pos.getOperand(0); 4425 4426 // The condition we need is now: 4427 // 4428 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 4429 // 4430 // If NegOp1 == Pos then we need: 4431 // 4432 // EltSize & Mask == NegC & Mask 4433 // 4434 // (because "x & Mask" is a truncation and distributes through subtraction). 4435 APInt Width; 4436 if (Pos == NegOp1) 4437 Width = NegC->getAPIntValue(); 4438 4439 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 4440 // Then the condition we want to prove becomes: 4441 // 4442 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 4443 // 4444 // which, again because "x & Mask" is a truncation, becomes: 4445 // 4446 // NegC & Mask == (EltSize - PosC) & Mask 4447 // EltSize & Mask == (NegC + PosC) & Mask 4448 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4449 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4450 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4451 else 4452 return false; 4453 } else 4454 return false; 4455 4456 // Now we just need to check that EltSize & Mask == Width & Mask. 4457 if (MaskLoBits) 4458 // EltSize & Mask is 0 since Mask is EltSize - 1. 4459 return Width.getLoBits(MaskLoBits) == 0; 4460 return Width == EltSize; 4461 } 4462 4463 // A subroutine of MatchRotate used once we have found an OR of two opposite 4464 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4465 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4466 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4467 // Neg with outer conversions stripped away. 4468 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4469 SDValue Neg, SDValue InnerPos, 4470 SDValue InnerNeg, unsigned PosOpcode, 4471 unsigned NegOpcode, const SDLoc &DL) { 4472 // fold (or (shl x, (*ext y)), 4473 // (srl x, (*ext (sub 32, y)))) -> 4474 // (rotl x, y) or (rotr x, (sub 32, y)) 4475 // 4476 // fold (or (shl x, (*ext (sub 32, y))), 4477 // (srl x, (*ext y))) -> 4478 // (rotr x, y) or (rotl x, (sub 32, y)) 4479 EVT VT = Shifted.getValueType(); 4480 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4481 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4482 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4483 HasPos ? Pos : Neg).getNode(); 4484 } 4485 4486 return nullptr; 4487 } 4488 4489 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4490 // idioms for rotate, and if the target supports rotation instructions, generate 4491 // a rot[lr]. 4492 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4493 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4494 EVT VT = LHS.getValueType(); 4495 if (!TLI.isTypeLegal(VT)) return nullptr; 4496 4497 // The target must have at least one rotate flavor. 4498 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4499 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4500 if (!HasROTL && !HasROTR) return nullptr; 4501 4502 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4503 SDValue LHSShift; // The shift. 4504 SDValue LHSMask; // AND value if any. 4505 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4506 return nullptr; // Not part of a rotate. 4507 4508 SDValue RHSShift; // The shift. 4509 SDValue RHSMask; // AND value if any. 4510 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4511 return nullptr; // Not part of a rotate. 4512 4513 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4514 return nullptr; // Not shifting the same value. 4515 4516 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4517 return nullptr; // Shifts must disagree. 4518 4519 // Canonicalize shl to left side in a shl/srl pair. 4520 if (RHSShift.getOpcode() == ISD::SHL) { 4521 std::swap(LHS, RHS); 4522 std::swap(LHSShift, RHSShift); 4523 std::swap(LHSMask, RHSMask); 4524 } 4525 4526 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4527 SDValue LHSShiftArg = LHSShift.getOperand(0); 4528 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4529 SDValue RHSShiftArg = RHSShift.getOperand(0); 4530 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4531 4532 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4533 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4534 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4535 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4536 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4537 if ((LShVal + RShVal) != EltSizeInBits) 4538 return nullptr; 4539 4540 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4541 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4542 4543 // If there is an AND of either shifted operand, apply it to the result. 4544 if (LHSMask.getNode() || RHSMask.getNode()) { 4545 SDValue Mask = DAG.getAllOnesConstant(DL, VT); 4546 4547 if (LHSMask.getNode()) { 4548 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4549 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4550 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4551 DAG.getConstant(RHSBits, DL, VT))); 4552 } 4553 if (RHSMask.getNode()) { 4554 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4555 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4556 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4557 DAG.getConstant(LHSBits, DL, VT))); 4558 } 4559 4560 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4561 } 4562 4563 return Rot.getNode(); 4564 } 4565 4566 // If there is a mask here, and we have a variable shift, we can't be sure 4567 // that we're masking out the right stuff. 4568 if (LHSMask.getNode() || RHSMask.getNode()) 4569 return nullptr; 4570 4571 // If the shift amount is sign/zext/any-extended just peel it off. 4572 SDValue LExtOp0 = LHSShiftAmt; 4573 SDValue RExtOp0 = RHSShiftAmt; 4574 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4575 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4576 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4577 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4578 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4579 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4580 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4581 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4582 LExtOp0 = LHSShiftAmt.getOperand(0); 4583 RExtOp0 = RHSShiftAmt.getOperand(0); 4584 } 4585 4586 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4587 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4588 if (TryL) 4589 return TryL; 4590 4591 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4592 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4593 if (TryR) 4594 return TryR; 4595 4596 return nullptr; 4597 } 4598 4599 namespace { 4600 /// Helper struct to parse and store a memory address as base + index + offset. 4601 /// We ignore sign extensions when it is safe to do so. 4602 /// The following two expressions are not equivalent. To differentiate we need 4603 /// to store whether there was a sign extension involved in the index 4604 /// computation. 4605 /// (load (i64 add (i64 copyfromreg %c) 4606 /// (i64 signextend (add (i8 load %index) 4607 /// (i8 1)))) 4608 /// vs 4609 /// 4610 /// (load (i64 add (i64 copyfromreg %c) 4611 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 4612 /// (i32 1))))) 4613 struct BaseIndexOffset { 4614 SDValue Base; 4615 SDValue Index; 4616 int64_t Offset; 4617 bool IsIndexSignExt; 4618 4619 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 4620 4621 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 4622 bool IsIndexSignExt) : 4623 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 4624 4625 bool equalBaseIndex(const BaseIndexOffset &Other) { 4626 return Other.Base == Base && Other.Index == Index && 4627 Other.IsIndexSignExt == IsIndexSignExt; 4628 } 4629 4630 /// Parses tree in Ptr for base, index, offset addresses. 4631 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG, 4632 int64_t PartialOffset = 0) { 4633 bool IsIndexSignExt = false; 4634 4635 // Split up a folded GlobalAddress+Offset into its component parts. 4636 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 4637 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 4638 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 4639 SDLoc(GA), 4640 GA->getValueType(0), 4641 /*Offset=*/PartialOffset, 4642 /*isTargetGA=*/false, 4643 GA->getTargetFlags()), 4644 SDValue(), 4645 GA->getOffset(), 4646 IsIndexSignExt); 4647 } 4648 4649 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 4650 // instruction, then it could be just the BASE or everything else we don't 4651 // know how to handle. Just use Ptr as BASE and give up. 4652 if (Ptr->getOpcode() != ISD::ADD) 4653 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4654 4655 // We know that we have at least an ADD instruction. Try to pattern match 4656 // the simple case of BASE + OFFSET. 4657 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 4658 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 4659 return match(Ptr->getOperand(0), DAG, Offset + PartialOffset); 4660 } 4661 4662 // Inside a loop the current BASE pointer is calculated using an ADD and a 4663 // MUL instruction. In this case Ptr is the actual BASE pointer. 4664 // (i64 add (i64 %array_ptr) 4665 // (i64 mul (i64 %induction_var) 4666 // (i64 %element_size))) 4667 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 4668 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4669 4670 // Look at Base + Index + Offset cases. 4671 SDValue Base = Ptr->getOperand(0); 4672 SDValue IndexOffset = Ptr->getOperand(1); 4673 4674 // Skip signextends. 4675 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 4676 IndexOffset = IndexOffset->getOperand(0); 4677 IsIndexSignExt = true; 4678 } 4679 4680 // Either the case of Base + Index (no offset) or something else. 4681 if (IndexOffset->getOpcode() != ISD::ADD) 4682 return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt); 4683 4684 // Now we have the case of Base + Index + offset. 4685 SDValue Index = IndexOffset->getOperand(0); 4686 SDValue Offset = IndexOffset->getOperand(1); 4687 4688 if (!isa<ConstantSDNode>(Offset)) 4689 return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt); 4690 4691 // Ignore signextends. 4692 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 4693 Index = Index->getOperand(0); 4694 IsIndexSignExt = true; 4695 } else IsIndexSignExt = false; 4696 4697 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 4698 return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt); 4699 } 4700 }; 4701 } // namespace 4702 4703 namespace { 4704 /// Represents known origin of an individual byte in load combine pattern. The 4705 /// value of the byte is either constant zero or comes from memory. 4706 struct ByteProvider { 4707 // For constant zero providers Load is set to nullptr. For memory providers 4708 // Load represents the node which loads the byte from memory. 4709 // ByteOffset is the offset of the byte in the value produced by the load. 4710 LoadSDNode *Load; 4711 unsigned ByteOffset; 4712 4713 ByteProvider() : Load(nullptr), ByteOffset(0) {} 4714 4715 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 4716 return ByteProvider(Load, ByteOffset); 4717 } 4718 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 4719 4720 bool isConstantZero() const { return !Load; } 4721 bool isMemory() const { return Load; } 4722 4723 bool operator==(const ByteProvider &Other) const { 4724 return Other.Load == Load && Other.ByteOffset == ByteOffset; 4725 } 4726 4727 private: 4728 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 4729 : Load(Load), ByteOffset(ByteOffset) {} 4730 }; 4731 4732 /// Recursively traverses the expression calculating the origin of the requested 4733 /// byte of the given value. Returns None if the provider can't be calculated. 4734 /// 4735 /// For all the values except the root of the expression verifies that the value 4736 /// has exactly one use and if it's not true return None. This way if the origin 4737 /// of the byte is returned it's guaranteed that the values which contribute to 4738 /// the byte are not used outside of this expression. 4739 /// 4740 /// Because the parts of the expression are not allowed to have more than one 4741 /// use this function iterates over trees, not DAGs. So it never visits the same 4742 /// node more than once. 4743 const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index, 4744 unsigned Depth, 4745 bool Root = false) { 4746 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 4747 if (Depth == 10) 4748 return None; 4749 4750 if (!Root && !Op.hasOneUse()) 4751 return None; 4752 4753 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 4754 unsigned BitWidth = Op.getValueSizeInBits(); 4755 if (BitWidth % 8 != 0) 4756 return None; 4757 unsigned ByteWidth = BitWidth / 8; 4758 assert(Index < ByteWidth && "invalid index requested"); 4759 (void) ByteWidth; 4760 4761 switch (Op.getOpcode()) { 4762 case ISD::OR: { 4763 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 4764 if (!LHS) 4765 return None; 4766 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 4767 if (!RHS) 4768 return None; 4769 4770 if (LHS->isConstantZero()) 4771 return RHS; 4772 if (RHS->isConstantZero()) 4773 return LHS; 4774 return None; 4775 } 4776 case ISD::SHL: { 4777 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 4778 if (!ShiftOp) 4779 return None; 4780 4781 uint64_t BitShift = ShiftOp->getZExtValue(); 4782 if (BitShift % 8 != 0) 4783 return None; 4784 uint64_t ByteShift = BitShift / 8; 4785 4786 return Index < ByteShift 4787 ? ByteProvider::getConstantZero() 4788 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 4789 Depth + 1); 4790 } 4791 case ISD::ANY_EXTEND: 4792 case ISD::SIGN_EXTEND: 4793 case ISD::ZERO_EXTEND: { 4794 SDValue NarrowOp = Op->getOperand(0); 4795 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 4796 if (NarrowBitWidth % 8 != 0) 4797 return None; 4798 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4799 4800 if (Index >= NarrowByteWidth) 4801 return Op.getOpcode() == ISD::ZERO_EXTEND 4802 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4803 : None; 4804 return calculateByteProvider(NarrowOp, Index, Depth + 1); 4805 } 4806 case ISD::BSWAP: 4807 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 4808 Depth + 1); 4809 case ISD::LOAD: { 4810 auto L = cast<LoadSDNode>(Op.getNode()); 4811 if (L->isVolatile() || L->isIndexed()) 4812 return None; 4813 4814 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 4815 if (NarrowBitWidth % 8 != 0) 4816 return None; 4817 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 4818 4819 if (Index >= NarrowByteWidth) 4820 return L->getExtensionType() == ISD::ZEXTLOAD 4821 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 4822 : None; 4823 return ByteProvider::getMemory(L, Index); 4824 } 4825 } 4826 4827 return None; 4828 } 4829 } // namespace 4830 4831 /// Match a pattern where a wide type scalar value is loaded by several narrow 4832 /// loads and combined by shifts and ors. Fold it into a single load or a load 4833 /// and a BSWAP if the targets supports it. 4834 /// 4835 /// Assuming little endian target: 4836 /// i8 *a = ... 4837 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 4838 /// => 4839 /// i32 val = *((i32)a) 4840 /// 4841 /// i8 *a = ... 4842 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 4843 /// => 4844 /// i32 val = BSWAP(*((i32)a)) 4845 /// 4846 /// TODO: This rule matches complex patterns with OR node roots and doesn't 4847 /// interact well with the worklist mechanism. When a part of the pattern is 4848 /// updated (e.g. one of the loads) its direct users are put into the worklist, 4849 /// but the root node of the pattern which triggers the load combine is not 4850 /// necessarily a direct user of the changed node. For example, once the address 4851 /// of t28 load is reassociated load combine won't be triggered: 4852 /// t25: i32 = add t4, Constant:i32<2> 4853 /// t26: i64 = sign_extend t25 4854 /// t27: i64 = add t2, t26 4855 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 4856 /// t29: i32 = zero_extend t28 4857 /// t32: i32 = shl t29, Constant:i8<8> 4858 /// t33: i32 = or t23, t32 4859 /// As a possible fix visitLoad can check if the load can be a part of a load 4860 /// combine pattern and add corresponding OR roots to the worklist. 4861 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 4862 assert(N->getOpcode() == ISD::OR && 4863 "Can only match load combining against OR nodes"); 4864 4865 // Handles simple types only 4866 EVT VT = N->getValueType(0); 4867 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 4868 return SDValue(); 4869 unsigned ByteWidth = VT.getSizeInBits() / 8; 4870 4871 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4872 // Before legalize we can introduce too wide illegal loads which will be later 4873 // split into legal sized loads. This enables us to combine i64 load by i8 4874 // patterns to a couple of i32 loads on 32 bit targets. 4875 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 4876 return SDValue(); 4877 4878 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 4879 unsigned BW, unsigned i) { return i; }; 4880 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 4881 unsigned BW, unsigned i) { return BW - i - 1; }; 4882 4883 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 4884 auto MemoryByteOffset = [&] (ByteProvider P) { 4885 assert(P.isMemory() && "Must be a memory byte provider"); 4886 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 4887 assert(LoadBitWidth % 8 == 0 && 4888 "can only analyze providers for individual bytes not bit"); 4889 unsigned LoadByteWidth = LoadBitWidth / 8; 4890 return IsBigEndianTarget 4891 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 4892 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 4893 }; 4894 4895 Optional<BaseIndexOffset> Base; 4896 SDValue Chain; 4897 4898 SmallSet<LoadSDNode *, 8> Loads; 4899 Optional<ByteProvider> FirstByteProvider; 4900 int64_t FirstOffset = INT64_MAX; 4901 4902 // Check if all the bytes of the OR we are looking at are loaded from the same 4903 // base address. Collect bytes offsets from Base address in ByteOffsets. 4904 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 4905 for (unsigned i = 0; i < ByteWidth; i++) { 4906 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 4907 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 4908 return SDValue(); 4909 4910 LoadSDNode *L = P->Load; 4911 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 4912 "Must be enforced by calculateByteProvider"); 4913 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 4914 4915 // All loads must share the same chain 4916 SDValue LChain = L->getChain(); 4917 if (!Chain) 4918 Chain = LChain; 4919 else if (Chain != LChain) 4920 return SDValue(); 4921 4922 // Loads must share the same base address 4923 BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG); 4924 if (!Base) 4925 Base = Ptr; 4926 else if (!Base->equalBaseIndex(Ptr)) 4927 return SDValue(); 4928 4929 // Calculate the offset of the current byte from the base address 4930 int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P); 4931 ByteOffsets[i] = ByteOffsetFromBase; 4932 4933 // Remember the first byte load 4934 if (ByteOffsetFromBase < FirstOffset) { 4935 FirstByteProvider = P; 4936 FirstOffset = ByteOffsetFromBase; 4937 } 4938 4939 Loads.insert(L); 4940 } 4941 assert(Loads.size() > 0 && "All the bytes of the value must be loaded from " 4942 "memory, so there must be at least one load which produces the value"); 4943 assert(Base && "Base address of the accessed memory location must be set"); 4944 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 4945 4946 // Check if the bytes of the OR we are looking at match with either big or 4947 // little endian value load 4948 bool BigEndian = true, LittleEndian = true; 4949 for (unsigned i = 0; i < ByteWidth; i++) { 4950 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 4951 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 4952 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 4953 if (!BigEndian && !LittleEndian) 4954 return SDValue(); 4955 } 4956 assert((BigEndian != LittleEndian) && "should be either or"); 4957 assert(FirstByteProvider && "must be set"); 4958 4959 // Ensure that the first byte is loaded from zero offset of the first load. 4960 // So the combined value can be loaded from the first load address. 4961 if (MemoryByteOffset(*FirstByteProvider) != 0) 4962 return SDValue(); 4963 LoadSDNode *FirstLoad = FirstByteProvider->Load; 4964 4965 // The node we are looking at matches with the pattern, check if we can 4966 // replace it with a single load and bswap if needed. 4967 4968 // If the load needs byte swap check if the target supports it 4969 bool NeedsBswap = IsBigEndianTarget != BigEndian; 4970 4971 // Before legalize we can introduce illegal bswaps which will be later 4972 // converted to an explicit bswap sequence. This way we end up with a single 4973 // load and byte shuffling instead of several loads and byte shuffling. 4974 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 4975 return SDValue(); 4976 4977 // Check that a load of the wide type is both allowed and fast on the target 4978 bool Fast = false; 4979 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 4980 VT, FirstLoad->getAddressSpace(), 4981 FirstLoad->getAlignment(), &Fast); 4982 if (!Allowed || !Fast) 4983 return SDValue(); 4984 4985 SDValue NewLoad = 4986 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 4987 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 4988 4989 // Transfer chain users from old loads to the new load. 4990 for (LoadSDNode *L : Loads) 4991 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 4992 4993 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 4994 } 4995 4996 SDValue DAGCombiner::visitXOR(SDNode *N) { 4997 SDValue N0 = N->getOperand(0); 4998 SDValue N1 = N->getOperand(1); 4999 EVT VT = N0.getValueType(); 5000 5001 // fold vector ops 5002 if (VT.isVector()) { 5003 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5004 return FoldedVOp; 5005 5006 // fold (xor x, 0) -> x, vector edition 5007 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5008 return N1; 5009 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5010 return N0; 5011 } 5012 5013 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 5014 if (N0.isUndef() && N1.isUndef()) 5015 return DAG.getConstant(0, SDLoc(N), VT); 5016 // fold (xor x, undef) -> undef 5017 if (N0.isUndef()) 5018 return N0; 5019 if (N1.isUndef()) 5020 return N1; 5021 // fold (xor c1, c2) -> c1^c2 5022 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5023 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 5024 if (N0C && N1C) 5025 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 5026 // canonicalize constant to RHS 5027 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5028 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5029 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 5030 // fold (xor x, 0) -> x 5031 if (isNullConstant(N1)) 5032 return N0; 5033 5034 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5035 return NewSel; 5036 5037 // reassociate xor 5038 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 5039 return RXOR; 5040 5041 // fold !(x cc y) -> (x !cc y) 5042 SDValue LHS, RHS, CC; 5043 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 5044 bool isInt = LHS.getValueType().isInteger(); 5045 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 5046 isInt); 5047 5048 if (!LegalOperations || 5049 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 5050 switch (N0.getOpcode()) { 5051 default: 5052 llvm_unreachable("Unhandled SetCC Equivalent!"); 5053 case ISD::SETCC: 5054 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 5055 case ISD::SELECT_CC: 5056 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 5057 N0.getOperand(3), NotCC); 5058 } 5059 } 5060 } 5061 5062 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 5063 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 5064 N0.getNode()->hasOneUse() && 5065 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 5066 SDValue V = N0.getOperand(0); 5067 SDLoc DL(N0); 5068 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 5069 DAG.getConstant(1, DL, V.getValueType())); 5070 AddToWorklist(V.getNode()); 5071 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 5072 } 5073 5074 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 5075 if (isOneConstant(N1) && VT == MVT::i1 && 5076 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5077 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5078 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 5079 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5080 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5081 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5082 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5083 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5084 } 5085 } 5086 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 5087 if (isAllOnesConstant(N1) && 5088 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 5089 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5090 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 5091 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 5092 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 5093 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 5094 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 5095 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 5096 } 5097 } 5098 // fold (xor (and x, y), y) -> (and (not x), y) 5099 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5100 N0->getOperand(1) == N1) { 5101 SDValue X = N0->getOperand(0); 5102 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 5103 AddToWorklist(NotX.getNode()); 5104 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 5105 } 5106 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 5107 if (N1C && N0.getOpcode() == ISD::XOR) { 5108 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 5109 SDLoc DL(N); 5110 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 5111 DAG.getConstant(N1C->getAPIntValue() ^ 5112 N00C->getAPIntValue(), DL, VT)); 5113 } 5114 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 5115 SDLoc DL(N); 5116 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 5117 DAG.getConstant(N1C->getAPIntValue() ^ 5118 N01C->getAPIntValue(), DL, VT)); 5119 } 5120 } 5121 5122 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 5123 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5124 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 5125 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) && 5126 TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 5127 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 5128 if (C->getAPIntValue() == (OpSizeInBits - 1)) 5129 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0)); 5130 } 5131 5132 // fold (xor x, x) -> 0 5133 if (N0 == N1) 5134 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 5135 5136 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 5137 // Here is a concrete example of this equivalence: 5138 // i16 x == 14 5139 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 5140 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 5141 // 5142 // => 5143 // 5144 // i16 ~1 == 0b1111111111111110 5145 // i16 rol(~1, 14) == 0b1011111111111111 5146 // 5147 // Some additional tips to help conceptualize this transform: 5148 // - Try to see the operation as placing a single zero in a value of all ones. 5149 // - There exists no value for x which would allow the result to contain zero. 5150 // - Values of x larger than the bitwidth are undefined and do not require a 5151 // consistent result. 5152 // - Pushing the zero left requires shifting one bits in from the right. 5153 // A rotate left of ~1 is a nice way of achieving the desired result. 5154 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 5155 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 5156 SDLoc DL(N); 5157 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 5158 N0.getOperand(1)); 5159 } 5160 5161 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 5162 if (N0.getOpcode() == N1.getOpcode()) 5163 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 5164 return Tmp; 5165 5166 // Simplify the expression using non-local knowledge. 5167 if (SimplifyDemandedBits(SDValue(N, 0))) 5168 return SDValue(N, 0); 5169 5170 return SDValue(); 5171 } 5172 5173 /// Handle transforms common to the three shifts, when the shift amount is a 5174 /// constant. 5175 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 5176 SDNode *LHS = N->getOperand(0).getNode(); 5177 if (!LHS->hasOneUse()) return SDValue(); 5178 5179 // We want to pull some binops through shifts, so that we have (and (shift)) 5180 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 5181 // thing happens with address calculations, so it's important to canonicalize 5182 // it. 5183 bool HighBitSet = false; // Can we transform this if the high bit is set? 5184 5185 switch (LHS->getOpcode()) { 5186 default: return SDValue(); 5187 case ISD::OR: 5188 case ISD::XOR: 5189 HighBitSet = false; // We can only transform sra if the high bit is clear. 5190 break; 5191 case ISD::AND: 5192 HighBitSet = true; // We can only transform sra if the high bit is set. 5193 break; 5194 case ISD::ADD: 5195 if (N->getOpcode() != ISD::SHL) 5196 return SDValue(); // only shl(add) not sr[al](add). 5197 HighBitSet = false; // We can only transform sra if the high bit is clear. 5198 break; 5199 } 5200 5201 // We require the RHS of the binop to be a constant and not opaque as well. 5202 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 5203 if (!BinOpCst) return SDValue(); 5204 5205 // FIXME: disable this unless the input to the binop is a shift by a constant 5206 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 5207 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 5208 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 5209 BinOpLHSVal->getOpcode() == ISD::SRA || 5210 BinOpLHSVal->getOpcode() == ISD::SRL; 5211 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 5212 BinOpLHSVal->getOpcode() == ISD::SELECT; 5213 5214 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 5215 !isCopyOrSelect) 5216 return SDValue(); 5217 5218 if (isCopyOrSelect && N->hasOneUse()) 5219 return SDValue(); 5220 5221 EVT VT = N->getValueType(0); 5222 5223 // If this is a signed shift right, and the high bit is modified by the 5224 // logical operation, do not perform the transformation. The highBitSet 5225 // boolean indicates the value of the high bit of the constant which would 5226 // cause it to be modified for this operation. 5227 if (N->getOpcode() == ISD::SRA) { 5228 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 5229 if (BinOpRHSSignSet != HighBitSet) 5230 return SDValue(); 5231 } 5232 5233 if (!TLI.isDesirableToCommuteWithShift(LHS)) 5234 return SDValue(); 5235 5236 // Fold the constants, shifting the binop RHS by the shift amount. 5237 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 5238 N->getValueType(0), 5239 LHS->getOperand(1), N->getOperand(1)); 5240 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 5241 5242 // Create the new shift. 5243 SDValue NewShift = DAG.getNode(N->getOpcode(), 5244 SDLoc(LHS->getOperand(0)), 5245 VT, LHS->getOperand(0), N->getOperand(1)); 5246 5247 // Create the new binop. 5248 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 5249 } 5250 5251 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 5252 assert(N->getOpcode() == ISD::TRUNCATE); 5253 assert(N->getOperand(0).getOpcode() == ISD::AND); 5254 5255 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 5256 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 5257 SDValue N01 = N->getOperand(0).getOperand(1); 5258 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 5259 SDLoc DL(N); 5260 EVT TruncVT = N->getValueType(0); 5261 SDValue N00 = N->getOperand(0).getOperand(0); 5262 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 5263 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 5264 AddToWorklist(Trunc00.getNode()); 5265 AddToWorklist(Trunc01.getNode()); 5266 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 5267 } 5268 } 5269 5270 return SDValue(); 5271 } 5272 5273 SDValue DAGCombiner::visitRotate(SDNode *N) { 5274 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 5275 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 5276 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 5277 if (SDValue NewOp1 = 5278 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 5279 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 5280 N->getOperand(0), NewOp1); 5281 } 5282 return SDValue(); 5283 } 5284 5285 SDValue DAGCombiner::visitSHL(SDNode *N) { 5286 SDValue N0 = N->getOperand(0); 5287 SDValue N1 = N->getOperand(1); 5288 EVT VT = N0.getValueType(); 5289 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5290 5291 // fold vector ops 5292 if (VT.isVector()) { 5293 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5294 return FoldedVOp; 5295 5296 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 5297 // If setcc produces all-one true value then: 5298 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 5299 if (N1CV && N1CV->isConstant()) { 5300 if (N0.getOpcode() == ISD::AND) { 5301 SDValue N00 = N0->getOperand(0); 5302 SDValue N01 = N0->getOperand(1); 5303 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 5304 5305 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 5306 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 5307 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5308 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 5309 N01CV, N1CV)) 5310 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 5311 } 5312 } 5313 } 5314 } 5315 5316 // If the target supports masking y in (shl, y), 5317 // fold (shl x, (and y, ((1 << numbits(x)) - 1))) -> (shl x, y) 5318 if (TLI.isOperationLegal(ISD::SHL, VT) && 5319 TLI.supportsModuloShift(ISD::SHL, VT) && N1->getOpcode() == ISD::AND) { 5320 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) { 5321 if (Mask->getZExtValue() == OpSizeInBits - 1) { 5322 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N1->getOperand(0)); 5323 } 5324 } 5325 } 5326 5327 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5328 5329 // fold (shl c1, c2) -> c1<<c2 5330 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5331 if (N0C && N1C && !N1C->isOpaque()) 5332 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 5333 // fold (shl 0, x) -> 0 5334 if (isNullConstant(N0)) 5335 return N0; 5336 // fold (shl x, c >= size(x)) -> undef 5337 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5338 return DAG.getUNDEF(VT); 5339 // fold (shl x, 0) -> x 5340 if (N1C && N1C->isNullValue()) 5341 return N0; 5342 // fold (shl undef, x) -> 0 5343 if (N0.isUndef()) 5344 return DAG.getConstant(0, SDLoc(N), VT); 5345 5346 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5347 return NewSel; 5348 5349 // if (shl x, c) is known to be zero, return 0 5350 if (DAG.MaskedValueIsZero(SDValue(N, 0), 5351 APInt::getAllOnesValue(OpSizeInBits))) 5352 return DAG.getConstant(0, SDLoc(N), VT); 5353 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 5354 if (N1.getOpcode() == ISD::TRUNCATE && 5355 N1.getOperand(0).getOpcode() == ISD::AND) { 5356 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5357 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 5358 } 5359 5360 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5361 return SDValue(N, 0); 5362 5363 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 5364 if (N1C && N0.getOpcode() == ISD::SHL) { 5365 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5366 SDLoc DL(N); 5367 APInt c1 = N0C1->getAPIntValue(); 5368 APInt c2 = N1C->getAPIntValue(); 5369 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5370 5371 APInt Sum = c1 + c2; 5372 if (Sum.uge(OpSizeInBits)) 5373 return DAG.getConstant(0, DL, VT); 5374 5375 return DAG.getNode( 5376 ISD::SHL, DL, VT, N0.getOperand(0), 5377 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5378 } 5379 } 5380 5381 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 5382 // For this to be valid, the second form must not preserve any of the bits 5383 // that are shifted out by the inner shift in the first form. This means 5384 // the outer shift size must be >= the number of bits added by the ext. 5385 // As a corollary, we don't care what kind of ext it is. 5386 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 5387 N0.getOpcode() == ISD::ANY_EXTEND || 5388 N0.getOpcode() == ISD::SIGN_EXTEND) && 5389 N0.getOperand(0).getOpcode() == ISD::SHL) { 5390 SDValue N0Op0 = N0.getOperand(0); 5391 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5392 APInt c1 = N0Op0C1->getAPIntValue(); 5393 APInt c2 = N1C->getAPIntValue(); 5394 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5395 5396 EVT InnerShiftVT = N0Op0.getValueType(); 5397 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5398 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 5399 SDLoc DL(N0); 5400 APInt Sum = c1 + c2; 5401 if (Sum.uge(OpSizeInBits)) 5402 return DAG.getConstant(0, DL, VT); 5403 5404 return DAG.getNode( 5405 ISD::SHL, DL, VT, 5406 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 5407 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5408 } 5409 } 5410 } 5411 5412 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 5413 // Only fold this if the inner zext has no other uses to avoid increasing 5414 // the total number of instructions. 5415 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 5416 N0.getOperand(0).getOpcode() == ISD::SRL) { 5417 SDValue N0Op0 = N0.getOperand(0); 5418 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 5419 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 5420 uint64_t c1 = N0Op0C1->getZExtValue(); 5421 uint64_t c2 = N1C->getZExtValue(); 5422 if (c1 == c2) { 5423 SDValue NewOp0 = N0.getOperand(0); 5424 EVT CountVT = NewOp0.getOperand(1).getValueType(); 5425 SDLoc DL(N); 5426 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 5427 NewOp0, 5428 DAG.getConstant(c2, DL, CountVT)); 5429 AddToWorklist(NewSHL.getNode()); 5430 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 5431 } 5432 } 5433 } 5434 } 5435 5436 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 5437 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 5438 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 5439 N0->getFlags().hasExact()) { 5440 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5441 uint64_t C1 = N0C1->getZExtValue(); 5442 uint64_t C2 = N1C->getZExtValue(); 5443 SDLoc DL(N); 5444 if (C1 <= C2) 5445 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5446 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 5447 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 5448 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 5449 } 5450 } 5451 5452 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 5453 // (and (srl x, (sub c1, c2), MASK) 5454 // Only fold this if the inner shift has no other uses -- if it does, folding 5455 // this will increase the total number of instructions. 5456 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5457 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5458 uint64_t c1 = N0C1->getZExtValue(); 5459 if (c1 < OpSizeInBits) { 5460 uint64_t c2 = N1C->getZExtValue(); 5461 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 5462 SDValue Shift; 5463 if (c2 > c1) { 5464 Mask <<= c2 - c1; 5465 SDLoc DL(N); 5466 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 5467 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 5468 } else { 5469 Mask.lshrInPlace(c1 - c2); 5470 SDLoc DL(N); 5471 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 5472 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 5473 } 5474 SDLoc DL(N0); 5475 return DAG.getNode(ISD::AND, DL, VT, Shift, 5476 DAG.getConstant(Mask, DL, VT)); 5477 } 5478 } 5479 } 5480 5481 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 5482 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 5483 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 5484 SDLoc DL(N); 5485 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 5486 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 5487 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 5488 } 5489 5490 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 5491 // Variant of version done on multiply, except mul by a power of 2 is turned 5492 // into a shift. 5493 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 5494 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5495 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5496 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 5497 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5498 AddToWorklist(Shl0.getNode()); 5499 AddToWorklist(Shl1.getNode()); 5500 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 5501 } 5502 5503 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 5504 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 5505 isConstantOrConstantVector(N1, /* No Opaques */ true) && 5506 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 5507 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 5508 if (isConstantOrConstantVector(Shl)) 5509 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 5510 } 5511 5512 if (N1C && !N1C->isOpaque()) 5513 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 5514 return NewSHL; 5515 5516 return SDValue(); 5517 } 5518 5519 SDValue DAGCombiner::visitSRA(SDNode *N) { 5520 SDValue N0 = N->getOperand(0); 5521 SDValue N1 = N->getOperand(1); 5522 EVT VT = N0.getValueType(); 5523 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5524 5525 // If the target supports masking y in (sra, y), 5526 // fold (sra x, (and y, ((1 << numbits(x)) - 1))) -> (sra x, y) 5527 if (TLI.isOperationLegal(ISD::SRA, VT) && 5528 TLI.supportsModuloShift(ISD::SRA, VT) && N1->getOpcode() == ISD::AND) { 5529 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) { 5530 if (Mask->getZExtValue() == OpSizeInBits - 1) { 5531 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, N1->getOperand(0)); 5532 } 5533 } 5534 } 5535 5536 // Arithmetic shifting an all-sign-bit value is a no-op. 5537 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 5538 return N0; 5539 5540 // fold vector ops 5541 if (VT.isVector()) 5542 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5543 return FoldedVOp; 5544 5545 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5546 5547 // fold (sra c1, c2) -> (sra c1, c2) 5548 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5549 if (N0C && N1C && !N1C->isOpaque()) 5550 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 5551 // fold (sra 0, x) -> 0 5552 if (isNullConstant(N0)) 5553 return N0; 5554 // fold (sra -1, x) -> -1 5555 if (isAllOnesConstant(N0)) 5556 return N0; 5557 // fold (sra x, c >= size(x)) -> undef 5558 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5559 return DAG.getUNDEF(VT); 5560 // fold (sra x, 0) -> x 5561 if (N1C && N1C->isNullValue()) 5562 return N0; 5563 5564 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5565 return NewSel; 5566 5567 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 5568 // sext_inreg. 5569 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 5570 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 5571 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 5572 if (VT.isVector()) 5573 ExtVT = EVT::getVectorVT(*DAG.getContext(), 5574 ExtVT, VT.getVectorNumElements()); 5575 if ((!LegalOperations || 5576 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 5577 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 5578 N0.getOperand(0), DAG.getValueType(ExtVT)); 5579 } 5580 5581 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 5582 if (N1C && N0.getOpcode() == ISD::SRA) { 5583 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5584 SDLoc DL(N); 5585 APInt c1 = N0C1->getAPIntValue(); 5586 APInt c2 = N1C->getAPIntValue(); 5587 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5588 5589 APInt Sum = c1 + c2; 5590 if (Sum.uge(OpSizeInBits)) 5591 Sum = APInt(OpSizeInBits, OpSizeInBits - 1); 5592 5593 return DAG.getNode( 5594 ISD::SRA, DL, VT, N0.getOperand(0), 5595 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5596 } 5597 } 5598 5599 // fold (sra (shl X, m), (sub result_size, n)) 5600 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 5601 // result_size - n != m. 5602 // If truncate is free for the target sext(shl) is likely to result in better 5603 // code. 5604 if (N0.getOpcode() == ISD::SHL && N1C) { 5605 // Get the two constanst of the shifts, CN0 = m, CN = n. 5606 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 5607 if (N01C) { 5608 LLVMContext &Ctx = *DAG.getContext(); 5609 // Determine what the truncate's result bitsize and type would be. 5610 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 5611 5612 if (VT.isVector()) 5613 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 5614 5615 // Determine the residual right-shift amount. 5616 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 5617 5618 // If the shift is not a no-op (in which case this should be just a sign 5619 // extend already), the truncated to type is legal, sign_extend is legal 5620 // on that type, and the truncate to that type is both legal and free, 5621 // perform the transform. 5622 if ((ShiftAmt > 0) && 5623 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 5624 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 5625 TLI.isTruncateFree(VT, TruncVT)) { 5626 5627 SDLoc DL(N); 5628 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 5629 getShiftAmountTy(N0.getOperand(0).getValueType())); 5630 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 5631 N0.getOperand(0), Amt); 5632 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 5633 Shift); 5634 return DAG.getNode(ISD::SIGN_EXTEND, DL, 5635 N->getValueType(0), Trunc); 5636 } 5637 } 5638 } 5639 5640 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 5641 if (N1.getOpcode() == ISD::TRUNCATE && 5642 N1.getOperand(0).getOpcode() == ISD::AND) { 5643 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5644 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 5645 } 5646 5647 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 5648 // if c1 is equal to the number of bits the trunc removes 5649 if (N0.getOpcode() == ISD::TRUNCATE && 5650 (N0.getOperand(0).getOpcode() == ISD::SRL || 5651 N0.getOperand(0).getOpcode() == ISD::SRA) && 5652 N0.getOperand(0).hasOneUse() && 5653 N0.getOperand(0).getOperand(1).hasOneUse() && 5654 N1C) { 5655 SDValue N0Op0 = N0.getOperand(0); 5656 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 5657 unsigned LargeShiftVal = LargeShift->getZExtValue(); 5658 EVT LargeVT = N0Op0.getValueType(); 5659 5660 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 5661 SDLoc DL(N); 5662 SDValue Amt = 5663 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 5664 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 5665 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 5666 N0Op0.getOperand(0), Amt); 5667 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 5668 } 5669 } 5670 } 5671 5672 // Simplify, based on bits shifted out of the LHS. 5673 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5674 return SDValue(N, 0); 5675 5676 5677 // If the sign bit is known to be zero, switch this to a SRL. 5678 if (DAG.SignBitIsZero(N0)) 5679 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 5680 5681 if (N1C && !N1C->isOpaque()) 5682 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 5683 return NewSRA; 5684 5685 return SDValue(); 5686 } 5687 5688 SDValue DAGCombiner::visitSRL(SDNode *N) { 5689 SDValue N0 = N->getOperand(0); 5690 SDValue N1 = N->getOperand(1); 5691 EVT VT = N0.getValueType(); 5692 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 5693 5694 // If the target supports masking y in (srl, y), 5695 // fold (srl x, (and y, ((1 << numbits(x)) - 1))) -> (srl x, y) 5696 if (TLI.isOperationLegal(ISD::SRL, VT) && 5697 TLI.supportsModuloShift(ISD::SRL, VT) && N1->getOpcode() == ISD::AND) { 5698 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1))) { 5699 if (Mask->getZExtValue() == OpSizeInBits - 1) { 5700 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1->getOperand(0)); 5701 } 5702 } 5703 } 5704 5705 // fold vector ops 5706 if (VT.isVector()) 5707 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5708 return FoldedVOp; 5709 5710 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5711 5712 // fold (srl c1, c2) -> c1 >>u c2 5713 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5714 if (N0C && N1C && !N1C->isOpaque()) 5715 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 5716 // fold (srl 0, x) -> 0 5717 if (isNullConstant(N0)) 5718 return N0; 5719 // fold (srl x, c >= size(x)) -> undef 5720 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 5721 return DAG.getUNDEF(VT); 5722 // fold (srl x, 0) -> x 5723 if (N1C && N1C->isNullValue()) 5724 return N0; 5725 5726 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5727 return NewSel; 5728 5729 // if (srl x, c) is known to be zero, return 0 5730 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 5731 APInt::getAllOnesValue(OpSizeInBits))) 5732 return DAG.getConstant(0, SDLoc(N), VT); 5733 5734 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 5735 if (N1C && N0.getOpcode() == ISD::SRL) { 5736 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 5737 SDLoc DL(N); 5738 APInt c1 = N0C1->getAPIntValue(); 5739 APInt c2 = N1C->getAPIntValue(); 5740 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 5741 5742 APInt Sum = c1 + c2; 5743 if (Sum.uge(OpSizeInBits)) 5744 return DAG.getConstant(0, DL, VT); 5745 5746 return DAG.getNode( 5747 ISD::SRL, DL, VT, N0.getOperand(0), 5748 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 5749 } 5750 } 5751 5752 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 5753 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 5754 N0.getOperand(0).getOpcode() == ISD::SRL) { 5755 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 5756 uint64_t c1 = N001C->getZExtValue(); 5757 uint64_t c2 = N1C->getZExtValue(); 5758 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 5759 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 5760 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 5761 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 5762 if (c1 + OpSizeInBits == InnerShiftSize) { 5763 SDLoc DL(N0); 5764 if (c1 + c2 >= InnerShiftSize) 5765 return DAG.getConstant(0, DL, VT); 5766 return DAG.getNode(ISD::TRUNCATE, DL, VT, 5767 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 5768 N0.getOperand(0).getOperand(0), 5769 DAG.getConstant(c1 + c2, DL, 5770 ShiftCountVT))); 5771 } 5772 } 5773 } 5774 5775 // fold (srl (shl x, c), c) -> (and x, cst2) 5776 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 5777 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 5778 SDLoc DL(N); 5779 SDValue Mask = 5780 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 5781 AddToWorklist(Mask.getNode()); 5782 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 5783 } 5784 5785 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 5786 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 5787 // Shifting in all undef bits? 5788 EVT SmallVT = N0.getOperand(0).getValueType(); 5789 unsigned BitSize = SmallVT.getScalarSizeInBits(); 5790 if (N1C->getZExtValue() >= BitSize) 5791 return DAG.getUNDEF(VT); 5792 5793 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 5794 uint64_t ShiftAmt = N1C->getZExtValue(); 5795 SDLoc DL0(N0); 5796 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 5797 N0.getOperand(0), 5798 DAG.getConstant(ShiftAmt, DL0, 5799 getShiftAmountTy(SmallVT))); 5800 AddToWorklist(SmallShift.getNode()); 5801 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 5802 SDLoc DL(N); 5803 return DAG.getNode(ISD::AND, DL, VT, 5804 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 5805 DAG.getConstant(Mask, DL, VT)); 5806 } 5807 } 5808 5809 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 5810 // bit, which is unmodified by sra. 5811 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 5812 if (N0.getOpcode() == ISD::SRA) 5813 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 5814 } 5815 5816 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 5817 if (N1C && N0.getOpcode() == ISD::CTLZ && 5818 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 5819 KnownBits Known; 5820 DAG.computeKnownBits(N0.getOperand(0), Known); 5821 5822 // If any of the input bits are KnownOne, then the input couldn't be all 5823 // zeros, thus the result of the srl will always be zero. 5824 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 5825 5826 // If all of the bits input the to ctlz node are known to be zero, then 5827 // the result of the ctlz is "32" and the result of the shift is one. 5828 APInt UnknownBits = ~Known.Zero; 5829 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 5830 5831 // Otherwise, check to see if there is exactly one bit input to the ctlz. 5832 if (UnknownBits.isPowerOf2()) { 5833 // Okay, we know that only that the single bit specified by UnknownBits 5834 // could be set on input to the CTLZ node. If this bit is set, the SRL 5835 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 5836 // to an SRL/XOR pair, which is likely to simplify more. 5837 unsigned ShAmt = UnknownBits.countTrailingZeros(); 5838 SDValue Op = N0.getOperand(0); 5839 5840 if (ShAmt) { 5841 SDLoc DL(N0); 5842 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 5843 DAG.getConstant(ShAmt, DL, 5844 getShiftAmountTy(Op.getValueType()))); 5845 AddToWorklist(Op.getNode()); 5846 } 5847 5848 SDLoc DL(N); 5849 return DAG.getNode(ISD::XOR, DL, VT, 5850 Op, DAG.getConstant(1, DL, VT)); 5851 } 5852 } 5853 5854 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 5855 if (N1.getOpcode() == ISD::TRUNCATE && 5856 N1.getOperand(0).getOpcode() == ISD::AND) { 5857 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 5858 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 5859 } 5860 5861 // fold operands of srl based on knowledge that the low bits are not 5862 // demanded. 5863 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 5864 return SDValue(N, 0); 5865 5866 if (N1C && !N1C->isOpaque()) 5867 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 5868 return NewSRL; 5869 5870 // Attempt to convert a srl of a load into a narrower zero-extending load. 5871 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 5872 return NarrowLoad; 5873 5874 // Here is a common situation. We want to optimize: 5875 // 5876 // %a = ... 5877 // %b = and i32 %a, 2 5878 // %c = srl i32 %b, 1 5879 // brcond i32 %c ... 5880 // 5881 // into 5882 // 5883 // %a = ... 5884 // %b = and %a, 2 5885 // %c = setcc eq %b, 0 5886 // brcond %c ... 5887 // 5888 // However when after the source operand of SRL is optimized into AND, the SRL 5889 // itself may not be optimized further. Look for it and add the BRCOND into 5890 // the worklist. 5891 if (N->hasOneUse()) { 5892 SDNode *Use = *N->use_begin(); 5893 if (Use->getOpcode() == ISD::BRCOND) 5894 AddToWorklist(Use); 5895 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 5896 // Also look pass the truncate. 5897 Use = *Use->use_begin(); 5898 if (Use->getOpcode() == ISD::BRCOND) 5899 AddToWorklist(Use); 5900 } 5901 } 5902 5903 return SDValue(); 5904 } 5905 5906 SDValue DAGCombiner::visitABS(SDNode *N) { 5907 SDValue N0 = N->getOperand(0); 5908 EVT VT = N->getValueType(0); 5909 5910 // fold (abs c1) -> c2 5911 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5912 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 5913 // fold (abs (abs x)) -> (abs x) 5914 if (N0.getOpcode() == ISD::ABS) 5915 return N0; 5916 // fold (abs x) -> x iff not-negative 5917 if (DAG.SignBitIsZero(N0)) 5918 return N0; 5919 return SDValue(); 5920 } 5921 5922 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 5923 SDValue N0 = N->getOperand(0); 5924 EVT VT = N->getValueType(0); 5925 5926 // fold (bswap c1) -> c2 5927 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5928 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 5929 // fold (bswap (bswap x)) -> x 5930 if (N0.getOpcode() == ISD::BSWAP) 5931 return N0->getOperand(0); 5932 return SDValue(); 5933 } 5934 5935 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 5936 SDValue N0 = N->getOperand(0); 5937 EVT VT = N->getValueType(0); 5938 5939 // fold (bitreverse c1) -> c2 5940 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5941 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 5942 // fold (bitreverse (bitreverse x)) -> x 5943 if (N0.getOpcode() == ISD::BITREVERSE) 5944 return N0.getOperand(0); 5945 return SDValue(); 5946 } 5947 5948 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 5949 SDValue N0 = N->getOperand(0); 5950 EVT VT = N->getValueType(0); 5951 5952 // fold (ctlz c1) -> c2 5953 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5954 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 5955 return SDValue(); 5956 } 5957 5958 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 5959 SDValue N0 = N->getOperand(0); 5960 EVT VT = N->getValueType(0); 5961 5962 // fold (ctlz_zero_undef c1) -> c2 5963 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5964 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5965 return SDValue(); 5966 } 5967 5968 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5969 SDValue N0 = N->getOperand(0); 5970 EVT VT = N->getValueType(0); 5971 5972 // fold (cttz c1) -> c2 5973 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5974 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5975 return SDValue(); 5976 } 5977 5978 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5979 SDValue N0 = N->getOperand(0); 5980 EVT VT = N->getValueType(0); 5981 5982 // fold (cttz_zero_undef c1) -> c2 5983 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5984 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5985 return SDValue(); 5986 } 5987 5988 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5989 SDValue N0 = N->getOperand(0); 5990 EVT VT = N->getValueType(0); 5991 5992 // fold (ctpop c1) -> c2 5993 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5994 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5995 return SDValue(); 5996 } 5997 5998 5999 /// \brief Generate Min/Max node 6000 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 6001 SDValue RHS, SDValue True, SDValue False, 6002 ISD::CondCode CC, const TargetLowering &TLI, 6003 SelectionDAG &DAG) { 6004 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 6005 return SDValue(); 6006 6007 switch (CC) { 6008 case ISD::SETOLT: 6009 case ISD::SETOLE: 6010 case ISD::SETLT: 6011 case ISD::SETLE: 6012 case ISD::SETULT: 6013 case ISD::SETULE: { 6014 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 6015 if (TLI.isOperationLegal(Opcode, VT)) 6016 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6017 return SDValue(); 6018 } 6019 case ISD::SETOGT: 6020 case ISD::SETOGE: 6021 case ISD::SETGT: 6022 case ISD::SETGE: 6023 case ISD::SETUGT: 6024 case ISD::SETUGE: { 6025 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 6026 if (TLI.isOperationLegal(Opcode, VT)) 6027 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 6028 return SDValue(); 6029 } 6030 default: 6031 return SDValue(); 6032 } 6033 } 6034 6035 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 6036 SDValue Cond = N->getOperand(0); 6037 SDValue N1 = N->getOperand(1); 6038 SDValue N2 = N->getOperand(2); 6039 EVT VT = N->getValueType(0); 6040 EVT CondVT = Cond.getValueType(); 6041 SDLoc DL(N); 6042 6043 if (!VT.isInteger()) 6044 return SDValue(); 6045 6046 auto *C1 = dyn_cast<ConstantSDNode>(N1); 6047 auto *C2 = dyn_cast<ConstantSDNode>(N2); 6048 if (!C1 || !C2) 6049 return SDValue(); 6050 6051 // Only do this before legalization to avoid conflicting with target-specific 6052 // transforms in the other direction (create a select from a zext/sext). There 6053 // is also a target-independent combine here in DAGCombiner in the other 6054 // direction for (select Cond, -1, 0) when the condition is not i1. 6055 if (CondVT == MVT::i1 && !LegalOperations) { 6056 if (C1->isNullValue() && C2->isOne()) { 6057 // select Cond, 0, 1 --> zext (!Cond) 6058 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6059 if (VT != MVT::i1) 6060 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 6061 return NotCond; 6062 } 6063 if (C1->isNullValue() && C2->isAllOnesValue()) { 6064 // select Cond, 0, -1 --> sext (!Cond) 6065 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 6066 if (VT != MVT::i1) 6067 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 6068 return NotCond; 6069 } 6070 if (C1->isOne() && C2->isNullValue()) { 6071 // select Cond, 1, 0 --> zext (Cond) 6072 if (VT != MVT::i1) 6073 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6074 return Cond; 6075 } 6076 if (C1->isAllOnesValue() && C2->isNullValue()) { 6077 // select Cond, -1, 0 --> sext (Cond) 6078 if (VT != MVT::i1) 6079 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6080 return Cond; 6081 } 6082 6083 // For any constants that differ by 1, we can transform the select into an 6084 // extend and add. Use a target hook because some targets may prefer to 6085 // transform in the other direction. 6086 if (TLI.convertSelectOfConstantsToMath()) { 6087 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 6088 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 6089 if (VT != MVT::i1) 6090 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 6091 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6092 } 6093 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 6094 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 6095 if (VT != MVT::i1) 6096 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 6097 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 6098 } 6099 } 6100 6101 return SDValue(); 6102 } 6103 6104 // fold (select Cond, 0, 1) -> (xor Cond, 1) 6105 // We can't do this reliably if integer based booleans have different contents 6106 // to floating point based booleans. This is because we can't tell whether we 6107 // have an integer-based boolean or a floating-point-based boolean unless we 6108 // can find the SETCC that produced it and inspect its operands. This is 6109 // fairly easy if C is the SETCC node, but it can potentially be 6110 // undiscoverable (or not reasonably discoverable). For example, it could be 6111 // in another basic block or it could require searching a complicated 6112 // expression. 6113 if (CondVT.isInteger() && 6114 TLI.getBooleanContents(false, true) == 6115 TargetLowering::ZeroOrOneBooleanContent && 6116 TLI.getBooleanContents(false, false) == 6117 TargetLowering::ZeroOrOneBooleanContent && 6118 C1->isNullValue() && C2->isOne()) { 6119 SDValue NotCond = 6120 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 6121 if (VT.bitsEq(CondVT)) 6122 return NotCond; 6123 return DAG.getZExtOrTrunc(NotCond, DL, VT); 6124 } 6125 6126 return SDValue(); 6127 } 6128 6129 SDValue DAGCombiner::visitSELECT(SDNode *N) { 6130 SDValue N0 = N->getOperand(0); 6131 SDValue N1 = N->getOperand(1); 6132 SDValue N2 = N->getOperand(2); 6133 EVT VT = N->getValueType(0); 6134 EVT VT0 = N0.getValueType(); 6135 6136 // fold (select C, X, X) -> X 6137 if (N1 == N2) 6138 return N1; 6139 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 6140 // fold (select true, X, Y) -> X 6141 // fold (select false, X, Y) -> Y 6142 return !N0C->isNullValue() ? N1 : N2; 6143 } 6144 // fold (select X, X, Y) -> (or X, Y) 6145 // fold (select X, 1, Y) -> (or C, Y) 6146 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 6147 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 6148 6149 if (SDValue V = foldSelectOfConstants(N)) 6150 return V; 6151 6152 // fold (select C, 0, X) -> (and (not C), X) 6153 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 6154 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6155 AddToWorklist(NOTNode.getNode()); 6156 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 6157 } 6158 // fold (select C, X, 1) -> (or (not C), X) 6159 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 6160 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 6161 AddToWorklist(NOTNode.getNode()); 6162 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 6163 } 6164 // fold (select X, Y, X) -> (and X, Y) 6165 // fold (select X, Y, 0) -> (and X, Y) 6166 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 6167 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 6168 6169 // If we can fold this based on the true/false value, do so. 6170 if (SimplifySelectOps(N, N1, N2)) 6171 return SDValue(N, 0); // Don't revisit N. 6172 6173 if (VT0 == MVT::i1) { 6174 // The code in this block deals with the following 2 equivalences: 6175 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 6176 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 6177 // The target can specify its preferred form with the 6178 // shouldNormalizeToSelectSequence() callback. However we always transform 6179 // to the right anyway if we find the inner select exists in the DAG anyway 6180 // and we always transform to the left side if we know that we can further 6181 // optimize the combination of the conditions. 6182 bool normalizeToSequence 6183 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 6184 // select (and Cond0, Cond1), X, Y 6185 // -> select Cond0, (select Cond1, X, Y), Y 6186 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 6187 SDValue Cond0 = N0->getOperand(0); 6188 SDValue Cond1 = N0->getOperand(1); 6189 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 6190 N1.getValueType(), Cond1, N1, N2); 6191 if (normalizeToSequence || !InnerSelect.use_empty()) 6192 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 6193 InnerSelect, N2); 6194 } 6195 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 6196 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 6197 SDValue Cond0 = N0->getOperand(0); 6198 SDValue Cond1 = N0->getOperand(1); 6199 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 6200 N1.getValueType(), Cond1, N1, N2); 6201 if (normalizeToSequence || !InnerSelect.use_empty()) 6202 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 6203 InnerSelect); 6204 } 6205 6206 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 6207 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 6208 SDValue N1_0 = N1->getOperand(0); 6209 SDValue N1_1 = N1->getOperand(1); 6210 SDValue N1_2 = N1->getOperand(2); 6211 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 6212 // Create the actual and node if we can generate good code for it. 6213 if (!normalizeToSequence) { 6214 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 6215 N0, N1_0); 6216 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 6217 N1_1, N2); 6218 } 6219 // Otherwise see if we can optimize the "and" to a better pattern. 6220 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 6221 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 6222 N1_1, N2); 6223 } 6224 } 6225 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 6226 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 6227 SDValue N2_0 = N2->getOperand(0); 6228 SDValue N2_1 = N2->getOperand(1); 6229 SDValue N2_2 = N2->getOperand(2); 6230 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 6231 // Create the actual or node if we can generate good code for it. 6232 if (!normalizeToSequence) { 6233 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 6234 N0, N2_0); 6235 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 6236 N1, N2_2); 6237 } 6238 // Otherwise see if we can optimize to a better pattern. 6239 if (SDValue Combined = visitORLike(N0, N2_0, N)) 6240 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 6241 N1, N2_2); 6242 } 6243 } 6244 } 6245 6246 // select (xor Cond, 1), X, Y -> select Cond, Y, X 6247 if (VT0 == MVT::i1) { 6248 if (N0->getOpcode() == ISD::XOR) { 6249 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) { 6250 SDValue Cond0 = N0->getOperand(0); 6251 if (C->isOne()) 6252 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), 6253 Cond0, N2, N1); 6254 } 6255 } 6256 } 6257 6258 // fold selects based on a setcc into other things, such as min/max/abs 6259 if (N0.getOpcode() == ISD::SETCC) { 6260 // select x, y (fcmp lt x, y) -> fminnum x, y 6261 // select x, y (fcmp gt x, y) -> fmaxnum x, y 6262 // 6263 // This is OK if we don't care about what happens if either operand is a 6264 // NaN. 6265 // 6266 6267 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 6268 // no signed zeros as well as no nans. 6269 const TargetOptions &Options = DAG.getTarget().Options; 6270 if (Options.UnsafeFPMath && 6271 VT.isFloatingPoint() && N0.hasOneUse() && 6272 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 6273 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6274 6275 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 6276 N0.getOperand(1), N1, N2, CC, 6277 TLI, DAG)) 6278 return FMinMax; 6279 } 6280 6281 if ((!LegalOperations && 6282 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 6283 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 6284 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 6285 N0.getOperand(0), N0.getOperand(1), 6286 N1, N2, N0.getOperand(2)); 6287 return SimplifySelect(SDLoc(N), N0, N1, N2); 6288 } 6289 6290 return SDValue(); 6291 } 6292 6293 static 6294 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 6295 SDLoc DL(N); 6296 EVT LoVT, HiVT; 6297 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 6298 6299 // Split the inputs. 6300 SDValue Lo, Hi, LL, LH, RL, RH; 6301 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 6302 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 6303 6304 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 6305 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 6306 6307 return std::make_pair(Lo, Hi); 6308 } 6309 6310 // This function assumes all the vselect's arguments are CONCAT_VECTOR 6311 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 6312 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 6313 SDLoc DL(N); 6314 SDValue Cond = N->getOperand(0); 6315 SDValue LHS = N->getOperand(1); 6316 SDValue RHS = N->getOperand(2); 6317 EVT VT = N->getValueType(0); 6318 int NumElems = VT.getVectorNumElements(); 6319 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 6320 RHS.getOpcode() == ISD::CONCAT_VECTORS && 6321 Cond.getOpcode() == ISD::BUILD_VECTOR); 6322 6323 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 6324 // binary ones here. 6325 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 6326 return SDValue(); 6327 6328 // We're sure we have an even number of elements due to the 6329 // concat_vectors we have as arguments to vselect. 6330 // Skip BV elements until we find one that's not an UNDEF 6331 // After we find an UNDEF element, keep looping until we get to half the 6332 // length of the BV and see if all the non-undef nodes are the same. 6333 ConstantSDNode *BottomHalf = nullptr; 6334 for (int i = 0; i < NumElems / 2; ++i) { 6335 if (Cond->getOperand(i)->isUndef()) 6336 continue; 6337 6338 if (BottomHalf == nullptr) 6339 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6340 else if (Cond->getOperand(i).getNode() != BottomHalf) 6341 return SDValue(); 6342 } 6343 6344 // Do the same for the second half of the BuildVector 6345 ConstantSDNode *TopHalf = nullptr; 6346 for (int i = NumElems / 2; i < NumElems; ++i) { 6347 if (Cond->getOperand(i)->isUndef()) 6348 continue; 6349 6350 if (TopHalf == nullptr) 6351 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 6352 else if (Cond->getOperand(i).getNode() != TopHalf) 6353 return SDValue(); 6354 } 6355 6356 assert(TopHalf && BottomHalf && 6357 "One half of the selector was all UNDEFs and the other was all the " 6358 "same value. This should have been addressed before this function."); 6359 return DAG.getNode( 6360 ISD::CONCAT_VECTORS, DL, VT, 6361 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 6362 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 6363 } 6364 6365 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 6366 6367 if (Level >= AfterLegalizeTypes) 6368 return SDValue(); 6369 6370 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 6371 SDValue Mask = MSC->getMask(); 6372 SDValue Data = MSC->getValue(); 6373 SDLoc DL(N); 6374 6375 // If the MSCATTER data type requires splitting and the mask is provided by a 6376 // SETCC, then split both nodes and its operands before legalization. This 6377 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6378 // and enables future optimizations (e.g. min/max pattern matching on X86). 6379 if (Mask.getOpcode() != ISD::SETCC) 6380 return SDValue(); 6381 6382 // Check if any splitting is required. 6383 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 6384 TargetLowering::TypeSplitVector) 6385 return SDValue(); 6386 SDValue MaskLo, MaskHi, Lo, Hi; 6387 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6388 6389 EVT LoVT, HiVT; 6390 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 6391 6392 SDValue Chain = MSC->getChain(); 6393 6394 EVT MemoryVT = MSC->getMemoryVT(); 6395 unsigned Alignment = MSC->getOriginalAlignment(); 6396 6397 EVT LoMemVT, HiMemVT; 6398 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6399 6400 SDValue DataLo, DataHi; 6401 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6402 6403 SDValue BasePtr = MSC->getBasePtr(); 6404 SDValue IndexLo, IndexHi; 6405 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 6406 6407 MachineMemOperand *MMO = DAG.getMachineFunction(). 6408 getMachineMemOperand(MSC->getPointerInfo(), 6409 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6410 Alignment, MSC->getAAInfo(), MSC->getRanges()); 6411 6412 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 6413 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 6414 DL, OpsLo, MMO); 6415 6416 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 6417 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 6418 DL, OpsHi, MMO); 6419 6420 AddToWorklist(Lo.getNode()); 6421 AddToWorklist(Hi.getNode()); 6422 6423 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6424 } 6425 6426 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 6427 6428 if (Level >= AfterLegalizeTypes) 6429 return SDValue(); 6430 6431 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 6432 SDValue Mask = MST->getMask(); 6433 SDValue Data = MST->getValue(); 6434 EVT VT = Data.getValueType(); 6435 SDLoc DL(N); 6436 6437 // If the MSTORE data type requires splitting and the mask is provided by a 6438 // SETCC, then split both nodes and its operands before legalization. This 6439 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6440 // and enables future optimizations (e.g. min/max pattern matching on X86). 6441 if (Mask.getOpcode() == ISD::SETCC) { 6442 6443 // Check if any splitting is required. 6444 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6445 TargetLowering::TypeSplitVector) 6446 return SDValue(); 6447 6448 SDValue MaskLo, MaskHi, Lo, Hi; 6449 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6450 6451 SDValue Chain = MST->getChain(); 6452 SDValue Ptr = MST->getBasePtr(); 6453 6454 EVT MemoryVT = MST->getMemoryVT(); 6455 unsigned Alignment = MST->getOriginalAlignment(); 6456 6457 // if Alignment is equal to the vector size, 6458 // take the half of it for the second part 6459 unsigned SecondHalfAlignment = 6460 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 6461 6462 EVT LoMemVT, HiMemVT; 6463 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6464 6465 SDValue DataLo, DataHi; 6466 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 6467 6468 MachineMemOperand *MMO = DAG.getMachineFunction(). 6469 getMachineMemOperand(MST->getPointerInfo(), 6470 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 6471 Alignment, MST->getAAInfo(), MST->getRanges()); 6472 6473 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 6474 MST->isTruncatingStore(), 6475 MST->isCompressingStore()); 6476 6477 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6478 MST->isCompressingStore()); 6479 6480 MMO = DAG.getMachineFunction(). 6481 getMachineMemOperand(MST->getPointerInfo(), 6482 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 6483 SecondHalfAlignment, MST->getAAInfo(), 6484 MST->getRanges()); 6485 6486 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 6487 MST->isTruncatingStore(), 6488 MST->isCompressingStore()); 6489 6490 AddToWorklist(Lo.getNode()); 6491 AddToWorklist(Hi.getNode()); 6492 6493 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 6494 } 6495 return SDValue(); 6496 } 6497 6498 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 6499 6500 if (Level >= AfterLegalizeTypes) 6501 return SDValue(); 6502 6503 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 6504 SDValue Mask = MGT->getMask(); 6505 SDLoc DL(N); 6506 6507 // If the MGATHER result requires splitting and the mask is provided by a 6508 // SETCC, then split both nodes and its operands before legalization. This 6509 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6510 // and enables future optimizations (e.g. min/max pattern matching on X86). 6511 6512 if (Mask.getOpcode() != ISD::SETCC) 6513 return SDValue(); 6514 6515 EVT VT = N->getValueType(0); 6516 6517 // Check if any splitting is required. 6518 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6519 TargetLowering::TypeSplitVector) 6520 return SDValue(); 6521 6522 SDValue MaskLo, MaskHi, Lo, Hi; 6523 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6524 6525 SDValue Src0 = MGT->getValue(); 6526 SDValue Src0Lo, Src0Hi; 6527 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6528 6529 EVT LoVT, HiVT; 6530 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 6531 6532 SDValue Chain = MGT->getChain(); 6533 EVT MemoryVT = MGT->getMemoryVT(); 6534 unsigned Alignment = MGT->getOriginalAlignment(); 6535 6536 EVT LoMemVT, HiMemVT; 6537 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6538 6539 SDValue BasePtr = MGT->getBasePtr(); 6540 SDValue Index = MGT->getIndex(); 6541 SDValue IndexLo, IndexHi; 6542 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 6543 6544 MachineMemOperand *MMO = DAG.getMachineFunction(). 6545 getMachineMemOperand(MGT->getPointerInfo(), 6546 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6547 Alignment, MGT->getAAInfo(), MGT->getRanges()); 6548 6549 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 6550 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 6551 MMO); 6552 6553 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 6554 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 6555 MMO); 6556 6557 AddToWorklist(Lo.getNode()); 6558 AddToWorklist(Hi.getNode()); 6559 6560 // Build a factor node to remember that this load is independent of the 6561 // other one. 6562 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6563 Hi.getValue(1)); 6564 6565 // Legalized the chain result - switch anything that used the old chain to 6566 // use the new one. 6567 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 6568 6569 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6570 6571 SDValue RetOps[] = { GatherRes, Chain }; 6572 return DAG.getMergeValues(RetOps, DL); 6573 } 6574 6575 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 6576 6577 if (Level >= AfterLegalizeTypes) 6578 return SDValue(); 6579 6580 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 6581 SDValue Mask = MLD->getMask(); 6582 SDLoc DL(N); 6583 6584 // If the MLOAD result requires splitting and the mask is provided by a 6585 // SETCC, then split both nodes and its operands before legalization. This 6586 // prevents the type legalizer from unrolling SETCC into scalar comparisons 6587 // and enables future optimizations (e.g. min/max pattern matching on X86). 6588 6589 if (Mask.getOpcode() == ISD::SETCC) { 6590 EVT VT = N->getValueType(0); 6591 6592 // Check if any splitting is required. 6593 if (TLI.getTypeAction(*DAG.getContext(), VT) != 6594 TargetLowering::TypeSplitVector) 6595 return SDValue(); 6596 6597 SDValue MaskLo, MaskHi, Lo, Hi; 6598 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 6599 6600 SDValue Src0 = MLD->getSrc0(); 6601 SDValue Src0Lo, Src0Hi; 6602 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 6603 6604 EVT LoVT, HiVT; 6605 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 6606 6607 SDValue Chain = MLD->getChain(); 6608 SDValue Ptr = MLD->getBasePtr(); 6609 EVT MemoryVT = MLD->getMemoryVT(); 6610 unsigned Alignment = MLD->getOriginalAlignment(); 6611 6612 // if Alignment is equal to the vector size, 6613 // take the half of it for the second part 6614 unsigned SecondHalfAlignment = 6615 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 6616 Alignment/2 : Alignment; 6617 6618 EVT LoMemVT, HiMemVT; 6619 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 6620 6621 MachineMemOperand *MMO = DAG.getMachineFunction(). 6622 getMachineMemOperand(MLD->getPointerInfo(), 6623 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 6624 Alignment, MLD->getAAInfo(), MLD->getRanges()); 6625 6626 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 6627 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6628 6629 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 6630 MLD->isExpandingLoad()); 6631 6632 MMO = DAG.getMachineFunction(). 6633 getMachineMemOperand(MLD->getPointerInfo(), 6634 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 6635 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 6636 6637 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 6638 ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 6639 6640 AddToWorklist(Lo.getNode()); 6641 AddToWorklist(Hi.getNode()); 6642 6643 // Build a factor node to remember that this load is independent of the 6644 // other one. 6645 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 6646 Hi.getValue(1)); 6647 6648 // Legalized the chain result - switch anything that used the old chain to 6649 // use the new one. 6650 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 6651 6652 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 6653 6654 SDValue RetOps[] = { LoadRes, Chain }; 6655 return DAG.getMergeValues(RetOps, DL); 6656 } 6657 return SDValue(); 6658 } 6659 6660 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 6661 SDValue N0 = N->getOperand(0); 6662 SDValue N1 = N->getOperand(1); 6663 SDValue N2 = N->getOperand(2); 6664 SDLoc DL(N); 6665 6666 // fold (vselect C, X, X) -> X 6667 if (N1 == N2) 6668 return N1; 6669 6670 // Canonicalize integer abs. 6671 // vselect (setg[te] X, 0), X, -X -> 6672 // vselect (setgt X, -1), X, -X -> 6673 // vselect (setl[te] X, 0), -X, X -> 6674 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 6675 if (N0.getOpcode() == ISD::SETCC) { 6676 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6677 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6678 bool isAbs = false; 6679 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 6680 6681 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 6682 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 6683 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 6684 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 6685 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 6686 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 6687 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 6688 6689 if (isAbs) { 6690 EVT VT = LHS.getValueType(); 6691 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 6692 return DAG.getNode(ISD::ABS, DL, VT, LHS); 6693 6694 SDValue Shift = DAG.getNode( 6695 ISD::SRA, DL, VT, LHS, 6696 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 6697 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 6698 AddToWorklist(Shift.getNode()); 6699 AddToWorklist(Add.getNode()); 6700 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 6701 } 6702 } 6703 6704 if (SimplifySelectOps(N, N1, N2)) 6705 return SDValue(N, 0); // Don't revisit N. 6706 6707 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 6708 if (ISD::isBuildVectorAllOnes(N0.getNode())) 6709 return N1; 6710 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 6711 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6712 return N2; 6713 6714 // The ConvertSelectToConcatVector function is assuming both the above 6715 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 6716 // and addressed. 6717 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 6718 N2.getOpcode() == ISD::CONCAT_VECTORS && 6719 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6720 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 6721 return CV; 6722 } 6723 6724 return SDValue(); 6725 } 6726 6727 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 6728 SDValue N0 = N->getOperand(0); 6729 SDValue N1 = N->getOperand(1); 6730 SDValue N2 = N->getOperand(2); 6731 SDValue N3 = N->getOperand(3); 6732 SDValue N4 = N->getOperand(4); 6733 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 6734 6735 // fold select_cc lhs, rhs, x, x, cc -> x 6736 if (N2 == N3) 6737 return N2; 6738 6739 // Determine if the condition we're dealing with is constant 6740 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 6741 CC, SDLoc(N), false)) { 6742 AddToWorklist(SCC.getNode()); 6743 6744 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 6745 if (!SCCC->isNullValue()) 6746 return N2; // cond always true -> true val 6747 else 6748 return N3; // cond always false -> false val 6749 } else if (SCC->isUndef()) { 6750 // When the condition is UNDEF, just return the first operand. This is 6751 // coherent the DAG creation, no setcc node is created in this case 6752 return N2; 6753 } else if (SCC.getOpcode() == ISD::SETCC) { 6754 // Fold to a simpler select_cc 6755 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 6756 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 6757 SCC.getOperand(2)); 6758 } 6759 } 6760 6761 // If we can fold this based on the true/false value, do so. 6762 if (SimplifySelectOps(N, N2, N3)) 6763 return SDValue(N, 0); // Don't revisit N. 6764 6765 // fold select_cc into other things, such as min/max/abs 6766 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 6767 } 6768 6769 SDValue DAGCombiner::visitSETCC(SDNode *N) { 6770 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 6771 cast<CondCodeSDNode>(N->getOperand(2))->get(), 6772 SDLoc(N)); 6773 } 6774 6775 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 6776 SDValue LHS = N->getOperand(0); 6777 SDValue RHS = N->getOperand(1); 6778 SDValue Carry = N->getOperand(2); 6779 SDValue Cond = N->getOperand(3); 6780 6781 // If Carry is false, fold to a regular SETCC. 6782 if (Carry.getOpcode() == ISD::CARRY_FALSE) 6783 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 6784 6785 return SDValue(); 6786 } 6787 6788 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 6789 /// a build_vector of constants. 6790 /// This function is called by the DAGCombiner when visiting sext/zext/aext 6791 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 6792 /// Vector extends are not folded if operations are legal; this is to 6793 /// avoid introducing illegal build_vector dag nodes. 6794 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 6795 SelectionDAG &DAG, bool LegalTypes, 6796 bool LegalOperations) { 6797 unsigned Opcode = N->getOpcode(); 6798 SDValue N0 = N->getOperand(0); 6799 EVT VT = N->getValueType(0); 6800 6801 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 6802 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 6803 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 6804 && "Expected EXTEND dag node in input!"); 6805 6806 // fold (sext c1) -> c1 6807 // fold (zext c1) -> c1 6808 // fold (aext c1) -> c1 6809 if (isa<ConstantSDNode>(N0)) 6810 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 6811 6812 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 6813 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 6814 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 6815 EVT SVT = VT.getScalarType(); 6816 if (!(VT.isVector() && 6817 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 6818 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 6819 return nullptr; 6820 6821 // We can fold this node into a build_vector. 6822 unsigned VTBits = SVT.getSizeInBits(); 6823 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 6824 SmallVector<SDValue, 8> Elts; 6825 unsigned NumElts = VT.getVectorNumElements(); 6826 SDLoc DL(N); 6827 6828 for (unsigned i=0; i != NumElts; ++i) { 6829 SDValue Op = N0->getOperand(i); 6830 if (Op->isUndef()) { 6831 Elts.push_back(DAG.getUNDEF(SVT)); 6832 continue; 6833 } 6834 6835 SDLoc DL(Op); 6836 // Get the constant value and if needed trunc it to the size of the type. 6837 // Nodes like build_vector might have constants wider than the scalar type. 6838 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 6839 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 6840 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 6841 else 6842 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 6843 } 6844 6845 return DAG.getBuildVector(VT, DL, Elts).getNode(); 6846 } 6847 6848 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 6849 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 6850 // transformation. Returns true if extension are possible and the above 6851 // mentioned transformation is profitable. 6852 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 6853 unsigned ExtOpc, 6854 SmallVectorImpl<SDNode *> &ExtendNodes, 6855 const TargetLowering &TLI) { 6856 bool HasCopyToRegUses = false; 6857 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 6858 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 6859 UE = N0.getNode()->use_end(); 6860 UI != UE; ++UI) { 6861 SDNode *User = *UI; 6862 if (User == N) 6863 continue; 6864 if (UI.getUse().getResNo() != N0.getResNo()) 6865 continue; 6866 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 6867 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 6868 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 6869 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 6870 // Sign bits will be lost after a zext. 6871 return false; 6872 bool Add = false; 6873 for (unsigned i = 0; i != 2; ++i) { 6874 SDValue UseOp = User->getOperand(i); 6875 if (UseOp == N0) 6876 continue; 6877 if (!isa<ConstantSDNode>(UseOp)) 6878 return false; 6879 Add = true; 6880 } 6881 if (Add) 6882 ExtendNodes.push_back(User); 6883 continue; 6884 } 6885 // If truncates aren't free and there are users we can't 6886 // extend, it isn't worthwhile. 6887 if (!isTruncFree) 6888 return false; 6889 // Remember if this value is live-out. 6890 if (User->getOpcode() == ISD::CopyToReg) 6891 HasCopyToRegUses = true; 6892 } 6893 6894 if (HasCopyToRegUses) { 6895 bool BothLiveOut = false; 6896 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6897 UI != UE; ++UI) { 6898 SDUse &Use = UI.getUse(); 6899 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 6900 BothLiveOut = true; 6901 break; 6902 } 6903 } 6904 if (BothLiveOut) 6905 // Both unextended and extended values are live out. There had better be 6906 // a good reason for the transformation. 6907 return ExtendNodes.size(); 6908 } 6909 return true; 6910 } 6911 6912 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 6913 SDValue Trunc, SDValue ExtLoad, 6914 const SDLoc &DL, ISD::NodeType ExtType) { 6915 // Extend SetCC uses if necessary. 6916 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 6917 SDNode *SetCC = SetCCs[i]; 6918 SmallVector<SDValue, 4> Ops; 6919 6920 for (unsigned j = 0; j != 2; ++j) { 6921 SDValue SOp = SetCC->getOperand(j); 6922 if (SOp == Trunc) 6923 Ops.push_back(ExtLoad); 6924 else 6925 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 6926 } 6927 6928 Ops.push_back(SetCC->getOperand(2)); 6929 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 6930 } 6931 } 6932 6933 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 6934 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 6935 SDValue N0 = N->getOperand(0); 6936 EVT DstVT = N->getValueType(0); 6937 EVT SrcVT = N0.getValueType(); 6938 6939 assert((N->getOpcode() == ISD::SIGN_EXTEND || 6940 N->getOpcode() == ISD::ZERO_EXTEND) && 6941 "Unexpected node type (not an extend)!"); 6942 6943 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 6944 // For example, on a target with legal v4i32, but illegal v8i32, turn: 6945 // (v8i32 (sext (v8i16 (load x)))) 6946 // into: 6947 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6948 // (v4i32 (sextload (x + 16))))) 6949 // Where uses of the original load, i.e.: 6950 // (v8i16 (load x)) 6951 // are replaced with: 6952 // (v8i16 (truncate 6953 // (v8i32 (concat_vectors (v4i32 (sextload x)), 6954 // (v4i32 (sextload (x + 16))))))) 6955 // 6956 // This combine is only applicable to illegal, but splittable, vectors. 6957 // All legal types, and illegal non-vector types, are handled elsewhere. 6958 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 6959 // 6960 if (N0->getOpcode() != ISD::LOAD) 6961 return SDValue(); 6962 6963 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6964 6965 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 6966 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 6967 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 6968 return SDValue(); 6969 6970 SmallVector<SDNode *, 4> SetCCs; 6971 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 6972 return SDValue(); 6973 6974 ISD::LoadExtType ExtType = 6975 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 6976 6977 // Try to split the vector types to get down to legal types. 6978 EVT SplitSrcVT = SrcVT; 6979 EVT SplitDstVT = DstVT; 6980 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 6981 SplitSrcVT.getVectorNumElements() > 1) { 6982 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 6983 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 6984 } 6985 6986 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 6987 return SDValue(); 6988 6989 SDLoc DL(N); 6990 const unsigned NumSplits = 6991 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 6992 const unsigned Stride = SplitSrcVT.getStoreSize(); 6993 SmallVector<SDValue, 4> Loads; 6994 SmallVector<SDValue, 4> Chains; 6995 6996 SDValue BasePtr = LN0->getBasePtr(); 6997 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 6998 const unsigned Offset = Idx * Stride; 6999 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 7000 7001 SDValue SplitLoad = DAG.getExtLoad( 7002 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 7003 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 7004 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7005 7006 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 7007 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 7008 7009 Loads.push_back(SplitLoad.getValue(0)); 7010 Chains.push_back(SplitLoad.getValue(1)); 7011 } 7012 7013 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 7014 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 7015 7016 // Simplify TF. 7017 AddToWorklist(NewChain.getNode()); 7018 7019 CombineTo(N, NewValue); 7020 7021 // Replace uses of the original load (before extension) 7022 // with a truncate of the concatenated sextloaded vectors. 7023 SDValue Trunc = 7024 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 7025 CombineTo(N0.getNode(), Trunc, NewChain); 7026 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 7027 (ISD::NodeType)N->getOpcode()); 7028 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7029 } 7030 7031 /// If we're narrowing or widening the result of a vector select and the final 7032 /// size is the same size as a setcc (compare) feeding the select, then try to 7033 /// apply the cast operation to the select's operands because matching vector 7034 /// sizes for a select condition and other operands should be more efficient. 7035 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 7036 unsigned CastOpcode = Cast->getOpcode(); 7037 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 7038 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 7039 CastOpcode == ISD::FP_ROUND) && 7040 "Unexpected opcode for vector select narrowing/widening"); 7041 7042 // We only do this transform before legal ops because the pattern may be 7043 // obfuscated by target-specific operations after legalization. Do not create 7044 // an illegal select op, however, because that may be difficult to lower. 7045 EVT VT = Cast->getValueType(0); 7046 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 7047 return SDValue(); 7048 7049 SDValue VSel = Cast->getOperand(0); 7050 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 7051 VSel.getOperand(0).getOpcode() != ISD::SETCC) 7052 return SDValue(); 7053 7054 // Does the setcc have the same vector size as the casted select? 7055 SDValue SetCC = VSel.getOperand(0); 7056 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 7057 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 7058 return SDValue(); 7059 7060 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 7061 SDValue A = VSel.getOperand(1); 7062 SDValue B = VSel.getOperand(2); 7063 SDValue CastA, CastB; 7064 SDLoc DL(Cast); 7065 if (CastOpcode == ISD::FP_ROUND) { 7066 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 7067 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 7068 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 7069 } else { 7070 CastA = DAG.getNode(CastOpcode, DL, VT, A); 7071 CastB = DAG.getNode(CastOpcode, DL, VT, B); 7072 } 7073 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 7074 } 7075 7076 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 7077 SDValue N0 = N->getOperand(0); 7078 EVT VT = N->getValueType(0); 7079 SDLoc DL(N); 7080 7081 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7082 LegalOperations)) 7083 return SDValue(Res, 0); 7084 7085 // fold (sext (sext x)) -> (sext x) 7086 // fold (sext (aext x)) -> (sext x) 7087 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7088 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 7089 7090 if (N0.getOpcode() == ISD::TRUNCATE) { 7091 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 7092 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 7093 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7094 SDNode *oye = N0.getOperand(0).getNode(); 7095 if (NarrowLoad.getNode() != N0.getNode()) { 7096 CombineTo(N0.getNode(), NarrowLoad); 7097 // CombineTo deleted the truncate, if needed, but not what's under it. 7098 AddToWorklist(oye); 7099 } 7100 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7101 } 7102 7103 // See if the value being truncated is already sign extended. If so, just 7104 // eliminate the trunc/sext pair. 7105 SDValue Op = N0.getOperand(0); 7106 unsigned OpBits = Op.getScalarValueSizeInBits(); 7107 unsigned MidBits = N0.getScalarValueSizeInBits(); 7108 unsigned DestBits = VT.getScalarSizeInBits(); 7109 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 7110 7111 if (OpBits == DestBits) { 7112 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 7113 // bits, it is already ready. 7114 if (NumSignBits > DestBits-MidBits) 7115 return Op; 7116 } else if (OpBits < DestBits) { 7117 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 7118 // bits, just sext from i32. 7119 if (NumSignBits > OpBits-MidBits) 7120 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 7121 } else { 7122 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 7123 // bits, just truncate to i32. 7124 if (NumSignBits > OpBits-MidBits) 7125 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 7126 } 7127 7128 // fold (sext (truncate x)) -> (sextinreg x). 7129 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 7130 N0.getValueType())) { 7131 if (OpBits < DestBits) 7132 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 7133 else if (OpBits > DestBits) 7134 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 7135 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 7136 DAG.getValueType(N0.getValueType())); 7137 } 7138 } 7139 7140 // fold (sext (load x)) -> (sext (truncate (sextload x))) 7141 // Only generate vector extloads when 1) they're legal, and 2) they are 7142 // deemed desirable by the target. 7143 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7144 ((!LegalOperations && !VT.isVector() && 7145 !cast<LoadSDNode>(N0)->isVolatile()) || 7146 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 7147 bool DoXform = true; 7148 SmallVector<SDNode*, 4> SetCCs; 7149 if (!N0.hasOneUse()) 7150 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 7151 if (VT.isVector()) 7152 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7153 if (DoXform) { 7154 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7155 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7156 LN0->getBasePtr(), N0.getValueType(), 7157 LN0->getMemOperand()); 7158 CombineTo(N, ExtLoad); 7159 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7160 N0.getValueType(), ExtLoad); 7161 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7162 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7163 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7164 } 7165 } 7166 7167 // fold (sext (load x)) to multiple smaller sextloads. 7168 // Only on illegal but splittable vectors. 7169 if (SDValue ExtLoad = CombineExtLoad(N)) 7170 return ExtLoad; 7171 7172 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 7173 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 7174 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7175 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7176 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7177 EVT MemVT = LN0->getMemoryVT(); 7178 if ((!LegalOperations && !LN0->isVolatile()) || 7179 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 7180 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(), 7181 LN0->getBasePtr(), MemVT, 7182 LN0->getMemOperand()); 7183 CombineTo(N, ExtLoad); 7184 CombineTo(N0.getNode(), 7185 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7186 N0.getValueType(), ExtLoad), 7187 ExtLoad.getValue(1)); 7188 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7189 } 7190 } 7191 7192 // fold (sext (and/or/xor (load x), cst)) -> 7193 // (and/or/xor (sextload x), (sext cst)) 7194 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7195 N0.getOpcode() == ISD::XOR) && 7196 isa<LoadSDNode>(N0.getOperand(0)) && 7197 N0.getOperand(1).getOpcode() == ISD::Constant && 7198 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 7199 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7200 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7201 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 7202 bool DoXform = true; 7203 SmallVector<SDNode*, 4> SetCCs; 7204 if (!N0.hasOneUse()) 7205 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 7206 SetCCs, TLI); 7207 if (DoXform) { 7208 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 7209 LN0->getChain(), LN0->getBasePtr(), 7210 LN0->getMemoryVT(), 7211 LN0->getMemOperand()); 7212 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7213 Mask = Mask.sext(VT.getSizeInBits()); 7214 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7215 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7216 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7217 SDLoc(N0.getOperand(0)), 7218 N0.getOperand(0).getValueType(), ExtLoad); 7219 CombineTo(N, And); 7220 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 7221 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND); 7222 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7223 } 7224 } 7225 } 7226 7227 if (N0.getOpcode() == ISD::SETCC) { 7228 SDValue N00 = N0.getOperand(0); 7229 SDValue N01 = N0.getOperand(1); 7230 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7231 EVT N00VT = N0.getOperand(0).getValueType(); 7232 7233 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 7234 // Only do this before legalize for now. 7235 if (VT.isVector() && !LegalOperations && 7236 TLI.getBooleanContents(N00VT) == 7237 TargetLowering::ZeroOrNegativeOneBooleanContent) { 7238 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 7239 // of the same size as the compared operands. Only optimize sext(setcc()) 7240 // if this is the case. 7241 EVT SVT = getSetCCResultType(N00VT); 7242 7243 // We know that the # elements of the results is the same as the 7244 // # elements of the compare (and the # elements of the compare result 7245 // for that matter). Check to see that they are the same size. If so, 7246 // we know that the element size of the sext'd result matches the 7247 // element size of the compare operands. 7248 if (VT.getSizeInBits() == SVT.getSizeInBits()) 7249 return DAG.getSetCC(DL, VT, N00, N01, CC); 7250 7251 // If the desired elements are smaller or larger than the source 7252 // elements, we can use a matching integer vector type and then 7253 // truncate/sign extend. 7254 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 7255 if (SVT == MatchingVecType) { 7256 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 7257 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 7258 } 7259 } 7260 7261 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 7262 // Here, T can be 1 or -1, depending on the type of the setcc and 7263 // getBooleanContents(). 7264 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 7265 7266 // To determine the "true" side of the select, we need to know the high bit 7267 // of the value returned by the setcc if it evaluates to true. 7268 // If the type of the setcc is i1, then the true case of the select is just 7269 // sext(i1 1), that is, -1. 7270 // If the type of the setcc is larger (say, i8) then the value of the high 7271 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 7272 // of the appropriate width. 7273 SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT) 7274 : TLI.getConstTrueVal(DAG, VT, DL); 7275 SDValue Zero = DAG.getConstant(0, DL, VT); 7276 if (SDValue SCC = 7277 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 7278 return SCC; 7279 7280 if (!VT.isVector()) { 7281 EVT SetCCVT = getSetCCResultType(N00VT); 7282 // Don't do this transform for i1 because there's a select transform 7283 // that would reverse it. 7284 // TODO: We should not do this transform at all without a target hook 7285 // because a sext is likely cheaper than a select? 7286 if (SetCCVT.getScalarSizeInBits() != 1 && 7287 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 7288 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 7289 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 7290 } 7291 } 7292 } 7293 7294 // fold (sext x) -> (zext x) if the sign bit is known zero. 7295 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 7296 DAG.SignBitIsZero(N0)) 7297 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 7298 7299 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7300 return NewVSel; 7301 7302 return SDValue(); 7303 } 7304 7305 // isTruncateOf - If N is a truncate of some other value, return true, record 7306 // the value being truncated in Op and which of Op's bits are zero/one in Known. 7307 // This function computes KnownBits to avoid a duplicated call to 7308 // computeKnownBits in the caller. 7309 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 7310 KnownBits &Known) { 7311 if (N->getOpcode() == ISD::TRUNCATE) { 7312 Op = N->getOperand(0); 7313 DAG.computeKnownBits(Op, Known); 7314 return true; 7315 } 7316 7317 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 7318 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 7319 return false; 7320 7321 SDValue Op0 = N->getOperand(0); 7322 SDValue Op1 = N->getOperand(1); 7323 assert(Op0.getValueType() == Op1.getValueType()); 7324 7325 if (isNullConstant(Op0)) 7326 Op = Op1; 7327 else if (isNullConstant(Op1)) 7328 Op = Op0; 7329 else 7330 return false; 7331 7332 DAG.computeKnownBits(Op, Known); 7333 7334 if (!(Known.Zero | 1).isAllOnesValue()) 7335 return false; 7336 7337 return true; 7338 } 7339 7340 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 7341 SDValue N0 = N->getOperand(0); 7342 EVT VT = N->getValueType(0); 7343 7344 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7345 LegalOperations)) 7346 return SDValue(Res, 0); 7347 7348 // fold (zext (zext x)) -> (zext x) 7349 // fold (zext (aext x)) -> (zext x) 7350 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 7351 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 7352 N0.getOperand(0)); 7353 7354 // fold (zext (truncate x)) -> (zext x) or 7355 // (zext (truncate x)) -> (truncate x) 7356 // This is valid when the truncated bits of x are already zero. 7357 // FIXME: We should extend this to work for vectors too. 7358 SDValue Op; 7359 KnownBits Known; 7360 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, Known)) { 7361 APInt TruncatedBits = 7362 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 7363 APInt(Op.getValueSizeInBits(), 0) : 7364 APInt::getBitsSet(Op.getValueSizeInBits(), 7365 N0.getValueSizeInBits(), 7366 std::min(Op.getValueSizeInBits(), 7367 VT.getSizeInBits())); 7368 if (TruncatedBits.isSubsetOf(Known.Zero)) { 7369 if (VT.bitsGT(Op.getValueType())) 7370 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 7371 if (VT.bitsLT(Op.getValueType())) 7372 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 7373 7374 return Op; 7375 } 7376 } 7377 7378 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7379 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 7380 if (N0.getOpcode() == ISD::TRUNCATE) { 7381 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7382 SDNode *oye = N0.getOperand(0).getNode(); 7383 if (NarrowLoad.getNode() != N0.getNode()) { 7384 CombineTo(N0.getNode(), NarrowLoad); 7385 // CombineTo deleted the truncate, if needed, but not what's under it. 7386 AddToWorklist(oye); 7387 } 7388 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7389 } 7390 } 7391 7392 // fold (zext (truncate x)) -> (and x, mask) 7393 if (N0.getOpcode() == ISD::TRUNCATE) { 7394 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 7395 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 7396 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7397 SDNode *oye = N0.getOperand(0).getNode(); 7398 if (NarrowLoad.getNode() != N0.getNode()) { 7399 CombineTo(N0.getNode(), NarrowLoad); 7400 // CombineTo deleted the truncate, if needed, but not what's under it. 7401 AddToWorklist(oye); 7402 } 7403 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7404 } 7405 7406 EVT SrcVT = N0.getOperand(0).getValueType(); 7407 EVT MinVT = N0.getValueType(); 7408 7409 // Try to mask before the extension to avoid having to generate a larger mask, 7410 // possibly over several sub-vectors. 7411 if (SrcVT.bitsLT(VT)) { 7412 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 7413 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 7414 SDValue Op = N0.getOperand(0); 7415 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7416 AddToWorklist(Op.getNode()); 7417 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 7418 } 7419 } 7420 7421 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 7422 SDValue Op = N0.getOperand(0); 7423 if (SrcVT.bitsLT(VT)) { 7424 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 7425 AddToWorklist(Op.getNode()); 7426 } else if (SrcVT.bitsGT(VT)) { 7427 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 7428 AddToWorklist(Op.getNode()); 7429 } 7430 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 7431 } 7432 } 7433 7434 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 7435 // if either of the casts is not free. 7436 if (N0.getOpcode() == ISD::AND && 7437 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7438 N0.getOperand(1).getOpcode() == ISD::Constant && 7439 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7440 N0.getValueType()) || 7441 !TLI.isZExtFree(N0.getValueType(), VT))) { 7442 SDValue X = N0.getOperand(0).getOperand(0); 7443 if (X.getValueType().bitsLT(VT)) { 7444 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 7445 } else if (X.getValueType().bitsGT(VT)) { 7446 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7447 } 7448 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7449 Mask = Mask.zext(VT.getSizeInBits()); 7450 SDLoc DL(N); 7451 return DAG.getNode(ISD::AND, DL, VT, 7452 X, DAG.getConstant(Mask, DL, VT)); 7453 } 7454 7455 // fold (zext (load x)) -> (zext (truncate (zextload x))) 7456 // Only generate vector extloads when 1) they're legal, and 2) they are 7457 // deemed desirable by the target. 7458 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7459 ((!LegalOperations && !VT.isVector() && 7460 !cast<LoadSDNode>(N0)->isVolatile()) || 7461 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 7462 bool DoXform = true; 7463 SmallVector<SDNode*, 4> SetCCs; 7464 if (!N0.hasOneUse()) 7465 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 7466 if (VT.isVector()) 7467 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 7468 if (DoXform) { 7469 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7470 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7471 LN0->getChain(), 7472 LN0->getBasePtr(), N0.getValueType(), 7473 LN0->getMemOperand()); 7474 7475 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7476 N0.getValueType(), ExtLoad); 7477 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7478 7479 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7480 ISD::ZERO_EXTEND); 7481 CombineTo(N, ExtLoad); 7482 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7483 } 7484 } 7485 7486 // fold (zext (load x)) to multiple smaller zextloads. 7487 // Only on illegal but splittable vectors. 7488 if (SDValue ExtLoad = CombineExtLoad(N)) 7489 return ExtLoad; 7490 7491 // fold (zext (and/or/xor (load x), cst)) -> 7492 // (and/or/xor (zextload x), (zext cst)) 7493 // Unless (and (load x) cst) will match as a zextload already and has 7494 // additional users. 7495 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 7496 N0.getOpcode() == ISD::XOR) && 7497 isa<LoadSDNode>(N0.getOperand(0)) && 7498 N0.getOperand(1).getOpcode() == ISD::Constant && 7499 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 7500 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 7501 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 7502 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 7503 bool DoXform = true; 7504 SmallVector<SDNode*, 4> SetCCs; 7505 if (!N0.hasOneUse()) { 7506 if (N0.getOpcode() == ISD::AND) { 7507 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 7508 auto NarrowLoad = false; 7509 EVT LoadResultTy = AndC->getValueType(0); 7510 EVT ExtVT, LoadedVT; 7511 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 7512 NarrowLoad)) 7513 DoXform = false; 7514 } 7515 if (DoXform) 7516 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 7517 ISD::ZERO_EXTEND, SetCCs, TLI); 7518 } 7519 if (DoXform) { 7520 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 7521 LN0->getChain(), LN0->getBasePtr(), 7522 LN0->getMemoryVT(), 7523 LN0->getMemOperand()); 7524 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7525 Mask = Mask.zext(VT.getSizeInBits()); 7526 SDLoc DL(N); 7527 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 7528 ExtLoad, DAG.getConstant(Mask, DL, VT)); 7529 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 7530 SDLoc(N0.getOperand(0)), 7531 N0.getOperand(0).getValueType(), ExtLoad); 7532 CombineTo(N, And); 7533 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 7534 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 7535 ISD::ZERO_EXTEND); 7536 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7537 } 7538 } 7539 } 7540 7541 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 7542 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 7543 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 7544 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 7545 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7546 EVT MemVT = LN0->getMemoryVT(); 7547 if ((!LegalOperations && !LN0->isVolatile()) || 7548 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 7549 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 7550 LN0->getChain(), 7551 LN0->getBasePtr(), MemVT, 7552 LN0->getMemOperand()); 7553 CombineTo(N, ExtLoad); 7554 CombineTo(N0.getNode(), 7555 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 7556 ExtLoad), 7557 ExtLoad.getValue(1)); 7558 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7559 } 7560 } 7561 7562 if (N0.getOpcode() == ISD::SETCC) { 7563 // Only do this before legalize for now. 7564 if (!LegalOperations && VT.isVector() && 7565 N0.getValueType().getVectorElementType() == MVT::i1) { 7566 EVT N00VT = N0.getOperand(0).getValueType(); 7567 if (getSetCCResultType(N00VT) == N0.getValueType()) 7568 return SDValue(); 7569 7570 // We know that the # elements of the results is the same as the # 7571 // elements of the compare (and the # elements of the compare result for 7572 // that matter). Check to see that they are the same size. If so, we know 7573 // that the element size of the sext'd result matches the element size of 7574 // the compare operands. 7575 SDLoc DL(N); 7576 SDValue VecOnes = DAG.getConstant(1, DL, VT); 7577 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 7578 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 7579 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 7580 N0.getOperand(1), N0.getOperand(2)); 7581 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 7582 } 7583 7584 // If the desired elements are smaller or larger than the source 7585 // elements we can use a matching integer vector type and then 7586 // truncate/sign extend. 7587 EVT MatchingElementType = EVT::getIntegerVT( 7588 *DAG.getContext(), N00VT.getScalarSizeInBits()); 7589 EVT MatchingVectorType = EVT::getVectorVT( 7590 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 7591 SDValue VsetCC = 7592 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 7593 N0.getOperand(1), N0.getOperand(2)); 7594 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 7595 VecOnes); 7596 } 7597 7598 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7599 SDLoc DL(N); 7600 if (SDValue SCC = SimplifySelectCC( 7601 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7602 DAG.getConstant(0, DL, VT), 7603 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7604 return SCC; 7605 } 7606 7607 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 7608 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 7609 isa<ConstantSDNode>(N0.getOperand(1)) && 7610 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 7611 N0.hasOneUse()) { 7612 SDValue ShAmt = N0.getOperand(1); 7613 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 7614 if (N0.getOpcode() == ISD::SHL) { 7615 SDValue InnerZExt = N0.getOperand(0); 7616 // If the original shl may be shifting out bits, do not perform this 7617 // transformation. 7618 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 7619 InnerZExt.getOperand(0).getValueSizeInBits(); 7620 if (ShAmtVal > KnownZeroBits) 7621 return SDValue(); 7622 } 7623 7624 SDLoc DL(N); 7625 7626 // Ensure that the shift amount is wide enough for the shifted value. 7627 if (VT.getSizeInBits() >= 256) 7628 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 7629 7630 return DAG.getNode(N0.getOpcode(), DL, VT, 7631 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 7632 ShAmt); 7633 } 7634 7635 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 7636 return NewVSel; 7637 7638 return SDValue(); 7639 } 7640 7641 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 7642 SDValue N0 = N->getOperand(0); 7643 EVT VT = N->getValueType(0); 7644 7645 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7646 LegalOperations)) 7647 return SDValue(Res, 0); 7648 7649 // fold (aext (aext x)) -> (aext x) 7650 // fold (aext (zext x)) -> (zext x) 7651 // fold (aext (sext x)) -> (sext x) 7652 if (N0.getOpcode() == ISD::ANY_EXTEND || 7653 N0.getOpcode() == ISD::ZERO_EXTEND || 7654 N0.getOpcode() == ISD::SIGN_EXTEND) 7655 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7656 7657 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 7658 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 7659 if (N0.getOpcode() == ISD::TRUNCATE) { 7660 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 7661 SDNode *oye = N0.getOperand(0).getNode(); 7662 if (NarrowLoad.getNode() != N0.getNode()) { 7663 CombineTo(N0.getNode(), NarrowLoad); 7664 // CombineTo deleted the truncate, if needed, but not what's under it. 7665 AddToWorklist(oye); 7666 } 7667 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7668 } 7669 } 7670 7671 // fold (aext (truncate x)) 7672 if (N0.getOpcode() == ISD::TRUNCATE) { 7673 SDValue TruncOp = N0.getOperand(0); 7674 if (TruncOp.getValueType() == VT) 7675 return TruncOp; // x iff x size == zext size. 7676 if (TruncOp.getValueType().bitsGT(VT)) 7677 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 7678 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 7679 } 7680 7681 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 7682 // if the trunc is not free. 7683 if (N0.getOpcode() == ISD::AND && 7684 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 7685 N0.getOperand(1).getOpcode() == ISD::Constant && 7686 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 7687 N0.getValueType())) { 7688 SDLoc DL(N); 7689 SDValue X = N0.getOperand(0).getOperand(0); 7690 if (X.getValueType().bitsLT(VT)) { 7691 X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X); 7692 } else if (X.getValueType().bitsGT(VT)) { 7693 X = DAG.getNode(ISD::TRUNCATE, DL, VT, X); 7694 } 7695 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 7696 Mask = Mask.zext(VT.getSizeInBits()); 7697 return DAG.getNode(ISD::AND, DL, VT, 7698 X, DAG.getConstant(Mask, DL, VT)); 7699 } 7700 7701 // fold (aext (load x)) -> (aext (truncate (extload x))) 7702 // None of the supported targets knows how to perform load and any_ext 7703 // on vectors in one instruction. We only perform this transformation on 7704 // scalars. 7705 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 7706 ISD::isUNINDEXEDLoad(N0.getNode()) && 7707 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 7708 bool DoXform = true; 7709 SmallVector<SDNode*, 4> SetCCs; 7710 if (!N0.hasOneUse()) 7711 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 7712 if (DoXform) { 7713 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7714 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7715 LN0->getChain(), 7716 LN0->getBasePtr(), N0.getValueType(), 7717 LN0->getMemOperand()); 7718 CombineTo(N, ExtLoad); 7719 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7720 N0.getValueType(), ExtLoad); 7721 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 7722 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 7723 ISD::ANY_EXTEND); 7724 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7725 } 7726 } 7727 7728 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 7729 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 7730 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 7731 if (N0.getOpcode() == ISD::LOAD && 7732 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7733 N0.hasOneUse()) { 7734 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7735 ISD::LoadExtType ExtType = LN0->getExtensionType(); 7736 EVT MemVT = LN0->getMemoryVT(); 7737 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 7738 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 7739 VT, LN0->getChain(), LN0->getBasePtr(), 7740 MemVT, LN0->getMemOperand()); 7741 CombineTo(N, ExtLoad); 7742 CombineTo(N0.getNode(), 7743 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 7744 N0.getValueType(), ExtLoad), 7745 ExtLoad.getValue(1)); 7746 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7747 } 7748 } 7749 7750 if (N0.getOpcode() == ISD::SETCC) { 7751 // For vectors: 7752 // aext(setcc) -> vsetcc 7753 // aext(setcc) -> truncate(vsetcc) 7754 // aext(setcc) -> aext(vsetcc) 7755 // Only do this before legalize for now. 7756 if (VT.isVector() && !LegalOperations) { 7757 EVT N0VT = N0.getOperand(0).getValueType(); 7758 // We know that the # elements of the results is the same as the 7759 // # elements of the compare (and the # elements of the compare result 7760 // for that matter). Check to see that they are the same size. If so, 7761 // we know that the element size of the sext'd result matches the 7762 // element size of the compare operands. 7763 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 7764 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 7765 N0.getOperand(1), 7766 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7767 // If the desired elements are smaller or larger than the source 7768 // elements we can use a matching integer vector type and then 7769 // truncate/any extend 7770 else { 7771 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 7772 SDValue VsetCC = 7773 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 7774 N0.getOperand(1), 7775 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 7776 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 7777 } 7778 } 7779 7780 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 7781 SDLoc DL(N); 7782 if (SDValue SCC = SimplifySelectCC( 7783 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 7784 DAG.getConstant(0, DL, VT), 7785 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 7786 return SCC; 7787 } 7788 7789 return SDValue(); 7790 } 7791 7792 SDValue DAGCombiner::visitAssertZext(SDNode *N) { 7793 SDValue N0 = N->getOperand(0); 7794 SDValue N1 = N->getOperand(1); 7795 EVT EVT = cast<VTSDNode>(N1)->getVT(); 7796 7797 // fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt) 7798 if (N0.getOpcode() == ISD::AssertZext && 7799 EVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 7800 return N0; 7801 7802 return SDValue(); 7803 } 7804 7805 /// See if the specified operand can be simplified with the knowledge that only 7806 /// the bits specified by Mask are used. If so, return the simpler operand, 7807 /// otherwise return a null SDValue. 7808 /// 7809 /// (This exists alongside SimplifyDemandedBits because GetDemandedBits can 7810 /// simplify nodes with multiple uses more aggressively.) 7811 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 7812 switch (V.getOpcode()) { 7813 default: break; 7814 case ISD::Constant: { 7815 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 7816 assert(CV && "Const value should be ConstSDNode."); 7817 const APInt &CVal = CV->getAPIntValue(); 7818 APInt NewVal = CVal & Mask; 7819 if (NewVal != CVal) 7820 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 7821 break; 7822 } 7823 case ISD::OR: 7824 case ISD::XOR: 7825 // If the LHS or RHS don't contribute bits to the or, drop them. 7826 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 7827 return V.getOperand(1); 7828 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 7829 return V.getOperand(0); 7830 break; 7831 case ISD::SRL: 7832 // Only look at single-use SRLs. 7833 if (!V.getNode()->hasOneUse()) 7834 break; 7835 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 7836 // See if we can recursively simplify the LHS. 7837 unsigned Amt = RHSC->getZExtValue(); 7838 7839 // Watch out for shift count overflow though. 7840 if (Amt >= Mask.getBitWidth()) break; 7841 APInt NewMask = Mask << Amt; 7842 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 7843 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 7844 SimplifyLHS, V.getOperand(1)); 7845 } 7846 break; 7847 case ISD::AND: { 7848 // X & -1 -> X (ignoring bits which aren't demanded). 7849 ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1)); 7850 if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask) 7851 return V.getOperand(0); 7852 break; 7853 } 7854 } 7855 return SDValue(); 7856 } 7857 7858 /// If the result of a wider load is shifted to right of N bits and then 7859 /// truncated to a narrower type and where N is a multiple of number of bits of 7860 /// the narrower type, transform it to a narrower load from address + N / num of 7861 /// bits of new type. If the result is to be extended, also fold the extension 7862 /// to form a extending load. 7863 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 7864 unsigned Opc = N->getOpcode(); 7865 7866 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 7867 SDValue N0 = N->getOperand(0); 7868 EVT VT = N->getValueType(0); 7869 EVT ExtVT = VT; 7870 7871 // This transformation isn't valid for vector loads. 7872 if (VT.isVector()) 7873 return SDValue(); 7874 7875 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 7876 // extended to VT. 7877 if (Opc == ISD::SIGN_EXTEND_INREG) { 7878 ExtType = ISD::SEXTLOAD; 7879 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7880 } else if (Opc == ISD::SRL) { 7881 // Another special-case: SRL is basically zero-extending a narrower value. 7882 ExtType = ISD::ZEXTLOAD; 7883 N0 = SDValue(N, 0); 7884 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7885 if (!N01) return SDValue(); 7886 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 7887 VT.getSizeInBits() - N01->getZExtValue()); 7888 } 7889 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 7890 return SDValue(); 7891 7892 unsigned EVTBits = ExtVT.getSizeInBits(); 7893 7894 // Do not generate loads of non-round integer types since these can 7895 // be expensive (and would be wrong if the type is not byte sized). 7896 if (!ExtVT.isRound()) 7897 return SDValue(); 7898 7899 unsigned ShAmt = 0; 7900 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 7901 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7902 ShAmt = N01->getZExtValue(); 7903 // Is the shift amount a multiple of size of VT? 7904 if ((ShAmt & (EVTBits-1)) == 0) { 7905 N0 = N0.getOperand(0); 7906 // Is the load width a multiple of size of VT? 7907 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 7908 return SDValue(); 7909 } 7910 7911 // At this point, we must have a load or else we can't do the transform. 7912 if (!isa<LoadSDNode>(N0)) return SDValue(); 7913 7914 // Because a SRL must be assumed to *need* to zero-extend the high bits 7915 // (as opposed to anyext the high bits), we can't combine the zextload 7916 // lowering of SRL and an sextload. 7917 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 7918 return SDValue(); 7919 7920 // If the shift amount is larger than the input type then we're not 7921 // accessing any of the loaded bytes. If the load was a zextload/extload 7922 // then the result of the shift+trunc is zero/undef (handled elsewhere). 7923 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 7924 return SDValue(); 7925 } 7926 } 7927 7928 // If the load is shifted left (and the result isn't shifted back right), 7929 // we can fold the truncate through the shift. 7930 unsigned ShLeftAmt = 0; 7931 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7932 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 7933 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 7934 ShLeftAmt = N01->getZExtValue(); 7935 N0 = N0.getOperand(0); 7936 } 7937 } 7938 7939 // If we haven't found a load, we can't narrow it. Don't transform one with 7940 // multiple uses, this would require adding a new load. 7941 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 7942 return SDValue(); 7943 7944 // Don't change the width of a volatile load. 7945 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7946 if (LN0->isVolatile()) 7947 return SDValue(); 7948 7949 // Verify that we are actually reducing a load width here. 7950 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 7951 return SDValue(); 7952 7953 // For the transform to be legal, the load must produce only two values 7954 // (the value loaded and the chain). Don't transform a pre-increment 7955 // load, for example, which produces an extra value. Otherwise the 7956 // transformation is not equivalent, and the downstream logic to replace 7957 // uses gets things wrong. 7958 if (LN0->getNumValues() > 2) 7959 return SDValue(); 7960 7961 // If the load that we're shrinking is an extload and we're not just 7962 // discarding the extension we can't simply shrink the load. Bail. 7963 // TODO: It would be possible to merge the extensions in some cases. 7964 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 7965 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 7966 return SDValue(); 7967 7968 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 7969 return SDValue(); 7970 7971 EVT PtrType = N0.getOperand(1).getValueType(); 7972 7973 if (PtrType == MVT::Untyped || PtrType.isExtended()) 7974 // It's not possible to generate a constant of extended or untyped type. 7975 return SDValue(); 7976 7977 // For big endian targets, we need to adjust the offset to the pointer to 7978 // load the correct bytes. 7979 if (DAG.getDataLayout().isBigEndian()) { 7980 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 7981 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 7982 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 7983 } 7984 7985 uint64_t PtrOff = ShAmt / 8; 7986 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 7987 SDLoc DL(LN0); 7988 // The original load itself didn't wrap, so an offset within it doesn't. 7989 SDNodeFlags Flags; 7990 Flags.setNoUnsignedWrap(true); 7991 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 7992 PtrType, LN0->getBasePtr(), 7993 DAG.getConstant(PtrOff, DL, PtrType), 7994 Flags); 7995 AddToWorklist(NewPtr.getNode()); 7996 7997 SDValue Load; 7998 if (ExtType == ISD::NON_EXTLOAD) 7999 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 8000 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 8001 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8002 else 8003 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 8004 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 8005 NewAlign, LN0->getMemOperand()->getFlags(), 8006 LN0->getAAInfo()); 8007 8008 // Replace the old load's chain with the new load's chain. 8009 WorklistRemover DeadNodes(*this); 8010 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8011 8012 // Shift the result left, if we've swallowed a left shift. 8013 SDValue Result = Load; 8014 if (ShLeftAmt != 0) { 8015 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 8016 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 8017 ShImmTy = VT; 8018 // If the shift amount is as large as the result size (but, presumably, 8019 // no larger than the source) then the useful bits of the result are 8020 // zero; we can't simply return the shortened shift, because the result 8021 // of that operation is undefined. 8022 SDLoc DL(N0); 8023 if (ShLeftAmt >= VT.getSizeInBits()) 8024 Result = DAG.getConstant(0, DL, VT); 8025 else 8026 Result = DAG.getNode(ISD::SHL, DL, VT, 8027 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 8028 } 8029 8030 // Return the new loaded value. 8031 return Result; 8032 } 8033 8034 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 8035 SDValue N0 = N->getOperand(0); 8036 SDValue N1 = N->getOperand(1); 8037 EVT VT = N->getValueType(0); 8038 EVT EVT = cast<VTSDNode>(N1)->getVT(); 8039 unsigned VTBits = VT.getScalarSizeInBits(); 8040 unsigned EVTBits = EVT.getScalarSizeInBits(); 8041 8042 if (N0.isUndef()) 8043 return DAG.getUNDEF(VT); 8044 8045 // fold (sext_in_reg c1) -> c1 8046 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8047 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 8048 8049 // If the input is already sign extended, just drop the extension. 8050 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 8051 return N0; 8052 8053 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 8054 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 8055 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 8056 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8057 N0.getOperand(0), N1); 8058 8059 // fold (sext_in_reg (sext x)) -> (sext x) 8060 // fold (sext_in_reg (aext x)) -> (sext x) 8061 // if x is small enough. 8062 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 8063 SDValue N00 = N0.getOperand(0); 8064 if (N00.getScalarValueSizeInBits() <= EVTBits && 8065 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8066 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8067 } 8068 8069 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x) 8070 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 8071 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 8072 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 8073 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 8074 if (!LegalOperations || 8075 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 8076 return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT); 8077 } 8078 8079 // fold (sext_in_reg (zext x)) -> (sext x) 8080 // iff we are extending the source sign bit. 8081 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 8082 SDValue N00 = N0.getOperand(0); 8083 if (N00.getScalarValueSizeInBits() == EVTBits && 8084 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 8085 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 8086 } 8087 8088 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 8089 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 8090 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 8091 8092 // fold operands of sext_in_reg based on knowledge that the top bits are not 8093 // demanded. 8094 if (SimplifyDemandedBits(SDValue(N, 0))) 8095 return SDValue(N, 0); 8096 8097 // fold (sext_in_reg (load x)) -> (smaller sextload x) 8098 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 8099 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 8100 return NarrowLoad; 8101 8102 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 8103 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 8104 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 8105 if (N0.getOpcode() == ISD::SRL) { 8106 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 8107 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 8108 // We can turn this into an SRA iff the input to the SRL is already sign 8109 // extended enough. 8110 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 8111 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 8112 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 8113 N0.getOperand(0), N0.getOperand(1)); 8114 } 8115 } 8116 8117 // fold (sext_inreg (extload x)) -> (sextload x) 8118 if (ISD::isEXTLoad(N0.getNode()) && 8119 ISD::isUNINDEXEDLoad(N0.getNode()) && 8120 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8121 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8122 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8123 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8124 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8125 LN0->getChain(), 8126 LN0->getBasePtr(), EVT, 8127 LN0->getMemOperand()); 8128 CombineTo(N, ExtLoad); 8129 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8130 AddToWorklist(ExtLoad.getNode()); 8131 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8132 } 8133 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 8134 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 8135 N0.hasOneUse() && 8136 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 8137 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 8138 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 8139 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8140 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 8141 LN0->getChain(), 8142 LN0->getBasePtr(), EVT, 8143 LN0->getMemOperand()); 8144 CombineTo(N, ExtLoad); 8145 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 8146 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8147 } 8148 8149 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 8150 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 8151 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 8152 N0.getOperand(1), false)) 8153 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8154 BSwap, N1); 8155 } 8156 8157 return SDValue(); 8158 } 8159 8160 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 8161 SDValue N0 = N->getOperand(0); 8162 EVT VT = N->getValueType(0); 8163 8164 if (N0.isUndef()) 8165 return DAG.getUNDEF(VT); 8166 8167 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8168 LegalOperations)) 8169 return SDValue(Res, 0); 8170 8171 return SDValue(); 8172 } 8173 8174 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 8175 SDValue N0 = N->getOperand(0); 8176 EVT VT = N->getValueType(0); 8177 8178 if (N0.isUndef()) 8179 return DAG.getUNDEF(VT); 8180 8181 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 8182 LegalOperations)) 8183 return SDValue(Res, 0); 8184 8185 return SDValue(); 8186 } 8187 8188 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 8189 SDValue N0 = N->getOperand(0); 8190 EVT VT = N->getValueType(0); 8191 bool isLE = DAG.getDataLayout().isLittleEndian(); 8192 8193 // noop truncate 8194 if (N0.getValueType() == N->getValueType(0)) 8195 return N0; 8196 // fold (truncate c1) -> c1 8197 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 8198 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 8199 // fold (truncate (truncate x)) -> (truncate x) 8200 if (N0.getOpcode() == ISD::TRUNCATE) 8201 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8202 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 8203 if (N0.getOpcode() == ISD::ZERO_EXTEND || 8204 N0.getOpcode() == ISD::SIGN_EXTEND || 8205 N0.getOpcode() == ISD::ANY_EXTEND) { 8206 // if the source is smaller than the dest, we still need an extend. 8207 if (N0.getOperand(0).getValueType().bitsLT(VT)) 8208 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 8209 // if the source is larger than the dest, than we just need the truncate. 8210 if (N0.getOperand(0).getValueType().bitsGT(VT)) 8211 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 8212 // if the source and dest are the same type, we can drop both the extend 8213 // and the truncate. 8214 return N0.getOperand(0); 8215 } 8216 8217 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 8218 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 8219 return SDValue(); 8220 8221 // Fold extract-and-trunc into a narrow extract. For example: 8222 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 8223 // i32 y = TRUNCATE(i64 x) 8224 // -- becomes -- 8225 // v16i8 b = BITCAST (v2i64 val) 8226 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 8227 // 8228 // Note: We only run this optimization after type legalization (which often 8229 // creates this pattern) and before operation legalization after which 8230 // we need to be more careful about the vector instructions that we generate. 8231 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 8232 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 8233 8234 EVT VecTy = N0.getOperand(0).getValueType(); 8235 EVT ExTy = N0.getValueType(); 8236 EVT TrTy = N->getValueType(0); 8237 8238 unsigned NumElem = VecTy.getVectorNumElements(); 8239 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 8240 8241 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 8242 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 8243 8244 SDValue EltNo = N0->getOperand(1); 8245 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 8246 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 8247 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 8248 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 8249 8250 SDLoc DL(N); 8251 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 8252 DAG.getBitcast(NVT, N0.getOperand(0)), 8253 DAG.getConstant(Index, DL, IndexTy)); 8254 } 8255 } 8256 8257 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 8258 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 8259 EVT SrcVT = N0.getValueType(); 8260 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 8261 TLI.isTruncateFree(SrcVT, VT)) { 8262 SDLoc SL(N0); 8263 SDValue Cond = N0.getOperand(0); 8264 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8265 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 8266 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 8267 } 8268 } 8269 8270 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 8271 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 8272 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 8273 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 8274 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 8275 uint64_t Amt = CAmt->getZExtValue(); 8276 unsigned Size = VT.getScalarSizeInBits(); 8277 8278 if (Amt < Size) { 8279 SDLoc SL(N); 8280 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 8281 8282 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8283 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 8284 DAG.getConstant(Amt, SL, AmtVT)); 8285 } 8286 } 8287 } 8288 8289 // Fold a series of buildvector, bitcast, and truncate if possible. 8290 // For example fold 8291 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 8292 // (2xi32 (buildvector x, y)). 8293 if (Level == AfterLegalizeVectorOps && VT.isVector() && 8294 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 8295 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 8296 N0.getOperand(0).hasOneUse()) { 8297 8298 SDValue BuildVect = N0.getOperand(0); 8299 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 8300 EVT TruncVecEltTy = VT.getVectorElementType(); 8301 8302 // Check that the element types match. 8303 if (BuildVectEltTy == TruncVecEltTy) { 8304 // Now we only need to compute the offset of the truncated elements. 8305 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 8306 unsigned TruncVecNumElts = VT.getVectorNumElements(); 8307 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 8308 8309 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 8310 "Invalid number of elements"); 8311 8312 SmallVector<SDValue, 8> Opnds; 8313 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 8314 Opnds.push_back(BuildVect.getOperand(i)); 8315 8316 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 8317 } 8318 } 8319 8320 // See if we can simplify the input to this truncate through knowledge that 8321 // only the low bits are being used. 8322 // For example "trunc (or (shl x, 8), y)" // -> trunc y 8323 // Currently we only perform this optimization on scalars because vectors 8324 // may have different active low bits. 8325 if (!VT.isVector()) { 8326 if (SDValue Shorter = 8327 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 8328 VT.getSizeInBits()))) 8329 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 8330 } 8331 8332 // fold (truncate (load x)) -> (smaller load x) 8333 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 8334 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 8335 if (SDValue Reduced = ReduceLoadWidth(N)) 8336 return Reduced; 8337 8338 // Handle the case where the load remains an extending load even 8339 // after truncation. 8340 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 8341 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8342 if (!LN0->isVolatile() && 8343 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 8344 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 8345 VT, LN0->getChain(), LN0->getBasePtr(), 8346 LN0->getMemoryVT(), 8347 LN0->getMemOperand()); 8348 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 8349 return NewLoad; 8350 } 8351 } 8352 } 8353 8354 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 8355 // where ... are all 'undef'. 8356 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 8357 SmallVector<EVT, 8> VTs; 8358 SDValue V; 8359 unsigned Idx = 0; 8360 unsigned NumDefs = 0; 8361 8362 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 8363 SDValue X = N0.getOperand(i); 8364 if (!X.isUndef()) { 8365 V = X; 8366 Idx = i; 8367 NumDefs++; 8368 } 8369 // Stop if more than one members are non-undef. 8370 if (NumDefs > 1) 8371 break; 8372 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 8373 VT.getVectorElementType(), 8374 X.getValueType().getVectorNumElements())); 8375 } 8376 8377 if (NumDefs == 0) 8378 return DAG.getUNDEF(VT); 8379 8380 if (NumDefs == 1) { 8381 assert(V.getNode() && "The single defined operand is empty!"); 8382 SmallVector<SDValue, 8> Opnds; 8383 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 8384 if (i != Idx) { 8385 Opnds.push_back(DAG.getUNDEF(VTs[i])); 8386 continue; 8387 } 8388 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 8389 AddToWorklist(NV.getNode()); 8390 Opnds.push_back(NV); 8391 } 8392 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 8393 } 8394 } 8395 8396 // Fold truncate of a bitcast of a vector to an extract of the low vector 8397 // element. 8398 // 8399 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 8400 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 8401 SDValue VecSrc = N0.getOperand(0); 8402 EVT SrcVT = VecSrc.getValueType(); 8403 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 8404 (!LegalOperations || 8405 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 8406 SDLoc SL(N); 8407 8408 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 8409 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 8410 VecSrc, DAG.getConstant(0, SL, IdxVT)); 8411 } 8412 } 8413 8414 // Simplify the operands using demanded-bits information. 8415 if (!VT.isVector() && 8416 SimplifyDemandedBits(SDValue(N, 0))) 8417 return SDValue(N, 0); 8418 8419 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 8420 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 8421 // When the adde's carry is not used. 8422 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 8423 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 8424 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 8425 SDLoc SL(N); 8426 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 8427 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 8428 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 8429 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 8430 } 8431 8432 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 8433 return NewVSel; 8434 8435 return SDValue(); 8436 } 8437 8438 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 8439 SDValue Elt = N->getOperand(i); 8440 if (Elt.getOpcode() != ISD::MERGE_VALUES) 8441 return Elt.getNode(); 8442 return Elt.getOperand(Elt.getResNo()).getNode(); 8443 } 8444 8445 /// build_pair (load, load) -> load 8446 /// if load locations are consecutive. 8447 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 8448 assert(N->getOpcode() == ISD::BUILD_PAIR); 8449 8450 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 8451 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 8452 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 8453 LD1->getAddressSpace() != LD2->getAddressSpace()) 8454 return SDValue(); 8455 EVT LD1VT = LD1->getValueType(0); 8456 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 8457 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 8458 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 8459 unsigned Align = LD1->getAlignment(); 8460 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 8461 VT.getTypeForEVT(*DAG.getContext())); 8462 8463 if (NewAlign <= Align && 8464 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 8465 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 8466 LD1->getPointerInfo(), Align); 8467 } 8468 8469 return SDValue(); 8470 } 8471 8472 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 8473 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 8474 // and Lo parts; on big-endian machines it doesn't. 8475 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 8476 } 8477 8478 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 8479 const TargetLowering &TLI) { 8480 // If this is not a bitcast to an FP type or if the target doesn't have 8481 // IEEE754-compliant FP logic, we're done. 8482 EVT VT = N->getValueType(0); 8483 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 8484 return SDValue(); 8485 8486 // TODO: Use splat values for the constant-checking below and remove this 8487 // restriction. 8488 SDValue N0 = N->getOperand(0); 8489 EVT SourceVT = N0.getValueType(); 8490 if (SourceVT.isVector()) 8491 return SDValue(); 8492 8493 unsigned FPOpcode; 8494 APInt SignMask; 8495 switch (N0.getOpcode()) { 8496 case ISD::AND: 8497 FPOpcode = ISD::FABS; 8498 SignMask = ~APInt::getSignMask(SourceVT.getSizeInBits()); 8499 break; 8500 case ISD::XOR: 8501 FPOpcode = ISD::FNEG; 8502 SignMask = APInt::getSignMask(SourceVT.getSizeInBits()); 8503 break; 8504 // TODO: ISD::OR --> ISD::FNABS? 8505 default: 8506 return SDValue(); 8507 } 8508 8509 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 8510 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 8511 SDValue LogicOp0 = N0.getOperand(0); 8512 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8513 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 8514 LogicOp0.getOpcode() == ISD::BITCAST && 8515 LogicOp0->getOperand(0).getValueType() == VT) 8516 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 8517 8518 return SDValue(); 8519 } 8520 8521 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 8522 SDValue N0 = N->getOperand(0); 8523 EVT VT = N->getValueType(0); 8524 8525 if (N0.isUndef()) 8526 return DAG.getUNDEF(VT); 8527 8528 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 8529 // Only do this before legalize, since afterward the target may be depending 8530 // on the bitconvert. 8531 // First check to see if this is all constant. 8532 if (!LegalTypes && 8533 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 8534 VT.isVector()) { 8535 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 8536 8537 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 8538 assert(!DestEltVT.isVector() && 8539 "Element type of vector ValueType must not be vector!"); 8540 if (isSimple) 8541 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 8542 } 8543 8544 // If the input is a constant, let getNode fold it. 8545 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 8546 // If we can't allow illegal operations, we need to check that this is just 8547 // a fp -> int or int -> conversion and that the resulting operation will 8548 // be legal. 8549 if (!LegalOperations || 8550 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 8551 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 8552 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 8553 TLI.isOperationLegal(ISD::Constant, VT))) 8554 return DAG.getBitcast(VT, N0); 8555 } 8556 8557 // (conv (conv x, t1), t2) -> (conv x, t2) 8558 if (N0.getOpcode() == ISD::BITCAST) 8559 return DAG.getBitcast(VT, N0.getOperand(0)); 8560 8561 // fold (conv (load x)) -> (load (conv*)x) 8562 // If the resultant load doesn't need a higher alignment than the original! 8563 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8564 // Do not change the width of a volatile load. 8565 !cast<LoadSDNode>(N0)->isVolatile() && 8566 // Do not remove the cast if the types differ in endian layout. 8567 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 8568 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 8569 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 8570 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 8571 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8572 unsigned OrigAlign = LN0->getAlignment(); 8573 8574 bool Fast = false; 8575 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 8576 LN0->getAddressSpace(), OrigAlign, &Fast) && 8577 Fast) { 8578 SDValue Load = 8579 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 8580 LN0->getPointerInfo(), OrigAlign, 8581 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8582 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 8583 return Load; 8584 } 8585 } 8586 8587 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 8588 return V; 8589 8590 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8591 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8592 // 8593 // For ppc_fp128: 8594 // fold (bitcast (fneg x)) -> 8595 // flipbit = signbit 8596 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8597 // 8598 // fold (bitcast (fabs x)) -> 8599 // flipbit = (and (extract_element (bitcast x), 0), signbit) 8600 // (xor (bitcast x) (build_pair flipbit, flipbit)) 8601 // This often reduces constant pool loads. 8602 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 8603 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 8604 N0.getNode()->hasOneUse() && VT.isInteger() && 8605 !VT.isVector() && !N0.getValueType().isVector()) { 8606 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 8607 AddToWorklist(NewConv.getNode()); 8608 8609 SDLoc DL(N); 8610 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8611 assert(VT.getSizeInBits() == 128); 8612 SDValue SignBit = DAG.getConstant( 8613 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 8614 SDValue FlipBit; 8615 if (N0.getOpcode() == ISD::FNEG) { 8616 FlipBit = SignBit; 8617 AddToWorklist(FlipBit.getNode()); 8618 } else { 8619 assert(N0.getOpcode() == ISD::FABS); 8620 SDValue Hi = 8621 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 8622 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8623 SDLoc(NewConv))); 8624 AddToWorklist(Hi.getNode()); 8625 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 8626 AddToWorklist(FlipBit.getNode()); 8627 } 8628 SDValue FlipBits = 8629 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8630 AddToWorklist(FlipBits.getNode()); 8631 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 8632 } 8633 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8634 if (N0.getOpcode() == ISD::FNEG) 8635 return DAG.getNode(ISD::XOR, DL, VT, 8636 NewConv, DAG.getConstant(SignBit, DL, VT)); 8637 assert(N0.getOpcode() == ISD::FABS); 8638 return DAG.getNode(ISD::AND, DL, VT, 8639 NewConv, DAG.getConstant(~SignBit, DL, VT)); 8640 } 8641 8642 // fold (bitconvert (fcopysign cst, x)) -> 8643 // (or (and (bitconvert x), sign), (and cst, (not sign))) 8644 // Note that we don't handle (copysign x, cst) because this can always be 8645 // folded to an fneg or fabs. 8646 // 8647 // For ppc_fp128: 8648 // fold (bitcast (fcopysign cst, x)) -> 8649 // flipbit = (and (extract_element 8650 // (xor (bitcast cst), (bitcast x)), 0), 8651 // signbit) 8652 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 8653 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 8654 isa<ConstantFPSDNode>(N0.getOperand(0)) && 8655 VT.isInteger() && !VT.isVector()) { 8656 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 8657 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 8658 if (isTypeLegal(IntXVT)) { 8659 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 8660 AddToWorklist(X.getNode()); 8661 8662 // If X has a different width than the result/lhs, sext it or truncate it. 8663 unsigned VTWidth = VT.getSizeInBits(); 8664 if (OrigXWidth < VTWidth) { 8665 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 8666 AddToWorklist(X.getNode()); 8667 } else if (OrigXWidth > VTWidth) { 8668 // To get the sign bit in the right place, we have to shift it right 8669 // before truncating. 8670 SDLoc DL(X); 8671 X = DAG.getNode(ISD::SRL, DL, 8672 X.getValueType(), X, 8673 DAG.getConstant(OrigXWidth-VTWidth, DL, 8674 X.getValueType())); 8675 AddToWorklist(X.getNode()); 8676 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 8677 AddToWorklist(X.getNode()); 8678 } 8679 8680 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 8681 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 8682 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8683 AddToWorklist(Cst.getNode()); 8684 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 8685 AddToWorklist(X.getNode()); 8686 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 8687 AddToWorklist(XorResult.getNode()); 8688 SDValue XorResult64 = DAG.getNode( 8689 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 8690 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 8691 SDLoc(XorResult))); 8692 AddToWorklist(XorResult64.getNode()); 8693 SDValue FlipBit = 8694 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 8695 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 8696 AddToWorklist(FlipBit.getNode()); 8697 SDValue FlipBits = 8698 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 8699 AddToWorklist(FlipBits.getNode()); 8700 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 8701 } 8702 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 8703 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 8704 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 8705 AddToWorklist(X.getNode()); 8706 8707 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 8708 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 8709 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 8710 AddToWorklist(Cst.getNode()); 8711 8712 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 8713 } 8714 } 8715 8716 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 8717 if (N0.getOpcode() == ISD::BUILD_PAIR) 8718 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 8719 return CombineLD; 8720 8721 // Remove double bitcasts from shuffles - this is often a legacy of 8722 // XformToShuffleWithZero being used to combine bitmaskings (of 8723 // float vectors bitcast to integer vectors) into shuffles. 8724 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 8725 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 8726 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 8727 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 8728 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 8729 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 8730 8731 // If operands are a bitcast, peek through if it casts the original VT. 8732 // If operands are a constant, just bitcast back to original VT. 8733 auto PeekThroughBitcast = [&](SDValue Op) { 8734 if (Op.getOpcode() == ISD::BITCAST && 8735 Op.getOperand(0).getValueType() == VT) 8736 return SDValue(Op.getOperand(0)); 8737 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 8738 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 8739 return DAG.getBitcast(VT, Op); 8740 return SDValue(); 8741 }; 8742 8743 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 8744 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 8745 if (!(SV0 && SV1)) 8746 return SDValue(); 8747 8748 int MaskScale = 8749 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 8750 SmallVector<int, 8> NewMask; 8751 for (int M : SVN->getMask()) 8752 for (int i = 0; i != MaskScale; ++i) 8753 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 8754 8755 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8756 if (!LegalMask) { 8757 std::swap(SV0, SV1); 8758 ShuffleVectorSDNode::commuteMask(NewMask); 8759 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 8760 } 8761 8762 if (LegalMask) 8763 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 8764 } 8765 8766 return SDValue(); 8767 } 8768 8769 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 8770 EVT VT = N->getValueType(0); 8771 return CombineConsecutiveLoads(N, VT); 8772 } 8773 8774 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 8775 /// operands. DstEltVT indicates the destination element value type. 8776 SDValue DAGCombiner:: 8777 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 8778 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 8779 8780 // If this is already the right type, we're done. 8781 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 8782 8783 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 8784 unsigned DstBitSize = DstEltVT.getSizeInBits(); 8785 8786 // If this is a conversion of N elements of one type to N elements of another 8787 // type, convert each element. This handles FP<->INT cases. 8788 if (SrcBitSize == DstBitSize) { 8789 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8790 BV->getValueType(0).getVectorNumElements()); 8791 8792 // Due to the FP element handling below calling this routine recursively, 8793 // we can end up with a scalar-to-vector node here. 8794 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 8795 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 8796 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 8797 8798 SmallVector<SDValue, 8> Ops; 8799 for (SDValue Op : BV->op_values()) { 8800 // If the vector element type is not legal, the BUILD_VECTOR operands 8801 // are promoted and implicitly truncated. Make that explicit here. 8802 if (Op.getValueType() != SrcEltVT) 8803 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 8804 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 8805 AddToWorklist(Ops.back().getNode()); 8806 } 8807 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 8808 } 8809 8810 // Otherwise, we're growing or shrinking the elements. To avoid having to 8811 // handle annoying details of growing/shrinking FP values, we convert them to 8812 // int first. 8813 if (SrcEltVT.isFloatingPoint()) { 8814 // Convert the input float vector to a int vector where the elements are the 8815 // same sizes. 8816 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 8817 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 8818 SrcEltVT = IntVT; 8819 } 8820 8821 // Now we know the input is an integer vector. If the output is a FP type, 8822 // convert to integer first, then to FP of the right size. 8823 if (DstEltVT.isFloatingPoint()) { 8824 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 8825 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 8826 8827 // Next, convert to FP elements of the same size. 8828 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 8829 } 8830 8831 SDLoc DL(BV); 8832 8833 // Okay, we know the src/dst types are both integers of differing types. 8834 // Handling growing first. 8835 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 8836 if (SrcBitSize < DstBitSize) { 8837 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 8838 8839 SmallVector<SDValue, 8> Ops; 8840 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 8841 i += NumInputsPerOutput) { 8842 bool isLE = DAG.getDataLayout().isLittleEndian(); 8843 APInt NewBits = APInt(DstBitSize, 0); 8844 bool EltIsUndef = true; 8845 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 8846 // Shift the previously computed bits over. 8847 NewBits <<= SrcBitSize; 8848 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 8849 if (Op.isUndef()) continue; 8850 EltIsUndef = false; 8851 8852 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 8853 zextOrTrunc(SrcBitSize).zext(DstBitSize); 8854 } 8855 8856 if (EltIsUndef) 8857 Ops.push_back(DAG.getUNDEF(DstEltVT)); 8858 else 8859 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 8860 } 8861 8862 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 8863 return DAG.getBuildVector(VT, DL, Ops); 8864 } 8865 8866 // Finally, this must be the case where we are shrinking elements: each input 8867 // turns into multiple outputs. 8868 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 8869 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 8870 NumOutputsPerInput*BV->getNumOperands()); 8871 SmallVector<SDValue, 8> Ops; 8872 8873 for (const SDValue &Op : BV->op_values()) { 8874 if (Op.isUndef()) { 8875 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 8876 continue; 8877 } 8878 8879 APInt OpVal = cast<ConstantSDNode>(Op)-> 8880 getAPIntValue().zextOrTrunc(SrcBitSize); 8881 8882 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 8883 APInt ThisVal = OpVal.trunc(DstBitSize); 8884 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 8885 OpVal.lshrInPlace(DstBitSize); 8886 } 8887 8888 // For big endian targets, swap the order of the pieces of each element. 8889 if (DAG.getDataLayout().isBigEndian()) 8890 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 8891 } 8892 8893 return DAG.getBuildVector(VT, DL, Ops); 8894 } 8895 8896 static bool isContractable(SDNode *N) { 8897 SDNodeFlags F = N->getFlags(); 8898 return F.hasAllowContract() || F.hasUnsafeAlgebra(); 8899 } 8900 8901 /// Try to perform FMA combining on a given FADD node. 8902 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 8903 SDValue N0 = N->getOperand(0); 8904 SDValue N1 = N->getOperand(1); 8905 EVT VT = N->getValueType(0); 8906 SDLoc SL(N); 8907 8908 const TargetOptions &Options = DAG.getTarget().Options; 8909 8910 // Floating-point multiply-add with intermediate rounding. 8911 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8912 8913 // Floating-point multiply-add without intermediate rounding. 8914 bool HasFMA = 8915 TLI.isFMAFasterThanFMulAndFAdd(VT) && 8916 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8917 8918 // No valid opcode, do not combine. 8919 if (!HasFMAD && !HasFMA) 8920 return SDValue(); 8921 8922 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 8923 Options.UnsafeFPMath || HasFMAD); 8924 // If the addition is not contractable, do not combine. 8925 if (!AllowFusionGlobally && !isContractable(N)) 8926 return SDValue(); 8927 8928 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8929 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8930 return SDValue(); 8931 8932 // Always prefer FMAD to FMA for precision. 8933 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8934 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8935 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8936 8937 // Is the node an FMUL and contractable either due to global flags or 8938 // SDNodeFlags. 8939 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 8940 if (N.getOpcode() != ISD::FMUL) 8941 return false; 8942 return AllowFusionGlobally || isContractable(N.getNode()); 8943 }; 8944 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 8945 // prefer to fold the multiply with fewer uses. 8946 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 8947 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 8948 std::swap(N0, N1); 8949 } 8950 8951 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 8952 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 8953 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8954 N0.getOperand(0), N0.getOperand(1), N1); 8955 } 8956 8957 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 8958 // Note: Commutes FADD operands. 8959 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 8960 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8961 N1.getOperand(0), N1.getOperand(1), N0); 8962 } 8963 8964 // Look through FP_EXTEND nodes to do more combining. 8965 if (LookThroughFPExt) { 8966 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 8967 if (N0.getOpcode() == ISD::FP_EXTEND) { 8968 SDValue N00 = N0.getOperand(0); 8969 if (isContractableFMUL(N00)) 8970 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8971 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8972 N00.getOperand(0)), 8973 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8974 N00.getOperand(1)), N1); 8975 } 8976 8977 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 8978 // Note: Commutes FADD operands. 8979 if (N1.getOpcode() == ISD::FP_EXTEND) { 8980 SDValue N10 = N1.getOperand(0); 8981 if (isContractableFMUL(N10)) 8982 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8983 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8984 N10.getOperand(0)), 8985 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8986 N10.getOperand(1)), N0); 8987 } 8988 } 8989 8990 // More folding opportunities when target permits. 8991 if (Aggressive) { 8992 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 8993 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 8994 // are currently only supported on binary nodes. 8995 if (Options.UnsafeFPMath && 8996 N0.getOpcode() == PreferredFusedOpcode && 8997 N0.getOperand(2).getOpcode() == ISD::FMUL && 8998 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 8999 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9000 N0.getOperand(0), N0.getOperand(1), 9001 DAG.getNode(PreferredFusedOpcode, SL, VT, 9002 N0.getOperand(2).getOperand(0), 9003 N0.getOperand(2).getOperand(1), 9004 N1)); 9005 } 9006 9007 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 9008 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9009 // are currently only supported on binary nodes. 9010 if (Options.UnsafeFPMath && 9011 N1->getOpcode() == PreferredFusedOpcode && 9012 N1.getOperand(2).getOpcode() == ISD::FMUL && 9013 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 9014 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9015 N1.getOperand(0), N1.getOperand(1), 9016 DAG.getNode(PreferredFusedOpcode, SL, VT, 9017 N1.getOperand(2).getOperand(0), 9018 N1.getOperand(2).getOperand(1), 9019 N0)); 9020 } 9021 9022 if (LookThroughFPExt) { 9023 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 9024 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 9025 auto FoldFAddFMAFPExtFMul = [&] ( 9026 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9027 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 9028 DAG.getNode(PreferredFusedOpcode, SL, VT, 9029 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9030 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9031 Z)); 9032 }; 9033 if (N0.getOpcode() == PreferredFusedOpcode) { 9034 SDValue N02 = N0.getOperand(2); 9035 if (N02.getOpcode() == ISD::FP_EXTEND) { 9036 SDValue N020 = N02.getOperand(0); 9037 if (isContractableFMUL(N020)) 9038 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 9039 N020.getOperand(0), N020.getOperand(1), 9040 N1); 9041 } 9042 } 9043 9044 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 9045 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 9046 // FIXME: This turns two single-precision and one double-precision 9047 // operation into two double-precision operations, which might not be 9048 // interesting for all targets, especially GPUs. 9049 auto FoldFAddFPExtFMAFMul = [&] ( 9050 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 9051 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9052 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 9053 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 9054 DAG.getNode(PreferredFusedOpcode, SL, VT, 9055 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 9056 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 9057 Z)); 9058 }; 9059 if (N0.getOpcode() == ISD::FP_EXTEND) { 9060 SDValue N00 = N0.getOperand(0); 9061 if (N00.getOpcode() == PreferredFusedOpcode) { 9062 SDValue N002 = N00.getOperand(2); 9063 if (isContractableFMUL(N002)) 9064 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 9065 N002.getOperand(0), N002.getOperand(1), 9066 N1); 9067 } 9068 } 9069 9070 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 9071 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 9072 if (N1.getOpcode() == PreferredFusedOpcode) { 9073 SDValue N12 = N1.getOperand(2); 9074 if (N12.getOpcode() == ISD::FP_EXTEND) { 9075 SDValue N120 = N12.getOperand(0); 9076 if (isContractableFMUL(N120)) 9077 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 9078 N120.getOperand(0), N120.getOperand(1), 9079 N0); 9080 } 9081 } 9082 9083 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 9084 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 9085 // FIXME: This turns two single-precision and one double-precision 9086 // operation into two double-precision operations, which might not be 9087 // interesting for all targets, especially GPUs. 9088 if (N1.getOpcode() == ISD::FP_EXTEND) { 9089 SDValue N10 = N1.getOperand(0); 9090 if (N10.getOpcode() == PreferredFusedOpcode) { 9091 SDValue N102 = N10.getOperand(2); 9092 if (isContractableFMUL(N102)) 9093 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 9094 N102.getOperand(0), N102.getOperand(1), 9095 N0); 9096 } 9097 } 9098 } 9099 } 9100 9101 return SDValue(); 9102 } 9103 9104 /// Try to perform FMA combining on a given FSUB node. 9105 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 9106 SDValue N0 = N->getOperand(0); 9107 SDValue N1 = N->getOperand(1); 9108 EVT VT = N->getValueType(0); 9109 SDLoc SL(N); 9110 9111 const TargetOptions &Options = DAG.getTarget().Options; 9112 // Floating-point multiply-add with intermediate rounding. 9113 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9114 9115 // Floating-point multiply-add without intermediate rounding. 9116 bool HasFMA = 9117 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9118 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9119 9120 // No valid opcode, do not combine. 9121 if (!HasFMAD && !HasFMA) 9122 return SDValue(); 9123 9124 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 9125 Options.UnsafeFPMath || HasFMAD); 9126 // If the subtraction is not contractable, do not combine. 9127 if (!AllowFusionGlobally && !isContractable(N)) 9128 return SDValue(); 9129 9130 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 9131 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 9132 return SDValue(); 9133 9134 // Always prefer FMAD to FMA for precision. 9135 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9136 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9137 bool LookThroughFPExt = TLI.isFPExtFree(VT); 9138 9139 // Is the node an FMUL and contractable either due to global flags or 9140 // SDNodeFlags. 9141 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 9142 if (N.getOpcode() != ISD::FMUL) 9143 return false; 9144 return AllowFusionGlobally || isContractable(N.getNode()); 9145 }; 9146 9147 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 9148 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 9149 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9150 N0.getOperand(0), N0.getOperand(1), 9151 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9152 } 9153 9154 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 9155 // Note: Commutes FSUB operands. 9156 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) 9157 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9158 DAG.getNode(ISD::FNEG, SL, VT, 9159 N1.getOperand(0)), 9160 N1.getOperand(1), N0); 9161 9162 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 9163 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 9164 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 9165 SDValue N00 = N0.getOperand(0).getOperand(0); 9166 SDValue N01 = N0.getOperand(0).getOperand(1); 9167 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9168 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 9169 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9170 } 9171 9172 // Look through FP_EXTEND nodes to do more combining. 9173 if (LookThroughFPExt) { 9174 // fold (fsub (fpext (fmul x, y)), z) 9175 // -> (fma (fpext x), (fpext y), (fneg z)) 9176 if (N0.getOpcode() == ISD::FP_EXTEND) { 9177 SDValue N00 = N0.getOperand(0); 9178 if (isContractableFMUL(N00)) 9179 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9180 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9181 N00.getOperand(0)), 9182 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9183 N00.getOperand(1)), 9184 DAG.getNode(ISD::FNEG, SL, VT, N1)); 9185 } 9186 9187 // fold (fsub x, (fpext (fmul y, z))) 9188 // -> (fma (fneg (fpext y)), (fpext z), x) 9189 // Note: Commutes FSUB operands. 9190 if (N1.getOpcode() == ISD::FP_EXTEND) { 9191 SDValue N10 = N1.getOperand(0); 9192 if (isContractableFMUL(N10)) 9193 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9194 DAG.getNode(ISD::FNEG, SL, VT, 9195 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9196 N10.getOperand(0))), 9197 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9198 N10.getOperand(1)), 9199 N0); 9200 } 9201 9202 // fold (fsub (fpext (fneg (fmul, x, y))), z) 9203 // -> (fneg (fma (fpext x), (fpext y), z)) 9204 // Note: This could be removed with appropriate canonicalization of the 9205 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9206 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9207 // from implementing the canonicalization in visitFSUB. 9208 if (N0.getOpcode() == ISD::FP_EXTEND) { 9209 SDValue N00 = N0.getOperand(0); 9210 if (N00.getOpcode() == ISD::FNEG) { 9211 SDValue N000 = N00.getOperand(0); 9212 if (isContractableFMUL(N000)) { 9213 return DAG.getNode(ISD::FNEG, SL, VT, 9214 DAG.getNode(PreferredFusedOpcode, SL, VT, 9215 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9216 N000.getOperand(0)), 9217 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9218 N000.getOperand(1)), 9219 N1)); 9220 } 9221 } 9222 } 9223 9224 // fold (fsub (fneg (fpext (fmul, x, y))), z) 9225 // -> (fneg (fma (fpext x)), (fpext y), z) 9226 // Note: This could be removed with appropriate canonicalization of the 9227 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 9228 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 9229 // from implementing the canonicalization in visitFSUB. 9230 if (N0.getOpcode() == ISD::FNEG) { 9231 SDValue N00 = N0.getOperand(0); 9232 if (N00.getOpcode() == ISD::FP_EXTEND) { 9233 SDValue N000 = N00.getOperand(0); 9234 if (isContractableFMUL(N000)) { 9235 return DAG.getNode(ISD::FNEG, SL, VT, 9236 DAG.getNode(PreferredFusedOpcode, SL, VT, 9237 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9238 N000.getOperand(0)), 9239 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9240 N000.getOperand(1)), 9241 N1)); 9242 } 9243 } 9244 } 9245 9246 } 9247 9248 // More folding opportunities when target permits. 9249 if (Aggressive) { 9250 // fold (fsub (fma x, y, (fmul u, v)), z) 9251 // -> (fma x, y (fma u, v, (fneg z))) 9252 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9253 // are currently only supported on binary nodes. 9254 if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode && 9255 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 9256 N0.getOperand(2)->hasOneUse()) { 9257 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9258 N0.getOperand(0), N0.getOperand(1), 9259 DAG.getNode(PreferredFusedOpcode, SL, VT, 9260 N0.getOperand(2).getOperand(0), 9261 N0.getOperand(2).getOperand(1), 9262 DAG.getNode(ISD::FNEG, SL, VT, 9263 N1))); 9264 } 9265 9266 // fold (fsub x, (fma y, z, (fmul u, v))) 9267 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 9268 // FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF 9269 // are currently only supported on binary nodes. 9270 if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode && 9271 isContractableFMUL(N1.getOperand(2))) { 9272 SDValue N20 = N1.getOperand(2).getOperand(0); 9273 SDValue N21 = N1.getOperand(2).getOperand(1); 9274 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9275 DAG.getNode(ISD::FNEG, SL, VT, 9276 N1.getOperand(0)), 9277 N1.getOperand(1), 9278 DAG.getNode(PreferredFusedOpcode, SL, VT, 9279 DAG.getNode(ISD::FNEG, SL, VT, N20), 9280 9281 N21, N0)); 9282 } 9283 9284 if (LookThroughFPExt) { 9285 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 9286 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 9287 if (N0.getOpcode() == PreferredFusedOpcode) { 9288 SDValue N02 = N0.getOperand(2); 9289 if (N02.getOpcode() == ISD::FP_EXTEND) { 9290 SDValue N020 = N02.getOperand(0); 9291 if (isContractableFMUL(N020)) 9292 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9293 N0.getOperand(0), N0.getOperand(1), 9294 DAG.getNode(PreferredFusedOpcode, SL, VT, 9295 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9296 N020.getOperand(0)), 9297 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9298 N020.getOperand(1)), 9299 DAG.getNode(ISD::FNEG, SL, VT, 9300 N1))); 9301 } 9302 } 9303 9304 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 9305 // -> (fma (fpext x), (fpext y), 9306 // (fma (fpext u), (fpext v), (fneg z))) 9307 // FIXME: This turns two single-precision and one double-precision 9308 // operation into two double-precision operations, which might not be 9309 // interesting for all targets, especially GPUs. 9310 if (N0.getOpcode() == ISD::FP_EXTEND) { 9311 SDValue N00 = N0.getOperand(0); 9312 if (N00.getOpcode() == PreferredFusedOpcode) { 9313 SDValue N002 = N00.getOperand(2); 9314 if (isContractableFMUL(N002)) 9315 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9316 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9317 N00.getOperand(0)), 9318 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9319 N00.getOperand(1)), 9320 DAG.getNode(PreferredFusedOpcode, SL, VT, 9321 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9322 N002.getOperand(0)), 9323 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9324 N002.getOperand(1)), 9325 DAG.getNode(ISD::FNEG, SL, VT, 9326 N1))); 9327 } 9328 } 9329 9330 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 9331 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 9332 if (N1.getOpcode() == PreferredFusedOpcode && 9333 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 9334 SDValue N120 = N1.getOperand(2).getOperand(0); 9335 if (isContractableFMUL(N120)) { 9336 SDValue N1200 = N120.getOperand(0); 9337 SDValue N1201 = N120.getOperand(1); 9338 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9339 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 9340 N1.getOperand(1), 9341 DAG.getNode(PreferredFusedOpcode, SL, VT, 9342 DAG.getNode(ISD::FNEG, SL, VT, 9343 DAG.getNode(ISD::FP_EXTEND, SL, 9344 VT, N1200)), 9345 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9346 N1201), 9347 N0)); 9348 } 9349 } 9350 9351 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 9352 // -> (fma (fneg (fpext y)), (fpext z), 9353 // (fma (fneg (fpext u)), (fpext v), x)) 9354 // FIXME: This turns two single-precision and one double-precision 9355 // operation into two double-precision operations, which might not be 9356 // interesting for all targets, especially GPUs. 9357 if (N1.getOpcode() == ISD::FP_EXTEND && 9358 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 9359 SDValue N100 = N1.getOperand(0).getOperand(0); 9360 SDValue N101 = N1.getOperand(0).getOperand(1); 9361 SDValue N102 = N1.getOperand(0).getOperand(2); 9362 if (isContractableFMUL(N102)) { 9363 SDValue N1020 = N102.getOperand(0); 9364 SDValue N1021 = N102.getOperand(1); 9365 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9366 DAG.getNode(ISD::FNEG, SL, VT, 9367 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9368 N100)), 9369 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 9370 DAG.getNode(PreferredFusedOpcode, SL, VT, 9371 DAG.getNode(ISD::FNEG, SL, VT, 9372 DAG.getNode(ISD::FP_EXTEND, SL, 9373 VT, N1020)), 9374 DAG.getNode(ISD::FP_EXTEND, SL, VT, 9375 N1021), 9376 N0)); 9377 } 9378 } 9379 } 9380 } 9381 9382 return SDValue(); 9383 } 9384 9385 /// Try to perform FMA combining on a given FMUL node based on the distributive 9386 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 9387 /// subtraction instead of addition). 9388 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 9389 SDValue N0 = N->getOperand(0); 9390 SDValue N1 = N->getOperand(1); 9391 EVT VT = N->getValueType(0); 9392 SDLoc SL(N); 9393 9394 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 9395 9396 const TargetOptions &Options = DAG.getTarget().Options; 9397 9398 // The transforms below are incorrect when x == 0 and y == inf, because the 9399 // intermediate multiplication produces a nan. 9400 if (!Options.NoInfsFPMath) 9401 return SDValue(); 9402 9403 // Floating-point multiply-add without intermediate rounding. 9404 bool HasFMA = 9405 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 9406 TLI.isFMAFasterThanFMulAndFAdd(VT) && 9407 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 9408 9409 // Floating-point multiply-add with intermediate rounding. This can result 9410 // in a less precise result due to the changed rounding order. 9411 bool HasFMAD = Options.UnsafeFPMath && 9412 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 9413 9414 // No valid opcode, do not combine. 9415 if (!HasFMAD && !HasFMA) 9416 return SDValue(); 9417 9418 // Always prefer FMAD to FMA for precision. 9419 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 9420 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 9421 9422 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 9423 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 9424 auto FuseFADD = [&](SDValue X, SDValue Y) { 9425 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 9426 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9427 if (XC1 && XC1->isExactlyValue(+1.0)) 9428 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9429 if (XC1 && XC1->isExactlyValue(-1.0)) 9430 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9431 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9432 } 9433 return SDValue(); 9434 }; 9435 9436 if (SDValue FMA = FuseFADD(N0, N1)) 9437 return FMA; 9438 if (SDValue FMA = FuseFADD(N1, N0)) 9439 return FMA; 9440 9441 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 9442 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 9443 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 9444 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 9445 auto FuseFSUB = [&](SDValue X, SDValue Y) { 9446 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 9447 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 9448 if (XC0 && XC0->isExactlyValue(+1.0)) 9449 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9450 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9451 Y); 9452 if (XC0 && XC0->isExactlyValue(-1.0)) 9453 return DAG.getNode(PreferredFusedOpcode, SL, VT, 9454 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 9455 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9456 9457 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 9458 if (XC1 && XC1->isExactlyValue(+1.0)) 9459 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 9460 DAG.getNode(ISD::FNEG, SL, VT, Y)); 9461 if (XC1 && XC1->isExactlyValue(-1.0)) 9462 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 9463 } 9464 return SDValue(); 9465 }; 9466 9467 if (SDValue FMA = FuseFSUB(N0, N1)) 9468 return FMA; 9469 if (SDValue FMA = FuseFSUB(N1, N0)) 9470 return FMA; 9471 9472 return SDValue(); 9473 } 9474 9475 static bool isFMulNegTwo(SDValue &N) { 9476 if (N.getOpcode() != ISD::FMUL) 9477 return false; 9478 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N.getOperand(1))) 9479 return CFP->isExactlyValue(-2.0); 9480 return false; 9481 } 9482 9483 SDValue DAGCombiner::visitFADD(SDNode *N) { 9484 SDValue N0 = N->getOperand(0); 9485 SDValue N1 = N->getOperand(1); 9486 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 9487 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 9488 EVT VT = N->getValueType(0); 9489 SDLoc DL(N); 9490 const TargetOptions &Options = DAG.getTarget().Options; 9491 const SDNodeFlags Flags = N->getFlags(); 9492 9493 // fold vector ops 9494 if (VT.isVector()) 9495 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9496 return FoldedVOp; 9497 9498 // fold (fadd c1, c2) -> c1 + c2 9499 if (N0CFP && N1CFP) 9500 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 9501 9502 // canonicalize constant to RHS 9503 if (N0CFP && !N1CFP) 9504 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 9505 9506 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9507 return NewSel; 9508 9509 // fold (fadd A, (fneg B)) -> (fsub A, B) 9510 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9511 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 9512 return DAG.getNode(ISD::FSUB, DL, VT, N0, 9513 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9514 9515 // fold (fadd (fneg A), B) -> (fsub B, A) 9516 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 9517 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 9518 return DAG.getNode(ISD::FSUB, DL, VT, N1, 9519 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 9520 9521 // fold (fadd A, (fmul B, -2.0)) -> (fsub A, (fadd B, B)) 9522 // fold (fadd (fmul B, -2.0), A) -> (fsub A, (fadd B, B)) 9523 if ((isFMulNegTwo(N0) && N0.hasOneUse()) || 9524 (isFMulNegTwo(N1) && N1.hasOneUse())) { 9525 bool N1IsFMul = isFMulNegTwo(N1); 9526 SDValue AddOp = N1IsFMul ? N1.getOperand(0) : N0.getOperand(0); 9527 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, AddOp, AddOp, Flags); 9528 return DAG.getNode(ISD::FSUB, DL, VT, N1IsFMul ? N0 : N1, Add, Flags); 9529 } 9530 9531 // FIXME: Auto-upgrade the target/function-level option. 9532 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9533 // fold (fadd A, 0) -> A 9534 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 9535 if (N1C->isZero()) 9536 return N0; 9537 } 9538 9539 // If 'unsafe math' is enabled, fold lots of things. 9540 if (Options.UnsafeFPMath) { 9541 // No FP constant should be created after legalization as Instruction 9542 // Selection pass has a hard time dealing with FP constants. 9543 bool AllowNewConst = (Level < AfterLegalizeDAG); 9544 9545 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 9546 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 9547 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 9548 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 9549 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 9550 Flags), 9551 Flags); 9552 9553 // If allowed, fold (fadd (fneg x), x) -> 0.0 9554 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 9555 return DAG.getConstantFP(0.0, DL, VT); 9556 9557 // If allowed, fold (fadd x, (fneg x)) -> 0.0 9558 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 9559 return DAG.getConstantFP(0.0, DL, VT); 9560 9561 // We can fold chains of FADD's of the same value into multiplications. 9562 // This transform is not safe in general because we are reducing the number 9563 // of rounding steps. 9564 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 9565 if (N0.getOpcode() == ISD::FMUL) { 9566 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9567 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 9568 9569 // (fadd (fmul x, c), x) -> (fmul x, c+1) 9570 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 9571 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9572 DAG.getConstantFP(1.0, DL, VT), Flags); 9573 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 9574 } 9575 9576 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 9577 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 9578 N1.getOperand(0) == N1.getOperand(1) && 9579 N0.getOperand(0) == N1.getOperand(0)) { 9580 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 9581 DAG.getConstantFP(2.0, DL, VT), Flags); 9582 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 9583 } 9584 } 9585 9586 if (N1.getOpcode() == ISD::FMUL) { 9587 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9588 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 9589 9590 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 9591 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 9592 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9593 DAG.getConstantFP(1.0, DL, VT), Flags); 9594 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 9595 } 9596 9597 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 9598 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 9599 N0.getOperand(0) == N0.getOperand(1) && 9600 N1.getOperand(0) == N0.getOperand(0)) { 9601 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 9602 DAG.getConstantFP(2.0, DL, VT), Flags); 9603 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 9604 } 9605 } 9606 9607 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 9608 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 9609 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 9610 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 9611 (N0.getOperand(0) == N1)) { 9612 return DAG.getNode(ISD::FMUL, DL, VT, 9613 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 9614 } 9615 } 9616 9617 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 9618 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 9619 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 9620 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 9621 N1.getOperand(0) == N0) { 9622 return DAG.getNode(ISD::FMUL, DL, VT, 9623 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 9624 } 9625 } 9626 9627 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 9628 if (AllowNewConst && 9629 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 9630 N0.getOperand(0) == N0.getOperand(1) && 9631 N1.getOperand(0) == N1.getOperand(1) && 9632 N0.getOperand(0) == N1.getOperand(0)) { 9633 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 9634 DAG.getConstantFP(4.0, DL, VT), Flags); 9635 } 9636 } 9637 } // enable-unsafe-fp-math 9638 9639 // FADD -> FMA combines: 9640 if (SDValue Fused = visitFADDForFMACombine(N)) { 9641 AddToWorklist(Fused.getNode()); 9642 return Fused; 9643 } 9644 return SDValue(); 9645 } 9646 9647 SDValue DAGCombiner::visitFSUB(SDNode *N) { 9648 SDValue N0 = N->getOperand(0); 9649 SDValue N1 = N->getOperand(1); 9650 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9651 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9652 EVT VT = N->getValueType(0); 9653 SDLoc DL(N); 9654 const TargetOptions &Options = DAG.getTarget().Options; 9655 const SDNodeFlags Flags = N->getFlags(); 9656 9657 // fold vector ops 9658 if (VT.isVector()) 9659 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9660 return FoldedVOp; 9661 9662 // fold (fsub c1, c2) -> c1-c2 9663 if (N0CFP && N1CFP) 9664 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 9665 9666 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9667 return NewSel; 9668 9669 // fold (fsub A, (fneg B)) -> (fadd A, B) 9670 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9671 return DAG.getNode(ISD::FADD, DL, VT, N0, 9672 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 9673 9674 // FIXME: Auto-upgrade the target/function-level option. 9675 if (Options.NoSignedZerosFPMath || N->getFlags().hasNoSignedZeros()) { 9676 // (fsub 0, B) -> -B 9677 if (N0CFP && N0CFP->isZero()) { 9678 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 9679 return GetNegatedExpression(N1, DAG, LegalOperations); 9680 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9681 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 9682 } 9683 } 9684 9685 // If 'unsafe math' is enabled, fold lots of things. 9686 if (Options.UnsafeFPMath) { 9687 // (fsub A, 0) -> A 9688 if (N1CFP && N1CFP->isZero()) 9689 return N0; 9690 9691 // (fsub x, x) -> 0.0 9692 if (N0 == N1) 9693 return DAG.getConstantFP(0.0f, DL, VT); 9694 9695 // (fsub x, (fadd x, y)) -> (fneg y) 9696 // (fsub x, (fadd y, x)) -> (fneg y) 9697 if (N1.getOpcode() == ISD::FADD) { 9698 SDValue N10 = N1->getOperand(0); 9699 SDValue N11 = N1->getOperand(1); 9700 9701 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 9702 return GetNegatedExpression(N11, DAG, LegalOperations); 9703 9704 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 9705 return GetNegatedExpression(N10, DAG, LegalOperations); 9706 } 9707 } 9708 9709 // FSUB -> FMA combines: 9710 if (SDValue Fused = visitFSUBForFMACombine(N)) { 9711 AddToWorklist(Fused.getNode()); 9712 return Fused; 9713 } 9714 9715 return SDValue(); 9716 } 9717 9718 SDValue DAGCombiner::visitFMUL(SDNode *N) { 9719 SDValue N0 = N->getOperand(0); 9720 SDValue N1 = N->getOperand(1); 9721 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9722 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9723 EVT VT = N->getValueType(0); 9724 SDLoc DL(N); 9725 const TargetOptions &Options = DAG.getTarget().Options; 9726 const SDNodeFlags Flags = N->getFlags(); 9727 9728 // fold vector ops 9729 if (VT.isVector()) { 9730 // This just handles C1 * C2 for vectors. Other vector folds are below. 9731 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9732 return FoldedVOp; 9733 } 9734 9735 // fold (fmul c1, c2) -> c1*c2 9736 if (N0CFP && N1CFP) 9737 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 9738 9739 // canonicalize constant to RHS 9740 if (isConstantFPBuildVectorOrConstantFP(N0) && 9741 !isConstantFPBuildVectorOrConstantFP(N1)) 9742 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 9743 9744 // fold (fmul A, 1.0) -> A 9745 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9746 return N0; 9747 9748 if (SDValue NewSel = foldBinOpIntoSelect(N)) 9749 return NewSel; 9750 9751 if (Options.UnsafeFPMath) { 9752 // fold (fmul A, 0) -> 0 9753 if (N1CFP && N1CFP->isZero()) 9754 return N1; 9755 9756 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 9757 if (N0.getOpcode() == ISD::FMUL) { 9758 // Fold scalars or any vector constants (not just splats). 9759 // This fold is done in general by InstCombine, but extra fmul insts 9760 // may have been generated during lowering. 9761 SDValue N00 = N0.getOperand(0); 9762 SDValue N01 = N0.getOperand(1); 9763 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 9764 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 9765 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 9766 9767 // Check 1: Make sure that the first operand of the inner multiply is NOT 9768 // a constant. Otherwise, we may induce infinite looping. 9769 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 9770 // Check 2: Make sure that the second operand of the inner multiply and 9771 // the second operand of the outer multiply are constants. 9772 if ((N1CFP && isConstOrConstSplatFP(N01)) || 9773 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 9774 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 9775 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 9776 } 9777 } 9778 } 9779 9780 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 9781 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 9782 // during an early run of DAGCombiner can prevent folding with fmuls 9783 // inserted during lowering. 9784 if (N0.getOpcode() == ISD::FADD && 9785 (N0.getOperand(0) == N0.getOperand(1)) && 9786 N0.hasOneUse()) { 9787 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 9788 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 9789 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 9790 } 9791 } 9792 9793 // fold (fmul X, 2.0) -> (fadd X, X) 9794 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 9795 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 9796 9797 // fold (fmul X, -1.0) -> (fneg X) 9798 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 9799 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9800 return DAG.getNode(ISD::FNEG, DL, VT, N0); 9801 9802 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 9803 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 9804 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 9805 // Both can be negated for free, check to see if at least one is cheaper 9806 // negated. 9807 if (LHSNeg == 2 || RHSNeg == 2) 9808 return DAG.getNode(ISD::FMUL, DL, VT, 9809 GetNegatedExpression(N0, DAG, LegalOperations), 9810 GetNegatedExpression(N1, DAG, LegalOperations), 9811 Flags); 9812 } 9813 } 9814 9815 // FMUL -> FMA combines: 9816 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 9817 AddToWorklist(Fused.getNode()); 9818 return Fused; 9819 } 9820 9821 return SDValue(); 9822 } 9823 9824 SDValue DAGCombiner::visitFMA(SDNode *N) { 9825 SDValue N0 = N->getOperand(0); 9826 SDValue N1 = N->getOperand(1); 9827 SDValue N2 = N->getOperand(2); 9828 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9829 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9830 EVT VT = N->getValueType(0); 9831 SDLoc DL(N); 9832 const TargetOptions &Options = DAG.getTarget().Options; 9833 9834 // Constant fold FMA. 9835 if (isa<ConstantFPSDNode>(N0) && 9836 isa<ConstantFPSDNode>(N1) && 9837 isa<ConstantFPSDNode>(N2)) { 9838 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 9839 } 9840 9841 if (Options.UnsafeFPMath) { 9842 if (N0CFP && N0CFP->isZero()) 9843 return N2; 9844 if (N1CFP && N1CFP->isZero()) 9845 return N2; 9846 } 9847 // TODO: The FMA node should have flags that propagate to these nodes. 9848 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9849 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 9850 if (N1CFP && N1CFP->isExactlyValue(1.0)) 9851 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 9852 9853 // Canonicalize (fma c, x, y) -> (fma x, c, y) 9854 if (isConstantFPBuildVectorOrConstantFP(N0) && 9855 !isConstantFPBuildVectorOrConstantFP(N1)) 9856 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 9857 9858 // TODO: FMA nodes should have flags that propagate to the created nodes. 9859 // For now, create a Flags object for use with all unsafe math transforms. 9860 SDNodeFlags Flags; 9861 Flags.setUnsafeAlgebra(true); 9862 9863 if (Options.UnsafeFPMath) { 9864 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 9865 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 9866 isConstantFPBuildVectorOrConstantFP(N1) && 9867 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 9868 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9869 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 9870 Flags), Flags); 9871 } 9872 9873 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 9874 if (N0.getOpcode() == ISD::FMUL && 9875 isConstantFPBuildVectorOrConstantFP(N1) && 9876 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 9877 return DAG.getNode(ISD::FMA, DL, VT, 9878 N0.getOperand(0), 9879 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 9880 Flags), 9881 N2); 9882 } 9883 } 9884 9885 // (fma x, 1, y) -> (fadd x, y) 9886 // (fma x, -1, y) -> (fadd (fneg x), y) 9887 if (N1CFP) { 9888 if (N1CFP->isExactlyValue(1.0)) 9889 // TODO: The FMA node should have flags that propagate to this node. 9890 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 9891 9892 if (N1CFP->isExactlyValue(-1.0) && 9893 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 9894 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 9895 AddToWorklist(RHSNeg.getNode()); 9896 // TODO: The FMA node should have flags that propagate to this node. 9897 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 9898 } 9899 } 9900 9901 if (Options.UnsafeFPMath) { 9902 // (fma x, c, x) -> (fmul x, (c+1)) 9903 if (N1CFP && N0 == N2) { 9904 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9905 DAG.getNode(ISD::FADD, DL, VT, N1, 9906 DAG.getConstantFP(1.0, DL, VT), Flags), 9907 Flags); 9908 } 9909 9910 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 9911 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 9912 return DAG.getNode(ISD::FMUL, DL, VT, N0, 9913 DAG.getNode(ISD::FADD, DL, VT, N1, 9914 DAG.getConstantFP(-1.0, DL, VT), Flags), 9915 Flags); 9916 } 9917 } 9918 9919 return SDValue(); 9920 } 9921 9922 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 9923 // reciprocal. 9924 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 9925 // Notice that this is not always beneficial. One reason is different targets 9926 // may have different costs for FDIV and FMUL, so sometimes the cost of two 9927 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 9928 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 9929 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 9930 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 9931 const SDNodeFlags Flags = N->getFlags(); 9932 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 9933 return SDValue(); 9934 9935 // Skip if current node is a reciprocal. 9936 SDValue N0 = N->getOperand(0); 9937 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9938 if (N0CFP && N0CFP->isExactlyValue(1.0)) 9939 return SDValue(); 9940 9941 // Exit early if the target does not want this transform or if there can't 9942 // possibly be enough uses of the divisor to make the transform worthwhile. 9943 SDValue N1 = N->getOperand(1); 9944 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 9945 if (!MinUses || N1->use_size() < MinUses) 9946 return SDValue(); 9947 9948 // Find all FDIV users of the same divisor. 9949 // Use a set because duplicates may be present in the user list. 9950 SetVector<SDNode *> Users; 9951 for (auto *U : N1->uses()) { 9952 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 9953 // This division is eligible for optimization only if global unsafe math 9954 // is enabled or if this division allows reciprocal formation. 9955 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 9956 Users.insert(U); 9957 } 9958 } 9959 9960 // Now that we have the actual number of divisor uses, make sure it meets 9961 // the minimum threshold specified by the target. 9962 if (Users.size() < MinUses) 9963 return SDValue(); 9964 9965 EVT VT = N->getValueType(0); 9966 SDLoc DL(N); 9967 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 9968 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 9969 9970 // Dividend / Divisor -> Dividend * Reciprocal 9971 for (auto *U : Users) { 9972 SDValue Dividend = U->getOperand(0); 9973 if (Dividend != FPOne) { 9974 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 9975 Reciprocal, Flags); 9976 CombineTo(U, NewNode); 9977 } else if (U != Reciprocal.getNode()) { 9978 // In the absence of fast-math-flags, this user node is always the 9979 // same node as Reciprocal, but with FMF they may be different nodes. 9980 CombineTo(U, Reciprocal); 9981 } 9982 } 9983 return SDValue(N, 0); // N was replaced. 9984 } 9985 9986 SDValue DAGCombiner::visitFDIV(SDNode *N) { 9987 SDValue N0 = N->getOperand(0); 9988 SDValue N1 = N->getOperand(1); 9989 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9990 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9991 EVT VT = N->getValueType(0); 9992 SDLoc DL(N); 9993 const TargetOptions &Options = DAG.getTarget().Options; 9994 SDNodeFlags Flags = N->getFlags(); 9995 9996 // fold vector ops 9997 if (VT.isVector()) 9998 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 9999 return FoldedVOp; 10000 10001 // fold (fdiv c1, c2) -> c1/c2 10002 if (N0CFP && N1CFP) 10003 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 10004 10005 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10006 return NewSel; 10007 10008 if (Options.UnsafeFPMath) { 10009 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 10010 if (N1CFP) { 10011 // Compute the reciprocal 1.0 / c2. 10012 const APFloat &N1APF = N1CFP->getValueAPF(); 10013 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 10014 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 10015 // Only do the transform if the reciprocal is a legal fp immediate that 10016 // isn't too nasty (eg NaN, denormal, ...). 10017 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 10018 (!LegalOperations || 10019 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 10020 // backend)... we should handle this gracefully after Legalize. 10021 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 10022 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 10023 TLI.isFPImmLegal(Recip, VT))) 10024 return DAG.getNode(ISD::FMUL, DL, VT, N0, 10025 DAG.getConstantFP(Recip, DL, VT), Flags); 10026 } 10027 10028 // If this FDIV is part of a reciprocal square root, it may be folded 10029 // into a target-specific square root estimate instruction. 10030 if (N1.getOpcode() == ISD::FSQRT) { 10031 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 10032 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10033 } 10034 } else if (N1.getOpcode() == ISD::FP_EXTEND && 10035 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10036 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10037 Flags)) { 10038 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 10039 AddToWorklist(RV.getNode()); 10040 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10041 } 10042 } else if (N1.getOpcode() == ISD::FP_ROUND && 10043 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10044 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 10045 Flags)) { 10046 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 10047 AddToWorklist(RV.getNode()); 10048 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10049 } 10050 } else if (N1.getOpcode() == ISD::FMUL) { 10051 // Look through an FMUL. Even though this won't remove the FDIV directly, 10052 // it's still worthwhile to get rid of the FSQRT if possible. 10053 SDValue SqrtOp; 10054 SDValue OtherOp; 10055 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 10056 SqrtOp = N1.getOperand(0); 10057 OtherOp = N1.getOperand(1); 10058 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 10059 SqrtOp = N1.getOperand(1); 10060 OtherOp = N1.getOperand(0); 10061 } 10062 if (SqrtOp.getNode()) { 10063 // We found a FSQRT, so try to make this fold: 10064 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 10065 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 10066 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 10067 AddToWorklist(RV.getNode()); 10068 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10069 } 10070 } 10071 } 10072 10073 // Fold into a reciprocal estimate and multiply instead of a real divide. 10074 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 10075 AddToWorklist(RV.getNode()); 10076 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 10077 } 10078 } 10079 10080 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 10081 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 10082 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 10083 // Both can be negated for free, check to see if at least one is cheaper 10084 // negated. 10085 if (LHSNeg == 2 || RHSNeg == 2) 10086 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 10087 GetNegatedExpression(N0, DAG, LegalOperations), 10088 GetNegatedExpression(N1, DAG, LegalOperations), 10089 Flags); 10090 } 10091 } 10092 10093 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 10094 return CombineRepeatedDivisors; 10095 10096 return SDValue(); 10097 } 10098 10099 SDValue DAGCombiner::visitFREM(SDNode *N) { 10100 SDValue N0 = N->getOperand(0); 10101 SDValue N1 = N->getOperand(1); 10102 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10103 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10104 EVT VT = N->getValueType(0); 10105 10106 // fold (frem c1, c2) -> fmod(c1,c2) 10107 if (N0CFP && N1CFP) 10108 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 10109 10110 if (SDValue NewSel = foldBinOpIntoSelect(N)) 10111 return NewSel; 10112 10113 return SDValue(); 10114 } 10115 10116 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 10117 if (!DAG.getTarget().Options.UnsafeFPMath) 10118 return SDValue(); 10119 10120 SDValue N0 = N->getOperand(0); 10121 if (TLI.isFsqrtCheap(N0, DAG)) 10122 return SDValue(); 10123 10124 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 10125 // For now, create a Flags object for use with all unsafe math transforms. 10126 SDNodeFlags Flags; 10127 Flags.setUnsafeAlgebra(true); 10128 return buildSqrtEstimate(N0, Flags); 10129 } 10130 10131 /// copysign(x, fp_extend(y)) -> copysign(x, y) 10132 /// copysign(x, fp_round(y)) -> copysign(x, y) 10133 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 10134 SDValue N1 = N->getOperand(1); 10135 if ((N1.getOpcode() == ISD::FP_EXTEND || 10136 N1.getOpcode() == ISD::FP_ROUND)) { 10137 // Do not optimize out type conversion of f128 type yet. 10138 // For some targets like x86_64, configuration is changed to keep one f128 10139 // value in one SSE register, but instruction selection cannot handle 10140 // FCOPYSIGN on SSE registers yet. 10141 EVT N1VT = N1->getValueType(0); 10142 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 10143 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 10144 } 10145 return false; 10146 } 10147 10148 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 10149 SDValue N0 = N->getOperand(0); 10150 SDValue N1 = N->getOperand(1); 10151 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10152 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 10153 EVT VT = N->getValueType(0); 10154 10155 if (N0CFP && N1CFP) // Constant fold 10156 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 10157 10158 if (N1CFP) { 10159 const APFloat &V = N1CFP->getValueAPF(); 10160 // copysign(x, c1) -> fabs(x) iff ispos(c1) 10161 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 10162 if (!V.isNegative()) { 10163 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 10164 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10165 } else { 10166 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 10167 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 10168 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 10169 } 10170 } 10171 10172 // copysign(fabs(x), y) -> copysign(x, y) 10173 // copysign(fneg(x), y) -> copysign(x, y) 10174 // copysign(copysign(x,z), y) -> copysign(x, y) 10175 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 10176 N0.getOpcode() == ISD::FCOPYSIGN) 10177 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 10178 10179 // copysign(x, abs(y)) -> abs(x) 10180 if (N1.getOpcode() == ISD::FABS) 10181 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10182 10183 // copysign(x, copysign(y,z)) -> copysign(x, z) 10184 if (N1.getOpcode() == ISD::FCOPYSIGN) 10185 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 10186 10187 // copysign(x, fp_extend(y)) -> copysign(x, y) 10188 // copysign(x, fp_round(y)) -> copysign(x, y) 10189 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 10190 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 10191 10192 return SDValue(); 10193 } 10194 10195 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 10196 SDValue N0 = N->getOperand(0); 10197 EVT VT = N->getValueType(0); 10198 EVT OpVT = N0.getValueType(); 10199 10200 // fold (sint_to_fp c1) -> c1fp 10201 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10202 // ...but only if the target supports immediate floating-point values 10203 (!LegalOperations || 10204 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 10205 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10206 10207 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 10208 // but UINT_TO_FP is legal on this target, try to convert. 10209 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 10210 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 10211 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 10212 if (DAG.SignBitIsZero(N0)) 10213 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10214 } 10215 10216 // The next optimizations are desirable only if SELECT_CC can be lowered. 10217 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10218 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10219 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 10220 !VT.isVector() && 10221 (!LegalOperations || 10222 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10223 SDLoc DL(N); 10224 SDValue Ops[] = 10225 { N0.getOperand(0), N0.getOperand(1), 10226 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10227 N0.getOperand(2) }; 10228 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10229 } 10230 10231 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 10232 // (select_cc x, y, 1.0, 0.0,, cc) 10233 if (N0.getOpcode() == ISD::ZERO_EXTEND && 10234 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 10235 (!LegalOperations || 10236 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10237 SDLoc DL(N); 10238 SDValue Ops[] = 10239 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 10240 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10241 N0.getOperand(0).getOperand(2) }; 10242 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10243 } 10244 } 10245 10246 return SDValue(); 10247 } 10248 10249 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 10250 SDValue N0 = N->getOperand(0); 10251 EVT VT = N->getValueType(0); 10252 EVT OpVT = N0.getValueType(); 10253 10254 // fold (uint_to_fp c1) -> c1fp 10255 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 10256 // ...but only if the target supports immediate floating-point values 10257 (!LegalOperations || 10258 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 10259 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 10260 10261 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 10262 // but SINT_TO_FP is legal on this target, try to convert. 10263 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 10264 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 10265 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 10266 if (DAG.SignBitIsZero(N0)) 10267 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 10268 } 10269 10270 // The next optimizations are desirable only if SELECT_CC can be lowered. 10271 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 10272 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 10273 10274 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 10275 (!LegalOperations || 10276 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 10277 SDLoc DL(N); 10278 SDValue Ops[] = 10279 { N0.getOperand(0), N0.getOperand(1), 10280 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 10281 N0.getOperand(2) }; 10282 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 10283 } 10284 } 10285 10286 return SDValue(); 10287 } 10288 10289 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 10290 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 10291 SDValue N0 = N->getOperand(0); 10292 EVT VT = N->getValueType(0); 10293 10294 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 10295 return SDValue(); 10296 10297 SDValue Src = N0.getOperand(0); 10298 EVT SrcVT = Src.getValueType(); 10299 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 10300 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 10301 10302 // We can safely assume the conversion won't overflow the output range, 10303 // because (for example) (uint8_t)18293.f is undefined behavior. 10304 10305 // Since we can assume the conversion won't overflow, our decision as to 10306 // whether the input will fit in the float should depend on the minimum 10307 // of the input range and output range. 10308 10309 // This means this is also safe for a signed input and unsigned output, since 10310 // a negative input would lead to undefined behavior. 10311 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 10312 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 10313 unsigned ActualSize = std::min(InputSize, OutputSize); 10314 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 10315 10316 // We can only fold away the float conversion if the input range can be 10317 // represented exactly in the float range. 10318 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 10319 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 10320 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 10321 : ISD::ZERO_EXTEND; 10322 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 10323 } 10324 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 10325 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 10326 return DAG.getBitcast(VT, Src); 10327 } 10328 return SDValue(); 10329 } 10330 10331 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 10332 SDValue N0 = N->getOperand(0); 10333 EVT VT = N->getValueType(0); 10334 10335 // fold (fp_to_sint c1fp) -> c1 10336 if (isConstantFPBuildVectorOrConstantFP(N0)) 10337 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 10338 10339 return FoldIntToFPToInt(N, DAG); 10340 } 10341 10342 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 10343 SDValue N0 = N->getOperand(0); 10344 EVT VT = N->getValueType(0); 10345 10346 // fold (fp_to_uint c1fp) -> c1 10347 if (isConstantFPBuildVectorOrConstantFP(N0)) 10348 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 10349 10350 return FoldIntToFPToInt(N, DAG); 10351 } 10352 10353 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 10354 SDValue N0 = N->getOperand(0); 10355 SDValue N1 = N->getOperand(1); 10356 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10357 EVT VT = N->getValueType(0); 10358 10359 // fold (fp_round c1fp) -> c1fp 10360 if (N0CFP) 10361 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 10362 10363 // fold (fp_round (fp_extend x)) -> x 10364 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 10365 return N0.getOperand(0); 10366 10367 // fold (fp_round (fp_round x)) -> (fp_round x) 10368 if (N0.getOpcode() == ISD::FP_ROUND) { 10369 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 10370 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 10371 10372 // Skip this folding if it results in an fp_round from f80 to f16. 10373 // 10374 // f80 to f16 always generates an expensive (and as yet, unimplemented) 10375 // libcall to __truncxfhf2 instead of selecting native f16 conversion 10376 // instructions from f32 or f64. Moreover, the first (value-preserving) 10377 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 10378 // x86. 10379 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 10380 return SDValue(); 10381 10382 // If the first fp_round isn't a value preserving truncation, it might 10383 // introduce a tie in the second fp_round, that wouldn't occur in the 10384 // single-step fp_round we want to fold to. 10385 // In other words, double rounding isn't the same as rounding. 10386 // Also, this is a value preserving truncation iff both fp_round's are. 10387 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 10388 SDLoc DL(N); 10389 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 10390 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 10391 } 10392 } 10393 10394 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 10395 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 10396 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 10397 N0.getOperand(0), N1); 10398 AddToWorklist(Tmp.getNode()); 10399 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 10400 Tmp, N0.getOperand(1)); 10401 } 10402 10403 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10404 return NewVSel; 10405 10406 return SDValue(); 10407 } 10408 10409 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 10410 SDValue N0 = N->getOperand(0); 10411 EVT VT = N->getValueType(0); 10412 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 10413 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 10414 10415 // fold (fp_round_inreg c1fp) -> c1fp 10416 if (N0CFP && isTypeLegal(EVT)) { 10417 SDLoc DL(N); 10418 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 10419 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 10420 } 10421 10422 return SDValue(); 10423 } 10424 10425 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 10426 SDValue N0 = N->getOperand(0); 10427 EVT VT = N->getValueType(0); 10428 10429 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 10430 if (N->hasOneUse() && 10431 N->use_begin()->getOpcode() == ISD::FP_ROUND) 10432 return SDValue(); 10433 10434 // fold (fp_extend c1fp) -> c1fp 10435 if (isConstantFPBuildVectorOrConstantFP(N0)) 10436 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 10437 10438 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 10439 if (N0.getOpcode() == ISD::FP16_TO_FP && 10440 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 10441 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 10442 10443 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 10444 // value of X. 10445 if (N0.getOpcode() == ISD::FP_ROUND 10446 && N0.getConstantOperandVal(1) == 1) { 10447 SDValue In = N0.getOperand(0); 10448 if (In.getValueType() == VT) return In; 10449 if (VT.bitsLT(In.getValueType())) 10450 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 10451 In, N0.getOperand(1)); 10452 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 10453 } 10454 10455 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 10456 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10457 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 10458 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10459 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 10460 LN0->getChain(), 10461 LN0->getBasePtr(), N0.getValueType(), 10462 LN0->getMemOperand()); 10463 CombineTo(N, ExtLoad); 10464 CombineTo(N0.getNode(), 10465 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 10466 N0.getValueType(), ExtLoad, 10467 DAG.getIntPtrConstant(1, SDLoc(N0))), 10468 ExtLoad.getValue(1)); 10469 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10470 } 10471 10472 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10473 return NewVSel; 10474 10475 return SDValue(); 10476 } 10477 10478 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 10479 SDValue N0 = N->getOperand(0); 10480 EVT VT = N->getValueType(0); 10481 10482 // fold (fceil c1) -> fceil(c1) 10483 if (isConstantFPBuildVectorOrConstantFP(N0)) 10484 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 10485 10486 return SDValue(); 10487 } 10488 10489 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 10490 SDValue N0 = N->getOperand(0); 10491 EVT VT = N->getValueType(0); 10492 10493 // fold (ftrunc c1) -> ftrunc(c1) 10494 if (isConstantFPBuildVectorOrConstantFP(N0)) 10495 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 10496 10497 return SDValue(); 10498 } 10499 10500 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 10501 SDValue N0 = N->getOperand(0); 10502 EVT VT = N->getValueType(0); 10503 10504 // fold (ffloor c1) -> ffloor(c1) 10505 if (isConstantFPBuildVectorOrConstantFP(N0)) 10506 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 10507 10508 return SDValue(); 10509 } 10510 10511 // FIXME: FNEG and FABS have a lot in common; refactor. 10512 SDValue DAGCombiner::visitFNEG(SDNode *N) { 10513 SDValue N0 = N->getOperand(0); 10514 EVT VT = N->getValueType(0); 10515 10516 // Constant fold FNEG. 10517 if (isConstantFPBuildVectorOrConstantFP(N0)) 10518 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 10519 10520 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 10521 &DAG.getTarget().Options)) 10522 return GetNegatedExpression(N0, DAG, LegalOperations); 10523 10524 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 10525 // constant pool values. 10526 if (!TLI.isFNegFree(VT) && 10527 N0.getOpcode() == ISD::BITCAST && 10528 N0.getNode()->hasOneUse()) { 10529 SDValue Int = N0.getOperand(0); 10530 EVT IntVT = Int.getValueType(); 10531 if (IntVT.isInteger() && !IntVT.isVector()) { 10532 APInt SignMask; 10533 if (N0.getValueType().isVector()) { 10534 // For a vector, get a mask such as 0x80... per scalar element 10535 // and splat it. 10536 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 10537 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10538 } else { 10539 // For a scalar, just generate 0x80... 10540 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 10541 } 10542 SDLoc DL0(N0); 10543 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 10544 DAG.getConstant(SignMask, DL0, IntVT)); 10545 AddToWorklist(Int.getNode()); 10546 return DAG.getBitcast(VT, Int); 10547 } 10548 } 10549 10550 // (fneg (fmul c, x)) -> (fmul -c, x) 10551 if (N0.getOpcode() == ISD::FMUL && 10552 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 10553 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10554 if (CFP1) { 10555 APFloat CVal = CFP1->getValueAPF(); 10556 CVal.changeSign(); 10557 if (Level >= AfterLegalizeDAG && 10558 (TLI.isFPImmLegal(CVal, VT) || 10559 TLI.isOperationLegal(ISD::ConstantFP, VT))) 10560 return DAG.getNode( 10561 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 10562 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 10563 N0->getFlags()); 10564 } 10565 } 10566 10567 return SDValue(); 10568 } 10569 10570 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 10571 SDValue N0 = N->getOperand(0); 10572 SDValue N1 = N->getOperand(1); 10573 EVT VT = N->getValueType(0); 10574 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10575 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10576 10577 if (N0CFP && N1CFP) { 10578 const APFloat &C0 = N0CFP->getValueAPF(); 10579 const APFloat &C1 = N1CFP->getValueAPF(); 10580 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 10581 } 10582 10583 // Canonicalize to constant on RHS. 10584 if (isConstantFPBuildVectorOrConstantFP(N0) && 10585 !isConstantFPBuildVectorOrConstantFP(N1)) 10586 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 10587 10588 return SDValue(); 10589 } 10590 10591 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 10592 SDValue N0 = N->getOperand(0); 10593 SDValue N1 = N->getOperand(1); 10594 EVT VT = N->getValueType(0); 10595 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 10596 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 10597 10598 if (N0CFP && N1CFP) { 10599 const APFloat &C0 = N0CFP->getValueAPF(); 10600 const APFloat &C1 = N1CFP->getValueAPF(); 10601 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 10602 } 10603 10604 // Canonicalize to constant on RHS. 10605 if (isConstantFPBuildVectorOrConstantFP(N0) && 10606 !isConstantFPBuildVectorOrConstantFP(N1)) 10607 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 10608 10609 return SDValue(); 10610 } 10611 10612 SDValue DAGCombiner::visitFABS(SDNode *N) { 10613 SDValue N0 = N->getOperand(0); 10614 EVT VT = N->getValueType(0); 10615 10616 // fold (fabs c1) -> fabs(c1) 10617 if (isConstantFPBuildVectorOrConstantFP(N0)) 10618 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 10619 10620 // fold (fabs (fabs x)) -> (fabs x) 10621 if (N0.getOpcode() == ISD::FABS) 10622 return N->getOperand(0); 10623 10624 // fold (fabs (fneg x)) -> (fabs x) 10625 // fold (fabs (fcopysign x, y)) -> (fabs x) 10626 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 10627 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 10628 10629 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 10630 // constant pool values. 10631 if (!TLI.isFAbsFree(VT) && 10632 N0.getOpcode() == ISD::BITCAST && 10633 N0.getNode()->hasOneUse()) { 10634 SDValue Int = N0.getOperand(0); 10635 EVT IntVT = Int.getValueType(); 10636 if (IntVT.isInteger() && !IntVT.isVector()) { 10637 APInt SignMask; 10638 if (N0.getValueType().isVector()) { 10639 // For a vector, get a mask such as 0x7f... per scalar element 10640 // and splat it. 10641 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 10642 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 10643 } else { 10644 // For a scalar, just generate 0x7f... 10645 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 10646 } 10647 SDLoc DL(N0); 10648 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 10649 DAG.getConstant(SignMask, DL, IntVT)); 10650 AddToWorklist(Int.getNode()); 10651 return DAG.getBitcast(N->getValueType(0), Int); 10652 } 10653 } 10654 10655 return SDValue(); 10656 } 10657 10658 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 10659 SDValue Chain = N->getOperand(0); 10660 SDValue N1 = N->getOperand(1); 10661 SDValue N2 = N->getOperand(2); 10662 10663 // If N is a constant we could fold this into a fallthrough or unconditional 10664 // branch. However that doesn't happen very often in normal code, because 10665 // Instcombine/SimplifyCFG should have handled the available opportunities. 10666 // If we did this folding here, it would be necessary to update the 10667 // MachineBasicBlock CFG, which is awkward. 10668 10669 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 10670 // on the target. 10671 if (N1.getOpcode() == ISD::SETCC && 10672 TLI.isOperationLegalOrCustom(ISD::BR_CC, 10673 N1.getOperand(0).getValueType())) { 10674 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10675 Chain, N1.getOperand(2), 10676 N1.getOperand(0), N1.getOperand(1), N2); 10677 } 10678 10679 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 10680 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 10681 (N1.getOperand(0).hasOneUse() && 10682 N1.getOperand(0).getOpcode() == ISD::SRL))) { 10683 SDNode *Trunc = nullptr; 10684 if (N1.getOpcode() == ISD::TRUNCATE) { 10685 // Look pass the truncate. 10686 Trunc = N1.getNode(); 10687 N1 = N1.getOperand(0); 10688 } 10689 10690 // Match this pattern so that we can generate simpler code: 10691 // 10692 // %a = ... 10693 // %b = and i32 %a, 2 10694 // %c = srl i32 %b, 1 10695 // brcond i32 %c ... 10696 // 10697 // into 10698 // 10699 // %a = ... 10700 // %b = and i32 %a, 2 10701 // %c = setcc eq %b, 0 10702 // brcond %c ... 10703 // 10704 // This applies only when the AND constant value has one bit set and the 10705 // SRL constant is equal to the log2 of the AND constant. The back-end is 10706 // smart enough to convert the result into a TEST/JMP sequence. 10707 SDValue Op0 = N1.getOperand(0); 10708 SDValue Op1 = N1.getOperand(1); 10709 10710 if (Op0.getOpcode() == ISD::AND && 10711 Op1.getOpcode() == ISD::Constant) { 10712 SDValue AndOp1 = Op0.getOperand(1); 10713 10714 if (AndOp1.getOpcode() == ISD::Constant) { 10715 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 10716 10717 if (AndConst.isPowerOf2() && 10718 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 10719 SDLoc DL(N); 10720 SDValue SetCC = 10721 DAG.getSetCC(DL, 10722 getSetCCResultType(Op0.getValueType()), 10723 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 10724 ISD::SETNE); 10725 10726 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 10727 MVT::Other, Chain, SetCC, N2); 10728 // Don't add the new BRCond into the worklist or else SimplifySelectCC 10729 // will convert it back to (X & C1) >> C2. 10730 CombineTo(N, NewBRCond, false); 10731 // Truncate is dead. 10732 if (Trunc) 10733 deleteAndRecombine(Trunc); 10734 // Replace the uses of SRL with SETCC 10735 WorklistRemover DeadNodes(*this); 10736 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10737 deleteAndRecombine(N1.getNode()); 10738 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10739 } 10740 } 10741 } 10742 10743 if (Trunc) 10744 // Restore N1 if the above transformation doesn't match. 10745 N1 = N->getOperand(1); 10746 } 10747 10748 // Transform br(xor(x, y)) -> br(x != y) 10749 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 10750 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 10751 SDNode *TheXor = N1.getNode(); 10752 SDValue Op0 = TheXor->getOperand(0); 10753 SDValue Op1 = TheXor->getOperand(1); 10754 if (Op0.getOpcode() == Op1.getOpcode()) { 10755 // Avoid missing important xor optimizations. 10756 if (SDValue Tmp = visitXOR(TheXor)) { 10757 if (Tmp.getNode() != TheXor) { 10758 DEBUG(dbgs() << "\nReplacing.8 "; 10759 TheXor->dump(&DAG); 10760 dbgs() << "\nWith: "; 10761 Tmp.getNode()->dump(&DAG); 10762 dbgs() << '\n'); 10763 WorklistRemover DeadNodes(*this); 10764 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 10765 deleteAndRecombine(TheXor); 10766 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10767 MVT::Other, Chain, Tmp, N2); 10768 } 10769 10770 // visitXOR has changed XOR's operands or replaced the XOR completely, 10771 // bail out. 10772 return SDValue(N, 0); 10773 } 10774 } 10775 10776 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 10777 bool Equal = false; 10778 if (isOneConstant(Op0) && Op0.hasOneUse() && 10779 Op0.getOpcode() == ISD::XOR) { 10780 TheXor = Op0.getNode(); 10781 Equal = true; 10782 } 10783 10784 EVT SetCCVT = N1.getValueType(); 10785 if (LegalTypes) 10786 SetCCVT = getSetCCResultType(SetCCVT); 10787 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 10788 SetCCVT, 10789 Op0, Op1, 10790 Equal ? ISD::SETEQ : ISD::SETNE); 10791 // Replace the uses of XOR with SETCC 10792 WorklistRemover DeadNodes(*this); 10793 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 10794 deleteAndRecombine(N1.getNode()); 10795 return DAG.getNode(ISD::BRCOND, SDLoc(N), 10796 MVT::Other, Chain, SetCC, N2); 10797 } 10798 } 10799 10800 return SDValue(); 10801 } 10802 10803 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 10804 // 10805 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 10806 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 10807 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 10808 10809 // If N is a constant we could fold this into a fallthrough or unconditional 10810 // branch. However that doesn't happen very often in normal code, because 10811 // Instcombine/SimplifyCFG should have handled the available opportunities. 10812 // If we did this folding here, it would be necessary to update the 10813 // MachineBasicBlock CFG, which is awkward. 10814 10815 // Use SimplifySetCC to simplify SETCC's. 10816 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 10817 CondLHS, CondRHS, CC->get(), SDLoc(N), 10818 false); 10819 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 10820 10821 // fold to a simpler setcc 10822 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 10823 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 10824 N->getOperand(0), Simp.getOperand(2), 10825 Simp.getOperand(0), Simp.getOperand(1), 10826 N->getOperand(4)); 10827 10828 return SDValue(); 10829 } 10830 10831 /// Return true if 'Use' is a load or a store that uses N as its base pointer 10832 /// and that N may be folded in the load / store addressing mode. 10833 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 10834 SelectionDAG &DAG, 10835 const TargetLowering &TLI) { 10836 EVT VT; 10837 unsigned AS; 10838 10839 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 10840 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 10841 return false; 10842 VT = LD->getMemoryVT(); 10843 AS = LD->getAddressSpace(); 10844 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 10845 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 10846 return false; 10847 VT = ST->getMemoryVT(); 10848 AS = ST->getAddressSpace(); 10849 } else 10850 return false; 10851 10852 TargetLowering::AddrMode AM; 10853 if (N->getOpcode() == ISD::ADD) { 10854 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10855 if (Offset) 10856 // [reg +/- imm] 10857 AM.BaseOffs = Offset->getSExtValue(); 10858 else 10859 // [reg +/- reg] 10860 AM.Scale = 1; 10861 } else if (N->getOpcode() == ISD::SUB) { 10862 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10863 if (Offset) 10864 // [reg +/- imm] 10865 AM.BaseOffs = -Offset->getSExtValue(); 10866 else 10867 // [reg +/- reg] 10868 AM.Scale = 1; 10869 } else 10870 return false; 10871 10872 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 10873 VT.getTypeForEVT(*DAG.getContext()), AS); 10874 } 10875 10876 /// Try turning a load/store into a pre-indexed load/store when the base 10877 /// pointer is an add or subtract and it has other uses besides the load/store. 10878 /// After the transformation, the new indexed load/store has effectively folded 10879 /// the add/subtract in and all of its other uses are redirected to the 10880 /// new load/store. 10881 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 10882 if (Level < AfterLegalizeDAG) 10883 return false; 10884 10885 bool isLoad = true; 10886 SDValue Ptr; 10887 EVT VT; 10888 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10889 if (LD->isIndexed()) 10890 return false; 10891 VT = LD->getMemoryVT(); 10892 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 10893 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 10894 return false; 10895 Ptr = LD->getBasePtr(); 10896 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10897 if (ST->isIndexed()) 10898 return false; 10899 VT = ST->getMemoryVT(); 10900 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 10901 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 10902 return false; 10903 Ptr = ST->getBasePtr(); 10904 isLoad = false; 10905 } else { 10906 return false; 10907 } 10908 10909 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 10910 // out. There is no reason to make this a preinc/predec. 10911 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 10912 Ptr.getNode()->hasOneUse()) 10913 return false; 10914 10915 // Ask the target to do addressing mode selection. 10916 SDValue BasePtr; 10917 SDValue Offset; 10918 ISD::MemIndexedMode AM = ISD::UNINDEXED; 10919 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 10920 return false; 10921 10922 // Backends without true r+i pre-indexed forms may need to pass a 10923 // constant base with a variable offset so that constant coercion 10924 // will work with the patterns in canonical form. 10925 bool Swapped = false; 10926 if (isa<ConstantSDNode>(BasePtr)) { 10927 std::swap(BasePtr, Offset); 10928 Swapped = true; 10929 } 10930 10931 // Don't create a indexed load / store with zero offset. 10932 if (isNullConstant(Offset)) 10933 return false; 10934 10935 // Try turning it into a pre-indexed load / store except when: 10936 // 1) The new base ptr is a frame index. 10937 // 2) If N is a store and the new base ptr is either the same as or is a 10938 // predecessor of the value being stored. 10939 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 10940 // that would create a cycle. 10941 // 4) All uses are load / store ops that use it as old base ptr. 10942 10943 // Check #1. Preinc'ing a frame index would require copying the stack pointer 10944 // (plus the implicit offset) to a register to preinc anyway. 10945 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 10946 return false; 10947 10948 // Check #2. 10949 if (!isLoad) { 10950 SDValue Val = cast<StoreSDNode>(N)->getValue(); 10951 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 10952 return false; 10953 } 10954 10955 // Caches for hasPredecessorHelper. 10956 SmallPtrSet<const SDNode *, 32> Visited; 10957 SmallVector<const SDNode *, 16> Worklist; 10958 Worklist.push_back(N); 10959 10960 // If the offset is a constant, there may be other adds of constants that 10961 // can be folded with this one. We should do this to avoid having to keep 10962 // a copy of the original base pointer. 10963 SmallVector<SDNode *, 16> OtherUses; 10964 if (isa<ConstantSDNode>(Offset)) 10965 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 10966 UE = BasePtr.getNode()->use_end(); 10967 UI != UE; ++UI) { 10968 SDUse &Use = UI.getUse(); 10969 // Skip the use that is Ptr and uses of other results from BasePtr's 10970 // node (important for nodes that return multiple results). 10971 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 10972 continue; 10973 10974 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 10975 continue; 10976 10977 if (Use.getUser()->getOpcode() != ISD::ADD && 10978 Use.getUser()->getOpcode() != ISD::SUB) { 10979 OtherUses.clear(); 10980 break; 10981 } 10982 10983 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 10984 if (!isa<ConstantSDNode>(Op1)) { 10985 OtherUses.clear(); 10986 break; 10987 } 10988 10989 // FIXME: In some cases, we can be smarter about this. 10990 if (Op1.getValueType() != Offset.getValueType()) { 10991 OtherUses.clear(); 10992 break; 10993 } 10994 10995 OtherUses.push_back(Use.getUser()); 10996 } 10997 10998 if (Swapped) 10999 std::swap(BasePtr, Offset); 11000 11001 // Now check for #3 and #4. 11002 bool RealUse = false; 11003 11004 for (SDNode *Use : Ptr.getNode()->uses()) { 11005 if (Use == N) 11006 continue; 11007 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 11008 return false; 11009 11010 // If Ptr may be folded in addressing mode of other use, then it's 11011 // not profitable to do this transformation. 11012 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 11013 RealUse = true; 11014 } 11015 11016 if (!RealUse) 11017 return false; 11018 11019 SDValue Result; 11020 if (isLoad) 11021 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11022 BasePtr, Offset, AM); 11023 else 11024 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11025 BasePtr, Offset, AM); 11026 ++PreIndexedNodes; 11027 ++NodesCombined; 11028 DEBUG(dbgs() << "\nReplacing.4 "; 11029 N->dump(&DAG); 11030 dbgs() << "\nWith: "; 11031 Result.getNode()->dump(&DAG); 11032 dbgs() << '\n'); 11033 WorklistRemover DeadNodes(*this); 11034 if (isLoad) { 11035 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11036 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11037 } else { 11038 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11039 } 11040 11041 // Finally, since the node is now dead, remove it from the graph. 11042 deleteAndRecombine(N); 11043 11044 if (Swapped) 11045 std::swap(BasePtr, Offset); 11046 11047 // Replace other uses of BasePtr that can be updated to use Ptr 11048 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 11049 unsigned OffsetIdx = 1; 11050 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 11051 OffsetIdx = 0; 11052 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 11053 BasePtr.getNode() && "Expected BasePtr operand"); 11054 11055 // We need to replace ptr0 in the following expression: 11056 // x0 * offset0 + y0 * ptr0 = t0 11057 // knowing that 11058 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 11059 // 11060 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 11061 // indexed load/store and the expresion that needs to be re-written. 11062 // 11063 // Therefore, we have: 11064 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 11065 11066 ConstantSDNode *CN = 11067 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 11068 int X0, X1, Y0, Y1; 11069 const APInt &Offset0 = CN->getAPIntValue(); 11070 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 11071 11072 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 11073 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 11074 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 11075 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 11076 11077 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 11078 11079 APInt CNV = Offset0; 11080 if (X0 < 0) CNV = -CNV; 11081 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 11082 else CNV = CNV - Offset1; 11083 11084 SDLoc DL(OtherUses[i]); 11085 11086 // We can now generate the new expression. 11087 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 11088 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 11089 11090 SDValue NewUse = DAG.getNode(Opcode, 11091 DL, 11092 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 11093 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 11094 deleteAndRecombine(OtherUses[i]); 11095 } 11096 11097 // Replace the uses of Ptr with uses of the updated base value. 11098 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 11099 deleteAndRecombine(Ptr.getNode()); 11100 11101 return true; 11102 } 11103 11104 /// Try to combine a load/store with a add/sub of the base pointer node into a 11105 /// post-indexed load/store. The transformation folded the add/subtract into the 11106 /// new indexed load/store effectively and all of its uses are redirected to the 11107 /// new load/store. 11108 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 11109 if (Level < AfterLegalizeDAG) 11110 return false; 11111 11112 bool isLoad = true; 11113 SDValue Ptr; 11114 EVT VT; 11115 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11116 if (LD->isIndexed()) 11117 return false; 11118 VT = LD->getMemoryVT(); 11119 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 11120 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 11121 return false; 11122 Ptr = LD->getBasePtr(); 11123 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11124 if (ST->isIndexed()) 11125 return false; 11126 VT = ST->getMemoryVT(); 11127 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 11128 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 11129 return false; 11130 Ptr = ST->getBasePtr(); 11131 isLoad = false; 11132 } else { 11133 return false; 11134 } 11135 11136 if (Ptr.getNode()->hasOneUse()) 11137 return false; 11138 11139 for (SDNode *Op : Ptr.getNode()->uses()) { 11140 if (Op == N || 11141 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 11142 continue; 11143 11144 SDValue BasePtr; 11145 SDValue Offset; 11146 ISD::MemIndexedMode AM = ISD::UNINDEXED; 11147 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 11148 // Don't create a indexed load / store with zero offset. 11149 if (isNullConstant(Offset)) 11150 continue; 11151 11152 // Try turning it into a post-indexed load / store except when 11153 // 1) All uses are load / store ops that use it as base ptr (and 11154 // it may be folded as addressing mmode). 11155 // 2) Op must be independent of N, i.e. Op is neither a predecessor 11156 // nor a successor of N. Otherwise, if Op is folded that would 11157 // create a cycle. 11158 11159 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 11160 continue; 11161 11162 // Check for #1. 11163 bool TryNext = false; 11164 for (SDNode *Use : BasePtr.getNode()->uses()) { 11165 if (Use == Ptr.getNode()) 11166 continue; 11167 11168 // If all the uses are load / store addresses, then don't do the 11169 // transformation. 11170 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 11171 bool RealUse = false; 11172 for (SDNode *UseUse : Use->uses()) { 11173 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 11174 RealUse = true; 11175 } 11176 11177 if (!RealUse) { 11178 TryNext = true; 11179 break; 11180 } 11181 } 11182 } 11183 11184 if (TryNext) 11185 continue; 11186 11187 // Check for #2 11188 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 11189 SDValue Result = isLoad 11190 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 11191 BasePtr, Offset, AM) 11192 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 11193 BasePtr, Offset, AM); 11194 ++PostIndexedNodes; 11195 ++NodesCombined; 11196 DEBUG(dbgs() << "\nReplacing.5 "; 11197 N->dump(&DAG); 11198 dbgs() << "\nWith: "; 11199 Result.getNode()->dump(&DAG); 11200 dbgs() << '\n'); 11201 WorklistRemover DeadNodes(*this); 11202 if (isLoad) { 11203 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 11204 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 11205 } else { 11206 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 11207 } 11208 11209 // Finally, since the node is now dead, remove it from the graph. 11210 deleteAndRecombine(N); 11211 11212 // Replace the uses of Use with uses of the updated base value. 11213 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 11214 Result.getValue(isLoad ? 1 : 0)); 11215 deleteAndRecombine(Op); 11216 return true; 11217 } 11218 } 11219 } 11220 11221 return false; 11222 } 11223 11224 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 11225 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 11226 ISD::MemIndexedMode AM = LD->getAddressingMode(); 11227 assert(AM != ISD::UNINDEXED); 11228 SDValue BP = LD->getOperand(1); 11229 SDValue Inc = LD->getOperand(2); 11230 11231 // Some backends use TargetConstants for load offsets, but don't expect 11232 // TargetConstants in general ADD nodes. We can convert these constants into 11233 // regular Constants (if the constant is not opaque). 11234 assert((Inc.getOpcode() != ISD::TargetConstant || 11235 !cast<ConstantSDNode>(Inc)->isOpaque()) && 11236 "Cannot split out indexing using opaque target constants"); 11237 if (Inc.getOpcode() == ISD::TargetConstant) { 11238 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 11239 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 11240 ConstInc->getValueType(0)); 11241 } 11242 11243 unsigned Opc = 11244 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 11245 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 11246 } 11247 11248 SDValue DAGCombiner::visitLOAD(SDNode *N) { 11249 LoadSDNode *LD = cast<LoadSDNode>(N); 11250 SDValue Chain = LD->getChain(); 11251 SDValue Ptr = LD->getBasePtr(); 11252 11253 // If load is not volatile and there are no uses of the loaded value (and 11254 // the updated indexed value in case of indexed loads), change uses of the 11255 // chain value into uses of the chain input (i.e. delete the dead load). 11256 if (!LD->isVolatile()) { 11257 if (N->getValueType(1) == MVT::Other) { 11258 // Unindexed loads. 11259 if (!N->hasAnyUseOfValue(0)) { 11260 // It's not safe to use the two value CombineTo variant here. e.g. 11261 // v1, chain2 = load chain1, loc 11262 // v2, chain3 = load chain2, loc 11263 // v3 = add v2, c 11264 // Now we replace use of chain2 with chain1. This makes the second load 11265 // isomorphic to the one we are deleting, and thus makes this load live. 11266 DEBUG(dbgs() << "\nReplacing.6 "; 11267 N->dump(&DAG); 11268 dbgs() << "\nWith chain: "; 11269 Chain.getNode()->dump(&DAG); 11270 dbgs() << "\n"); 11271 WorklistRemover DeadNodes(*this); 11272 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11273 AddUsersToWorklist(Chain.getNode()); 11274 if (N->use_empty()) 11275 deleteAndRecombine(N); 11276 11277 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11278 } 11279 } else { 11280 // Indexed loads. 11281 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 11282 11283 // If this load has an opaque TargetConstant offset, then we cannot split 11284 // the indexing into an add/sub directly (that TargetConstant may not be 11285 // valid for a different type of node, and we cannot convert an opaque 11286 // target constant into a regular constant). 11287 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 11288 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 11289 11290 if (!N->hasAnyUseOfValue(0) && 11291 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 11292 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 11293 SDValue Index; 11294 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 11295 Index = SplitIndexingFromLoad(LD); 11296 // Try to fold the base pointer arithmetic into subsequent loads and 11297 // stores. 11298 AddUsersToWorklist(N); 11299 } else 11300 Index = DAG.getUNDEF(N->getValueType(1)); 11301 DEBUG(dbgs() << "\nReplacing.7 "; 11302 N->dump(&DAG); 11303 dbgs() << "\nWith: "; 11304 Undef.getNode()->dump(&DAG); 11305 dbgs() << " and 2 other values\n"); 11306 WorklistRemover DeadNodes(*this); 11307 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 11308 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 11309 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 11310 deleteAndRecombine(N); 11311 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11312 } 11313 } 11314 } 11315 11316 // If this load is directly stored, replace the load value with the stored 11317 // value. 11318 // TODO: Handle store large -> read small portion. 11319 // TODO: Handle TRUNCSTORE/LOADEXT 11320 if (OptLevel != CodeGenOpt::None && 11321 ISD::isNormalLoad(N) && !LD->isVolatile()) { 11322 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 11323 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 11324 if (PrevST->getBasePtr() == Ptr && 11325 PrevST->getValue().getValueType() == N->getValueType(0)) 11326 return CombineTo(N, PrevST->getOperand(1), Chain); 11327 } 11328 } 11329 11330 // Try to infer better alignment information than the load already has. 11331 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 11332 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11333 if (Align > LD->getMemOperand()->getBaseAlignment()) { 11334 SDValue NewLoad = DAG.getExtLoad( 11335 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 11336 LD->getPointerInfo(), LD->getMemoryVT(), Align, 11337 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11338 if (NewLoad.getNode() != N) 11339 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 11340 } 11341 } 11342 } 11343 11344 if (LD->isUnindexed()) { 11345 // Walk up chain skipping non-aliasing memory nodes. 11346 SDValue BetterChain = FindBetterChain(N, Chain); 11347 11348 // If there is a better chain. 11349 if (Chain != BetterChain) { 11350 SDValue ReplLoad; 11351 11352 // Replace the chain to void dependency. 11353 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 11354 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 11355 BetterChain, Ptr, LD->getMemOperand()); 11356 } else { 11357 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 11358 LD->getValueType(0), 11359 BetterChain, Ptr, LD->getMemoryVT(), 11360 LD->getMemOperand()); 11361 } 11362 11363 // Create token factor to keep old chain connected. 11364 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11365 MVT::Other, Chain, ReplLoad.getValue(1)); 11366 11367 // Make sure the new and old chains are cleaned up. 11368 AddToWorklist(Token.getNode()); 11369 11370 // Replace uses with load result and token factor. Don't add users 11371 // to work list. 11372 return CombineTo(N, ReplLoad.getValue(0), Token, false); 11373 } 11374 } 11375 11376 // Try transforming N to an indexed load. 11377 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11378 return SDValue(N, 0); 11379 11380 // Try to slice up N to more direct loads if the slices are mapped to 11381 // different register banks or pairing can take place. 11382 if (SliceUpLoad(N)) 11383 return SDValue(N, 0); 11384 11385 return SDValue(); 11386 } 11387 11388 namespace { 11389 /// \brief Helper structure used to slice a load in smaller loads. 11390 /// Basically a slice is obtained from the following sequence: 11391 /// Origin = load Ty1, Base 11392 /// Shift = srl Ty1 Origin, CstTy Amount 11393 /// Inst = trunc Shift to Ty2 11394 /// 11395 /// Then, it will be rewriten into: 11396 /// Slice = load SliceTy, Base + SliceOffset 11397 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 11398 /// 11399 /// SliceTy is deduced from the number of bits that are actually used to 11400 /// build Inst. 11401 struct LoadedSlice { 11402 /// \brief Helper structure used to compute the cost of a slice. 11403 struct Cost { 11404 /// Are we optimizing for code size. 11405 bool ForCodeSize; 11406 /// Various cost. 11407 unsigned Loads; 11408 unsigned Truncates; 11409 unsigned CrossRegisterBanksCopies; 11410 unsigned ZExts; 11411 unsigned Shift; 11412 11413 Cost(bool ForCodeSize = false) 11414 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 11415 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 11416 11417 /// \brief Get the cost of one isolated slice. 11418 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 11419 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 11420 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 11421 EVT TruncType = LS.Inst->getValueType(0); 11422 EVT LoadedType = LS.getLoadedType(); 11423 if (TruncType != LoadedType && 11424 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 11425 ZExts = 1; 11426 } 11427 11428 /// \brief Account for slicing gain in the current cost. 11429 /// Slicing provide a few gains like removing a shift or a 11430 /// truncate. This method allows to grow the cost of the original 11431 /// load with the gain from this slice. 11432 void addSliceGain(const LoadedSlice &LS) { 11433 // Each slice saves a truncate. 11434 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 11435 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 11436 LS.Inst->getValueType(0))) 11437 ++Truncates; 11438 // If there is a shift amount, this slice gets rid of it. 11439 if (LS.Shift) 11440 ++Shift; 11441 // If this slice can merge a cross register bank copy, account for it. 11442 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 11443 ++CrossRegisterBanksCopies; 11444 } 11445 11446 Cost &operator+=(const Cost &RHS) { 11447 Loads += RHS.Loads; 11448 Truncates += RHS.Truncates; 11449 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 11450 ZExts += RHS.ZExts; 11451 Shift += RHS.Shift; 11452 return *this; 11453 } 11454 11455 bool operator==(const Cost &RHS) const { 11456 return Loads == RHS.Loads && Truncates == RHS.Truncates && 11457 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 11458 ZExts == RHS.ZExts && Shift == RHS.Shift; 11459 } 11460 11461 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 11462 11463 bool operator<(const Cost &RHS) const { 11464 // Assume cross register banks copies are as expensive as loads. 11465 // FIXME: Do we want some more target hooks? 11466 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 11467 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 11468 // Unless we are optimizing for code size, consider the 11469 // expensive operation first. 11470 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 11471 return ExpensiveOpsLHS < ExpensiveOpsRHS; 11472 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 11473 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 11474 } 11475 11476 bool operator>(const Cost &RHS) const { return RHS < *this; } 11477 11478 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 11479 11480 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 11481 }; 11482 // The last instruction that represent the slice. This should be a 11483 // truncate instruction. 11484 SDNode *Inst; 11485 // The original load instruction. 11486 LoadSDNode *Origin; 11487 // The right shift amount in bits from the original load. 11488 unsigned Shift; 11489 // The DAG from which Origin came from. 11490 // This is used to get some contextual information about legal types, etc. 11491 SelectionDAG *DAG; 11492 11493 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 11494 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 11495 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 11496 11497 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 11498 /// \return Result is \p BitWidth and has used bits set to 1 and 11499 /// not used bits set to 0. 11500 APInt getUsedBits() const { 11501 // Reproduce the trunc(lshr) sequence: 11502 // - Start from the truncated value. 11503 // - Zero extend to the desired bit width. 11504 // - Shift left. 11505 assert(Origin && "No original load to compare against."); 11506 unsigned BitWidth = Origin->getValueSizeInBits(0); 11507 assert(Inst && "This slice is not bound to an instruction"); 11508 assert(Inst->getValueSizeInBits(0) <= BitWidth && 11509 "Extracted slice is bigger than the whole type!"); 11510 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 11511 UsedBits.setAllBits(); 11512 UsedBits = UsedBits.zext(BitWidth); 11513 UsedBits <<= Shift; 11514 return UsedBits; 11515 } 11516 11517 /// \brief Get the size of the slice to be loaded in bytes. 11518 unsigned getLoadedSize() const { 11519 unsigned SliceSize = getUsedBits().countPopulation(); 11520 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 11521 return SliceSize / 8; 11522 } 11523 11524 /// \brief Get the type that will be loaded for this slice. 11525 /// Note: This may not be the final type for the slice. 11526 EVT getLoadedType() const { 11527 assert(DAG && "Missing context"); 11528 LLVMContext &Ctxt = *DAG->getContext(); 11529 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 11530 } 11531 11532 /// \brief Get the alignment of the load used for this slice. 11533 unsigned getAlignment() const { 11534 unsigned Alignment = Origin->getAlignment(); 11535 unsigned Offset = getOffsetFromBase(); 11536 if (Offset != 0) 11537 Alignment = MinAlign(Alignment, Alignment + Offset); 11538 return Alignment; 11539 } 11540 11541 /// \brief Check if this slice can be rewritten with legal operations. 11542 bool isLegal() const { 11543 // An invalid slice is not legal. 11544 if (!Origin || !Inst || !DAG) 11545 return false; 11546 11547 // Offsets are for indexed load only, we do not handle that. 11548 if (!Origin->getOffset().isUndef()) 11549 return false; 11550 11551 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11552 11553 // Check that the type is legal. 11554 EVT SliceType = getLoadedType(); 11555 if (!TLI.isTypeLegal(SliceType)) 11556 return false; 11557 11558 // Check that the load is legal for this type. 11559 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 11560 return false; 11561 11562 // Check that the offset can be computed. 11563 // 1. Check its type. 11564 EVT PtrType = Origin->getBasePtr().getValueType(); 11565 if (PtrType == MVT::Untyped || PtrType.isExtended()) 11566 return false; 11567 11568 // 2. Check that it fits in the immediate. 11569 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 11570 return false; 11571 11572 // 3. Check that the computation is legal. 11573 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 11574 return false; 11575 11576 // Check that the zext is legal if it needs one. 11577 EVT TruncateType = Inst->getValueType(0); 11578 if (TruncateType != SliceType && 11579 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 11580 return false; 11581 11582 return true; 11583 } 11584 11585 /// \brief Get the offset in bytes of this slice in the original chunk of 11586 /// bits. 11587 /// \pre DAG != nullptr. 11588 uint64_t getOffsetFromBase() const { 11589 assert(DAG && "Missing context."); 11590 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 11591 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 11592 uint64_t Offset = Shift / 8; 11593 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 11594 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 11595 "The size of the original loaded type is not a multiple of a" 11596 " byte."); 11597 // If Offset is bigger than TySizeInBytes, it means we are loading all 11598 // zeros. This should have been optimized before in the process. 11599 assert(TySizeInBytes > Offset && 11600 "Invalid shift amount for given loaded size"); 11601 if (IsBigEndian) 11602 Offset = TySizeInBytes - Offset - getLoadedSize(); 11603 return Offset; 11604 } 11605 11606 /// \brief Generate the sequence of instructions to load the slice 11607 /// represented by this object and redirect the uses of this slice to 11608 /// this new sequence of instructions. 11609 /// \pre this->Inst && this->Origin are valid Instructions and this 11610 /// object passed the legal check: LoadedSlice::isLegal returned true. 11611 /// \return The last instruction of the sequence used to load the slice. 11612 SDValue loadSlice() const { 11613 assert(Inst && Origin && "Unable to replace a non-existing slice."); 11614 const SDValue &OldBaseAddr = Origin->getBasePtr(); 11615 SDValue BaseAddr = OldBaseAddr; 11616 // Get the offset in that chunk of bytes w.r.t. the endianness. 11617 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 11618 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 11619 if (Offset) { 11620 // BaseAddr = BaseAddr + Offset. 11621 EVT ArithType = BaseAddr.getValueType(); 11622 SDLoc DL(Origin); 11623 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 11624 DAG->getConstant(Offset, DL, ArithType)); 11625 } 11626 11627 // Create the type of the loaded slice according to its size. 11628 EVT SliceType = getLoadedType(); 11629 11630 // Create the load for the slice. 11631 SDValue LastInst = 11632 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 11633 Origin->getPointerInfo().getWithOffset(Offset), 11634 getAlignment(), Origin->getMemOperand()->getFlags()); 11635 // If the final type is not the same as the loaded type, this means that 11636 // we have to pad with zero. Create a zero extend for that. 11637 EVT FinalType = Inst->getValueType(0); 11638 if (SliceType != FinalType) 11639 LastInst = 11640 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 11641 return LastInst; 11642 } 11643 11644 /// \brief Check if this slice can be merged with an expensive cross register 11645 /// bank copy. E.g., 11646 /// i = load i32 11647 /// f = bitcast i32 i to float 11648 bool canMergeExpensiveCrossRegisterBankCopy() const { 11649 if (!Inst || !Inst->hasOneUse()) 11650 return false; 11651 SDNode *Use = *Inst->use_begin(); 11652 if (Use->getOpcode() != ISD::BITCAST) 11653 return false; 11654 assert(DAG && "Missing context"); 11655 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 11656 EVT ResVT = Use->getValueType(0); 11657 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 11658 const TargetRegisterClass *ArgRC = 11659 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 11660 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 11661 return false; 11662 11663 // At this point, we know that we perform a cross-register-bank copy. 11664 // Check if it is expensive. 11665 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 11666 // Assume bitcasts are cheap, unless both register classes do not 11667 // explicitly share a common sub class. 11668 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 11669 return false; 11670 11671 // Check if it will be merged with the load. 11672 // 1. Check the alignment constraint. 11673 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 11674 ResVT.getTypeForEVT(*DAG->getContext())); 11675 11676 if (RequiredAlignment > getAlignment()) 11677 return false; 11678 11679 // 2. Check that the load is a legal operation for that type. 11680 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 11681 return false; 11682 11683 // 3. Check that we do not have a zext in the way. 11684 if (Inst->getValueType(0) != getLoadedType()) 11685 return false; 11686 11687 return true; 11688 } 11689 }; 11690 } 11691 11692 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 11693 /// \p UsedBits looks like 0..0 1..1 0..0. 11694 static bool areUsedBitsDense(const APInt &UsedBits) { 11695 // If all the bits are one, this is dense! 11696 if (UsedBits.isAllOnesValue()) 11697 return true; 11698 11699 // Get rid of the unused bits on the right. 11700 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 11701 // Get rid of the unused bits on the left. 11702 if (NarrowedUsedBits.countLeadingZeros()) 11703 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 11704 // Check that the chunk of bits is completely used. 11705 return NarrowedUsedBits.isAllOnesValue(); 11706 } 11707 11708 /// \brief Check whether or not \p First and \p Second are next to each other 11709 /// in memory. This means that there is no hole between the bits loaded 11710 /// by \p First and the bits loaded by \p Second. 11711 static bool areSlicesNextToEachOther(const LoadedSlice &First, 11712 const LoadedSlice &Second) { 11713 assert(First.Origin == Second.Origin && First.Origin && 11714 "Unable to match different memory origins."); 11715 APInt UsedBits = First.getUsedBits(); 11716 assert((UsedBits & Second.getUsedBits()) == 0 && 11717 "Slices are not supposed to overlap."); 11718 UsedBits |= Second.getUsedBits(); 11719 return areUsedBitsDense(UsedBits); 11720 } 11721 11722 /// \brief Adjust the \p GlobalLSCost according to the target 11723 /// paring capabilities and the layout of the slices. 11724 /// \pre \p GlobalLSCost should account for at least as many loads as 11725 /// there is in the slices in \p LoadedSlices. 11726 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11727 LoadedSlice::Cost &GlobalLSCost) { 11728 unsigned NumberOfSlices = LoadedSlices.size(); 11729 // If there is less than 2 elements, no pairing is possible. 11730 if (NumberOfSlices < 2) 11731 return; 11732 11733 // Sort the slices so that elements that are likely to be next to each 11734 // other in memory are next to each other in the list. 11735 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 11736 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 11737 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 11738 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 11739 }); 11740 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 11741 // First (resp. Second) is the first (resp. Second) potentially candidate 11742 // to be placed in a paired load. 11743 const LoadedSlice *First = nullptr; 11744 const LoadedSlice *Second = nullptr; 11745 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 11746 // Set the beginning of the pair. 11747 First = Second) { 11748 11749 Second = &LoadedSlices[CurrSlice]; 11750 11751 // If First is NULL, it means we start a new pair. 11752 // Get to the next slice. 11753 if (!First) 11754 continue; 11755 11756 EVT LoadedType = First->getLoadedType(); 11757 11758 // If the types of the slices are different, we cannot pair them. 11759 if (LoadedType != Second->getLoadedType()) 11760 continue; 11761 11762 // Check if the target supplies paired loads for this type. 11763 unsigned RequiredAlignment = 0; 11764 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 11765 // move to the next pair, this type is hopeless. 11766 Second = nullptr; 11767 continue; 11768 } 11769 // Check if we meet the alignment requirement. 11770 if (RequiredAlignment > First->getAlignment()) 11771 continue; 11772 11773 // Check that both loads are next to each other in memory. 11774 if (!areSlicesNextToEachOther(*First, *Second)) 11775 continue; 11776 11777 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 11778 --GlobalLSCost.Loads; 11779 // Move to the next pair. 11780 Second = nullptr; 11781 } 11782 } 11783 11784 /// \brief Check the profitability of all involved LoadedSlice. 11785 /// Currently, it is considered profitable if there is exactly two 11786 /// involved slices (1) which are (2) next to each other in memory, and 11787 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 11788 /// 11789 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 11790 /// the elements themselves. 11791 /// 11792 /// FIXME: When the cost model will be mature enough, we can relax 11793 /// constraints (1) and (2). 11794 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 11795 const APInt &UsedBits, bool ForCodeSize) { 11796 unsigned NumberOfSlices = LoadedSlices.size(); 11797 if (StressLoadSlicing) 11798 return NumberOfSlices > 1; 11799 11800 // Check (1). 11801 if (NumberOfSlices != 2) 11802 return false; 11803 11804 // Check (2). 11805 if (!areUsedBitsDense(UsedBits)) 11806 return false; 11807 11808 // Check (3). 11809 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 11810 // The original code has one big load. 11811 OrigCost.Loads = 1; 11812 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 11813 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 11814 // Accumulate the cost of all the slices. 11815 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 11816 GlobalSlicingCost += SliceCost; 11817 11818 // Account as cost in the original configuration the gain obtained 11819 // with the current slices. 11820 OrigCost.addSliceGain(LS); 11821 } 11822 11823 // If the target supports paired load, adjust the cost accordingly. 11824 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 11825 return OrigCost > GlobalSlicingCost; 11826 } 11827 11828 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 11829 /// operations, split it in the various pieces being extracted. 11830 /// 11831 /// This sort of thing is introduced by SROA. 11832 /// This slicing takes care not to insert overlapping loads. 11833 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 11834 bool DAGCombiner::SliceUpLoad(SDNode *N) { 11835 if (Level < AfterLegalizeDAG) 11836 return false; 11837 11838 LoadSDNode *LD = cast<LoadSDNode>(N); 11839 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 11840 !LD->getValueType(0).isInteger()) 11841 return false; 11842 11843 // Keep track of already used bits to detect overlapping values. 11844 // In that case, we will just abort the transformation. 11845 APInt UsedBits(LD->getValueSizeInBits(0), 0); 11846 11847 SmallVector<LoadedSlice, 4> LoadedSlices; 11848 11849 // Check if this load is used as several smaller chunks of bits. 11850 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 11851 // of computation for each trunc. 11852 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 11853 UI != UIEnd; ++UI) { 11854 // Skip the uses of the chain. 11855 if (UI.getUse().getResNo() != 0) 11856 continue; 11857 11858 SDNode *User = *UI; 11859 unsigned Shift = 0; 11860 11861 // Check if this is a trunc(lshr). 11862 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 11863 isa<ConstantSDNode>(User->getOperand(1))) { 11864 Shift = User->getConstantOperandVal(1); 11865 User = *User->use_begin(); 11866 } 11867 11868 // At this point, User is a Truncate, iff we encountered, trunc or 11869 // trunc(lshr). 11870 if (User->getOpcode() != ISD::TRUNCATE) 11871 return false; 11872 11873 // The width of the type must be a power of 2 and greater than 8-bits. 11874 // Otherwise the load cannot be represented in LLVM IR. 11875 // Moreover, if we shifted with a non-8-bits multiple, the slice 11876 // will be across several bytes. We do not support that. 11877 unsigned Width = User->getValueSizeInBits(0); 11878 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 11879 return 0; 11880 11881 // Build the slice for this chain of computations. 11882 LoadedSlice LS(User, LD, Shift, &DAG); 11883 APInt CurrentUsedBits = LS.getUsedBits(); 11884 11885 // Check if this slice overlaps with another. 11886 if ((CurrentUsedBits & UsedBits) != 0) 11887 return false; 11888 // Update the bits used globally. 11889 UsedBits |= CurrentUsedBits; 11890 11891 // Check if the new slice would be legal. 11892 if (!LS.isLegal()) 11893 return false; 11894 11895 // Record the slice. 11896 LoadedSlices.push_back(LS); 11897 } 11898 11899 // Abort slicing if it does not seem to be profitable. 11900 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 11901 return false; 11902 11903 ++SlicedLoads; 11904 11905 // Rewrite each chain to use an independent load. 11906 // By construction, each chain can be represented by a unique load. 11907 11908 // Prepare the argument for the new token factor for all the slices. 11909 SmallVector<SDValue, 8> ArgChains; 11910 for (SmallVectorImpl<LoadedSlice>::const_iterator 11911 LSIt = LoadedSlices.begin(), 11912 LSItEnd = LoadedSlices.end(); 11913 LSIt != LSItEnd; ++LSIt) { 11914 SDValue SliceInst = LSIt->loadSlice(); 11915 CombineTo(LSIt->Inst, SliceInst, true); 11916 if (SliceInst.getOpcode() != ISD::LOAD) 11917 SliceInst = SliceInst.getOperand(0); 11918 assert(SliceInst->getOpcode() == ISD::LOAD && 11919 "It takes more than a zext to get to the loaded slice!!"); 11920 ArgChains.push_back(SliceInst.getValue(1)); 11921 } 11922 11923 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 11924 ArgChains); 11925 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 11926 AddToWorklist(Chain.getNode()); 11927 return true; 11928 } 11929 11930 /// Check to see if V is (and load (ptr), imm), where the load is having 11931 /// specific bytes cleared out. If so, return the byte size being masked out 11932 /// and the shift amount. 11933 static std::pair<unsigned, unsigned> 11934 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 11935 std::pair<unsigned, unsigned> Result(0, 0); 11936 11937 // Check for the structure we're looking for. 11938 if (V->getOpcode() != ISD::AND || 11939 !isa<ConstantSDNode>(V->getOperand(1)) || 11940 !ISD::isNormalLoad(V->getOperand(0).getNode())) 11941 return Result; 11942 11943 // Check the chain and pointer. 11944 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 11945 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 11946 11947 // The store should be chained directly to the load or be an operand of a 11948 // tokenfactor. 11949 if (LD == Chain.getNode()) 11950 ; // ok. 11951 else if (Chain->getOpcode() != ISD::TokenFactor) 11952 return Result; // Fail. 11953 else { 11954 bool isOk = false; 11955 for (const SDValue &ChainOp : Chain->op_values()) 11956 if (ChainOp.getNode() == LD) { 11957 isOk = true; 11958 break; 11959 } 11960 if (!isOk) return Result; 11961 } 11962 11963 // This only handles simple types. 11964 if (V.getValueType() != MVT::i16 && 11965 V.getValueType() != MVT::i32 && 11966 V.getValueType() != MVT::i64) 11967 return Result; 11968 11969 // Check the constant mask. Invert it so that the bits being masked out are 11970 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 11971 // follow the sign bit for uniformity. 11972 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 11973 unsigned NotMaskLZ = countLeadingZeros(NotMask); 11974 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 11975 unsigned NotMaskTZ = countTrailingZeros(NotMask); 11976 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 11977 if (NotMaskLZ == 64) return Result; // All zero mask. 11978 11979 // See if we have a continuous run of bits. If so, we have 0*1+0* 11980 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 11981 return Result; 11982 11983 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 11984 if (V.getValueType() != MVT::i64 && NotMaskLZ) 11985 NotMaskLZ -= 64-V.getValueSizeInBits(); 11986 11987 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 11988 switch (MaskedBytes) { 11989 case 1: 11990 case 2: 11991 case 4: break; 11992 default: return Result; // All one mask, or 5-byte mask. 11993 } 11994 11995 // Verify that the first bit starts at a multiple of mask so that the access 11996 // is aligned the same as the access width. 11997 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 11998 11999 Result.first = MaskedBytes; 12000 Result.second = NotMaskTZ/8; 12001 return Result; 12002 } 12003 12004 12005 /// Check to see if IVal is something that provides a value as specified by 12006 /// MaskInfo. If so, replace the specified store with a narrower store of 12007 /// truncated IVal. 12008 static SDNode * 12009 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 12010 SDValue IVal, StoreSDNode *St, 12011 DAGCombiner *DC) { 12012 unsigned NumBytes = MaskInfo.first; 12013 unsigned ByteShift = MaskInfo.second; 12014 SelectionDAG &DAG = DC->getDAG(); 12015 12016 // Check to see if IVal is all zeros in the part being masked in by the 'or' 12017 // that uses this. If not, this is not a replacement. 12018 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 12019 ByteShift*8, (ByteShift+NumBytes)*8); 12020 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 12021 12022 // Check that it is legal on the target to do this. It is legal if the new 12023 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 12024 // legalization. 12025 MVT VT = MVT::getIntegerVT(NumBytes*8); 12026 if (!DC->isTypeLegal(VT)) 12027 return nullptr; 12028 12029 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 12030 // shifted by ByteShift and truncated down to NumBytes. 12031 if (ByteShift) { 12032 SDLoc DL(IVal); 12033 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 12034 DAG.getConstant(ByteShift*8, DL, 12035 DC->getShiftAmountTy(IVal.getValueType()))); 12036 } 12037 12038 // Figure out the offset for the store and the alignment of the access. 12039 unsigned StOffset; 12040 unsigned NewAlign = St->getAlignment(); 12041 12042 if (DAG.getDataLayout().isLittleEndian()) 12043 StOffset = ByteShift; 12044 else 12045 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 12046 12047 SDValue Ptr = St->getBasePtr(); 12048 if (StOffset) { 12049 SDLoc DL(IVal); 12050 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 12051 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 12052 NewAlign = MinAlign(NewAlign, StOffset); 12053 } 12054 12055 // Truncate down to the new size. 12056 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 12057 12058 ++OpsNarrowed; 12059 return DAG 12060 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 12061 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 12062 .getNode(); 12063 } 12064 12065 12066 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 12067 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 12068 /// narrowing the load and store if it would end up being a win for performance 12069 /// or code size. 12070 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 12071 StoreSDNode *ST = cast<StoreSDNode>(N); 12072 if (ST->isVolatile()) 12073 return SDValue(); 12074 12075 SDValue Chain = ST->getChain(); 12076 SDValue Value = ST->getValue(); 12077 SDValue Ptr = ST->getBasePtr(); 12078 EVT VT = Value.getValueType(); 12079 12080 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 12081 return SDValue(); 12082 12083 unsigned Opc = Value.getOpcode(); 12084 12085 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 12086 // is a byte mask indicating a consecutive number of bytes, check to see if 12087 // Y is known to provide just those bytes. If so, we try to replace the 12088 // load + replace + store sequence with a single (narrower) store, which makes 12089 // the load dead. 12090 if (Opc == ISD::OR) { 12091 std::pair<unsigned, unsigned> MaskedLoad; 12092 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 12093 if (MaskedLoad.first) 12094 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12095 Value.getOperand(1), ST,this)) 12096 return SDValue(NewST, 0); 12097 12098 // Or is commutative, so try swapping X and Y. 12099 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 12100 if (MaskedLoad.first) 12101 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 12102 Value.getOperand(0), ST,this)) 12103 return SDValue(NewST, 0); 12104 } 12105 12106 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 12107 Value.getOperand(1).getOpcode() != ISD::Constant) 12108 return SDValue(); 12109 12110 SDValue N0 = Value.getOperand(0); 12111 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12112 Chain == SDValue(N0.getNode(), 1)) { 12113 LoadSDNode *LD = cast<LoadSDNode>(N0); 12114 if (LD->getBasePtr() != Ptr || 12115 LD->getPointerInfo().getAddrSpace() != 12116 ST->getPointerInfo().getAddrSpace()) 12117 return SDValue(); 12118 12119 // Find the type to narrow it the load / op / store to. 12120 SDValue N1 = Value.getOperand(1); 12121 unsigned BitWidth = N1.getValueSizeInBits(); 12122 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 12123 if (Opc == ISD::AND) 12124 Imm ^= APInt::getAllOnesValue(BitWidth); 12125 if (Imm == 0 || Imm.isAllOnesValue()) 12126 return SDValue(); 12127 unsigned ShAmt = Imm.countTrailingZeros(); 12128 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 12129 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 12130 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12131 // The narrowing should be profitable, the load/store operation should be 12132 // legal (or custom) and the store size should be equal to the NewVT width. 12133 while (NewBW < BitWidth && 12134 (NewVT.getStoreSizeInBits() != NewBW || 12135 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 12136 !TLI.isNarrowingProfitable(VT, NewVT))) { 12137 NewBW = NextPowerOf2(NewBW); 12138 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 12139 } 12140 if (NewBW >= BitWidth) 12141 return SDValue(); 12142 12143 // If the lsb changed does not start at the type bitwidth boundary, 12144 // start at the previous one. 12145 if (ShAmt % NewBW) 12146 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 12147 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 12148 std::min(BitWidth, ShAmt + NewBW)); 12149 if ((Imm & Mask) == Imm) { 12150 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 12151 if (Opc == ISD::AND) 12152 NewImm ^= APInt::getAllOnesValue(NewBW); 12153 uint64_t PtrOff = ShAmt / 8; 12154 // For big endian targets, we need to adjust the offset to the pointer to 12155 // load the correct bytes. 12156 if (DAG.getDataLayout().isBigEndian()) 12157 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 12158 12159 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 12160 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 12161 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 12162 return SDValue(); 12163 12164 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 12165 Ptr.getValueType(), Ptr, 12166 DAG.getConstant(PtrOff, SDLoc(LD), 12167 Ptr.getValueType())); 12168 SDValue NewLD = 12169 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 12170 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 12171 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 12172 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 12173 DAG.getConstant(NewImm, SDLoc(Value), 12174 NewVT)); 12175 SDValue NewST = 12176 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 12177 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 12178 12179 AddToWorklist(NewPtr.getNode()); 12180 AddToWorklist(NewLD.getNode()); 12181 AddToWorklist(NewVal.getNode()); 12182 WorklistRemover DeadNodes(*this); 12183 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 12184 ++OpsNarrowed; 12185 return NewST; 12186 } 12187 } 12188 12189 return SDValue(); 12190 } 12191 12192 /// For a given floating point load / store pair, if the load value isn't used 12193 /// by any other operations, then consider transforming the pair to integer 12194 /// load / store operations if the target deems the transformation profitable. 12195 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 12196 StoreSDNode *ST = cast<StoreSDNode>(N); 12197 SDValue Chain = ST->getChain(); 12198 SDValue Value = ST->getValue(); 12199 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 12200 Value.hasOneUse() && 12201 Chain == SDValue(Value.getNode(), 1)) { 12202 LoadSDNode *LD = cast<LoadSDNode>(Value); 12203 EVT VT = LD->getMemoryVT(); 12204 if (!VT.isFloatingPoint() || 12205 VT != ST->getMemoryVT() || 12206 LD->isNonTemporal() || 12207 ST->isNonTemporal() || 12208 LD->getPointerInfo().getAddrSpace() != 0 || 12209 ST->getPointerInfo().getAddrSpace() != 0) 12210 return SDValue(); 12211 12212 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 12213 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 12214 !TLI.isOperationLegal(ISD::STORE, IntVT) || 12215 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 12216 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 12217 return SDValue(); 12218 12219 unsigned LDAlign = LD->getAlignment(); 12220 unsigned STAlign = ST->getAlignment(); 12221 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 12222 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 12223 if (LDAlign < ABIAlign || STAlign < ABIAlign) 12224 return SDValue(); 12225 12226 SDValue NewLD = 12227 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 12228 LD->getPointerInfo(), LDAlign); 12229 12230 SDValue NewST = 12231 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 12232 ST->getPointerInfo(), STAlign); 12233 12234 AddToWorklist(NewLD.getNode()); 12235 AddToWorklist(NewST.getNode()); 12236 WorklistRemover DeadNodes(*this); 12237 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 12238 ++LdStFP2Int; 12239 return NewST; 12240 } 12241 12242 return SDValue(); 12243 } 12244 12245 // This is a helper function for visitMUL to check the profitability 12246 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 12247 // MulNode is the original multiply, AddNode is (add x, c1), 12248 // and ConstNode is c2. 12249 // 12250 // If the (add x, c1) has multiple uses, we could increase 12251 // the number of adds if we make this transformation. 12252 // It would only be worth doing this if we can remove a 12253 // multiply in the process. Check for that here. 12254 // To illustrate: 12255 // (A + c1) * c3 12256 // (A + c2) * c3 12257 // We're checking for cases where we have common "c3 * A" expressions. 12258 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 12259 SDValue &AddNode, 12260 SDValue &ConstNode) { 12261 APInt Val; 12262 12263 // If the add only has one use, this would be OK to do. 12264 if (AddNode.getNode()->hasOneUse()) 12265 return true; 12266 12267 // Walk all the users of the constant with which we're multiplying. 12268 for (SDNode *Use : ConstNode->uses()) { 12269 12270 if (Use == MulNode) // This use is the one we're on right now. Skip it. 12271 continue; 12272 12273 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 12274 SDNode *OtherOp; 12275 SDNode *MulVar = AddNode.getOperand(0).getNode(); 12276 12277 // OtherOp is what we're multiplying against the constant. 12278 if (Use->getOperand(0) == ConstNode) 12279 OtherOp = Use->getOperand(1).getNode(); 12280 else 12281 OtherOp = Use->getOperand(0).getNode(); 12282 12283 // Check to see if multiply is with the same operand of our "add". 12284 // 12285 // ConstNode = CONST 12286 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 12287 // ... 12288 // AddNode = (A + c1) <-- MulVar is A. 12289 // = AddNode * ConstNode <-- current visiting instruction. 12290 // 12291 // If we make this transformation, we will have a common 12292 // multiply (ConstNode * A) that we can save. 12293 if (OtherOp == MulVar) 12294 return true; 12295 12296 // Now check to see if a future expansion will give us a common 12297 // multiply. 12298 // 12299 // ConstNode = CONST 12300 // AddNode = (A + c1) 12301 // ... = AddNode * ConstNode <-- current visiting instruction. 12302 // ... 12303 // OtherOp = (A + c2) 12304 // Use = OtherOp * ConstNode <-- visiting Use. 12305 // 12306 // If we make this transformation, we will have a common 12307 // multiply (CONST * A) after we also do the same transformation 12308 // to the "t2" instruction. 12309 if (OtherOp->getOpcode() == ISD::ADD && 12310 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 12311 OtherOp->getOperand(0).getNode() == MulVar) 12312 return true; 12313 } 12314 } 12315 12316 // Didn't find a case where this would be profitable. 12317 return false; 12318 } 12319 12320 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 12321 unsigned NumStores) { 12322 SmallVector<SDValue, 8> Chains; 12323 SmallPtrSet<const SDNode *, 8> Visited; 12324 SDLoc StoreDL(StoreNodes[0].MemNode); 12325 12326 for (unsigned i = 0; i < NumStores; ++i) { 12327 Visited.insert(StoreNodes[i].MemNode); 12328 } 12329 12330 // don't include nodes that are children 12331 for (unsigned i = 0; i < NumStores; ++i) { 12332 if (Visited.count(StoreNodes[i].MemNode->getChain().getNode()) == 0) 12333 Chains.push_back(StoreNodes[i].MemNode->getChain()); 12334 } 12335 12336 assert(Chains.size() > 0 && "Chain should have generated a chain"); 12337 return DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, Chains); 12338 } 12339 12340 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 12341 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 12342 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 12343 // Make sure we have something to merge. 12344 if (NumStores < 2) 12345 return false; 12346 12347 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12348 12349 // The latest Node in the DAG. 12350 SDLoc DL(StoreNodes[0].MemNode); 12351 12352 SDValue StoredVal; 12353 if (UseVector) { 12354 bool IsVec = MemVT.isVector(); 12355 unsigned Elts = NumStores; 12356 if (IsVec) { 12357 // When merging vector stores, get the total number of elements. 12358 Elts *= MemVT.getVectorNumElements(); 12359 } 12360 // Get the type for the merged vector store. 12361 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12362 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 12363 12364 if (IsConstantSrc) { 12365 SmallVector<SDValue, 8> BuildVector; 12366 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 12367 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 12368 SDValue Val = St->getValue(); 12369 if (MemVT.getScalarType().isInteger()) 12370 if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue())) 12371 Val = DAG.getConstant( 12372 (uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(), 12373 SDLoc(CFP), MemVT); 12374 BuildVector.push_back(Val); 12375 } 12376 StoredVal = DAG.getBuildVector(Ty, DL, BuildVector); 12377 } else { 12378 SmallVector<SDValue, 8> Ops; 12379 for (unsigned i = 0; i < NumStores; ++i) { 12380 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12381 SDValue Val = St->getValue(); 12382 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 12383 if (Val.getValueType() != MemVT) 12384 return false; 12385 Ops.push_back(Val); 12386 } 12387 12388 // Build the extracted vector elements back into a vector. 12389 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 12390 DL, Ty, Ops); } 12391 } else { 12392 // We should always use a vector store when merging extracted vector 12393 // elements, so this path implies a store of constants. 12394 assert(IsConstantSrc && "Merged vector elements should use vector store"); 12395 12396 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 12397 APInt StoreInt(SizeInBits, 0); 12398 12399 // Construct a single integer constant which is made of the smaller 12400 // constant inputs. 12401 bool IsLE = DAG.getDataLayout().isLittleEndian(); 12402 for (unsigned i = 0; i < NumStores; ++i) { 12403 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 12404 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 12405 12406 SDValue Val = St->getValue(); 12407 StoreInt <<= ElementSizeBytes * 8; 12408 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 12409 StoreInt |= C->getAPIntValue().zext(SizeInBits); 12410 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 12411 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 12412 } else { 12413 llvm_unreachable("Invalid constant element type"); 12414 } 12415 } 12416 12417 // Create the new Load and Store operations. 12418 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 12419 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 12420 } 12421 12422 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12423 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 12424 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 12425 FirstInChain->getBasePtr(), 12426 FirstInChain->getPointerInfo(), 12427 FirstInChain->getAlignment()); 12428 12429 // Replace all merged stores with the new store. 12430 for (unsigned i = 0; i < NumStores; ++i) 12431 CombineTo(StoreNodes[i].MemNode, NewStore); 12432 12433 AddToWorklist(NewChain.getNode()); 12434 return true; 12435 } 12436 12437 void DAGCombiner::getStoreMergeCandidates( 12438 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) { 12439 // This holds the base pointer, index, and the offset in bytes from the base 12440 // pointer. 12441 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 12442 EVT MemVT = St->getMemoryVT(); 12443 12444 // We must have a base and an offset. 12445 if (!BasePtr.Base.getNode()) 12446 return; 12447 12448 // Do not handle stores to undef base pointers. 12449 if (BasePtr.Base.isUndef()) 12450 return; 12451 12452 bool IsLoadSrc = isa<LoadSDNode>(St->getValue()); 12453 bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) || 12454 isa<ConstantFPSDNode>(St->getValue()); 12455 bool IsExtractVecSrc = 12456 (St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12457 St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR); 12458 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr) -> bool { 12459 if (Other->isVolatile() || Other->isIndexed()) 12460 return false; 12461 // We can merge constant floats to equivalent integers 12462 if (Other->getMemoryVT() != MemVT) 12463 if (!(MemVT.isInteger() && MemVT.bitsEq(Other->getMemoryVT()) && 12464 isa<ConstantFPSDNode>(Other->getValue()))) 12465 return false; 12466 if (IsLoadSrc) 12467 if (!isa<LoadSDNode>(Other->getValue())) 12468 return false; 12469 if (IsConstantSrc) 12470 if (!(isa<ConstantSDNode>(Other->getValue()) || 12471 isa<ConstantFPSDNode>(Other->getValue()))) 12472 return false; 12473 if (IsExtractVecSrc) 12474 if (!(Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12475 Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR)) 12476 return false; 12477 Ptr = BaseIndexOffset::match(Other->getBasePtr(), DAG); 12478 return (Ptr.equalBaseIndex(BasePtr)); 12479 }; 12480 // We looking for a root node which is an ancestor to all mergable 12481 // stores. We search up through a load, to our root and then down 12482 // through all children. For instance we will find Store{1,2,3} if 12483 // St is Store1, Store2. or Store3 where the root is not a load 12484 // which always true for nonvolatile ops. TODO: Expand 12485 // the search to find all valid candidates through multiple layers of loads. 12486 // 12487 // Root 12488 // |-------|-------| 12489 // Load Load Store3 12490 // | | 12491 // Store1 Store2 12492 // 12493 // FIXME: We should be able to climb and 12494 // descend TokenFactors to find candidates as well. 12495 12496 SDNode *RootNode = (St->getChain()).getNode(); 12497 12498 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 12499 RootNode = Ldn->getChain().getNode(); 12500 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12501 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 12502 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 12503 if (I2.getOperandNo() == 0) 12504 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 12505 BaseIndexOffset Ptr; 12506 if (CandidateMatch(OtherST, Ptr)) 12507 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset)); 12508 } 12509 } else 12510 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 12511 if (I.getOperandNo() == 0) 12512 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 12513 BaseIndexOffset Ptr; 12514 if (CandidateMatch(OtherST, Ptr)) 12515 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset)); 12516 } 12517 } 12518 12519 // We need to check that merging these stores does not cause a loop 12520 // in the DAG. Any store candidate may depend on another candidate 12521 // indirectly through its operand (we already consider dependencies 12522 // through the chain). Check in parallel by searching up from 12523 // non-chain operands of candidates. 12524 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 12525 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores) { 12526 SmallPtrSet<const SDNode *, 16> Visited; 12527 SmallVector<const SDNode *, 8> Worklist; 12528 // search ops of store candidates 12529 for (unsigned i = 0; i < NumStores; ++i) { 12530 SDNode *n = StoreNodes[i].MemNode; 12531 // Potential loops may happen only through non-chain operands 12532 for (unsigned j = 1; j < n->getNumOperands(); ++j) 12533 Worklist.push_back(n->getOperand(j).getNode()); 12534 } 12535 // search through DAG. We can stop early if we find a storenode 12536 for (unsigned i = 0; i < NumStores; ++i) { 12537 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 12538 return false; 12539 } 12540 return true; 12541 } 12542 12543 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 12544 if (OptLevel == CodeGenOpt::None) 12545 return false; 12546 12547 EVT MemVT = St->getMemoryVT(); 12548 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 12549 12550 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 12551 return false; 12552 12553 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 12554 Attribute::NoImplicitFloat); 12555 12556 // This function cannot currently deal with non-byte-sized memory sizes. 12557 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 12558 return false; 12559 12560 if (!MemVT.isSimple()) 12561 return false; 12562 12563 // Perform an early exit check. Do not bother looking at stored values that 12564 // are not constants, loads, or extracted vector elements. 12565 SDValue StoredVal = St->getValue(); 12566 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 12567 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 12568 isa<ConstantFPSDNode>(StoredVal); 12569 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 12570 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 12571 12572 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 12573 return false; 12574 12575 // Don't merge vectors into wider vectors if the source data comes from loads. 12576 // TODO: This restriction can be lifted by using logic similar to the 12577 // ExtractVecSrc case. 12578 if (MemVT.isVector() && IsLoadSrc) 12579 return false; 12580 12581 SmallVector<MemOpLink, 8> StoreNodes; 12582 // Find potential store merge candidates by searching through chain sub-DAG 12583 getStoreMergeCandidates(St, StoreNodes); 12584 12585 // Check if there is anything to merge. 12586 if (StoreNodes.size() < 2) 12587 return false; 12588 12589 // Sort the memory operands according to their distance from the 12590 // base pointer. 12591 std::sort(StoreNodes.begin(), StoreNodes.end(), 12592 [](MemOpLink LHS, MemOpLink RHS) { 12593 return LHS.OffsetFromBase < RHS.OffsetFromBase; 12594 }); 12595 12596 // Store Merge attempts to merge the lowest stores. This generally 12597 // works out as if successful, as the remaining stores are checked 12598 // after the first collection of stores is merged. However, in the 12599 // case that a non-mergeable store is found first, e.g., {p[-2], 12600 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 12601 // mergeable cases. To prevent this, we prune such stores from the 12602 // front of StoreNodes here. 12603 12604 unsigned StartIdx = 0; 12605 while ((StartIdx + 1 < StoreNodes.size()) && 12606 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 12607 StoreNodes[StartIdx + 1].OffsetFromBase) 12608 ++StartIdx; 12609 12610 // Bail if we don't have enough candidates to merge. 12611 if (StartIdx + 1 >= StoreNodes.size()) 12612 return false; 12613 12614 if (StartIdx) 12615 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 12616 12617 // Scan the memory operations on the chain and find the first non-consecutive 12618 // store memory address. 12619 unsigned NumConsecutiveStores = 0; 12620 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 12621 12622 // Check that the addresses are consecutive starting from the second 12623 // element in the list of stores. 12624 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 12625 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 12626 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12627 break; 12628 NumConsecutiveStores = i + 1; 12629 } 12630 12631 if (NumConsecutiveStores < 2) 12632 return false; 12633 12634 // Check that we can merge these candidates without causing a cycle 12635 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumConsecutiveStores)) 12636 return false; 12637 12638 12639 // The node with the lowest store address. 12640 LLVMContext &Context = *DAG.getContext(); 12641 const DataLayout &DL = DAG.getDataLayout(); 12642 12643 // Store the constants into memory as one consecutive store. 12644 if (IsConstantSrc) { 12645 bool RV = false; 12646 while (NumConsecutiveStores > 1) { 12647 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12648 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12649 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12650 unsigned LastLegalType = 0; 12651 unsigned LastLegalVectorType = 0; 12652 bool NonZero = false; 12653 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12654 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 12655 SDValue StoredVal = ST->getValue(); 12656 12657 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 12658 NonZero |= !C->isNullValue(); 12659 } else if (ConstantFPSDNode *C = 12660 dyn_cast<ConstantFPSDNode>(StoredVal)) { 12661 NonZero |= !C->getConstantFPValue()->isNullValue(); 12662 } else { 12663 // Non-constant. 12664 break; 12665 } 12666 12667 // Find a legal type for the constant store. 12668 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 12669 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12670 bool IsFast = false; 12671 if (TLI.isTypeLegal(StoreTy) && 12672 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12673 FirstStoreAlign, &IsFast) && 12674 IsFast) { 12675 LastLegalType = i + 1; 12676 // Or check whether a truncstore is legal. 12677 } else if (TLI.getTypeAction(Context, StoreTy) == 12678 TargetLowering::TypePromoteInteger) { 12679 EVT LegalizedStoredValueTy = 12680 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 12681 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12682 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12683 FirstStoreAS, FirstStoreAlign, &IsFast) && 12684 IsFast) { 12685 LastLegalType = i + 1; 12686 } 12687 } 12688 12689 // We only use vectors if the constant is known to be zero or the target 12690 // allows it and the function is not marked with the noimplicitfloat 12691 // attribute. 12692 if ((!NonZero || 12693 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 12694 !NoVectors) { 12695 // Find a legal type for the vector store. 12696 EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1); 12697 if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(Ty) && 12698 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12699 FirstStoreAlign, &IsFast) && 12700 IsFast) 12701 LastLegalVectorType = i + 1; 12702 } 12703 } 12704 12705 // Check if we found a legal integer type that creates a meaningful merge. 12706 if (LastLegalType < 2 && LastLegalVectorType < 2) 12707 break; 12708 12709 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 12710 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 12711 12712 bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 12713 true, UseVector); 12714 if (!Merged) 12715 break; 12716 // Remove merged stores for next iteration. 12717 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 12718 RV = true; 12719 NumConsecutiveStores -= NumElem; 12720 } 12721 return RV; 12722 } 12723 12724 // When extracting multiple vector elements, try to store them 12725 // in one vector store rather than a sequence of scalar stores. 12726 if (IsExtractVecSrc) { 12727 bool RV = false; 12728 while (StoreNodes.size() >= 2) { 12729 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12730 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12731 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12732 unsigned NumStoresToMerge = 0; 12733 bool IsVec = MemVT.isVector(); 12734 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12735 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12736 unsigned StoreValOpcode = St->getValue().getOpcode(); 12737 // This restriction could be loosened. 12738 // Bail out if any stored values are not elements extracted from a 12739 // vector. It should be possible to handle mixed sources, but load 12740 // sources need more careful handling (see the block of code below that 12741 // handles consecutive loads). 12742 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 12743 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 12744 return false; 12745 12746 // Find a legal type for the vector store. 12747 unsigned Elts = i + 1; 12748 if (IsVec) { 12749 // When merging vector stores, get the total number of elements. 12750 Elts *= MemVT.getVectorNumElements(); 12751 } 12752 EVT Ty = 12753 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 12754 bool IsFast; 12755 if (TLI.isTypeLegal(Ty) && 12756 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 12757 FirstStoreAlign, &IsFast) && 12758 IsFast) 12759 NumStoresToMerge = i + 1; 12760 } 12761 12762 bool Merged = MergeStoresOfConstantsOrVecElts( 12763 StoreNodes, MemVT, NumStoresToMerge, false, true); 12764 if (!Merged) 12765 break; 12766 // Remove merged stores for next iteration. 12767 StoreNodes.erase(StoreNodes.begin(), 12768 StoreNodes.begin() + NumStoresToMerge); 12769 RV = true; 12770 NumConsecutiveStores -= NumStoresToMerge; 12771 } 12772 return RV; 12773 } 12774 12775 // Below we handle the case of multiple consecutive stores that 12776 // come from multiple consecutive loads. We merge them into a single 12777 // wide load and a single wide store. 12778 12779 // Look for load nodes which are used by the stored values. 12780 SmallVector<MemOpLink, 8> LoadNodes; 12781 12782 // Find acceptable loads. Loads need to have the same chain (token factor), 12783 // must not be zext, volatile, indexed, and they must be consecutive. 12784 BaseIndexOffset LdBasePtr; 12785 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 12786 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 12787 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 12788 if (!Ld) break; 12789 12790 // Loads must only have one use. 12791 if (!Ld->hasNUsesOfValue(1, 0)) 12792 break; 12793 12794 // The memory operands must not be volatile. 12795 if (Ld->isVolatile() || Ld->isIndexed()) 12796 break; 12797 12798 // We do not accept ext loads. 12799 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 12800 break; 12801 12802 // The stored memory type must be the same. 12803 if (Ld->getMemoryVT() != MemVT) 12804 break; 12805 12806 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 12807 // If this is not the first ptr that we check. 12808 if (LdBasePtr.Base.getNode()) { 12809 // The base ptr must be the same. 12810 if (!LdPtr.equalBaseIndex(LdBasePtr)) 12811 break; 12812 } else { 12813 // Check that all other base pointers are the same as this one. 12814 LdBasePtr = LdPtr; 12815 } 12816 12817 // We found a potential memory operand to merge. 12818 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset)); 12819 } 12820 12821 if (LoadNodes.size() < 2) 12822 return false; 12823 12824 // If we have load/store pair instructions and we only have two values, 12825 // don't bother. 12826 unsigned RequiredAlignment; 12827 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 12828 St->getAlignment() >= RequiredAlignment) 12829 return false; 12830 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 12831 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 12832 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 12833 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 12834 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 12835 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 12836 12837 // Scan the memory operations on the chain and find the first non-consecutive 12838 // load memory address. These variables hold the index in the store node 12839 // array. 12840 unsigned LastConsecutiveLoad = 0; 12841 // This variable refers to the size and not index in the array. 12842 unsigned LastLegalVectorType = 0; 12843 unsigned LastLegalIntegerType = 0; 12844 StartAddress = LoadNodes[0].OffsetFromBase; 12845 SDValue FirstChain = FirstLoad->getChain(); 12846 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 12847 // All loads must share the same chain. 12848 if (LoadNodes[i].MemNode->getChain() != FirstChain) 12849 break; 12850 12851 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 12852 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 12853 break; 12854 LastConsecutiveLoad = i; 12855 // Find a legal type for the vector store. 12856 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 12857 bool IsFastSt, IsFastLd; 12858 if (TLI.isTypeLegal(StoreTy) && 12859 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12860 FirstStoreAlign, &IsFastSt) && IsFastSt && 12861 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12862 FirstLoadAlign, &IsFastLd) && IsFastLd) { 12863 LastLegalVectorType = i + 1; 12864 } 12865 12866 // Find a legal type for the integer store. 12867 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 12868 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 12869 if (TLI.isTypeLegal(StoreTy) && 12870 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 12871 FirstStoreAlign, &IsFastSt) && IsFastSt && 12872 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 12873 FirstLoadAlign, &IsFastLd) && IsFastLd) 12874 LastLegalIntegerType = i + 1; 12875 // Or check whether a truncstore and extload is legal. 12876 else if (TLI.getTypeAction(Context, StoreTy) == 12877 TargetLowering::TypePromoteInteger) { 12878 EVT LegalizedStoredValueTy = 12879 TLI.getTypeToTransformTo(Context, StoreTy); 12880 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 12881 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 12882 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 12883 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 12884 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12885 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 12886 IsFastSt && 12887 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 12888 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 12889 IsFastLd) 12890 LastLegalIntegerType = i+1; 12891 } 12892 } 12893 12894 // Only use vector types if the vector type is larger than the integer type. 12895 // If they are the same, use integers. 12896 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 12897 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 12898 12899 // We add +1 here because the LastXXX variables refer to location while 12900 // the NumElem refers to array/index size. 12901 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 12902 NumElem = std::min(LastLegalType, NumElem); 12903 12904 if (NumElem < 2) 12905 return false; 12906 12907 // Find if it is better to use vectors or integers to load and store 12908 // to memory. 12909 EVT JointMemOpVT; 12910 if (UseVectorTy) { 12911 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 12912 } else { 12913 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 12914 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 12915 } 12916 12917 SDLoc LoadDL(LoadNodes[0].MemNode); 12918 SDLoc StoreDL(StoreNodes[0].MemNode); 12919 12920 // The merged loads are required to have the same incoming chain, so 12921 // using the first's chain is acceptable. 12922 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 12923 FirstLoad->getBasePtr(), 12924 FirstLoad->getPointerInfo(), FirstLoadAlign); 12925 12926 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 12927 12928 AddToWorklist(NewStoreChain.getNode()); 12929 12930 SDValue NewStore = 12931 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 12932 FirstInChain->getPointerInfo(), FirstStoreAlign); 12933 12934 // Transfer chain users from old loads to the new load. 12935 for (unsigned i = 0; i < NumElem; ++i) { 12936 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 12937 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 12938 SDValue(NewLoad.getNode(), 1)); 12939 } 12940 12941 // Replace the all stores with the new store. 12942 for (unsigned i = 0; i < NumElem; ++i) 12943 CombineTo(StoreNodes[i].MemNode, NewStore); 12944 return true; 12945 } 12946 12947 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 12948 SDLoc SL(ST); 12949 SDValue ReplStore; 12950 12951 // Replace the chain to avoid dependency. 12952 if (ST->isTruncatingStore()) { 12953 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 12954 ST->getBasePtr(), ST->getMemoryVT(), 12955 ST->getMemOperand()); 12956 } else { 12957 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 12958 ST->getMemOperand()); 12959 } 12960 12961 // Create token to keep both nodes around. 12962 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 12963 MVT::Other, ST->getChain(), ReplStore); 12964 12965 // Make sure the new and old chains are cleaned up. 12966 AddToWorklist(Token.getNode()); 12967 12968 // Don't add users to work list. 12969 return CombineTo(ST, Token, false); 12970 } 12971 12972 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 12973 SDValue Value = ST->getValue(); 12974 if (Value.getOpcode() == ISD::TargetConstantFP) 12975 return SDValue(); 12976 12977 SDLoc DL(ST); 12978 12979 SDValue Chain = ST->getChain(); 12980 SDValue Ptr = ST->getBasePtr(); 12981 12982 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 12983 12984 // NOTE: If the original store is volatile, this transform must not increase 12985 // the number of stores. For example, on x86-32 an f64 can be stored in one 12986 // processor operation but an i64 (which is not legal) requires two. So the 12987 // transform should not be done in this case. 12988 12989 SDValue Tmp; 12990 switch (CFP->getSimpleValueType(0).SimpleTy) { 12991 default: 12992 llvm_unreachable("Unknown FP type"); 12993 case MVT::f16: // We don't do this for these yet. 12994 case MVT::f80: 12995 case MVT::f128: 12996 case MVT::ppcf128: 12997 return SDValue(); 12998 case MVT::f32: 12999 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 13000 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13001 ; 13002 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 13003 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 13004 MVT::i32); 13005 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 13006 } 13007 13008 return SDValue(); 13009 case MVT::f64: 13010 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 13011 !ST->isVolatile()) || 13012 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 13013 ; 13014 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 13015 getZExtValue(), SDLoc(CFP), MVT::i64); 13016 return DAG.getStore(Chain, DL, Tmp, 13017 Ptr, ST->getMemOperand()); 13018 } 13019 13020 if (!ST->isVolatile() && 13021 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 13022 // Many FP stores are not made apparent until after legalize, e.g. for 13023 // argument passing. Since this is so common, custom legalize the 13024 // 64-bit integer store into two 32-bit stores. 13025 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 13026 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 13027 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 13028 if (DAG.getDataLayout().isBigEndian()) 13029 std::swap(Lo, Hi); 13030 13031 unsigned Alignment = ST->getAlignment(); 13032 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13033 AAMDNodes AAInfo = ST->getAAInfo(); 13034 13035 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13036 ST->getAlignment(), MMOFlags, AAInfo); 13037 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13038 DAG.getConstant(4, DL, Ptr.getValueType())); 13039 Alignment = MinAlign(Alignment, 4U); 13040 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 13041 ST->getPointerInfo().getWithOffset(4), 13042 Alignment, MMOFlags, AAInfo); 13043 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 13044 St0, St1); 13045 } 13046 13047 return SDValue(); 13048 } 13049 } 13050 13051 SDValue DAGCombiner::visitSTORE(SDNode *N) { 13052 StoreSDNode *ST = cast<StoreSDNode>(N); 13053 SDValue Chain = ST->getChain(); 13054 SDValue Value = ST->getValue(); 13055 SDValue Ptr = ST->getBasePtr(); 13056 13057 // If this is a store of a bit convert, store the input value if the 13058 // resultant store does not need a higher alignment than the original. 13059 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 13060 ST->isUnindexed()) { 13061 EVT SVT = Value.getOperand(0).getValueType(); 13062 if (((!LegalOperations && !ST->isVolatile()) || 13063 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 13064 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 13065 unsigned OrigAlign = ST->getAlignment(); 13066 bool Fast = false; 13067 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 13068 ST->getAddressSpace(), OrigAlign, &Fast) && 13069 Fast) { 13070 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 13071 ST->getPointerInfo(), OrigAlign, 13072 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13073 } 13074 } 13075 } 13076 13077 // Turn 'store undef, Ptr' -> nothing. 13078 if (Value.isUndef() && ST->isUnindexed()) 13079 return Chain; 13080 13081 // Try to infer better alignment information than the store already has. 13082 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 13083 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 13084 if (Align > ST->getAlignment()) { 13085 SDValue NewStore = 13086 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 13087 ST->getMemoryVT(), Align, 13088 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 13089 if (NewStore.getNode() != N) 13090 return CombineTo(ST, NewStore, true); 13091 } 13092 } 13093 } 13094 13095 // Try transforming a pair floating point load / store ops to integer 13096 // load / store ops. 13097 if (SDValue NewST = TransformFPLoadStorePair(N)) 13098 return NewST; 13099 13100 if (ST->isUnindexed()) { 13101 // Walk up chain skipping non-aliasing memory nodes, on this store and any 13102 // adjacent stores. 13103 if (findBetterNeighborChains(ST)) { 13104 // replaceStoreChain uses CombineTo, which handled all of the worklist 13105 // manipulation. Return the original node to not do anything else. 13106 return SDValue(ST, 0); 13107 } 13108 Chain = ST->getChain(); 13109 } 13110 13111 // Try transforming N to an indexed store. 13112 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 13113 return SDValue(N, 0); 13114 13115 // FIXME: is there such a thing as a truncating indexed store? 13116 if (ST->isTruncatingStore() && ST->isUnindexed() && 13117 Value.getValueType().isInteger()) { 13118 // See if we can simplify the input to this truncstore with knowledge that 13119 // only the low bits are being used. For example: 13120 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 13121 SDValue Shorter = GetDemandedBits( 13122 Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13123 ST->getMemoryVT().getScalarSizeInBits())); 13124 AddToWorklist(Value.getNode()); 13125 if (Shorter.getNode()) 13126 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 13127 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13128 13129 // Otherwise, see if we can simplify the operation with 13130 // SimplifyDemandedBits, which only works if the value has a single use. 13131 if (SimplifyDemandedBits( 13132 Value, 13133 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 13134 ST->getMemoryVT().getScalarSizeInBits()))) { 13135 // Re-visit the store if anything changed and the store hasn't been merged 13136 // with another node (N is deleted) SimplifyDemandedBits will add Value's 13137 // node back to the worklist if necessary, but we also need to re-visit 13138 // the Store node itself. 13139 if (N->getOpcode() != ISD::DELETED_NODE) 13140 AddToWorklist(N); 13141 return SDValue(N, 0); 13142 } 13143 } 13144 13145 // If this is a load followed by a store to the same location, then the store 13146 // is dead/noop. 13147 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 13148 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 13149 ST->isUnindexed() && !ST->isVolatile() && 13150 // There can't be any side effects between the load and store, such as 13151 // a call or store. 13152 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 13153 // The store is dead, remove it. 13154 return Chain; 13155 } 13156 } 13157 13158 // If this is a store followed by a store with the same value to the same 13159 // location, then the store is dead/noop. 13160 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 13161 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 13162 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 13163 ST1->isUnindexed() && !ST1->isVolatile()) { 13164 // The store is dead, remove it. 13165 return Chain; 13166 } 13167 } 13168 13169 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 13170 // truncating store. We can do this even if this is already a truncstore. 13171 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 13172 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 13173 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 13174 ST->getMemoryVT())) { 13175 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 13176 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 13177 } 13178 13179 // Only perform this optimization before the types are legal, because we 13180 // don't want to perform this optimization on every DAGCombine invocation. 13181 if (!LegalTypes) { 13182 for (;;) { 13183 // There can be multiple store sequences on the same chain. 13184 // Keep trying to merge store sequences until we are unable to do so 13185 // or until we merge the last store on the chain. 13186 bool Changed = MergeConsecutiveStores(ST); 13187 if (!Changed) break; 13188 // Return N as merge only uses CombineTo and no worklist clean 13189 // up is necessary. 13190 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 13191 return SDValue(N, 0); 13192 } 13193 } 13194 13195 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 13196 // 13197 // Make sure to do this only after attempting to merge stores in order to 13198 // avoid changing the types of some subset of stores due to visit order, 13199 // preventing their merging. 13200 if (isa<ConstantFPSDNode>(ST->getValue())) { 13201 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 13202 return NewSt; 13203 } 13204 13205 if (SDValue NewSt = splitMergedValStore(ST)) 13206 return NewSt; 13207 13208 return ReduceLoadOpStoreWidth(N); 13209 } 13210 13211 /// For the instruction sequence of store below, F and I values 13212 /// are bundled together as an i64 value before being stored into memory. 13213 /// Sometimes it is more efficent to generate separate stores for F and I, 13214 /// which can remove the bitwise instructions or sink them to colder places. 13215 /// 13216 /// (store (or (zext (bitcast F to i32) to i64), 13217 /// (shl (zext I to i64), 32)), addr) --> 13218 /// (store F, addr) and (store I, addr+4) 13219 /// 13220 /// Similarly, splitting for other merged store can also be beneficial, like: 13221 /// For pair of {i32, i32}, i64 store --> two i32 stores. 13222 /// For pair of {i32, i16}, i64 store --> two i32 stores. 13223 /// For pair of {i16, i16}, i32 store --> two i16 stores. 13224 /// For pair of {i16, i8}, i32 store --> two i16 stores. 13225 /// For pair of {i8, i8}, i16 store --> two i8 stores. 13226 /// 13227 /// We allow each target to determine specifically which kind of splitting is 13228 /// supported. 13229 /// 13230 /// The store patterns are commonly seen from the simple code snippet below 13231 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 13232 /// void goo(const std::pair<int, float> &); 13233 /// hoo() { 13234 /// ... 13235 /// goo(std::make_pair(tmp, ftmp)); 13236 /// ... 13237 /// } 13238 /// 13239 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 13240 if (OptLevel == CodeGenOpt::None) 13241 return SDValue(); 13242 13243 SDValue Val = ST->getValue(); 13244 SDLoc DL(ST); 13245 13246 // Match OR operand. 13247 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 13248 return SDValue(); 13249 13250 // Match SHL operand and get Lower and Higher parts of Val. 13251 SDValue Op1 = Val.getOperand(0); 13252 SDValue Op2 = Val.getOperand(1); 13253 SDValue Lo, Hi; 13254 if (Op1.getOpcode() != ISD::SHL) { 13255 std::swap(Op1, Op2); 13256 if (Op1.getOpcode() != ISD::SHL) 13257 return SDValue(); 13258 } 13259 Lo = Op2; 13260 Hi = Op1.getOperand(0); 13261 if (!Op1.hasOneUse()) 13262 return SDValue(); 13263 13264 // Match shift amount to HalfValBitSize. 13265 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 13266 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 13267 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 13268 return SDValue(); 13269 13270 // Lo and Hi are zero-extended from int with size less equal than 32 13271 // to i64. 13272 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 13273 !Lo.getOperand(0).getValueType().isScalarInteger() || 13274 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 13275 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 13276 !Hi.getOperand(0).getValueType().isScalarInteger() || 13277 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 13278 return SDValue(); 13279 13280 // Use the EVT of low and high parts before bitcast as the input 13281 // of target query. 13282 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 13283 ? Lo.getOperand(0).getValueType() 13284 : Lo.getValueType(); 13285 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 13286 ? Hi.getOperand(0).getValueType() 13287 : Hi.getValueType(); 13288 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 13289 return SDValue(); 13290 13291 // Start to split store. 13292 unsigned Alignment = ST->getAlignment(); 13293 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 13294 AAMDNodes AAInfo = ST->getAAInfo(); 13295 13296 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 13297 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 13298 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 13299 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 13300 13301 SDValue Chain = ST->getChain(); 13302 SDValue Ptr = ST->getBasePtr(); 13303 // Lower value store. 13304 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 13305 ST->getAlignment(), MMOFlags, AAInfo); 13306 Ptr = 13307 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 13308 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 13309 // Higher value store. 13310 SDValue St1 = 13311 DAG.getStore(St0, DL, Hi, Ptr, 13312 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 13313 Alignment / 2, MMOFlags, AAInfo); 13314 return St1; 13315 } 13316 13317 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 13318 SDValue InVec = N->getOperand(0); 13319 SDValue InVal = N->getOperand(1); 13320 SDValue EltNo = N->getOperand(2); 13321 SDLoc DL(N); 13322 13323 // If the inserted element is an UNDEF, just use the input vector. 13324 if (InVal.isUndef()) 13325 return InVec; 13326 13327 EVT VT = InVec.getValueType(); 13328 13329 // Check that we know which element is being inserted 13330 if (!isa<ConstantSDNode>(EltNo)) 13331 return SDValue(); 13332 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13333 13334 // Canonicalize insert_vector_elt dag nodes. 13335 // Example: 13336 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 13337 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 13338 // 13339 // Do this only if the child insert_vector node has one use; also 13340 // do this only if indices are both constants and Idx1 < Idx0. 13341 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 13342 && isa<ConstantSDNode>(InVec.getOperand(2))) { 13343 unsigned OtherElt = InVec.getConstantOperandVal(2); 13344 if (Elt < OtherElt) { 13345 // Swap nodes. 13346 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 13347 InVec.getOperand(0), InVal, EltNo); 13348 AddToWorklist(NewOp.getNode()); 13349 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 13350 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 13351 } 13352 } 13353 13354 // If we can't generate a legal BUILD_VECTOR, exit 13355 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 13356 return SDValue(); 13357 13358 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 13359 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 13360 // vector elements. 13361 SmallVector<SDValue, 8> Ops; 13362 // Do not combine these two vectors if the output vector will not replace 13363 // the input vector. 13364 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 13365 Ops.append(InVec.getNode()->op_begin(), 13366 InVec.getNode()->op_end()); 13367 } else if (InVec.isUndef()) { 13368 unsigned NElts = VT.getVectorNumElements(); 13369 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 13370 } else { 13371 return SDValue(); 13372 } 13373 13374 // Insert the element 13375 if (Elt < Ops.size()) { 13376 // All the operands of BUILD_VECTOR must have the same type; 13377 // we enforce that here. 13378 EVT OpVT = Ops[0].getValueType(); 13379 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 13380 } 13381 13382 // Return the new vector 13383 return DAG.getBuildVector(VT, DL, Ops); 13384 } 13385 13386 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 13387 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 13388 assert(!OriginalLoad->isVolatile()); 13389 13390 EVT ResultVT = EVE->getValueType(0); 13391 EVT VecEltVT = InVecVT.getVectorElementType(); 13392 unsigned Align = OriginalLoad->getAlignment(); 13393 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 13394 VecEltVT.getTypeForEVT(*DAG.getContext())); 13395 13396 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 13397 return SDValue(); 13398 13399 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 13400 ISD::NON_EXTLOAD : ISD::EXTLOAD; 13401 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 13402 return SDValue(); 13403 13404 Align = NewAlign; 13405 13406 SDValue NewPtr = OriginalLoad->getBasePtr(); 13407 SDValue Offset; 13408 EVT PtrType = NewPtr.getValueType(); 13409 MachinePointerInfo MPI; 13410 SDLoc DL(EVE); 13411 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 13412 int Elt = ConstEltNo->getZExtValue(); 13413 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 13414 Offset = DAG.getConstant(PtrOff, DL, PtrType); 13415 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 13416 } else { 13417 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 13418 Offset = DAG.getNode( 13419 ISD::MUL, DL, PtrType, Offset, 13420 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 13421 MPI = OriginalLoad->getPointerInfo(); 13422 } 13423 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 13424 13425 // The replacement we need to do here is a little tricky: we need to 13426 // replace an extractelement of a load with a load. 13427 // Use ReplaceAllUsesOfValuesWith to do the replacement. 13428 // Note that this replacement assumes that the extractvalue is the only 13429 // use of the load; that's okay because we don't want to perform this 13430 // transformation in other cases anyway. 13431 SDValue Load; 13432 SDValue Chain; 13433 if (ResultVT.bitsGT(VecEltVT)) { 13434 // If the result type of vextract is wider than the load, then issue an 13435 // extending load instead. 13436 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 13437 VecEltVT) 13438 ? ISD::ZEXTLOAD 13439 : ISD::EXTLOAD; 13440 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 13441 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 13442 Align, OriginalLoad->getMemOperand()->getFlags(), 13443 OriginalLoad->getAAInfo()); 13444 Chain = Load.getValue(1); 13445 } else { 13446 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 13447 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 13448 OriginalLoad->getAAInfo()); 13449 Chain = Load.getValue(1); 13450 if (ResultVT.bitsLT(VecEltVT)) 13451 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 13452 else 13453 Load = DAG.getBitcast(ResultVT, Load); 13454 } 13455 WorklistRemover DeadNodes(*this); 13456 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 13457 SDValue To[] = { Load, Chain }; 13458 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 13459 // Since we're explicitly calling ReplaceAllUses, add the new node to the 13460 // worklist explicitly as well. 13461 AddToWorklist(Load.getNode()); 13462 AddUsersToWorklist(Load.getNode()); // Add users too 13463 // Make sure to revisit this node to clean it up; it will usually be dead. 13464 AddToWorklist(EVE); 13465 ++OpsNarrowed; 13466 return SDValue(EVE, 0); 13467 } 13468 13469 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 13470 // (vextract (scalar_to_vector val, 0) -> val 13471 SDValue InVec = N->getOperand(0); 13472 EVT VT = InVec.getValueType(); 13473 EVT NVT = N->getValueType(0); 13474 13475 if (InVec.isUndef()) 13476 return DAG.getUNDEF(NVT); 13477 13478 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 13479 // Check if the result type doesn't match the inserted element type. A 13480 // SCALAR_TO_VECTOR may truncate the inserted element and the 13481 // EXTRACT_VECTOR_ELT may widen the extracted vector. 13482 SDValue InOp = InVec.getOperand(0); 13483 if (InOp.getValueType() != NVT) { 13484 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13485 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 13486 } 13487 return InOp; 13488 } 13489 13490 SDValue EltNo = N->getOperand(1); 13491 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 13492 13493 // extract_vector_elt (build_vector x, y), 1 -> y 13494 if (ConstEltNo && 13495 InVec.getOpcode() == ISD::BUILD_VECTOR && 13496 TLI.isTypeLegal(VT) && 13497 (InVec.hasOneUse() || 13498 TLI.aggressivelyPreferBuildVectorSources(VT))) { 13499 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 13500 EVT InEltVT = Elt.getValueType(); 13501 13502 // Sometimes build_vector's scalar input types do not match result type. 13503 if (NVT == InEltVT) 13504 return Elt; 13505 13506 // TODO: It may be useful to truncate if free if the build_vector implicitly 13507 // converts. 13508 } 13509 13510 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 13511 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 13512 ConstEltNo->isNullValue() && VT.isInteger()) { 13513 SDValue BCSrc = InVec.getOperand(0); 13514 if (BCSrc.getValueType().isScalarInteger()) 13515 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 13516 } 13517 13518 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 13519 // 13520 // This only really matters if the index is non-constant since other combines 13521 // on the constant elements already work. 13522 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 13523 EltNo == InVec.getOperand(2)) { 13524 SDValue Elt = InVec.getOperand(1); 13525 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 13526 } 13527 13528 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 13529 // We only perform this optimization before the op legalization phase because 13530 // we may introduce new vector instructions which are not backed by TD 13531 // patterns. For example on AVX, extracting elements from a wide vector 13532 // without using extract_subvector. However, if we can find an underlying 13533 // scalar value, then we can always use that. 13534 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 13535 int NumElem = VT.getVectorNumElements(); 13536 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 13537 // Find the new index to extract from. 13538 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 13539 13540 // Extracting an undef index is undef. 13541 if (OrigElt == -1) 13542 return DAG.getUNDEF(NVT); 13543 13544 // Select the right vector half to extract from. 13545 SDValue SVInVec; 13546 if (OrigElt < NumElem) { 13547 SVInVec = InVec->getOperand(0); 13548 } else { 13549 SVInVec = InVec->getOperand(1); 13550 OrigElt -= NumElem; 13551 } 13552 13553 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 13554 SDValue InOp = SVInVec.getOperand(OrigElt); 13555 if (InOp.getValueType() != NVT) { 13556 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 13557 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 13558 } 13559 13560 return InOp; 13561 } 13562 13563 // FIXME: We should handle recursing on other vector shuffles and 13564 // scalar_to_vector here as well. 13565 13566 if (!LegalOperations) { 13567 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13568 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 13569 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 13570 } 13571 } 13572 13573 bool BCNumEltsChanged = false; 13574 EVT ExtVT = VT.getVectorElementType(); 13575 EVT LVT = ExtVT; 13576 13577 // If the result of load has to be truncated, then it's not necessarily 13578 // profitable. 13579 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 13580 return SDValue(); 13581 13582 if (InVec.getOpcode() == ISD::BITCAST) { 13583 // Don't duplicate a load with other uses. 13584 if (!InVec.hasOneUse()) 13585 return SDValue(); 13586 13587 EVT BCVT = InVec.getOperand(0).getValueType(); 13588 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 13589 return SDValue(); 13590 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 13591 BCNumEltsChanged = true; 13592 InVec = InVec.getOperand(0); 13593 ExtVT = BCVT.getVectorElementType(); 13594 } 13595 13596 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 13597 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 13598 ISD::isNormalLoad(InVec.getNode()) && 13599 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 13600 SDValue Index = N->getOperand(1); 13601 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 13602 if (!OrigLoad->isVolatile()) { 13603 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 13604 OrigLoad); 13605 } 13606 } 13607 } 13608 13609 // Perform only after legalization to ensure build_vector / vector_shuffle 13610 // optimizations have already been done. 13611 if (!LegalOperations) return SDValue(); 13612 13613 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 13614 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 13615 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 13616 13617 if (ConstEltNo) { 13618 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 13619 13620 LoadSDNode *LN0 = nullptr; 13621 const ShuffleVectorSDNode *SVN = nullptr; 13622 if (ISD::isNormalLoad(InVec.getNode())) { 13623 LN0 = cast<LoadSDNode>(InVec); 13624 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 13625 InVec.getOperand(0).getValueType() == ExtVT && 13626 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 13627 // Don't duplicate a load with other uses. 13628 if (!InVec.hasOneUse()) 13629 return SDValue(); 13630 13631 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 13632 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 13633 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 13634 // => 13635 // (load $addr+1*size) 13636 13637 // Don't duplicate a load with other uses. 13638 if (!InVec.hasOneUse()) 13639 return SDValue(); 13640 13641 // If the bit convert changed the number of elements, it is unsafe 13642 // to examine the mask. 13643 if (BCNumEltsChanged) 13644 return SDValue(); 13645 13646 // Select the input vector, guarding against out of range extract vector. 13647 unsigned NumElems = VT.getVectorNumElements(); 13648 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 13649 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 13650 13651 if (InVec.getOpcode() == ISD::BITCAST) { 13652 // Don't duplicate a load with other uses. 13653 if (!InVec.hasOneUse()) 13654 return SDValue(); 13655 13656 InVec = InVec.getOperand(0); 13657 } 13658 if (ISD::isNormalLoad(InVec.getNode())) { 13659 LN0 = cast<LoadSDNode>(InVec); 13660 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 13661 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 13662 } 13663 } 13664 13665 // Make sure we found a non-volatile load and the extractelement is 13666 // the only use. 13667 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 13668 return SDValue(); 13669 13670 // If Idx was -1 above, Elt is going to be -1, so just return undef. 13671 if (Elt == -1) 13672 return DAG.getUNDEF(LVT); 13673 13674 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 13675 } 13676 13677 return SDValue(); 13678 } 13679 13680 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 13681 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 13682 // We perform this optimization post type-legalization because 13683 // the type-legalizer often scalarizes integer-promoted vectors. 13684 // Performing this optimization before may create bit-casts which 13685 // will be type-legalized to complex code sequences. 13686 // We perform this optimization only before the operation legalizer because we 13687 // may introduce illegal operations. 13688 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 13689 return SDValue(); 13690 13691 unsigned NumInScalars = N->getNumOperands(); 13692 SDLoc DL(N); 13693 EVT VT = N->getValueType(0); 13694 13695 // Check to see if this is a BUILD_VECTOR of a bunch of values 13696 // which come from any_extend or zero_extend nodes. If so, we can create 13697 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 13698 // optimizations. We do not handle sign-extend because we can't fill the sign 13699 // using shuffles. 13700 EVT SourceType = MVT::Other; 13701 bool AllAnyExt = true; 13702 13703 for (unsigned i = 0; i != NumInScalars; ++i) { 13704 SDValue In = N->getOperand(i); 13705 // Ignore undef inputs. 13706 if (In.isUndef()) continue; 13707 13708 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 13709 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 13710 13711 // Abort if the element is not an extension. 13712 if (!ZeroExt && !AnyExt) { 13713 SourceType = MVT::Other; 13714 break; 13715 } 13716 13717 // The input is a ZeroExt or AnyExt. Check the original type. 13718 EVT InTy = In.getOperand(0).getValueType(); 13719 13720 // Check that all of the widened source types are the same. 13721 if (SourceType == MVT::Other) 13722 // First time. 13723 SourceType = InTy; 13724 else if (InTy != SourceType) { 13725 // Multiple income types. Abort. 13726 SourceType = MVT::Other; 13727 break; 13728 } 13729 13730 // Check if all of the extends are ANY_EXTENDs. 13731 AllAnyExt &= AnyExt; 13732 } 13733 13734 // In order to have valid types, all of the inputs must be extended from the 13735 // same source type and all of the inputs must be any or zero extend. 13736 // Scalar sizes must be a power of two. 13737 EVT OutScalarTy = VT.getScalarType(); 13738 bool ValidTypes = SourceType != MVT::Other && 13739 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 13740 isPowerOf2_32(SourceType.getSizeInBits()); 13741 13742 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 13743 // turn into a single shuffle instruction. 13744 if (!ValidTypes) 13745 return SDValue(); 13746 13747 bool isLE = DAG.getDataLayout().isLittleEndian(); 13748 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 13749 assert(ElemRatio > 1 && "Invalid element size ratio"); 13750 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 13751 DAG.getConstant(0, DL, SourceType); 13752 13753 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 13754 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 13755 13756 // Populate the new build_vector 13757 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13758 SDValue Cast = N->getOperand(i); 13759 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 13760 Cast.getOpcode() == ISD::ZERO_EXTEND || 13761 Cast.isUndef()) && "Invalid cast opcode"); 13762 SDValue In; 13763 if (Cast.isUndef()) 13764 In = DAG.getUNDEF(SourceType); 13765 else 13766 In = Cast->getOperand(0); 13767 unsigned Index = isLE ? (i * ElemRatio) : 13768 (i * ElemRatio + (ElemRatio - 1)); 13769 13770 assert(Index < Ops.size() && "Invalid index"); 13771 Ops[Index] = In; 13772 } 13773 13774 // The type of the new BUILD_VECTOR node. 13775 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 13776 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 13777 "Invalid vector size"); 13778 // Check if the new vector type is legal. 13779 if (!isTypeLegal(VecVT)) return SDValue(); 13780 13781 // Make the new BUILD_VECTOR. 13782 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 13783 13784 // The new BUILD_VECTOR node has the potential to be further optimized. 13785 AddToWorklist(BV.getNode()); 13786 // Bitcast to the desired type. 13787 return DAG.getBitcast(VT, BV); 13788 } 13789 13790 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 13791 EVT VT = N->getValueType(0); 13792 13793 unsigned NumInScalars = N->getNumOperands(); 13794 SDLoc DL(N); 13795 13796 EVT SrcVT = MVT::Other; 13797 unsigned Opcode = ISD::DELETED_NODE; 13798 unsigned NumDefs = 0; 13799 13800 for (unsigned i = 0; i != NumInScalars; ++i) { 13801 SDValue In = N->getOperand(i); 13802 unsigned Opc = In.getOpcode(); 13803 13804 if (Opc == ISD::UNDEF) 13805 continue; 13806 13807 // If all scalar values are floats and converted from integers. 13808 if (Opcode == ISD::DELETED_NODE && 13809 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 13810 Opcode = Opc; 13811 } 13812 13813 if (Opc != Opcode) 13814 return SDValue(); 13815 13816 EVT InVT = In.getOperand(0).getValueType(); 13817 13818 // If all scalar values are typed differently, bail out. It's chosen to 13819 // simplify BUILD_VECTOR of integer types. 13820 if (SrcVT == MVT::Other) 13821 SrcVT = InVT; 13822 if (SrcVT != InVT) 13823 return SDValue(); 13824 NumDefs++; 13825 } 13826 13827 // If the vector has just one element defined, it's not worth to fold it into 13828 // a vectorized one. 13829 if (NumDefs < 2) 13830 return SDValue(); 13831 13832 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 13833 && "Should only handle conversion from integer to float."); 13834 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 13835 13836 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 13837 13838 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 13839 return SDValue(); 13840 13841 // Just because the floating-point vector type is legal does not necessarily 13842 // mean that the corresponding integer vector type is. 13843 if (!isTypeLegal(NVT)) 13844 return SDValue(); 13845 13846 SmallVector<SDValue, 8> Opnds; 13847 for (unsigned i = 0; i != NumInScalars; ++i) { 13848 SDValue In = N->getOperand(i); 13849 13850 if (In.isUndef()) 13851 Opnds.push_back(DAG.getUNDEF(SrcVT)); 13852 else 13853 Opnds.push_back(In.getOperand(0)); 13854 } 13855 SDValue BV = DAG.getBuildVector(NVT, DL, Opnds); 13856 AddToWorklist(BV.getNode()); 13857 13858 return DAG.getNode(Opcode, DL, VT, BV); 13859 } 13860 13861 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 13862 ArrayRef<int> VectorMask, 13863 SDValue VecIn1, SDValue VecIn2, 13864 unsigned LeftIdx) { 13865 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 13866 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 13867 13868 EVT VT = N->getValueType(0); 13869 EVT InVT1 = VecIn1.getValueType(); 13870 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 13871 13872 unsigned Vec2Offset = InVT1.getVectorNumElements(); 13873 unsigned NumElems = VT.getVectorNumElements(); 13874 unsigned ShuffleNumElems = NumElems; 13875 13876 // We can't generate a shuffle node with mismatched input and output types. 13877 // Try to make the types match the type of the output. 13878 if (InVT1 != VT || InVT2 != VT) { 13879 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 13880 // If the output vector length is a multiple of both input lengths, 13881 // we can concatenate them and pad the rest with undefs. 13882 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 13883 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 13884 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 13885 ConcatOps[0] = VecIn1; 13886 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 13887 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 13888 VecIn2 = SDValue(); 13889 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 13890 if (!TLI.isExtractSubvectorCheap(VT, NumElems)) 13891 return SDValue(); 13892 13893 if (!VecIn2.getNode()) { 13894 // If we only have one input vector, and it's twice the size of the 13895 // output, split it in two. 13896 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 13897 DAG.getConstant(NumElems, DL, IdxTy)); 13898 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 13899 // Since we now have shorter input vectors, adjust the offset of the 13900 // second vector's start. 13901 Vec2Offset = NumElems; 13902 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 13903 // VecIn1 is wider than the output, and we have another, possibly 13904 // smaller input. Pad the smaller input with undefs, shuffle at the 13905 // input vector width, and extract the output. 13906 // The shuffle type is different than VT, so check legality again. 13907 if (LegalOperations && 13908 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 13909 return SDValue(); 13910 13911 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 13912 // lower it back into a BUILD_VECTOR. So if the inserted type is 13913 // illegal, don't even try. 13914 if (InVT1 != InVT2) { 13915 if (!TLI.isTypeLegal(InVT2)) 13916 return SDValue(); 13917 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 13918 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 13919 } 13920 ShuffleNumElems = NumElems * 2; 13921 } else { 13922 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 13923 // than VecIn1. We can't handle this for now - this case will disappear 13924 // when we start sorting the vectors by type. 13925 return SDValue(); 13926 } 13927 } else { 13928 // TODO: Support cases where the length mismatch isn't exactly by a 13929 // factor of 2. 13930 // TODO: Move this check upwards, so that if we have bad type 13931 // mismatches, we don't create any DAG nodes. 13932 return SDValue(); 13933 } 13934 } 13935 13936 // Initialize mask to undef. 13937 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 13938 13939 // Only need to run up to the number of elements actually used, not the 13940 // total number of elements in the shuffle - if we are shuffling a wider 13941 // vector, the high lanes should be set to undef. 13942 for (unsigned i = 0; i != NumElems; ++i) { 13943 if (VectorMask[i] <= 0) 13944 continue; 13945 13946 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 13947 if (VectorMask[i] == (int)LeftIdx) { 13948 Mask[i] = ExtIndex; 13949 } else if (VectorMask[i] == (int)LeftIdx + 1) { 13950 Mask[i] = Vec2Offset + ExtIndex; 13951 } 13952 } 13953 13954 // The type the input vectors may have changed above. 13955 InVT1 = VecIn1.getValueType(); 13956 13957 // If we already have a VecIn2, it should have the same type as VecIn1. 13958 // If we don't, get an undef/zero vector of the appropriate type. 13959 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 13960 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 13961 13962 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 13963 if (ShuffleNumElems > NumElems) 13964 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 13965 13966 return Shuffle; 13967 } 13968 13969 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 13970 // operations. If the types of the vectors we're extracting from allow it, 13971 // turn this into a vector_shuffle node. 13972 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 13973 SDLoc DL(N); 13974 EVT VT = N->getValueType(0); 13975 13976 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 13977 if (!isTypeLegal(VT)) 13978 return SDValue(); 13979 13980 // May only combine to shuffle after legalize if shuffle is legal. 13981 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 13982 return SDValue(); 13983 13984 bool UsesZeroVector = false; 13985 unsigned NumElems = N->getNumOperands(); 13986 13987 // Record, for each element of the newly built vector, which input vector 13988 // that element comes from. -1 stands for undef, 0 for the zero vector, 13989 // and positive values for the input vectors. 13990 // VectorMask maps each element to its vector number, and VecIn maps vector 13991 // numbers to their initial SDValues. 13992 13993 SmallVector<int, 8> VectorMask(NumElems, -1); 13994 SmallVector<SDValue, 8> VecIn; 13995 VecIn.push_back(SDValue()); 13996 13997 for (unsigned i = 0; i != NumElems; ++i) { 13998 SDValue Op = N->getOperand(i); 13999 14000 if (Op.isUndef()) 14001 continue; 14002 14003 // See if we can use a blend with a zero vector. 14004 // TODO: Should we generalize this to a blend with an arbitrary constant 14005 // vector? 14006 if (isNullConstant(Op) || isNullFPConstant(Op)) { 14007 UsesZeroVector = true; 14008 VectorMask[i] = 0; 14009 continue; 14010 } 14011 14012 // Not an undef or zero. If the input is something other than an 14013 // EXTRACT_VECTOR_ELT with a constant index, bail out. 14014 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 14015 !isa<ConstantSDNode>(Op.getOperand(1))) 14016 return SDValue(); 14017 14018 SDValue ExtractedFromVec = Op.getOperand(0); 14019 14020 // All inputs must have the same element type as the output. 14021 if (VT.getVectorElementType() != 14022 ExtractedFromVec.getValueType().getVectorElementType()) 14023 return SDValue(); 14024 14025 // Have we seen this input vector before? 14026 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 14027 // a map back from SDValues to numbers isn't worth it. 14028 unsigned Idx = std::distance( 14029 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 14030 if (Idx == VecIn.size()) 14031 VecIn.push_back(ExtractedFromVec); 14032 14033 VectorMask[i] = Idx; 14034 } 14035 14036 // If we didn't find at least one input vector, bail out. 14037 if (VecIn.size() < 2) 14038 return SDValue(); 14039 14040 // TODO: We want to sort the vectors by descending length, so that adjacent 14041 // pairs have similar length, and the longer vector is always first in the 14042 // pair. 14043 14044 // TODO: Should this fire if some of the input vectors has illegal type (like 14045 // it does now), or should we let legalization run its course first? 14046 14047 // Shuffle phase: 14048 // Take pairs of vectors, and shuffle them so that the result has elements 14049 // from these vectors in the correct places. 14050 // For example, given: 14051 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 14052 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 14053 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 14054 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 14055 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 14056 // We will generate: 14057 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 14058 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 14059 SmallVector<SDValue, 4> Shuffles; 14060 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 14061 unsigned LeftIdx = 2 * In + 1; 14062 SDValue VecLeft = VecIn[LeftIdx]; 14063 SDValue VecRight = 14064 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 14065 14066 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 14067 VecRight, LeftIdx)) 14068 Shuffles.push_back(Shuffle); 14069 else 14070 return SDValue(); 14071 } 14072 14073 // If we need the zero vector as an "ingredient" in the blend tree, add it 14074 // to the list of shuffles. 14075 if (UsesZeroVector) 14076 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 14077 : DAG.getConstantFP(0.0, DL, VT)); 14078 14079 // If we only have one shuffle, we're done. 14080 if (Shuffles.size() == 1) 14081 return Shuffles[0]; 14082 14083 // Update the vector mask to point to the post-shuffle vectors. 14084 for (int &Vec : VectorMask) 14085 if (Vec == 0) 14086 Vec = Shuffles.size() - 1; 14087 else 14088 Vec = (Vec - 1) / 2; 14089 14090 // More than one shuffle. Generate a binary tree of blends, e.g. if from 14091 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 14092 // generate: 14093 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 14094 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 14095 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 14096 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 14097 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 14098 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 14099 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 14100 14101 // Make sure the initial size of the shuffle list is even. 14102 if (Shuffles.size() % 2) 14103 Shuffles.push_back(DAG.getUNDEF(VT)); 14104 14105 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 14106 if (CurSize % 2) { 14107 Shuffles[CurSize] = DAG.getUNDEF(VT); 14108 CurSize++; 14109 } 14110 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 14111 int Left = 2 * In; 14112 int Right = 2 * In + 1; 14113 SmallVector<int, 8> Mask(NumElems, -1); 14114 for (unsigned i = 0; i != NumElems; ++i) { 14115 if (VectorMask[i] == Left) { 14116 Mask[i] = i; 14117 VectorMask[i] = In; 14118 } else if (VectorMask[i] == Right) { 14119 Mask[i] = i + NumElems; 14120 VectorMask[i] = In; 14121 } 14122 } 14123 14124 Shuffles[In] = 14125 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 14126 } 14127 } 14128 14129 return Shuffles[0]; 14130 } 14131 14132 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 14133 EVT VT = N->getValueType(0); 14134 14135 // A vector built entirely of undefs is undef. 14136 if (ISD::allOperandsUndef(N)) 14137 return DAG.getUNDEF(VT); 14138 14139 // Check if we can express BUILD VECTOR via subvector extract. 14140 if (!LegalTypes && (N->getNumOperands() > 1)) { 14141 SDValue Op0 = N->getOperand(0); 14142 auto checkElem = [&](SDValue Op) -> uint64_t { 14143 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 14144 (Op0.getOperand(0) == Op.getOperand(0))) 14145 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 14146 return CNode->getZExtValue(); 14147 return -1; 14148 }; 14149 14150 int Offset = checkElem(Op0); 14151 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 14152 if (Offset + i != checkElem(N->getOperand(i))) { 14153 Offset = -1; 14154 break; 14155 } 14156 } 14157 14158 if ((Offset == 0) && 14159 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 14160 return Op0.getOperand(0); 14161 if ((Offset != -1) && 14162 ((Offset % N->getValueType(0).getVectorNumElements()) == 14163 0)) // IDX must be multiple of output size. 14164 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 14165 Op0.getOperand(0), Op0.getOperand(1)); 14166 } 14167 14168 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 14169 return V; 14170 14171 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 14172 return V; 14173 14174 if (SDValue V = reduceBuildVecToShuffle(N)) 14175 return V; 14176 14177 return SDValue(); 14178 } 14179 14180 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 14181 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 14182 EVT OpVT = N->getOperand(0).getValueType(); 14183 14184 // If the operands are legal vectors, leave them alone. 14185 if (TLI.isTypeLegal(OpVT)) 14186 return SDValue(); 14187 14188 SDLoc DL(N); 14189 EVT VT = N->getValueType(0); 14190 SmallVector<SDValue, 8> Ops; 14191 14192 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 14193 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14194 14195 // Keep track of what we encounter. 14196 bool AnyInteger = false; 14197 bool AnyFP = false; 14198 for (const SDValue &Op : N->ops()) { 14199 if (ISD::BITCAST == Op.getOpcode() && 14200 !Op.getOperand(0).getValueType().isVector()) 14201 Ops.push_back(Op.getOperand(0)); 14202 else if (ISD::UNDEF == Op.getOpcode()) 14203 Ops.push_back(ScalarUndef); 14204 else 14205 return SDValue(); 14206 14207 // Note whether we encounter an integer or floating point scalar. 14208 // If it's neither, bail out, it could be something weird like x86mmx. 14209 EVT LastOpVT = Ops.back().getValueType(); 14210 if (LastOpVT.isFloatingPoint()) 14211 AnyFP = true; 14212 else if (LastOpVT.isInteger()) 14213 AnyInteger = true; 14214 else 14215 return SDValue(); 14216 } 14217 14218 // If any of the operands is a floating point scalar bitcast to a vector, 14219 // use floating point types throughout, and bitcast everything. 14220 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 14221 if (AnyFP) { 14222 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 14223 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 14224 if (AnyInteger) { 14225 for (SDValue &Op : Ops) { 14226 if (Op.getValueType() == SVT) 14227 continue; 14228 if (Op.isUndef()) 14229 Op = ScalarUndef; 14230 else 14231 Op = DAG.getBitcast(SVT, Op); 14232 } 14233 } 14234 } 14235 14236 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 14237 VT.getSizeInBits() / SVT.getSizeInBits()); 14238 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 14239 } 14240 14241 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 14242 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 14243 // most two distinct vectors the same size as the result, attempt to turn this 14244 // into a legal shuffle. 14245 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 14246 EVT VT = N->getValueType(0); 14247 EVT OpVT = N->getOperand(0).getValueType(); 14248 int NumElts = VT.getVectorNumElements(); 14249 int NumOpElts = OpVT.getVectorNumElements(); 14250 14251 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 14252 SmallVector<int, 8> Mask; 14253 14254 for (SDValue Op : N->ops()) { 14255 // Peek through any bitcast. 14256 while (Op.getOpcode() == ISD::BITCAST) 14257 Op = Op.getOperand(0); 14258 14259 // UNDEF nodes convert to UNDEF shuffle mask values. 14260 if (Op.isUndef()) { 14261 Mask.append((unsigned)NumOpElts, -1); 14262 continue; 14263 } 14264 14265 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14266 return SDValue(); 14267 14268 // What vector are we extracting the subvector from and at what index? 14269 SDValue ExtVec = Op.getOperand(0); 14270 14271 // We want the EVT of the original extraction to correctly scale the 14272 // extraction index. 14273 EVT ExtVT = ExtVec.getValueType(); 14274 14275 // Peek through any bitcast. 14276 while (ExtVec.getOpcode() == ISD::BITCAST) 14277 ExtVec = ExtVec.getOperand(0); 14278 14279 // UNDEF nodes convert to UNDEF shuffle mask values. 14280 if (ExtVec.isUndef()) { 14281 Mask.append((unsigned)NumOpElts, -1); 14282 continue; 14283 } 14284 14285 if (!isa<ConstantSDNode>(Op.getOperand(1))) 14286 return SDValue(); 14287 int ExtIdx = Op.getConstantOperandVal(1); 14288 14289 // Ensure that we are extracting a subvector from a vector the same 14290 // size as the result. 14291 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 14292 return SDValue(); 14293 14294 // Scale the subvector index to account for any bitcast. 14295 int NumExtElts = ExtVT.getVectorNumElements(); 14296 if (0 == (NumExtElts % NumElts)) 14297 ExtIdx /= (NumExtElts / NumElts); 14298 else if (0 == (NumElts % NumExtElts)) 14299 ExtIdx *= (NumElts / NumExtElts); 14300 else 14301 return SDValue(); 14302 14303 // At most we can reference 2 inputs in the final shuffle. 14304 if (SV0.isUndef() || SV0 == ExtVec) { 14305 SV0 = ExtVec; 14306 for (int i = 0; i != NumOpElts; ++i) 14307 Mask.push_back(i + ExtIdx); 14308 } else if (SV1.isUndef() || SV1 == ExtVec) { 14309 SV1 = ExtVec; 14310 for (int i = 0; i != NumOpElts; ++i) 14311 Mask.push_back(i + ExtIdx + NumElts); 14312 } else { 14313 return SDValue(); 14314 } 14315 } 14316 14317 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 14318 return SDValue(); 14319 14320 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 14321 DAG.getBitcast(VT, SV1), Mask); 14322 } 14323 14324 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 14325 // If we only have one input vector, we don't need to do any concatenation. 14326 if (N->getNumOperands() == 1) 14327 return N->getOperand(0); 14328 14329 // Check if all of the operands are undefs. 14330 EVT VT = N->getValueType(0); 14331 if (ISD::allOperandsUndef(N)) 14332 return DAG.getUNDEF(VT); 14333 14334 // Optimize concat_vectors where all but the first of the vectors are undef. 14335 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 14336 return Op.isUndef(); 14337 })) { 14338 SDValue In = N->getOperand(0); 14339 assert(In.getValueType().isVector() && "Must concat vectors"); 14340 14341 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 14342 if (In->getOpcode() == ISD::BITCAST && 14343 !In->getOperand(0)->getValueType(0).isVector()) { 14344 SDValue Scalar = In->getOperand(0); 14345 14346 // If the bitcast type isn't legal, it might be a trunc of a legal type; 14347 // look through the trunc so we can still do the transform: 14348 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 14349 if (Scalar->getOpcode() == ISD::TRUNCATE && 14350 !TLI.isTypeLegal(Scalar.getValueType()) && 14351 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 14352 Scalar = Scalar->getOperand(0); 14353 14354 EVT SclTy = Scalar->getValueType(0); 14355 14356 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 14357 return SDValue(); 14358 14359 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 14360 if (VNTNumElms < 2) 14361 return SDValue(); 14362 14363 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 14364 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 14365 return SDValue(); 14366 14367 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 14368 return DAG.getBitcast(VT, Res); 14369 } 14370 } 14371 14372 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 14373 // We have already tested above for an UNDEF only concatenation. 14374 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 14375 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 14376 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 14377 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 14378 }; 14379 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 14380 SmallVector<SDValue, 8> Opnds; 14381 EVT SVT = VT.getScalarType(); 14382 14383 EVT MinVT = SVT; 14384 if (!SVT.isFloatingPoint()) { 14385 // If BUILD_VECTOR are from built from integer, they may have different 14386 // operand types. Get the smallest type and truncate all operands to it. 14387 bool FoundMinVT = false; 14388 for (const SDValue &Op : N->ops()) 14389 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14390 EVT OpSVT = Op.getOperand(0)->getValueType(0); 14391 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 14392 FoundMinVT = true; 14393 } 14394 assert(FoundMinVT && "Concat vector type mismatch"); 14395 } 14396 14397 for (const SDValue &Op : N->ops()) { 14398 EVT OpVT = Op.getValueType(); 14399 unsigned NumElts = OpVT.getVectorNumElements(); 14400 14401 if (ISD::UNDEF == Op.getOpcode()) 14402 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 14403 14404 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 14405 if (SVT.isFloatingPoint()) { 14406 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 14407 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 14408 } else { 14409 for (unsigned i = 0; i != NumElts; ++i) 14410 Opnds.push_back( 14411 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 14412 } 14413 } 14414 } 14415 14416 assert(VT.getVectorNumElements() == Opnds.size() && 14417 "Concat vector type mismatch"); 14418 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 14419 } 14420 14421 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 14422 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 14423 return V; 14424 14425 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 14426 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 14427 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 14428 return V; 14429 14430 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 14431 // nodes often generate nop CONCAT_VECTOR nodes. 14432 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 14433 // place the incoming vectors at the exact same location. 14434 SDValue SingleSource = SDValue(); 14435 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 14436 14437 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 14438 SDValue Op = N->getOperand(i); 14439 14440 if (Op.isUndef()) 14441 continue; 14442 14443 // Check if this is the identity extract: 14444 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14445 return SDValue(); 14446 14447 // Find the single incoming vector for the extract_subvector. 14448 if (SingleSource.getNode()) { 14449 if (Op.getOperand(0) != SingleSource) 14450 return SDValue(); 14451 } else { 14452 SingleSource = Op.getOperand(0); 14453 14454 // Check the source type is the same as the type of the result. 14455 // If not, this concat may extend the vector, so we can not 14456 // optimize it away. 14457 if (SingleSource.getValueType() != N->getValueType(0)) 14458 return SDValue(); 14459 } 14460 14461 unsigned IdentityIndex = i * PartNumElem; 14462 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 14463 // The extract index must be constant. 14464 if (!CS) 14465 return SDValue(); 14466 14467 // Check that we are reading from the identity index. 14468 if (CS->getZExtValue() != IdentityIndex) 14469 return SDValue(); 14470 } 14471 14472 if (SingleSource.getNode()) 14473 return SingleSource; 14474 14475 return SDValue(); 14476 } 14477 14478 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 14479 EVT NVT = N->getValueType(0); 14480 SDValue V = N->getOperand(0); 14481 14482 // Extract from UNDEF is UNDEF. 14483 if (V.isUndef()) 14484 return DAG.getUNDEF(NVT); 14485 14486 // Combine: 14487 // (extract_subvec (concat V1, V2, ...), i) 14488 // Into: 14489 // Vi if possible 14490 // Only operand 0 is checked as 'concat' assumes all inputs of the same 14491 // type. 14492 if (V->getOpcode() == ISD::CONCAT_VECTORS && 14493 isa<ConstantSDNode>(N->getOperand(1)) && 14494 V->getOperand(0).getValueType() == NVT) { 14495 unsigned Idx = N->getConstantOperandVal(1); 14496 unsigned NumElems = NVT.getVectorNumElements(); 14497 assert((Idx % NumElems) == 0 && 14498 "IDX in concat is not a multiple of the result vector length."); 14499 return V->getOperand(Idx / NumElems); 14500 } 14501 14502 // Skip bitcasting 14503 if (V->getOpcode() == ISD::BITCAST) 14504 V = V.getOperand(0); 14505 14506 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 14507 // Handle only simple case where vector being inserted and vector 14508 // being extracted are of same size. 14509 EVT SmallVT = V->getOperand(1).getValueType(); 14510 if (!NVT.bitsEq(SmallVT)) 14511 return SDValue(); 14512 14513 // Only handle cases where both indexes are constants. 14514 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 14515 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14516 14517 if (InsIdx && ExtIdx) { 14518 // Combine: 14519 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 14520 // Into: 14521 // indices are equal or bit offsets are equal => V1 14522 // otherwise => (extract_subvec V1, ExtIdx) 14523 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 14524 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 14525 return DAG.getBitcast(NVT, V->getOperand(1)); 14526 return DAG.getNode( 14527 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 14528 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 14529 N->getOperand(1)); 14530 } 14531 } 14532 14533 return SDValue(); 14534 } 14535 14536 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 14537 SDValue V, SelectionDAG &DAG) { 14538 SDLoc DL(V); 14539 EVT VT = V.getValueType(); 14540 14541 switch (V.getOpcode()) { 14542 default: 14543 return V; 14544 14545 case ISD::CONCAT_VECTORS: { 14546 EVT OpVT = V->getOperand(0).getValueType(); 14547 int OpSize = OpVT.getVectorNumElements(); 14548 SmallBitVector OpUsedElements(OpSize, false); 14549 bool FoundSimplification = false; 14550 SmallVector<SDValue, 4> NewOps; 14551 NewOps.reserve(V->getNumOperands()); 14552 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 14553 SDValue Op = V->getOperand(i); 14554 bool OpUsed = false; 14555 for (int j = 0; j < OpSize; ++j) 14556 if (UsedElements[i * OpSize + j]) { 14557 OpUsedElements[j] = true; 14558 OpUsed = true; 14559 } 14560 NewOps.push_back( 14561 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 14562 : DAG.getUNDEF(OpVT)); 14563 FoundSimplification |= Op == NewOps.back(); 14564 OpUsedElements.reset(); 14565 } 14566 if (FoundSimplification) 14567 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 14568 return V; 14569 } 14570 14571 case ISD::INSERT_SUBVECTOR: { 14572 SDValue BaseV = V->getOperand(0); 14573 SDValue SubV = V->getOperand(1); 14574 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 14575 if (!IdxN) 14576 return V; 14577 14578 int SubSize = SubV.getValueType().getVectorNumElements(); 14579 int Idx = IdxN->getZExtValue(); 14580 bool SubVectorUsed = false; 14581 SmallBitVector SubUsedElements(SubSize, false); 14582 for (int i = 0; i < SubSize; ++i) 14583 if (UsedElements[i + Idx]) { 14584 SubVectorUsed = true; 14585 SubUsedElements[i] = true; 14586 UsedElements[i + Idx] = false; 14587 } 14588 14589 // Now recurse on both the base and sub vectors. 14590 SDValue SimplifiedSubV = 14591 SubVectorUsed 14592 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 14593 : DAG.getUNDEF(SubV.getValueType()); 14594 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 14595 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 14596 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 14597 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 14598 return V; 14599 } 14600 } 14601 } 14602 14603 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 14604 SDValue N1, SelectionDAG &DAG) { 14605 EVT VT = SVN->getValueType(0); 14606 int NumElts = VT.getVectorNumElements(); 14607 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 14608 for (int M : SVN->getMask()) 14609 if (M >= 0 && M < NumElts) 14610 N0UsedElements[M] = true; 14611 else if (M >= NumElts) 14612 N1UsedElements[M - NumElts] = true; 14613 14614 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 14615 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 14616 if (S0 == N0 && S1 == N1) 14617 return SDValue(); 14618 14619 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 14620 } 14621 14622 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 14623 // or turn a shuffle of a single concat into simpler shuffle then concat. 14624 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 14625 EVT VT = N->getValueType(0); 14626 unsigned NumElts = VT.getVectorNumElements(); 14627 14628 SDValue N0 = N->getOperand(0); 14629 SDValue N1 = N->getOperand(1); 14630 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14631 14632 SmallVector<SDValue, 4> Ops; 14633 EVT ConcatVT = N0.getOperand(0).getValueType(); 14634 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 14635 unsigned NumConcats = NumElts / NumElemsPerConcat; 14636 14637 // Special case: shuffle(concat(A,B)) can be more efficiently represented 14638 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 14639 // half vector elements. 14640 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 14641 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 14642 SVN->getMask().end(), [](int i) { return i == -1; })) { 14643 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 14644 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 14645 N1 = DAG.getUNDEF(ConcatVT); 14646 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 14647 } 14648 14649 // Look at every vector that's inserted. We're looking for exact 14650 // subvector-sized copies from a concatenated vector 14651 for (unsigned I = 0; I != NumConcats; ++I) { 14652 // Make sure we're dealing with a copy. 14653 unsigned Begin = I * NumElemsPerConcat; 14654 bool AllUndef = true, NoUndef = true; 14655 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 14656 if (SVN->getMaskElt(J) >= 0) 14657 AllUndef = false; 14658 else 14659 NoUndef = false; 14660 } 14661 14662 if (NoUndef) { 14663 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 14664 return SDValue(); 14665 14666 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 14667 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 14668 return SDValue(); 14669 14670 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 14671 if (FirstElt < N0.getNumOperands()) 14672 Ops.push_back(N0.getOperand(FirstElt)); 14673 else 14674 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 14675 14676 } else if (AllUndef) { 14677 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 14678 } else { // Mixed with general masks and undefs, can't do optimization. 14679 return SDValue(); 14680 } 14681 } 14682 14683 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 14684 } 14685 14686 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 14687 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 14688 // 14689 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 14690 // a simplification in some sense, but it isn't appropriate in general: some 14691 // BUILD_VECTORs are substantially cheaper than others. The general case 14692 // of a BUILD_VECTOR requires inserting each element individually (or 14693 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 14694 // all constants is a single constant pool load. A BUILD_VECTOR where each 14695 // element is identical is a splat. A BUILD_VECTOR where most of the operands 14696 // are undef lowers to a small number of element insertions. 14697 // 14698 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 14699 // We don't fold shuffles where one side is a non-zero constant, and we don't 14700 // fold shuffles if the resulting BUILD_VECTOR would have duplicate 14701 // non-constant operands. This seems to work out reasonably well in practice. 14702 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 14703 SelectionDAG &DAG, 14704 const TargetLowering &TLI) { 14705 EVT VT = SVN->getValueType(0); 14706 unsigned NumElts = VT.getVectorNumElements(); 14707 SDValue N0 = SVN->getOperand(0); 14708 SDValue N1 = SVN->getOperand(1); 14709 14710 if (!N0->hasOneUse() || !N1->hasOneUse()) 14711 return SDValue(); 14712 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 14713 // discussed above. 14714 if (!N1.isUndef()) { 14715 bool N0AnyConst = isAnyConstantBuildVector(N0.getNode()); 14716 bool N1AnyConst = isAnyConstantBuildVector(N1.getNode()); 14717 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 14718 return SDValue(); 14719 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 14720 return SDValue(); 14721 } 14722 14723 SmallVector<SDValue, 8> Ops; 14724 SmallSet<SDValue, 16> DuplicateOps; 14725 for (int M : SVN->getMask()) { 14726 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 14727 if (M >= 0) { 14728 int Idx = M < (int)NumElts ? M : M - NumElts; 14729 SDValue &S = (M < (int)NumElts ? N0 : N1); 14730 if (S.getOpcode() == ISD::BUILD_VECTOR) { 14731 Op = S.getOperand(Idx); 14732 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 14733 if (Idx == 0) 14734 Op = S.getOperand(0); 14735 } else { 14736 // Operand can't be combined - bail out. 14737 return SDValue(); 14738 } 14739 } 14740 14741 // Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is 14742 // fine, but it's likely to generate low-quality code if the target can't 14743 // reconstruct an appropriate shuffle. 14744 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 14745 if (!DuplicateOps.insert(Op).second) 14746 return SDValue(); 14747 14748 Ops.push_back(Op); 14749 } 14750 // BUILD_VECTOR requires all inputs to be of the same type, find the 14751 // maximum type and extend them all. 14752 EVT SVT = VT.getScalarType(); 14753 if (SVT.isInteger()) 14754 for (SDValue &Op : Ops) 14755 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 14756 if (SVT != VT.getScalarType()) 14757 for (SDValue &Op : Ops) 14758 Op = TLI.isZExtFree(Op.getValueType(), SVT) 14759 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 14760 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 14761 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 14762 } 14763 14764 // Match shuffles that can be converted to any_vector_extend_in_reg. 14765 // This is often generated during legalization. 14766 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 14767 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 14768 SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 14769 SelectionDAG &DAG, 14770 const TargetLowering &TLI, 14771 bool LegalOperations) { 14772 EVT VT = SVN->getValueType(0); 14773 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 14774 14775 // TODO Add support for big-endian when we have a test case. 14776 if (!VT.isInteger() || IsBigEndian) 14777 return SDValue(); 14778 14779 unsigned NumElts = VT.getVectorNumElements(); 14780 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 14781 ArrayRef<int> Mask = SVN->getMask(); 14782 SDValue N0 = SVN->getOperand(0); 14783 14784 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 14785 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 14786 for (unsigned i = 0; i != NumElts; ++i) { 14787 if (Mask[i] < 0) 14788 continue; 14789 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 14790 continue; 14791 return false; 14792 } 14793 return true; 14794 }; 14795 14796 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 14797 // power-of-2 extensions as they are the most likely. 14798 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 14799 if (!isAnyExtend(Scale)) 14800 continue; 14801 14802 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 14803 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 14804 if (!LegalOperations || 14805 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 14806 return DAG.getBitcast(VT, 14807 DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT)); 14808 } 14809 14810 return SDValue(); 14811 } 14812 14813 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 14814 // each source element of a large type into the lowest elements of a smaller 14815 // destination type. This is often generated during legalization. 14816 // If the source node itself was a '*_extend_vector_inreg' node then we should 14817 // then be able to remove it. 14818 SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) { 14819 EVT VT = SVN->getValueType(0); 14820 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 14821 14822 // TODO Add support for big-endian when we have a test case. 14823 if (!VT.isInteger() || IsBigEndian) 14824 return SDValue(); 14825 14826 SDValue N0 = SVN->getOperand(0); 14827 while (N0.getOpcode() == ISD::BITCAST) 14828 N0 = N0.getOperand(0); 14829 14830 unsigned Opcode = N0.getOpcode(); 14831 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 14832 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 14833 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 14834 return SDValue(); 14835 14836 SDValue N00 = N0.getOperand(0); 14837 ArrayRef<int> Mask = SVN->getMask(); 14838 unsigned NumElts = VT.getVectorNumElements(); 14839 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 14840 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 14841 14842 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 14843 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 14844 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 14845 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 14846 for (unsigned i = 0; i != NumElts; ++i) { 14847 if (Mask[i] < 0) 14848 continue; 14849 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 14850 continue; 14851 return false; 14852 } 14853 return true; 14854 }; 14855 14856 // At the moment we just handle the case where we've truncated back to the 14857 // same size as before the extension. 14858 // TODO: handle more extension/truncation cases as cases arise. 14859 if (EltSizeInBits != ExtSrcSizeInBits) 14860 return SDValue(); 14861 14862 // Attempt to match a 'truncate_vector_inreg' shuffle, we just search for 14863 // power-of-2 truncations as they are the most likely. 14864 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) 14865 if (isTruncate(Scale)) 14866 return DAG.getBitcast(VT, N00); 14867 14868 return SDValue(); 14869 } 14870 14871 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 14872 EVT VT = N->getValueType(0); 14873 unsigned NumElts = VT.getVectorNumElements(); 14874 14875 SDValue N0 = N->getOperand(0); 14876 SDValue N1 = N->getOperand(1); 14877 14878 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 14879 14880 // Canonicalize shuffle undef, undef -> undef 14881 if (N0.isUndef() && N1.isUndef()) 14882 return DAG.getUNDEF(VT); 14883 14884 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 14885 14886 // Canonicalize shuffle v, v -> v, undef 14887 if (N0 == N1) { 14888 SmallVector<int, 8> NewMask; 14889 for (unsigned i = 0; i != NumElts; ++i) { 14890 int Idx = SVN->getMaskElt(i); 14891 if (Idx >= (int)NumElts) Idx -= NumElts; 14892 NewMask.push_back(Idx); 14893 } 14894 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 14895 } 14896 14897 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 14898 if (N0.isUndef()) 14899 return DAG.getCommutedVectorShuffle(*SVN); 14900 14901 // Remove references to rhs if it is undef 14902 if (N1.isUndef()) { 14903 bool Changed = false; 14904 SmallVector<int, 8> NewMask; 14905 for (unsigned i = 0; i != NumElts; ++i) { 14906 int Idx = SVN->getMaskElt(i); 14907 if (Idx >= (int)NumElts) { 14908 Idx = -1; 14909 Changed = true; 14910 } 14911 NewMask.push_back(Idx); 14912 } 14913 if (Changed) 14914 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 14915 } 14916 14917 // If it is a splat, check if the argument vector is another splat or a 14918 // build_vector. 14919 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 14920 SDNode *V = N0.getNode(); 14921 14922 // If this is a bit convert that changes the element type of the vector but 14923 // not the number of vector elements, look through it. Be careful not to 14924 // look though conversions that change things like v4f32 to v2f64. 14925 if (V->getOpcode() == ISD::BITCAST) { 14926 SDValue ConvInput = V->getOperand(0); 14927 if (ConvInput.getValueType().isVector() && 14928 ConvInput.getValueType().getVectorNumElements() == NumElts) 14929 V = ConvInput.getNode(); 14930 } 14931 14932 if (V->getOpcode() == ISD::BUILD_VECTOR) { 14933 assert(V->getNumOperands() == NumElts && 14934 "BUILD_VECTOR has wrong number of operands"); 14935 SDValue Base; 14936 bool AllSame = true; 14937 for (unsigned i = 0; i != NumElts; ++i) { 14938 if (!V->getOperand(i).isUndef()) { 14939 Base = V->getOperand(i); 14940 break; 14941 } 14942 } 14943 // Splat of <u, u, u, u>, return <u, u, u, u> 14944 if (!Base.getNode()) 14945 return N0; 14946 for (unsigned i = 0; i != NumElts; ++i) { 14947 if (V->getOperand(i) != Base) { 14948 AllSame = false; 14949 break; 14950 } 14951 } 14952 // Splat of <x, x, x, x>, return <x, x, x, x> 14953 if (AllSame) 14954 return N0; 14955 14956 // Canonicalize any other splat as a build_vector. 14957 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 14958 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 14959 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 14960 14961 // We may have jumped through bitcasts, so the type of the 14962 // BUILD_VECTOR may not match the type of the shuffle. 14963 if (V->getValueType(0) != VT) 14964 NewBV = DAG.getBitcast(VT, NewBV); 14965 return NewBV; 14966 } 14967 } 14968 14969 // There are various patterns used to build up a vector from smaller vectors, 14970 // subvectors, or elements. Scan chains of these and replace unused insertions 14971 // or components with undef. 14972 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 14973 return S; 14974 14975 // Match shuffles that can be converted to any_vector_extend_in_reg. 14976 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) 14977 return V; 14978 14979 // Combine "truncate_vector_in_reg" style shuffles. 14980 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 14981 return V; 14982 14983 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 14984 Level < AfterLegalizeVectorOps && 14985 (N1.isUndef() || 14986 (N1.getOpcode() == ISD::CONCAT_VECTORS && 14987 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 14988 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 14989 return V; 14990 } 14991 14992 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 14993 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 14994 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 14995 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 14996 return Res; 14997 14998 // If this shuffle only has a single input that is a bitcasted shuffle, 14999 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 15000 // back to their original types. 15001 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 15002 N1.isUndef() && Level < AfterLegalizeVectorOps && 15003 TLI.isTypeLegal(VT)) { 15004 15005 // Peek through the bitcast only if there is one user. 15006 SDValue BC0 = N0; 15007 while (BC0.getOpcode() == ISD::BITCAST) { 15008 if (!BC0.hasOneUse()) 15009 break; 15010 BC0 = BC0.getOperand(0); 15011 } 15012 15013 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 15014 if (Scale == 1) 15015 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 15016 15017 SmallVector<int, 8> NewMask; 15018 for (int M : Mask) 15019 for (int s = 0; s != Scale; ++s) 15020 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 15021 return NewMask; 15022 }; 15023 15024 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 15025 EVT SVT = VT.getScalarType(); 15026 EVT InnerVT = BC0->getValueType(0); 15027 EVT InnerSVT = InnerVT.getScalarType(); 15028 15029 // Determine which shuffle works with the smaller scalar type. 15030 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 15031 EVT ScaleSVT = ScaleVT.getScalarType(); 15032 15033 if (TLI.isTypeLegal(ScaleVT) && 15034 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 15035 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 15036 15037 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 15038 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 15039 15040 // Scale the shuffle masks to the smaller scalar type. 15041 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 15042 SmallVector<int, 8> InnerMask = 15043 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 15044 SmallVector<int, 8> OuterMask = 15045 ScaleShuffleMask(SVN->getMask(), OuterScale); 15046 15047 // Merge the shuffle masks. 15048 SmallVector<int, 8> NewMask; 15049 for (int M : OuterMask) 15050 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 15051 15052 // Test for shuffle mask legality over both commutations. 15053 SDValue SV0 = BC0->getOperand(0); 15054 SDValue SV1 = BC0->getOperand(1); 15055 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 15056 if (!LegalMask) { 15057 std::swap(SV0, SV1); 15058 ShuffleVectorSDNode::commuteMask(NewMask); 15059 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 15060 } 15061 15062 if (LegalMask) { 15063 SV0 = DAG.getBitcast(ScaleVT, SV0); 15064 SV1 = DAG.getBitcast(ScaleVT, SV1); 15065 return DAG.getBitcast( 15066 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 15067 } 15068 } 15069 } 15070 } 15071 15072 // Canonicalize shuffles according to rules: 15073 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 15074 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 15075 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 15076 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 15077 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 15078 TLI.isTypeLegal(VT)) { 15079 // The incoming shuffle must be of the same type as the result of the 15080 // current shuffle. 15081 assert(N1->getOperand(0).getValueType() == VT && 15082 "Shuffle types don't match"); 15083 15084 SDValue SV0 = N1->getOperand(0); 15085 SDValue SV1 = N1->getOperand(1); 15086 bool HasSameOp0 = N0 == SV0; 15087 bool IsSV1Undef = SV1.isUndef(); 15088 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 15089 // Commute the operands of this shuffle so that next rule 15090 // will trigger. 15091 return DAG.getCommutedVectorShuffle(*SVN); 15092 } 15093 15094 // Try to fold according to rules: 15095 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 15096 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 15097 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 15098 // Don't try to fold shuffles with illegal type. 15099 // Only fold if this shuffle is the only user of the other shuffle. 15100 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 15101 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 15102 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 15103 15104 // Don't try to fold splats; they're likely to simplify somehow, or they 15105 // might be free. 15106 if (OtherSV->isSplat()) 15107 return SDValue(); 15108 15109 // The incoming shuffle must be of the same type as the result of the 15110 // current shuffle. 15111 assert(OtherSV->getOperand(0).getValueType() == VT && 15112 "Shuffle types don't match"); 15113 15114 SDValue SV0, SV1; 15115 SmallVector<int, 4> Mask; 15116 // Compute the combined shuffle mask for a shuffle with SV0 as the first 15117 // operand, and SV1 as the second operand. 15118 for (unsigned i = 0; i != NumElts; ++i) { 15119 int Idx = SVN->getMaskElt(i); 15120 if (Idx < 0) { 15121 // Propagate Undef. 15122 Mask.push_back(Idx); 15123 continue; 15124 } 15125 15126 SDValue CurrentVec; 15127 if (Idx < (int)NumElts) { 15128 // This shuffle index refers to the inner shuffle N0. Lookup the inner 15129 // shuffle mask to identify which vector is actually referenced. 15130 Idx = OtherSV->getMaskElt(Idx); 15131 if (Idx < 0) { 15132 // Propagate Undef. 15133 Mask.push_back(Idx); 15134 continue; 15135 } 15136 15137 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 15138 : OtherSV->getOperand(1); 15139 } else { 15140 // This shuffle index references an element within N1. 15141 CurrentVec = N1; 15142 } 15143 15144 // Simple case where 'CurrentVec' is UNDEF. 15145 if (CurrentVec.isUndef()) { 15146 Mask.push_back(-1); 15147 continue; 15148 } 15149 15150 // Canonicalize the shuffle index. We don't know yet if CurrentVec 15151 // will be the first or second operand of the combined shuffle. 15152 Idx = Idx % NumElts; 15153 if (!SV0.getNode() || SV0 == CurrentVec) { 15154 // Ok. CurrentVec is the left hand side. 15155 // Update the mask accordingly. 15156 SV0 = CurrentVec; 15157 Mask.push_back(Idx); 15158 continue; 15159 } 15160 15161 // Bail out if we cannot convert the shuffle pair into a single shuffle. 15162 if (SV1.getNode() && SV1 != CurrentVec) 15163 return SDValue(); 15164 15165 // Ok. CurrentVec is the right hand side. 15166 // Update the mask accordingly. 15167 SV1 = CurrentVec; 15168 Mask.push_back(Idx + NumElts); 15169 } 15170 15171 // Check if all indices in Mask are Undef. In case, propagate Undef. 15172 bool isUndefMask = true; 15173 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 15174 isUndefMask &= Mask[i] < 0; 15175 15176 if (isUndefMask) 15177 return DAG.getUNDEF(VT); 15178 15179 if (!SV0.getNode()) 15180 SV0 = DAG.getUNDEF(VT); 15181 if (!SV1.getNode()) 15182 SV1 = DAG.getUNDEF(VT); 15183 15184 // Avoid introducing shuffles with illegal mask. 15185 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 15186 ShuffleVectorSDNode::commuteMask(Mask); 15187 15188 if (!TLI.isShuffleMaskLegal(Mask, VT)) 15189 return SDValue(); 15190 15191 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 15192 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 15193 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 15194 std::swap(SV0, SV1); 15195 } 15196 15197 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 15198 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 15199 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 15200 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 15201 } 15202 15203 return SDValue(); 15204 } 15205 15206 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 15207 SDValue InVal = N->getOperand(0); 15208 EVT VT = N->getValueType(0); 15209 15210 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 15211 // with a VECTOR_SHUFFLE. 15212 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 15213 SDValue InVec = InVal->getOperand(0); 15214 SDValue EltNo = InVal->getOperand(1); 15215 15216 // FIXME: We could support implicit truncation if the shuffle can be 15217 // scaled to a smaller vector scalar type. 15218 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 15219 if (C0 && VT == InVec.getValueType() && 15220 VT.getScalarType() == InVal.getValueType()) { 15221 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 15222 int Elt = C0->getZExtValue(); 15223 NewMask[0] = Elt; 15224 15225 if (TLI.isShuffleMaskLegal(NewMask, VT)) 15226 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 15227 NewMask); 15228 } 15229 } 15230 15231 return SDValue(); 15232 } 15233 15234 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 15235 EVT VT = N->getValueType(0); 15236 SDValue N0 = N->getOperand(0); 15237 SDValue N1 = N->getOperand(1); 15238 SDValue N2 = N->getOperand(2); 15239 15240 // If inserting an UNDEF, just return the original vector. 15241 if (N1.isUndef()) 15242 return N0; 15243 15244 // If this is an insert of an extracted vector into an undef vector, we can 15245 // just use the input to the extract. 15246 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 15247 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 15248 return N1.getOperand(0); 15249 15250 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 15251 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 15252 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 15253 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 15254 N0.getOperand(1).getValueType() == N1.getValueType() && 15255 N0.getOperand(2) == N2) 15256 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 15257 N1, N2); 15258 15259 if (!isa<ConstantSDNode>(N2)) 15260 return SDValue(); 15261 15262 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 15263 15264 // Canonicalize insert_subvector dag nodes. 15265 // Example: 15266 // (insert_subvector (insert_subvector A, Idx0), Idx1) 15267 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 15268 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 15269 N1.getValueType() == N0.getOperand(1).getValueType() && 15270 isa<ConstantSDNode>(N0.getOperand(2))) { 15271 unsigned OtherIdx = N0.getConstantOperandVal(2); 15272 if (InsIdx < OtherIdx) { 15273 // Swap nodes. 15274 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 15275 N0.getOperand(0), N1, N2); 15276 AddToWorklist(NewOp.getNode()); 15277 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 15278 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 15279 } 15280 } 15281 15282 // If the input vector is a concatenation, and the insert replaces 15283 // one of the pieces, we can optimize into a single concat_vectors. 15284 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 15285 N0.getOperand(0).getValueType() == N1.getValueType()) { 15286 unsigned Factor = N1.getValueType().getVectorNumElements(); 15287 15288 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 15289 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 15290 15291 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 15292 } 15293 15294 return SDValue(); 15295 } 15296 15297 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 15298 SDValue N0 = N->getOperand(0); 15299 15300 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 15301 if (N0->getOpcode() == ISD::FP16_TO_FP) 15302 return N0->getOperand(0); 15303 15304 return SDValue(); 15305 } 15306 15307 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 15308 SDValue N0 = N->getOperand(0); 15309 15310 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 15311 if (N0->getOpcode() == ISD::AND) { 15312 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 15313 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 15314 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 15315 N0.getOperand(0)); 15316 } 15317 } 15318 15319 return SDValue(); 15320 } 15321 15322 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 15323 /// with the destination vector and a zero vector. 15324 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 15325 /// vector_shuffle V, Zero, <0, 4, 2, 4> 15326 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 15327 EVT VT = N->getValueType(0); 15328 SDValue LHS = N->getOperand(0); 15329 SDValue RHS = N->getOperand(1); 15330 SDLoc DL(N); 15331 15332 // Make sure we're not running after operation legalization where it 15333 // may have custom lowered the vector shuffles. 15334 if (LegalOperations) 15335 return SDValue(); 15336 15337 if (N->getOpcode() != ISD::AND) 15338 return SDValue(); 15339 15340 if (RHS.getOpcode() == ISD::BITCAST) 15341 RHS = RHS.getOperand(0); 15342 15343 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 15344 return SDValue(); 15345 15346 EVT RVT = RHS.getValueType(); 15347 unsigned NumElts = RHS.getNumOperands(); 15348 15349 // Attempt to create a valid clear mask, splitting the mask into 15350 // sub elements and checking to see if each is 15351 // all zeros or all ones - suitable for shuffle masking. 15352 auto BuildClearMask = [&](int Split) { 15353 int NumSubElts = NumElts * Split; 15354 int NumSubBits = RVT.getScalarSizeInBits() / Split; 15355 15356 SmallVector<int, 8> Indices; 15357 for (int i = 0; i != NumSubElts; ++i) { 15358 int EltIdx = i / Split; 15359 int SubIdx = i % Split; 15360 SDValue Elt = RHS.getOperand(EltIdx); 15361 if (Elt.isUndef()) { 15362 Indices.push_back(-1); 15363 continue; 15364 } 15365 15366 APInt Bits; 15367 if (isa<ConstantSDNode>(Elt)) 15368 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 15369 else if (isa<ConstantFPSDNode>(Elt)) 15370 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 15371 else 15372 return SDValue(); 15373 15374 // Extract the sub element from the constant bit mask. 15375 if (DAG.getDataLayout().isBigEndian()) { 15376 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 15377 } else { 15378 Bits.lshrInPlace(SubIdx * NumSubBits); 15379 } 15380 15381 if (Split > 1) 15382 Bits = Bits.trunc(NumSubBits); 15383 15384 if (Bits.isAllOnesValue()) 15385 Indices.push_back(i); 15386 else if (Bits == 0) 15387 Indices.push_back(i + NumSubElts); 15388 else 15389 return SDValue(); 15390 } 15391 15392 // Let's see if the target supports this vector_shuffle. 15393 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 15394 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 15395 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 15396 return SDValue(); 15397 15398 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 15399 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 15400 DAG.getBitcast(ClearVT, LHS), 15401 Zero, Indices)); 15402 }; 15403 15404 // Determine maximum split level (byte level masking). 15405 int MaxSplit = 1; 15406 if (RVT.getScalarSizeInBits() % 8 == 0) 15407 MaxSplit = RVT.getScalarSizeInBits() / 8; 15408 15409 for (int Split = 1; Split <= MaxSplit; ++Split) 15410 if (RVT.getScalarSizeInBits() % Split == 0) 15411 if (SDValue S = BuildClearMask(Split)) 15412 return S; 15413 15414 return SDValue(); 15415 } 15416 15417 /// Visit a binary vector operation, like ADD. 15418 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 15419 assert(N->getValueType(0).isVector() && 15420 "SimplifyVBinOp only works on vectors!"); 15421 15422 SDValue LHS = N->getOperand(0); 15423 SDValue RHS = N->getOperand(1); 15424 SDValue Ops[] = {LHS, RHS}; 15425 15426 // See if we can constant fold the vector operation. 15427 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 15428 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 15429 return Fold; 15430 15431 // Try to convert a constant mask AND into a shuffle clear mask. 15432 if (SDValue Shuffle = XformToShuffleWithZero(N)) 15433 return Shuffle; 15434 15435 // Type legalization might introduce new shuffles in the DAG. 15436 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 15437 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 15438 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 15439 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 15440 LHS.getOperand(1).isUndef() && 15441 RHS.getOperand(1).isUndef()) { 15442 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 15443 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 15444 15445 if (SVN0->getMask().equals(SVN1->getMask())) { 15446 EVT VT = N->getValueType(0); 15447 SDValue UndefVector = LHS.getOperand(1); 15448 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 15449 LHS.getOperand(0), RHS.getOperand(0), 15450 N->getFlags()); 15451 AddUsersToWorklist(N); 15452 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 15453 SVN0->getMask()); 15454 } 15455 } 15456 15457 return SDValue(); 15458 } 15459 15460 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 15461 SDValue N2) { 15462 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 15463 15464 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 15465 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 15466 15467 // If we got a simplified select_cc node back from SimplifySelectCC, then 15468 // break it down into a new SETCC node, and a new SELECT node, and then return 15469 // the SELECT node, since we were called with a SELECT node. 15470 if (SCC.getNode()) { 15471 // Check to see if we got a select_cc back (to turn into setcc/select). 15472 // Otherwise, just return whatever node we got back, like fabs. 15473 if (SCC.getOpcode() == ISD::SELECT_CC) { 15474 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 15475 N0.getValueType(), 15476 SCC.getOperand(0), SCC.getOperand(1), 15477 SCC.getOperand(4)); 15478 AddToWorklist(SETCC.getNode()); 15479 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 15480 SCC.getOperand(2), SCC.getOperand(3)); 15481 } 15482 15483 return SCC; 15484 } 15485 return SDValue(); 15486 } 15487 15488 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 15489 /// being selected between, see if we can simplify the select. Callers of this 15490 /// should assume that TheSelect is deleted if this returns true. As such, they 15491 /// should return the appropriate thing (e.g. the node) back to the top-level of 15492 /// the DAG combiner loop to avoid it being looked at. 15493 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 15494 SDValue RHS) { 15495 15496 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15497 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 15498 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 15499 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 15500 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 15501 SDValue Sqrt = RHS; 15502 ISD::CondCode CC; 15503 SDValue CmpLHS; 15504 const ConstantFPSDNode *Zero = nullptr; 15505 15506 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 15507 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 15508 CmpLHS = TheSelect->getOperand(0); 15509 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 15510 } else { 15511 // SELECT or VSELECT 15512 SDValue Cmp = TheSelect->getOperand(0); 15513 if (Cmp.getOpcode() == ISD::SETCC) { 15514 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 15515 CmpLHS = Cmp.getOperand(0); 15516 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 15517 } 15518 } 15519 if (Zero && Zero->isZero() && 15520 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 15521 CC == ISD::SETULT || CC == ISD::SETLT)) { 15522 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 15523 CombineTo(TheSelect, Sqrt); 15524 return true; 15525 } 15526 } 15527 } 15528 // Cannot simplify select with vector condition 15529 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 15530 15531 // If this is a select from two identical things, try to pull the operation 15532 // through the select. 15533 if (LHS.getOpcode() != RHS.getOpcode() || 15534 !LHS.hasOneUse() || !RHS.hasOneUse()) 15535 return false; 15536 15537 // If this is a load and the token chain is identical, replace the select 15538 // of two loads with a load through a select of the address to load from. 15539 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 15540 // constants have been dropped into the constant pool. 15541 if (LHS.getOpcode() == ISD::LOAD) { 15542 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 15543 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 15544 15545 // Token chains must be identical. 15546 if (LHS.getOperand(0) != RHS.getOperand(0) || 15547 // Do not let this transformation reduce the number of volatile loads. 15548 LLD->isVolatile() || RLD->isVolatile() || 15549 // FIXME: If either is a pre/post inc/dec load, 15550 // we'd need to split out the address adjustment. 15551 LLD->isIndexed() || RLD->isIndexed() || 15552 // If this is an EXTLOAD, the VT's must match. 15553 LLD->getMemoryVT() != RLD->getMemoryVT() || 15554 // If this is an EXTLOAD, the kind of extension must match. 15555 (LLD->getExtensionType() != RLD->getExtensionType() && 15556 // The only exception is if one of the extensions is anyext. 15557 LLD->getExtensionType() != ISD::EXTLOAD && 15558 RLD->getExtensionType() != ISD::EXTLOAD) || 15559 // FIXME: this discards src value information. This is 15560 // over-conservative. It would be beneficial to be able to remember 15561 // both potential memory locations. Since we are discarding 15562 // src value info, don't do the transformation if the memory 15563 // locations are not in the default address space. 15564 LLD->getPointerInfo().getAddrSpace() != 0 || 15565 RLD->getPointerInfo().getAddrSpace() != 0 || 15566 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 15567 LLD->getBasePtr().getValueType())) 15568 return false; 15569 15570 // Check that the select condition doesn't reach either load. If so, 15571 // folding this will induce a cycle into the DAG. If not, this is safe to 15572 // xform, so create a select of the addresses. 15573 SDValue Addr; 15574 if (TheSelect->getOpcode() == ISD::SELECT) { 15575 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 15576 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 15577 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 15578 return false; 15579 // The loads must not depend on one another. 15580 if (LLD->isPredecessorOf(RLD) || 15581 RLD->isPredecessorOf(LLD)) 15582 return false; 15583 Addr = DAG.getSelect(SDLoc(TheSelect), 15584 LLD->getBasePtr().getValueType(), 15585 TheSelect->getOperand(0), LLD->getBasePtr(), 15586 RLD->getBasePtr()); 15587 } else { // Otherwise SELECT_CC 15588 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 15589 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 15590 15591 if ((LLD->hasAnyUseOfValue(1) && 15592 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 15593 (RLD->hasAnyUseOfValue(1) && 15594 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 15595 return false; 15596 15597 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 15598 LLD->getBasePtr().getValueType(), 15599 TheSelect->getOperand(0), 15600 TheSelect->getOperand(1), 15601 LLD->getBasePtr(), RLD->getBasePtr(), 15602 TheSelect->getOperand(4)); 15603 } 15604 15605 SDValue Load; 15606 // It is safe to replace the two loads if they have different alignments, 15607 // but the new load must be the minimum (most restrictive) alignment of the 15608 // inputs. 15609 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 15610 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 15611 if (!RLD->isInvariant()) 15612 MMOFlags &= ~MachineMemOperand::MOInvariant; 15613 if (!RLD->isDereferenceable()) 15614 MMOFlags &= ~MachineMemOperand::MODereferenceable; 15615 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 15616 // FIXME: Discards pointer and AA info. 15617 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 15618 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 15619 MMOFlags); 15620 } else { 15621 // FIXME: Discards pointer and AA info. 15622 Load = DAG.getExtLoad( 15623 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 15624 : LLD->getExtensionType(), 15625 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 15626 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 15627 } 15628 15629 // Users of the select now use the result of the load. 15630 CombineTo(TheSelect, Load); 15631 15632 // Users of the old loads now use the new load's chain. We know the 15633 // old-load value is dead now. 15634 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 15635 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 15636 return true; 15637 } 15638 15639 return false; 15640 } 15641 15642 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 15643 /// bitwise 'and'. 15644 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 15645 SDValue N1, SDValue N2, SDValue N3, 15646 ISD::CondCode CC) { 15647 // If this is a select where the false operand is zero and the compare is a 15648 // check of the sign bit, see if we can perform the "gzip trick": 15649 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 15650 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 15651 EVT XType = N0.getValueType(); 15652 EVT AType = N2.getValueType(); 15653 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 15654 return SDValue(); 15655 15656 // If the comparison is testing for a positive value, we have to invert 15657 // the sign bit mask, so only do that transform if the target has a bitwise 15658 // 'and not' instruction (the invert is free). 15659 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 15660 // (X > -1) ? A : 0 15661 // (X > 0) ? X : 0 <-- This is canonical signed max. 15662 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 15663 return SDValue(); 15664 } else if (CC == ISD::SETLT) { 15665 // (X < 0) ? A : 0 15666 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 15667 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 15668 return SDValue(); 15669 } else { 15670 return SDValue(); 15671 } 15672 15673 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 15674 // constant. 15675 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 15676 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15677 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 15678 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 15679 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 15680 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 15681 AddToWorklist(Shift.getNode()); 15682 15683 if (XType.bitsGT(AType)) { 15684 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 15685 AddToWorklist(Shift.getNode()); 15686 } 15687 15688 if (CC == ISD::SETGT) 15689 Shift = DAG.getNOT(DL, Shift, AType); 15690 15691 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 15692 } 15693 15694 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 15695 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 15696 AddToWorklist(Shift.getNode()); 15697 15698 if (XType.bitsGT(AType)) { 15699 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 15700 AddToWorklist(Shift.getNode()); 15701 } 15702 15703 if (CC == ISD::SETGT) 15704 Shift = DAG.getNOT(DL, Shift, AType); 15705 15706 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 15707 } 15708 15709 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 15710 /// where 'cond' is the comparison specified by CC. 15711 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 15712 SDValue N2, SDValue N3, ISD::CondCode CC, 15713 bool NotExtCompare) { 15714 // (x ? y : y) -> y. 15715 if (N2 == N3) return N2; 15716 15717 EVT VT = N2.getValueType(); 15718 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 15719 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 15720 15721 // Determine if the condition we're dealing with is constant 15722 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 15723 N0, N1, CC, DL, false); 15724 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 15725 15726 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 15727 // fold select_cc true, x, y -> x 15728 // fold select_cc false, x, y -> y 15729 return !SCCC->isNullValue() ? N2 : N3; 15730 } 15731 15732 // Check to see if we can simplify the select into an fabs node 15733 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 15734 // Allow either -0.0 or 0.0 15735 if (CFP->isZero()) { 15736 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 15737 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 15738 N0 == N2 && N3.getOpcode() == ISD::FNEG && 15739 N2 == N3.getOperand(0)) 15740 return DAG.getNode(ISD::FABS, DL, VT, N0); 15741 15742 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 15743 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 15744 N0 == N3 && N2.getOpcode() == ISD::FNEG && 15745 N2.getOperand(0) == N3) 15746 return DAG.getNode(ISD::FABS, DL, VT, N3); 15747 } 15748 } 15749 15750 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 15751 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 15752 // in it. This is a win when the constant is not otherwise available because 15753 // it replaces two constant pool loads with one. We only do this if the FP 15754 // type is known to be legal, because if it isn't, then we are before legalize 15755 // types an we want the other legalization to happen first (e.g. to avoid 15756 // messing with soft float) and if the ConstantFP is not legal, because if 15757 // it is legal, we may not need to store the FP constant in a constant pool. 15758 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 15759 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 15760 if (TLI.isTypeLegal(N2.getValueType()) && 15761 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 15762 TargetLowering::Legal && 15763 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 15764 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 15765 // If both constants have multiple uses, then we won't need to do an 15766 // extra load, they are likely around in registers for other users. 15767 (TV->hasOneUse() || FV->hasOneUse())) { 15768 Constant *Elts[] = { 15769 const_cast<ConstantFP*>(FV->getConstantFPValue()), 15770 const_cast<ConstantFP*>(TV->getConstantFPValue()) 15771 }; 15772 Type *FPTy = Elts[0]->getType(); 15773 const DataLayout &TD = DAG.getDataLayout(); 15774 15775 // Create a ConstantArray of the two constants. 15776 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 15777 SDValue CPIdx = 15778 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 15779 TD.getPrefTypeAlignment(FPTy)); 15780 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 15781 15782 // Get the offsets to the 0 and 1 element of the array so that we can 15783 // select between them. 15784 SDValue Zero = DAG.getIntPtrConstant(0, DL); 15785 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 15786 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 15787 15788 SDValue Cond = DAG.getSetCC(DL, 15789 getSetCCResultType(N0.getValueType()), 15790 N0, N1, CC); 15791 AddToWorklist(Cond.getNode()); 15792 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 15793 Cond, One, Zero); 15794 AddToWorklist(CstOffset.getNode()); 15795 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 15796 CstOffset); 15797 AddToWorklist(CPIdx.getNode()); 15798 return DAG.getLoad( 15799 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 15800 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 15801 Alignment); 15802 } 15803 } 15804 15805 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 15806 return V; 15807 15808 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 15809 // where y is has a single bit set. 15810 // A plaintext description would be, we can turn the SELECT_CC into an AND 15811 // when the condition can be materialized as an all-ones register. Any 15812 // single bit-test can be materialized as an all-ones register with 15813 // shift-left and shift-right-arith. 15814 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 15815 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 15816 SDValue AndLHS = N0->getOperand(0); 15817 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 15818 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 15819 // Shift the tested bit over the sign bit. 15820 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 15821 SDValue ShlAmt = 15822 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 15823 getShiftAmountTy(AndLHS.getValueType())); 15824 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 15825 15826 // Now arithmetic right shift it all the way over, so the result is either 15827 // all-ones, or zero. 15828 SDValue ShrAmt = 15829 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 15830 getShiftAmountTy(Shl.getValueType())); 15831 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 15832 15833 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 15834 } 15835 } 15836 15837 // fold select C, 16, 0 -> shl C, 4 15838 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 15839 TLI.getBooleanContents(N0.getValueType()) == 15840 TargetLowering::ZeroOrOneBooleanContent) { 15841 15842 // If the caller doesn't want us to simplify this into a zext of a compare, 15843 // don't do it. 15844 if (NotExtCompare && N2C->isOne()) 15845 return SDValue(); 15846 15847 // Get a SetCC of the condition 15848 // NOTE: Don't create a SETCC if it's not legal on this target. 15849 if (!LegalOperations || 15850 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 15851 SDValue Temp, SCC; 15852 // cast from setcc result type to select result type 15853 if (LegalTypes) { 15854 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 15855 N0, N1, CC); 15856 if (N2.getValueType().bitsLT(SCC.getValueType())) 15857 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 15858 N2.getValueType()); 15859 else 15860 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 15861 N2.getValueType(), SCC); 15862 } else { 15863 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 15864 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 15865 N2.getValueType(), SCC); 15866 } 15867 15868 AddToWorklist(SCC.getNode()); 15869 AddToWorklist(Temp.getNode()); 15870 15871 if (N2C->isOne()) 15872 return Temp; 15873 15874 // shl setcc result by log2 n2c 15875 return DAG.getNode( 15876 ISD::SHL, DL, N2.getValueType(), Temp, 15877 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 15878 getShiftAmountTy(Temp.getValueType()))); 15879 } 15880 } 15881 15882 // Check to see if this is an integer abs. 15883 // select_cc setg[te] X, 0, X, -X -> 15884 // select_cc setgt X, -1, X, -X -> 15885 // select_cc setl[te] X, 0, -X, X -> 15886 // select_cc setlt X, 1, -X, X -> 15887 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 15888 if (N1C) { 15889 ConstantSDNode *SubC = nullptr; 15890 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 15891 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 15892 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 15893 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 15894 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 15895 (N1C->isOne() && CC == ISD::SETLT)) && 15896 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 15897 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 15898 15899 EVT XType = N0.getValueType(); 15900 if (SubC && SubC->isNullValue() && XType.isInteger()) { 15901 SDLoc DL(N0); 15902 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 15903 N0, 15904 DAG.getConstant(XType.getSizeInBits() - 1, DL, 15905 getShiftAmountTy(N0.getValueType()))); 15906 SDValue Add = DAG.getNode(ISD::ADD, DL, 15907 XType, N0, Shift); 15908 AddToWorklist(Shift.getNode()); 15909 AddToWorklist(Add.getNode()); 15910 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 15911 } 15912 } 15913 15914 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 15915 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 15916 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 15917 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 15918 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 15919 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 15920 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 15921 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 15922 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 15923 SDValue ValueOnZero = N2; 15924 SDValue Count = N3; 15925 // If the condition is NE instead of E, swap the operands. 15926 if (CC == ISD::SETNE) 15927 std::swap(ValueOnZero, Count); 15928 // Check if the value on zero is a constant equal to the bits in the type. 15929 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 15930 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 15931 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 15932 // legal, combine to just cttz. 15933 if ((Count.getOpcode() == ISD::CTTZ || 15934 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 15935 N0 == Count.getOperand(0) && 15936 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 15937 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 15938 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 15939 // legal, combine to just ctlz. 15940 if ((Count.getOpcode() == ISD::CTLZ || 15941 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 15942 N0 == Count.getOperand(0) && 15943 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 15944 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 15945 } 15946 } 15947 } 15948 15949 return SDValue(); 15950 } 15951 15952 /// This is a stub for TargetLowering::SimplifySetCC. 15953 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 15954 ISD::CondCode Cond, const SDLoc &DL, 15955 bool foldBooleans) { 15956 TargetLowering::DAGCombinerInfo 15957 DagCombineInfo(DAG, Level, false, this); 15958 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 15959 } 15960 15961 /// Given an ISD::SDIV node expressing a divide by constant, return 15962 /// a DAG expression to select that will generate the same value by multiplying 15963 /// by a magic number. 15964 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 15965 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 15966 // when optimising for minimum size, we don't want to expand a div to a mul 15967 // and a shift. 15968 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 15969 return SDValue(); 15970 15971 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15972 if (!C) 15973 return SDValue(); 15974 15975 // Avoid division by zero. 15976 if (C->isNullValue()) 15977 return SDValue(); 15978 15979 std::vector<SDNode*> Built; 15980 SDValue S = 15981 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 15982 15983 for (SDNode *N : Built) 15984 AddToWorklist(N); 15985 return S; 15986 } 15987 15988 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 15989 /// DAG expression that will generate the same value by right shifting. 15990 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 15991 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 15992 if (!C) 15993 return SDValue(); 15994 15995 // Avoid division by zero. 15996 if (C->isNullValue()) 15997 return SDValue(); 15998 15999 std::vector<SDNode *> Built; 16000 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 16001 16002 for (SDNode *N : Built) 16003 AddToWorklist(N); 16004 return S; 16005 } 16006 16007 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 16008 /// expression that will generate the same value by multiplying by a magic 16009 /// number. 16010 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 16011 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 16012 // when optimising for minimum size, we don't want to expand a div to a mul 16013 // and a shift. 16014 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 16015 return SDValue(); 16016 16017 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 16018 if (!C) 16019 return SDValue(); 16020 16021 // Avoid division by zero. 16022 if (C->isNullValue()) 16023 return SDValue(); 16024 16025 std::vector<SDNode*> Built; 16026 SDValue S = 16027 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 16028 16029 for (SDNode *N : Built) 16030 AddToWorklist(N); 16031 return S; 16032 } 16033 16034 /// Determines the LogBase2 value for a non-null input value using the 16035 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 16036 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 16037 EVT VT = V.getValueType(); 16038 unsigned EltBits = VT.getScalarSizeInBits(); 16039 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 16040 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 16041 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 16042 return LogBase2; 16043 } 16044 16045 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16046 /// For the reciprocal, we need to find the zero of the function: 16047 /// F(X) = A X - 1 [which has a zero at X = 1/A] 16048 /// => 16049 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 16050 /// does not require additional intermediate precision] 16051 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 16052 if (Level >= AfterLegalizeDAG) 16053 return SDValue(); 16054 16055 // TODO: Handle half and/or extended types? 16056 EVT VT = Op.getValueType(); 16057 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 16058 return SDValue(); 16059 16060 // If estimates are explicitly disabled for this function, we're done. 16061 MachineFunction &MF = DAG.getMachineFunction(); 16062 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 16063 if (Enabled == TLI.ReciprocalEstimate::Disabled) 16064 return SDValue(); 16065 16066 // Estimates may be explicitly enabled for this type with a custom number of 16067 // refinement steps. 16068 int Iterations = TLI.getDivRefinementSteps(VT, MF); 16069 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 16070 AddToWorklist(Est.getNode()); 16071 16072 if (Iterations) { 16073 EVT VT = Op.getValueType(); 16074 SDLoc DL(Op); 16075 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 16076 16077 // Newton iterations: Est = Est + Est (1 - Arg * Est) 16078 for (int i = 0; i < Iterations; ++i) { 16079 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 16080 AddToWorklist(NewEst.getNode()); 16081 16082 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 16083 AddToWorklist(NewEst.getNode()); 16084 16085 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 16086 AddToWorklist(NewEst.getNode()); 16087 16088 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 16089 AddToWorklist(Est.getNode()); 16090 } 16091 } 16092 return Est; 16093 } 16094 16095 return SDValue(); 16096 } 16097 16098 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16099 /// For the reciprocal sqrt, we need to find the zero of the function: 16100 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 16101 /// => 16102 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 16103 /// As a result, we precompute A/2 prior to the iteration loop. 16104 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 16105 unsigned Iterations, 16106 SDNodeFlags Flags, bool Reciprocal) { 16107 EVT VT = Arg.getValueType(); 16108 SDLoc DL(Arg); 16109 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 16110 16111 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 16112 // this entire sequence requires only one FP constant. 16113 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 16114 AddToWorklist(HalfArg.getNode()); 16115 16116 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 16117 AddToWorklist(HalfArg.getNode()); 16118 16119 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 16120 for (unsigned i = 0; i < Iterations; ++i) { 16121 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 16122 AddToWorklist(NewEst.getNode()); 16123 16124 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 16125 AddToWorklist(NewEst.getNode()); 16126 16127 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 16128 AddToWorklist(NewEst.getNode()); 16129 16130 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 16131 AddToWorklist(Est.getNode()); 16132 } 16133 16134 // If non-reciprocal square root is requested, multiply the result by Arg. 16135 if (!Reciprocal) { 16136 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 16137 AddToWorklist(Est.getNode()); 16138 } 16139 16140 return Est; 16141 } 16142 16143 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 16144 /// For the reciprocal sqrt, we need to find the zero of the function: 16145 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 16146 /// => 16147 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 16148 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 16149 unsigned Iterations, 16150 SDNodeFlags Flags, bool Reciprocal) { 16151 EVT VT = Arg.getValueType(); 16152 SDLoc DL(Arg); 16153 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 16154 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 16155 16156 // This routine must enter the loop below to work correctly 16157 // when (Reciprocal == false). 16158 assert(Iterations > 0); 16159 16160 // Newton iterations for reciprocal square root: 16161 // E = (E * -0.5) * ((A * E) * E + -3.0) 16162 for (unsigned i = 0; i < Iterations; ++i) { 16163 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 16164 AddToWorklist(AE.getNode()); 16165 16166 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 16167 AddToWorklist(AEE.getNode()); 16168 16169 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 16170 AddToWorklist(RHS.getNode()); 16171 16172 // When calculating a square root at the last iteration build: 16173 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 16174 // (notice a common subexpression) 16175 SDValue LHS; 16176 if (Reciprocal || (i + 1) < Iterations) { 16177 // RSQRT: LHS = (E * -0.5) 16178 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 16179 } else { 16180 // SQRT: LHS = (A * E) * -0.5 16181 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 16182 } 16183 AddToWorklist(LHS.getNode()); 16184 16185 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 16186 AddToWorklist(Est.getNode()); 16187 } 16188 16189 return Est; 16190 } 16191 16192 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 16193 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 16194 /// Op can be zero. 16195 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 16196 bool Reciprocal) { 16197 if (Level >= AfterLegalizeDAG) 16198 return SDValue(); 16199 16200 // TODO: Handle half and/or extended types? 16201 EVT VT = Op.getValueType(); 16202 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 16203 return SDValue(); 16204 16205 // If estimates are explicitly disabled for this function, we're done. 16206 MachineFunction &MF = DAG.getMachineFunction(); 16207 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 16208 if (Enabled == TLI.ReciprocalEstimate::Disabled) 16209 return SDValue(); 16210 16211 // Estimates may be explicitly enabled for this type with a custom number of 16212 // refinement steps. 16213 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 16214 16215 bool UseOneConstNR = false; 16216 if (SDValue Est = 16217 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 16218 Reciprocal)) { 16219 AddToWorklist(Est.getNode()); 16220 16221 if (Iterations) { 16222 Est = UseOneConstNR 16223 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 16224 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 16225 16226 if (!Reciprocal) { 16227 // Unfortunately, Est is now NaN if the input was exactly 0.0. 16228 // Select out this case and force the answer to 0.0. 16229 EVT VT = Op.getValueType(); 16230 SDLoc DL(Op); 16231 16232 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 16233 EVT CCVT = getSetCCResultType(VT); 16234 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 16235 AddToWorklist(ZeroCmp.getNode()); 16236 16237 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 16238 ZeroCmp, FPZero, Est); 16239 AddToWorklist(Est.getNode()); 16240 } 16241 } 16242 return Est; 16243 } 16244 16245 return SDValue(); 16246 } 16247 16248 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 16249 return buildSqrtEstimateImpl(Op, Flags, true); 16250 } 16251 16252 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 16253 return buildSqrtEstimateImpl(Op, Flags, false); 16254 } 16255 16256 /// Return true if base is a frame index, which is known not to alias with 16257 /// anything but itself. Provides base object and offset as results. 16258 static bool findBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 16259 const GlobalValue *&GV, const void *&CV) { 16260 // Assume it is a primitive operation. 16261 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 16262 16263 // If it's an adding a simple constant then integrate the offset. 16264 if (Base.getOpcode() == ISD::ADD) { 16265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 16266 Base = Base.getOperand(0); 16267 Offset += C->getSExtValue(); 16268 } 16269 } 16270 16271 // Return the underlying GlobalValue, and update the Offset. Return false 16272 // for GlobalAddressSDNode since the same GlobalAddress may be represented 16273 // by multiple nodes with different offsets. 16274 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 16275 GV = G->getGlobal(); 16276 Offset += G->getOffset(); 16277 return false; 16278 } 16279 16280 // Return the underlying Constant value, and update the Offset. Return false 16281 // for ConstantSDNodes since the same constant pool entry may be represented 16282 // by multiple nodes with different offsets. 16283 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 16284 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 16285 : (const void *)C->getConstVal(); 16286 Offset += C->getOffset(); 16287 return false; 16288 } 16289 // If it's any of the following then it can't alias with anything but itself. 16290 return isa<FrameIndexSDNode>(Base); 16291 } 16292 16293 /// Return true if there is any possibility that the two addresses overlap. 16294 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 16295 // If they are the same then they must be aliases. 16296 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 16297 16298 // If they are both volatile then they cannot be reordered. 16299 if (Op0->isVolatile() && Op1->isVolatile()) return true; 16300 16301 // If one operation reads from invariant memory, and the other may store, they 16302 // cannot alias. These should really be checking the equivalent of mayWrite, 16303 // but it only matters for memory nodes other than load /store. 16304 if (Op0->isInvariant() && Op1->writeMem()) 16305 return false; 16306 16307 if (Op1->isInvariant() && Op0->writeMem()) 16308 return false; 16309 16310 unsigned NumBytes0 = Op0->getMemoryVT().getSizeInBits() >> 3; 16311 unsigned NumBytes1 = Op1->getMemoryVT().getSizeInBits() >> 3; 16312 16313 // Check for BaseIndexOffset matching. 16314 BaseIndexOffset BasePtr0 = BaseIndexOffset::match(Op0->getBasePtr(), DAG); 16315 BaseIndexOffset BasePtr1 = BaseIndexOffset::match(Op1->getBasePtr(), DAG); 16316 if (BasePtr0.equalBaseIndex(BasePtr1)) 16317 return !((BasePtr0.Offset + NumBytes0 <= BasePtr1.Offset) || 16318 (BasePtr1.Offset + NumBytes1 <= BasePtr0.Offset)); 16319 16320 // FIXME: findBaseOffset and ConstantValue/GlobalValue/FrameIndex analysis 16321 // modified to use BaseIndexOffset. 16322 16323 // Gather base node and offset information. 16324 SDValue Base0, Base1; 16325 int64_t Offset0, Offset1; 16326 const GlobalValue *GV0, *GV1; 16327 const void *CV0, *CV1; 16328 bool IsFrameIndex0 = findBaseOffset(Op0->getBasePtr(), 16329 Base0, Offset0, GV0, CV0); 16330 bool IsFrameIndex1 = findBaseOffset(Op1->getBasePtr(), 16331 Base1, Offset1, GV1, CV1); 16332 16333 // If they have the same base address, then check to see if they overlap. 16334 if (Base0 == Base1 || (GV0 && (GV0 == GV1)) || (CV0 && (CV0 == CV1))) 16335 return !((Offset0 + NumBytes0) <= Offset1 || 16336 (Offset1 + NumBytes1) <= Offset0); 16337 16338 // It is possible for different frame indices to alias each other, mostly 16339 // when tail call optimization reuses return address slots for arguments. 16340 // To catch this case, look up the actual index of frame indices to compute 16341 // the real alias relationship. 16342 if (IsFrameIndex0 && IsFrameIndex1) { 16343 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 16344 Offset0 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base0)->getIndex()); 16345 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 16346 return !((Offset0 + NumBytes0) <= Offset1 || 16347 (Offset1 + NumBytes1) <= Offset0); 16348 } 16349 16350 // Otherwise, if we know what the bases are, and they aren't identical, then 16351 // we know they cannot alias. 16352 if ((IsFrameIndex0 || CV0 || GV0) && (IsFrameIndex1 || CV1 || GV1)) 16353 return false; 16354 16355 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 16356 // compared to the size and offset of the access, we may be able to prove they 16357 // do not alias. This check is conservative for now to catch cases created by 16358 // splitting vector types. 16359 int64_t SrcValOffset0 = Op0->getSrcValueOffset(); 16360 int64_t SrcValOffset1 = Op1->getSrcValueOffset(); 16361 unsigned OrigAlignment0 = Op0->getOriginalAlignment(); 16362 unsigned OrigAlignment1 = Op1->getOriginalAlignment(); 16363 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 16364 NumBytes0 == NumBytes1 && OrigAlignment0 > NumBytes0) { 16365 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 16366 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 16367 16368 // There is no overlap between these relatively aligned accesses of similar 16369 // size. Return no alias. 16370 if ((OffAlign0 + NumBytes0) <= OffAlign1 || 16371 (OffAlign1 + NumBytes1) <= OffAlign0) 16372 return false; 16373 } 16374 16375 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 16376 ? CombinerGlobalAA 16377 : DAG.getSubtarget().useAA(); 16378 #ifndef NDEBUG 16379 if (CombinerAAOnlyFunc.getNumOccurrences() && 16380 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 16381 UseAA = false; 16382 #endif 16383 16384 if (UseAA && 16385 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 16386 // Use alias analysis information. 16387 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 16388 int64_t Overlap0 = NumBytes0 + SrcValOffset0 - MinOffset; 16389 int64_t Overlap1 = NumBytes1 + SrcValOffset1 - MinOffset; 16390 AliasResult AAResult = 16391 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap0, 16392 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 16393 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap1, 16394 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 16395 if (AAResult == NoAlias) 16396 return false; 16397 } 16398 16399 // Otherwise we have to assume they alias. 16400 return true; 16401 } 16402 16403 /// Walk up chain skipping non-aliasing memory nodes, 16404 /// looking for aliasing nodes and adding them to the Aliases vector. 16405 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 16406 SmallVectorImpl<SDValue> &Aliases) { 16407 SmallVector<SDValue, 8> Chains; // List of chains to visit. 16408 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 16409 16410 // Get alias information for node. 16411 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 16412 16413 // Starting off. 16414 Chains.push_back(OriginalChain); 16415 unsigned Depth = 0; 16416 16417 // Look at each chain and determine if it is an alias. If so, add it to the 16418 // aliases list. If not, then continue up the chain looking for the next 16419 // candidate. 16420 while (!Chains.empty()) { 16421 SDValue Chain = Chains.pop_back_val(); 16422 16423 // For TokenFactor nodes, look at each operand and only continue up the 16424 // chain until we reach the depth limit. 16425 // 16426 // FIXME: The depth check could be made to return the last non-aliasing 16427 // chain we found before we hit a tokenfactor rather than the original 16428 // chain. 16429 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 16430 Aliases.clear(); 16431 Aliases.push_back(OriginalChain); 16432 return; 16433 } 16434 16435 // Don't bother if we've been before. 16436 if (!Visited.insert(Chain.getNode()).second) 16437 continue; 16438 16439 switch (Chain.getOpcode()) { 16440 case ISD::EntryToken: 16441 // Entry token is ideal chain operand, but handled in FindBetterChain. 16442 break; 16443 16444 case ISD::LOAD: 16445 case ISD::STORE: { 16446 // Get alias information for Chain. 16447 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 16448 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 16449 16450 // If chain is alias then stop here. 16451 if (!(IsLoad && IsOpLoad) && 16452 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 16453 Aliases.push_back(Chain); 16454 } else { 16455 // Look further up the chain. 16456 Chains.push_back(Chain.getOperand(0)); 16457 ++Depth; 16458 } 16459 break; 16460 } 16461 16462 case ISD::TokenFactor: 16463 // We have to check each of the operands of the token factor for "small" 16464 // token factors, so we queue them up. Adding the operands to the queue 16465 // (stack) in reverse order maintains the original order and increases the 16466 // likelihood that getNode will find a matching token factor (CSE.) 16467 if (Chain.getNumOperands() > 16) { 16468 Aliases.push_back(Chain); 16469 break; 16470 } 16471 for (unsigned n = Chain.getNumOperands(); n;) 16472 Chains.push_back(Chain.getOperand(--n)); 16473 ++Depth; 16474 break; 16475 16476 case ISD::CopyFromReg: 16477 // Forward past CopyFromReg. 16478 Chains.push_back(Chain.getOperand(0)); 16479 ++Depth; 16480 break; 16481 16482 default: 16483 // For all other instructions we will just have to take what we can get. 16484 Aliases.push_back(Chain); 16485 break; 16486 } 16487 } 16488 } 16489 16490 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 16491 /// (aliasing node.) 16492 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 16493 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 16494 16495 // Accumulate all the aliases to this node. 16496 GatherAllAliases(N, OldChain, Aliases); 16497 16498 // If no operands then chain to entry token. 16499 if (Aliases.size() == 0) 16500 return DAG.getEntryNode(); 16501 16502 // If a single operand then chain to it. We don't need to revisit it. 16503 if (Aliases.size() == 1) 16504 return Aliases[0]; 16505 16506 // Construct a custom tailored token factor. 16507 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 16508 } 16509 16510 // This function tries to collect a bunch of potentially interesting 16511 // nodes to improve the chains of, all at once. This might seem 16512 // redundant, as this function gets called when visiting every store 16513 // node, so why not let the work be done on each store as it's visited? 16514 // 16515 // I believe this is mainly important because MergeConsecutiveStores 16516 // is unable to deal with merging stores of different sizes, so unless 16517 // we improve the chains of all the potential candidates up-front 16518 // before running MergeConsecutiveStores, it might only see some of 16519 // the nodes that will eventually be candidates, and then not be able 16520 // to go from a partially-merged state to the desired final 16521 // fully-merged state. 16522 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 16523 // This holds the base pointer, index, and the offset in bytes from the base 16524 // pointer. 16525 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 16526 16527 // We must have a base and an offset. 16528 if (!BasePtr.Base.getNode()) 16529 return false; 16530 16531 // Do not handle stores to undef base pointers. 16532 if (BasePtr.Base.isUndef()) 16533 return false; 16534 16535 SmallVector<StoreSDNode *, 8> ChainedStores; 16536 ChainedStores.push_back(St); 16537 16538 // Walk up the chain and look for nodes with offsets from the same 16539 // base pointer. Stop when reaching an instruction with a different kind 16540 // or instruction which has a different base pointer. 16541 StoreSDNode *Index = St; 16542 while (Index) { 16543 // If the chain has more than one use, then we can't reorder the mem ops. 16544 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 16545 break; 16546 16547 if (Index->isVolatile() || Index->isIndexed()) 16548 break; 16549 16550 // Find the base pointer and offset for this memory node. 16551 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 16552 16553 // Check that the base pointer is the same as the original one. 16554 if (!Ptr.equalBaseIndex(BasePtr)) 16555 break; 16556 16557 // Walk up the chain to find the next store node, ignoring any 16558 // intermediate loads. Any other kind of node will halt the loop. 16559 SDNode *NextInChain = Index->getChain().getNode(); 16560 while (true) { 16561 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 16562 // We found a store node. Use it for the next iteration. 16563 if (STn->isVolatile() || STn->isIndexed()) { 16564 Index = nullptr; 16565 break; 16566 } 16567 ChainedStores.push_back(STn); 16568 Index = STn; 16569 break; 16570 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 16571 NextInChain = Ldn->getChain().getNode(); 16572 continue; 16573 } else { 16574 Index = nullptr; 16575 break; 16576 } 16577 } // end while 16578 } 16579 16580 // At this point, ChainedStores lists all of the Store nodes 16581 // reachable by iterating up through chain nodes matching the above 16582 // conditions. For each such store identified, try to find an 16583 // earlier chain to attach the store to which won't violate the 16584 // required ordering. 16585 bool MadeChangeToSt = false; 16586 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 16587 16588 for (StoreSDNode *ChainedStore : ChainedStores) { 16589 SDValue Chain = ChainedStore->getChain(); 16590 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 16591 16592 if (Chain != BetterChain) { 16593 if (ChainedStore == St) 16594 MadeChangeToSt = true; 16595 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 16596 } 16597 } 16598 16599 // Do all replacements after finding the replacements to make to avoid making 16600 // the chains more complicated by introducing new TokenFactors. 16601 for (auto Replacement : BetterChains) 16602 replaceStoreChain(Replacement.first, Replacement.second); 16603 16604 return MadeChangeToSt; 16605 } 16606 16607 /// This is the entry point for the file. 16608 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 16609 CodeGenOpt::Level OptLevel) { 16610 /// This is the main entry point to this class. 16611 DAGCombiner(*this, AA, OptLevel).Run(Level); 16612 } 16613