1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/SelectionDAG.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetLowering.h" 37 #include "llvm/Target/TargetOptions.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 #define DEBUG_TYPE "dagcombine" 44 45 STATISTIC(NodesCombined , "Number of dag nodes combined"); 46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 50 STATISTIC(SlicedLoads, "Number of load sliced"); 51 52 namespace { 53 static cl::opt<bool> 54 CombinerAA("combiner-alias-analysis", cl::Hidden, 55 cl::desc("Enable DAG combiner alias-analysis heuristics")); 56 57 static cl::opt<bool> 58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 59 cl::desc("Enable DAG combiner's use of IR alias analysis")); 60 61 static cl::opt<bool> 62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 63 cl::desc("Enable DAG combiner's use of TBAA")); 64 65 #ifndef NDEBUG 66 static cl::opt<std::string> 67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 68 cl::desc("Only use DAG-combiner alias analysis in this" 69 " function")); 70 #endif 71 72 /// Hidden option to stress test load slicing, i.e., when this option 73 /// is enabled, load slicing bypasses most of its profitability guards. 74 static cl::opt<bool> 75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 76 cl::desc("Bypass the profitability model of load " 77 "slicing"), 78 cl::init(false)); 79 80 static cl::opt<bool> 81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 82 cl::desc("DAG combiner may split indexing from loads")); 83 84 //------------------------------ DAGCombiner ---------------------------------// 85 86 class DAGCombiner { 87 SelectionDAG &DAG; 88 const TargetLowering &TLI; 89 CombineLevel Level; 90 CodeGenOpt::Level OptLevel; 91 bool LegalOperations; 92 bool LegalTypes; 93 bool ForCodeSize; 94 95 /// \brief Worklist of all of the nodes that need to be simplified. 96 /// 97 /// This must behave as a stack -- new nodes to process are pushed onto the 98 /// back and when processing we pop off of the back. 99 /// 100 /// The worklist will not contain duplicates but may contain null entries 101 /// due to nodes being deleted from the underlying DAG. 102 SmallVector<SDNode *, 64> Worklist; 103 104 /// \brief Mapping from an SDNode to its position on the worklist. 105 /// 106 /// This is used to find and remove nodes from the worklist (by nulling 107 /// them) when they are deleted from the underlying DAG. It relies on 108 /// stable indices of nodes within the worklist. 109 DenseMap<SDNode *, unsigned> WorklistMap; 110 111 /// \brief Set of nodes which have been combined (at least once). 112 /// 113 /// This is used to allow us to reliably add any operands of a DAG node 114 /// which have not yet been combined to the worklist. 115 SmallPtrSet<SDNode *, 64> CombinedNodes; 116 117 // AA - Used for DAG load/store alias analysis. 118 AliasAnalysis &AA; 119 120 /// When an instruction is simplified, add all users of the instruction to 121 /// the work lists because they might get more simplified now. 122 void AddUsersToWorklist(SDNode *N) { 123 for (SDNode *Node : N->uses()) 124 AddToWorklist(Node); 125 } 126 127 /// Call the node-specific routine that folds each particular type of node. 128 SDValue visit(SDNode *N); 129 130 public: 131 /// Add to the worklist making sure its instance is at the back (next to be 132 /// processed.) 133 void AddToWorklist(SDNode *N) { 134 // Skip handle nodes as they can't usefully be combined and confuse the 135 // zero-use deletion strategy. 136 if (N->getOpcode() == ISD::HANDLENODE) 137 return; 138 139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 140 Worklist.push_back(N); 141 } 142 143 /// Remove all instances of N from the worklist. 144 void removeFromWorklist(SDNode *N) { 145 CombinedNodes.erase(N); 146 147 auto It = WorklistMap.find(N); 148 if (It == WorklistMap.end()) 149 return; // Not in the worklist. 150 151 // Null out the entry rather than erasing it to avoid a linear operation. 152 Worklist[It->second] = nullptr; 153 WorklistMap.erase(It); 154 } 155 156 void deleteAndRecombine(SDNode *N); 157 bool recursivelyDeleteUnusedNodes(SDNode *N); 158 159 /// Replaces all uses of the results of one DAG node with new values. 160 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 161 bool AddTo = true); 162 163 /// Replaces all uses of the results of one DAG node with new values. 164 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 165 return CombineTo(N, &Res, 1, AddTo); 166 } 167 168 /// Replaces all uses of the results of one DAG node with new values. 169 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 170 bool AddTo = true) { 171 SDValue To[] = { Res0, Res1 }; 172 return CombineTo(N, To, 2, AddTo); 173 } 174 175 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 176 177 private: 178 179 /// Check the specified integer node value to see if it can be simplified or 180 /// if things it uses can be simplified by bit propagation. 181 /// If so, return true. 182 bool SimplifyDemandedBits(SDValue Op) { 183 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 184 APInt Demanded = APInt::getAllOnesValue(BitWidth); 185 return SimplifyDemandedBits(Op, Demanded); 186 } 187 188 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 189 190 bool CombineToPreIndexedLoadStore(SDNode *N); 191 bool CombineToPostIndexedLoadStore(SDNode *N); 192 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 193 bool SliceUpLoad(SDNode *N); 194 195 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 196 /// load. 197 /// 198 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 199 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 200 /// \param EltNo index of the vector element to load. 201 /// \param OriginalLoad load that EVE came from to be replaced. 202 /// \returns EVE on success SDValue() on failure. 203 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 204 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 205 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 206 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 207 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 208 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 209 SDValue PromoteIntBinOp(SDValue Op); 210 SDValue PromoteIntShiftOp(SDValue Op); 211 SDValue PromoteExtend(SDValue Op); 212 bool PromoteLoad(SDValue Op); 213 214 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 215 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 216 ISD::NodeType ExtType); 217 218 /// Call the node-specific routine that knows how to fold each 219 /// particular type of node. If that doesn't do anything, try the 220 /// target-specific DAG combines. 221 SDValue combine(SDNode *N); 222 223 // Visitation implementation - Implement dag node combining for different 224 // node types. The semantics are as follows: 225 // Return Value: 226 // SDValue.getNode() == 0 - No change was made 227 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 228 // otherwise - N should be replaced by the returned Operand. 229 // 230 SDValue visitTokenFactor(SDNode *N); 231 SDValue visitMERGE_VALUES(SDNode *N); 232 SDValue visitADD(SDNode *N); 233 SDValue visitSUB(SDNode *N); 234 SDValue visitADDC(SDNode *N); 235 SDValue visitSUBC(SDNode *N); 236 SDValue visitADDE(SDNode *N); 237 SDValue visitSUBE(SDNode *N); 238 SDValue visitMUL(SDNode *N); 239 SDValue useDivRem(SDNode *N); 240 SDValue visitSDIV(SDNode *N); 241 SDValue visitUDIV(SDNode *N); 242 SDValue visitREM(SDNode *N); 243 SDValue visitMULHU(SDNode *N); 244 SDValue visitMULHS(SDNode *N); 245 SDValue visitSMUL_LOHI(SDNode *N); 246 SDValue visitUMUL_LOHI(SDNode *N); 247 SDValue visitSMULO(SDNode *N); 248 SDValue visitUMULO(SDNode *N); 249 SDValue visitIMINMAX(SDNode *N); 250 SDValue visitAND(SDNode *N); 251 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 252 SDValue visitOR(SDNode *N); 253 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 254 SDValue visitXOR(SDNode *N); 255 SDValue SimplifyVBinOp(SDNode *N); 256 SDValue visitSHL(SDNode *N); 257 SDValue visitSRA(SDNode *N); 258 SDValue visitSRL(SDNode *N); 259 SDValue visitRotate(SDNode *N); 260 SDValue visitBSWAP(SDNode *N); 261 SDValue visitCTLZ(SDNode *N); 262 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 263 SDValue visitCTTZ(SDNode *N); 264 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 265 SDValue visitCTPOP(SDNode *N); 266 SDValue visitSELECT(SDNode *N); 267 SDValue visitVSELECT(SDNode *N); 268 SDValue visitSELECT_CC(SDNode *N); 269 SDValue visitSETCC(SDNode *N); 270 SDValue visitSETCCE(SDNode *N); 271 SDValue visitSIGN_EXTEND(SDNode *N); 272 SDValue visitZERO_EXTEND(SDNode *N); 273 SDValue visitANY_EXTEND(SDNode *N); 274 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 275 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 276 SDValue visitTRUNCATE(SDNode *N); 277 SDValue visitBITCAST(SDNode *N); 278 SDValue visitBUILD_PAIR(SDNode *N); 279 SDValue visitFADD(SDNode *N); 280 SDValue visitFSUB(SDNode *N); 281 SDValue visitFMUL(SDNode *N); 282 SDValue visitFMA(SDNode *N); 283 SDValue visitFDIV(SDNode *N); 284 SDValue visitFREM(SDNode *N); 285 SDValue visitFSQRT(SDNode *N); 286 SDValue visitFCOPYSIGN(SDNode *N); 287 SDValue visitSINT_TO_FP(SDNode *N); 288 SDValue visitUINT_TO_FP(SDNode *N); 289 SDValue visitFP_TO_SINT(SDNode *N); 290 SDValue visitFP_TO_UINT(SDNode *N); 291 SDValue visitFP_ROUND(SDNode *N); 292 SDValue visitFP_ROUND_INREG(SDNode *N); 293 SDValue visitFP_EXTEND(SDNode *N); 294 SDValue visitFNEG(SDNode *N); 295 SDValue visitFABS(SDNode *N); 296 SDValue visitFCEIL(SDNode *N); 297 SDValue visitFTRUNC(SDNode *N); 298 SDValue visitFFLOOR(SDNode *N); 299 SDValue visitFMINNUM(SDNode *N); 300 SDValue visitFMAXNUM(SDNode *N); 301 SDValue visitBRCOND(SDNode *N); 302 SDValue visitBR_CC(SDNode *N); 303 SDValue visitLOAD(SDNode *N); 304 305 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 306 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 307 308 SDValue visitSTORE(SDNode *N); 309 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 310 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 311 SDValue visitBUILD_VECTOR(SDNode *N); 312 SDValue visitCONCAT_VECTORS(SDNode *N); 313 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 314 SDValue visitVECTOR_SHUFFLE(SDNode *N); 315 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 316 SDValue visitINSERT_SUBVECTOR(SDNode *N); 317 SDValue visitMLOAD(SDNode *N); 318 SDValue visitMSTORE(SDNode *N); 319 SDValue visitMGATHER(SDNode *N); 320 SDValue visitMSCATTER(SDNode *N); 321 SDValue visitFP_TO_FP16(SDNode *N); 322 SDValue visitFP16_TO_FP(SDNode *N); 323 324 SDValue visitFADDForFMACombine(SDNode *N); 325 SDValue visitFSUBForFMACombine(SDNode *N); 326 SDValue visitFMULForFMACombine(SDNode *N); 327 328 SDValue XformToShuffleWithZero(SDNode *N); 329 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 330 331 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 332 333 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 334 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 335 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 336 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 337 SDValue N3, ISD::CondCode CC, 338 bool NotExtCompare = false); 339 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 340 SDLoc DL, bool foldBooleans = true); 341 342 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 343 SDValue &CC) const; 344 bool isOneUseSetCC(SDValue N) const; 345 346 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 347 unsigned HiOp); 348 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 349 SDValue CombineExtLoad(SDNode *N); 350 SDValue combineRepeatedFPDivisors(SDNode *N); 351 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 352 SDValue BuildSDIV(SDNode *N); 353 SDValue BuildSDIVPow2(SDNode *N); 354 SDValue BuildUDIV(SDNode *N); 355 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 356 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 357 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 358 SDNodeFlags *Flags); 359 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 360 SDNodeFlags *Flags); 361 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 362 bool DemandHighBits = true); 363 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 364 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 365 SDValue InnerPos, SDValue InnerNeg, 366 unsigned PosOpcode, unsigned NegOpcode, 367 SDLoc DL); 368 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 369 SDValue ReduceLoadWidth(SDNode *N); 370 SDValue ReduceLoadOpStoreWidth(SDNode *N); 371 SDValue TransformFPLoadStorePair(SDNode *N); 372 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 373 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 374 375 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 376 377 /// Walk up chain skipping non-aliasing memory nodes, 378 /// looking for aliasing nodes and adding them to the Aliases vector. 379 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 380 SmallVectorImpl<SDValue> &Aliases); 381 382 /// Return true if there is any possibility that the two addresses overlap. 383 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 384 385 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 386 /// chain (aliasing node.) 387 SDValue FindBetterChain(SDNode *N, SDValue Chain); 388 389 /// Do FindBetterChain for a store and any possibly adjacent stores on 390 /// consecutive chains. 391 bool findBetterNeighborChains(StoreSDNode *St); 392 393 /// Holds a pointer to an LSBaseSDNode as well as information on where it 394 /// is located in a sequence of memory operations connected by a chain. 395 struct MemOpLink { 396 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 397 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 398 // Ptr to the mem node. 399 LSBaseSDNode *MemNode; 400 // Offset from the base ptr. 401 int64_t OffsetFromBase; 402 // What is the sequence number of this mem node. 403 // Lowest mem operand in the DAG starts at zero. 404 unsigned SequenceNum; 405 }; 406 407 /// This is a helper function for visitMUL to check the profitability 408 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 409 /// MulNode is the original multiply, AddNode is (add x, c1), 410 /// and ConstNode is c2. 411 bool isMulAddWithConstProfitable(SDNode *MulNode, 412 SDValue &AddNode, 413 SDValue &ConstNode); 414 415 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 416 /// constant build_vector of the stored constant values in Stores. 417 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, 418 SDLoc SL, 419 ArrayRef<MemOpLink> Stores, 420 SmallVectorImpl<SDValue> &Chains, 421 EVT Ty) const; 422 423 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 424 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 425 /// the type of the loaded value to be extended. LoadedVT returns the type 426 /// of the original loaded value. NarrowLoad returns whether the load would 427 /// need to be narrowed in order to match. 428 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 429 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 430 bool &NarrowLoad); 431 432 /// This is a helper function for MergeConsecutiveStores. When the source 433 /// elements of the consecutive stores are all constants or all extracted 434 /// vector elements, try to merge them into one larger store. 435 /// \return True if a merged store was created. 436 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 437 EVT MemVT, unsigned NumStores, 438 bool IsConstantSrc, bool UseVector); 439 440 /// This is a helper function for MergeConsecutiveStores. 441 /// Stores that may be merged are placed in StoreNodes. 442 /// Loads that may alias with those stores are placed in AliasLoadNodes. 443 void getStoreMergeAndAliasCandidates( 444 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 445 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 446 447 /// Merge consecutive store operations into a wide store. 448 /// This optimization uses wide integers or vectors when possible. 449 /// \return True if some memory operations were changed. 450 bool MergeConsecutiveStores(StoreSDNode *N); 451 452 /// \brief Try to transform a truncation where C is a constant: 453 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 454 /// 455 /// \p N needs to be a truncation and its first operand an AND. Other 456 /// requirements are checked by the function (e.g. that trunc is 457 /// single-use) and if missed an empty SDValue is returned. 458 SDValue distributeTruncateThroughAnd(SDNode *N); 459 460 public: 461 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 462 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 463 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 464 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 465 } 466 467 /// Runs the dag combiner on all nodes in the work list 468 void Run(CombineLevel AtLevel); 469 470 SelectionDAG &getDAG() const { return DAG; } 471 472 /// Returns a type large enough to hold any valid shift amount - before type 473 /// legalization these can be huge. 474 EVT getShiftAmountTy(EVT LHSTy) { 475 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 476 if (LHSTy.isVector()) 477 return LHSTy; 478 auto &DL = DAG.getDataLayout(); 479 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 480 : TLI.getPointerTy(DL); 481 } 482 483 /// This method returns true if we are running before type legalization or 484 /// if the specified VT is legal. 485 bool isTypeLegal(const EVT &VT) { 486 if (!LegalTypes) return true; 487 return TLI.isTypeLegal(VT); 488 } 489 490 /// Convenience wrapper around TargetLowering::getSetCCResultType 491 EVT getSetCCResultType(EVT VT) const { 492 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 493 } 494 }; 495 } 496 497 498 namespace { 499 /// This class is a DAGUpdateListener that removes any deleted 500 /// nodes from the worklist. 501 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 502 DAGCombiner &DC; 503 public: 504 explicit WorklistRemover(DAGCombiner &dc) 505 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 506 507 void NodeDeleted(SDNode *N, SDNode *E) override { 508 DC.removeFromWorklist(N); 509 } 510 }; 511 } 512 513 //===----------------------------------------------------------------------===// 514 // TargetLowering::DAGCombinerInfo implementation 515 //===----------------------------------------------------------------------===// 516 517 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 518 ((DAGCombiner*)DC)->AddToWorklist(N); 519 } 520 521 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 522 ((DAGCombiner*)DC)->removeFromWorklist(N); 523 } 524 525 SDValue TargetLowering::DAGCombinerInfo:: 526 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 527 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 528 } 529 530 SDValue TargetLowering::DAGCombinerInfo:: 531 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 532 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 533 } 534 535 536 SDValue TargetLowering::DAGCombinerInfo:: 537 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 538 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 539 } 540 541 void TargetLowering::DAGCombinerInfo:: 542 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 543 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 544 } 545 546 //===----------------------------------------------------------------------===// 547 // Helper Functions 548 //===----------------------------------------------------------------------===// 549 550 void DAGCombiner::deleteAndRecombine(SDNode *N) { 551 removeFromWorklist(N); 552 553 // If the operands of this node are only used by the node, they will now be 554 // dead. Make sure to re-visit them and recursively delete dead nodes. 555 for (const SDValue &Op : N->ops()) 556 // For an operand generating multiple values, one of the values may 557 // become dead allowing further simplification (e.g. split index 558 // arithmetic from an indexed load). 559 if (Op->hasOneUse() || Op->getNumValues() > 1) 560 AddToWorklist(Op.getNode()); 561 562 DAG.DeleteNode(N); 563 } 564 565 /// Return 1 if we can compute the negated form of the specified expression for 566 /// the same cost as the expression itself, or 2 if we can compute the negated 567 /// form more cheaply than the expression itself. 568 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 569 const TargetLowering &TLI, 570 const TargetOptions *Options, 571 unsigned Depth = 0) { 572 // fneg is removable even if it has multiple uses. 573 if (Op.getOpcode() == ISD::FNEG) return 2; 574 575 // Don't allow anything with multiple uses. 576 if (!Op.hasOneUse()) return 0; 577 578 // Don't recurse exponentially. 579 if (Depth > 6) return 0; 580 581 switch (Op.getOpcode()) { 582 default: return false; 583 case ISD::ConstantFP: 584 // Don't invert constant FP values after legalize. The negated constant 585 // isn't necessarily legal. 586 return LegalOperations ? 0 : 1; 587 case ISD::FADD: 588 // FIXME: determine better conditions for this xform. 589 if (!Options->UnsafeFPMath) return 0; 590 591 // After operation legalization, it might not be legal to create new FSUBs. 592 if (LegalOperations && 593 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 594 return 0; 595 596 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 597 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 598 Options, Depth + 1)) 599 return V; 600 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 601 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 602 Depth + 1); 603 case ISD::FSUB: 604 // We can't turn -(A-B) into B-A when we honor signed zeros. 605 if (!Options->UnsafeFPMath) return 0; 606 607 // fold (fneg (fsub A, B)) -> (fsub B, A) 608 return 1; 609 610 case ISD::FMUL: 611 case ISD::FDIV: 612 if (Options->HonorSignDependentRoundingFPMath()) return 0; 613 614 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 615 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 616 Options, Depth + 1)) 617 return V; 618 619 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 620 Depth + 1); 621 622 case ISD::FP_EXTEND: 623 case ISD::FP_ROUND: 624 case ISD::FSIN: 625 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 626 Depth + 1); 627 } 628 } 629 630 /// If isNegatibleForFree returns true, return the newly negated expression. 631 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 632 bool LegalOperations, unsigned Depth = 0) { 633 const TargetOptions &Options = DAG.getTarget().Options; 634 // fneg is removable even if it has multiple uses. 635 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 636 637 // Don't allow anything with multiple uses. 638 assert(Op.hasOneUse() && "Unknown reuse!"); 639 640 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 641 642 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 643 644 switch (Op.getOpcode()) { 645 default: llvm_unreachable("Unknown code"); 646 case ISD::ConstantFP: { 647 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 648 V.changeSign(); 649 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 650 } 651 case ISD::FADD: 652 // FIXME: determine better conditions for this xform. 653 assert(Options.UnsafeFPMath); 654 655 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 656 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 657 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 658 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 659 GetNegatedExpression(Op.getOperand(0), DAG, 660 LegalOperations, Depth+1), 661 Op.getOperand(1), Flags); 662 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 663 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 664 GetNegatedExpression(Op.getOperand(1), DAG, 665 LegalOperations, Depth+1), 666 Op.getOperand(0), Flags); 667 case ISD::FSUB: 668 // We can't turn -(A-B) into B-A when we honor signed zeros. 669 assert(Options.UnsafeFPMath); 670 671 // fold (fneg (fsub 0, B)) -> B 672 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 673 if (N0CFP->isZero()) 674 return Op.getOperand(1); 675 676 // fold (fneg (fsub A, B)) -> (fsub B, A) 677 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 678 Op.getOperand(1), Op.getOperand(0), Flags); 679 680 case ISD::FMUL: 681 case ISD::FDIV: 682 assert(!Options.HonorSignDependentRoundingFPMath()); 683 684 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 685 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 686 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 687 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 688 GetNegatedExpression(Op.getOperand(0), DAG, 689 LegalOperations, Depth+1), 690 Op.getOperand(1), Flags); 691 692 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 693 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 694 Op.getOperand(0), 695 GetNegatedExpression(Op.getOperand(1), DAG, 696 LegalOperations, Depth+1), Flags); 697 698 case ISD::FP_EXTEND: 699 case ISD::FSIN: 700 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 701 GetNegatedExpression(Op.getOperand(0), DAG, 702 LegalOperations, Depth+1)); 703 case ISD::FP_ROUND: 704 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 705 GetNegatedExpression(Op.getOperand(0), DAG, 706 LegalOperations, Depth+1), 707 Op.getOperand(1)); 708 } 709 } 710 711 // Return true if this node is a setcc, or is a select_cc 712 // that selects between the target values used for true and false, making it 713 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 714 // the appropriate nodes based on the type of node we are checking. This 715 // simplifies life a bit for the callers. 716 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 717 SDValue &CC) const { 718 if (N.getOpcode() == ISD::SETCC) { 719 LHS = N.getOperand(0); 720 RHS = N.getOperand(1); 721 CC = N.getOperand(2); 722 return true; 723 } 724 725 if (N.getOpcode() != ISD::SELECT_CC || 726 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 727 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 728 return false; 729 730 if (TLI.getBooleanContents(N.getValueType()) == 731 TargetLowering::UndefinedBooleanContent) 732 return false; 733 734 LHS = N.getOperand(0); 735 RHS = N.getOperand(1); 736 CC = N.getOperand(4); 737 return true; 738 } 739 740 /// Return true if this is a SetCC-equivalent operation with only one use. 741 /// If this is true, it allows the users to invert the operation for free when 742 /// it is profitable to do so. 743 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 744 SDValue N0, N1, N2; 745 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 746 return true; 747 return false; 748 } 749 750 /// Returns true if N is a BUILD_VECTOR node whose 751 /// elements are all the same constant or undefined. 752 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 753 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 754 if (!C) 755 return false; 756 757 APInt SplatUndef; 758 unsigned SplatBitSize; 759 bool HasAnyUndefs; 760 EVT EltVT = N->getValueType(0).getVectorElementType(); 761 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 762 HasAnyUndefs) && 763 EltVT.getSizeInBits() >= SplatBitSize); 764 } 765 766 // \brief Returns the SDNode if it is a constant integer BuildVector 767 // or constant integer. 768 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) { 769 if (isa<ConstantSDNode>(N)) 770 return N.getNode(); 771 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 772 return N.getNode(); 773 return nullptr; 774 } 775 776 // \brief Returns the SDNode if it is a constant float BuildVector 777 // or constant float. 778 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 779 if (isa<ConstantFPSDNode>(N)) 780 return N.getNode(); 781 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 782 return N.getNode(); 783 return nullptr; 784 } 785 786 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 787 // int. 788 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 789 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 790 return CN; 791 792 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 793 BitVector UndefElements; 794 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 795 796 // BuildVectors can truncate their operands. Ignore that case here. 797 // FIXME: We blindly ignore splats which include undef which is overly 798 // pessimistic. 799 if (CN && UndefElements.none() && 800 CN->getValueType(0) == N.getValueType().getScalarType()) 801 return CN; 802 } 803 804 return nullptr; 805 } 806 807 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 808 // float. 809 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 810 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 811 return CN; 812 813 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 814 BitVector UndefElements; 815 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 816 817 if (CN && UndefElements.none()) 818 return CN; 819 } 820 821 return nullptr; 822 } 823 824 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 825 SDValue N0, SDValue N1) { 826 EVT VT = N0.getValueType(); 827 if (N0.getOpcode() == Opc) { 828 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 829 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) { 830 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 831 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 832 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 833 return SDValue(); 834 } 835 if (N0.hasOneUse()) { 836 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 837 // use 838 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 839 if (!OpNode.getNode()) 840 return SDValue(); 841 AddToWorklist(OpNode.getNode()); 842 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 843 } 844 } 845 } 846 847 if (N1.getOpcode() == Opc) { 848 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 849 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) { 850 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 851 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 852 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 853 return SDValue(); 854 } 855 if (N1.hasOneUse()) { 856 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 857 // use 858 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 859 if (!OpNode.getNode()) 860 return SDValue(); 861 AddToWorklist(OpNode.getNode()); 862 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 863 } 864 } 865 } 866 867 return SDValue(); 868 } 869 870 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 871 bool AddTo) { 872 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 873 ++NodesCombined; 874 DEBUG(dbgs() << "\nReplacing.1 "; 875 N->dump(&DAG); 876 dbgs() << "\nWith: "; 877 To[0].getNode()->dump(&DAG); 878 dbgs() << " and " << NumTo-1 << " other values\n"); 879 for (unsigned i = 0, e = NumTo; i != e; ++i) 880 assert((!To[i].getNode() || 881 N->getValueType(i) == To[i].getValueType()) && 882 "Cannot combine value to value of different type!"); 883 884 WorklistRemover DeadNodes(*this); 885 DAG.ReplaceAllUsesWith(N, To); 886 if (AddTo) { 887 // Push the new nodes and any users onto the worklist 888 for (unsigned i = 0, e = NumTo; i != e; ++i) { 889 if (To[i].getNode()) { 890 AddToWorklist(To[i].getNode()); 891 AddUsersToWorklist(To[i].getNode()); 892 } 893 } 894 } 895 896 // Finally, if the node is now dead, remove it from the graph. The node 897 // may not be dead if the replacement process recursively simplified to 898 // something else needing this node. 899 if (N->use_empty()) 900 deleteAndRecombine(N); 901 return SDValue(N, 0); 902 } 903 904 void DAGCombiner:: 905 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 906 // Replace all uses. If any nodes become isomorphic to other nodes and 907 // are deleted, make sure to remove them from our worklist. 908 WorklistRemover DeadNodes(*this); 909 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 910 911 // Push the new node and any (possibly new) users onto the worklist. 912 AddToWorklist(TLO.New.getNode()); 913 AddUsersToWorklist(TLO.New.getNode()); 914 915 // Finally, if the node is now dead, remove it from the graph. The node 916 // may not be dead if the replacement process recursively simplified to 917 // something else needing this node. 918 if (TLO.Old.getNode()->use_empty()) 919 deleteAndRecombine(TLO.Old.getNode()); 920 } 921 922 /// Check the specified integer node value to see if it can be simplified or if 923 /// things it uses can be simplified by bit propagation. If so, return true. 924 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 925 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 926 APInt KnownZero, KnownOne; 927 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 928 return false; 929 930 // Revisit the node. 931 AddToWorklist(Op.getNode()); 932 933 // Replace the old value with the new one. 934 ++NodesCombined; 935 DEBUG(dbgs() << "\nReplacing.2 "; 936 TLO.Old.getNode()->dump(&DAG); 937 dbgs() << "\nWith: "; 938 TLO.New.getNode()->dump(&DAG); 939 dbgs() << '\n'); 940 941 CommitTargetLoweringOpt(TLO); 942 return true; 943 } 944 945 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 946 SDLoc dl(Load); 947 EVT VT = Load->getValueType(0); 948 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 949 950 DEBUG(dbgs() << "\nReplacing.9 "; 951 Load->dump(&DAG); 952 dbgs() << "\nWith: "; 953 Trunc.getNode()->dump(&DAG); 954 dbgs() << '\n'); 955 WorklistRemover DeadNodes(*this); 956 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 957 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 958 deleteAndRecombine(Load); 959 AddToWorklist(Trunc.getNode()); 960 } 961 962 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 963 Replace = false; 964 SDLoc dl(Op); 965 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 966 EVT MemVT = LD->getMemoryVT(); 967 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 968 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 969 : ISD::EXTLOAD) 970 : LD->getExtensionType(); 971 Replace = true; 972 return DAG.getExtLoad(ExtType, dl, PVT, 973 LD->getChain(), LD->getBasePtr(), 974 MemVT, LD->getMemOperand()); 975 } 976 977 unsigned Opc = Op.getOpcode(); 978 switch (Opc) { 979 default: break; 980 case ISD::AssertSext: 981 return DAG.getNode(ISD::AssertSext, dl, PVT, 982 SExtPromoteOperand(Op.getOperand(0), PVT), 983 Op.getOperand(1)); 984 case ISD::AssertZext: 985 return DAG.getNode(ISD::AssertZext, dl, PVT, 986 ZExtPromoteOperand(Op.getOperand(0), PVT), 987 Op.getOperand(1)); 988 case ISD::Constant: { 989 unsigned ExtOpc = 990 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 991 return DAG.getNode(ExtOpc, dl, PVT, Op); 992 } 993 } 994 995 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 996 return SDValue(); 997 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 998 } 999 1000 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1001 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1002 return SDValue(); 1003 EVT OldVT = Op.getValueType(); 1004 SDLoc dl(Op); 1005 bool Replace = false; 1006 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1007 if (!NewOp.getNode()) 1008 return SDValue(); 1009 AddToWorklist(NewOp.getNode()); 1010 1011 if (Replace) 1012 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1013 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 1014 DAG.getValueType(OldVT)); 1015 } 1016 1017 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1018 EVT OldVT = Op.getValueType(); 1019 SDLoc dl(Op); 1020 bool Replace = false; 1021 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1022 if (!NewOp.getNode()) 1023 return SDValue(); 1024 AddToWorklist(NewOp.getNode()); 1025 1026 if (Replace) 1027 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1028 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1029 } 1030 1031 /// Promote the specified integer binary operation if the target indicates it is 1032 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1033 /// i32 since i16 instructions are longer. 1034 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1035 if (!LegalOperations) 1036 return SDValue(); 1037 1038 EVT VT = Op.getValueType(); 1039 if (VT.isVector() || !VT.isInteger()) 1040 return SDValue(); 1041 1042 // If operation type is 'undesirable', e.g. i16 on x86, consider 1043 // promoting it. 1044 unsigned Opc = Op.getOpcode(); 1045 if (TLI.isTypeDesirableForOp(Opc, VT)) 1046 return SDValue(); 1047 1048 EVT PVT = VT; 1049 // Consult target whether it is a good idea to promote this operation and 1050 // what's the right type to promote it to. 1051 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1052 assert(PVT != VT && "Don't know what type to promote to!"); 1053 1054 bool Replace0 = false; 1055 SDValue N0 = Op.getOperand(0); 1056 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1057 if (!NN0.getNode()) 1058 return SDValue(); 1059 1060 bool Replace1 = false; 1061 SDValue N1 = Op.getOperand(1); 1062 SDValue NN1; 1063 if (N0 == N1) 1064 NN1 = NN0; 1065 else { 1066 NN1 = PromoteOperand(N1, PVT, Replace1); 1067 if (!NN1.getNode()) 1068 return SDValue(); 1069 } 1070 1071 AddToWorklist(NN0.getNode()); 1072 if (NN1.getNode()) 1073 AddToWorklist(NN1.getNode()); 1074 1075 if (Replace0) 1076 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1077 if (Replace1) 1078 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1079 1080 DEBUG(dbgs() << "\nPromoting "; 1081 Op.getNode()->dump(&DAG)); 1082 SDLoc dl(Op); 1083 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1084 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1085 } 1086 return SDValue(); 1087 } 1088 1089 /// Promote the specified integer shift operation if the target indicates it is 1090 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1091 /// i32 since i16 instructions are longer. 1092 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1093 if (!LegalOperations) 1094 return SDValue(); 1095 1096 EVT VT = Op.getValueType(); 1097 if (VT.isVector() || !VT.isInteger()) 1098 return SDValue(); 1099 1100 // If operation type is 'undesirable', e.g. i16 on x86, consider 1101 // promoting it. 1102 unsigned Opc = Op.getOpcode(); 1103 if (TLI.isTypeDesirableForOp(Opc, VT)) 1104 return SDValue(); 1105 1106 EVT PVT = VT; 1107 // Consult target whether it is a good idea to promote this operation and 1108 // what's the right type to promote it to. 1109 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1110 assert(PVT != VT && "Don't know what type to promote to!"); 1111 1112 bool Replace = false; 1113 SDValue N0 = Op.getOperand(0); 1114 if (Opc == ISD::SRA) 1115 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1116 else if (Opc == ISD::SRL) 1117 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1118 else 1119 N0 = PromoteOperand(N0, PVT, Replace); 1120 if (!N0.getNode()) 1121 return SDValue(); 1122 1123 AddToWorklist(N0.getNode()); 1124 if (Replace) 1125 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1126 1127 DEBUG(dbgs() << "\nPromoting "; 1128 Op.getNode()->dump(&DAG)); 1129 SDLoc dl(Op); 1130 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1131 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1132 } 1133 return SDValue(); 1134 } 1135 1136 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1137 if (!LegalOperations) 1138 return SDValue(); 1139 1140 EVT VT = Op.getValueType(); 1141 if (VT.isVector() || !VT.isInteger()) 1142 return SDValue(); 1143 1144 // If operation type is 'undesirable', e.g. i16 on x86, consider 1145 // promoting it. 1146 unsigned Opc = Op.getOpcode(); 1147 if (TLI.isTypeDesirableForOp(Opc, VT)) 1148 return SDValue(); 1149 1150 EVT PVT = VT; 1151 // Consult target whether it is a good idea to promote this operation and 1152 // what's the right type to promote it to. 1153 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1154 assert(PVT != VT && "Don't know what type to promote to!"); 1155 // fold (aext (aext x)) -> (aext x) 1156 // fold (aext (zext x)) -> (zext x) 1157 // fold (aext (sext x)) -> (sext x) 1158 DEBUG(dbgs() << "\nPromoting "; 1159 Op.getNode()->dump(&DAG)); 1160 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1161 } 1162 return SDValue(); 1163 } 1164 1165 bool DAGCombiner::PromoteLoad(SDValue Op) { 1166 if (!LegalOperations) 1167 return false; 1168 1169 EVT VT = Op.getValueType(); 1170 if (VT.isVector() || !VT.isInteger()) 1171 return false; 1172 1173 // If operation type is 'undesirable', e.g. i16 on x86, consider 1174 // promoting it. 1175 unsigned Opc = Op.getOpcode(); 1176 if (TLI.isTypeDesirableForOp(Opc, VT)) 1177 return false; 1178 1179 EVT PVT = VT; 1180 // Consult target whether it is a good idea to promote this operation and 1181 // what's the right type to promote it to. 1182 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1183 assert(PVT != VT && "Don't know what type to promote to!"); 1184 1185 SDLoc dl(Op); 1186 SDNode *N = Op.getNode(); 1187 LoadSDNode *LD = cast<LoadSDNode>(N); 1188 EVT MemVT = LD->getMemoryVT(); 1189 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1190 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1191 : ISD::EXTLOAD) 1192 : LD->getExtensionType(); 1193 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1194 LD->getChain(), LD->getBasePtr(), 1195 MemVT, LD->getMemOperand()); 1196 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1197 1198 DEBUG(dbgs() << "\nPromoting "; 1199 N->dump(&DAG); 1200 dbgs() << "\nTo: "; 1201 Result.getNode()->dump(&DAG); 1202 dbgs() << '\n'); 1203 WorklistRemover DeadNodes(*this); 1204 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1205 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1206 deleteAndRecombine(N); 1207 AddToWorklist(Result.getNode()); 1208 return true; 1209 } 1210 return false; 1211 } 1212 1213 /// \brief Recursively delete a node which has no uses and any operands for 1214 /// which it is the only use. 1215 /// 1216 /// Note that this both deletes the nodes and removes them from the worklist. 1217 /// It also adds any nodes who have had a user deleted to the worklist as they 1218 /// may now have only one use and subject to other combines. 1219 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1220 if (!N->use_empty()) 1221 return false; 1222 1223 SmallSetVector<SDNode *, 16> Nodes; 1224 Nodes.insert(N); 1225 do { 1226 N = Nodes.pop_back_val(); 1227 if (!N) 1228 continue; 1229 1230 if (N->use_empty()) { 1231 for (const SDValue &ChildN : N->op_values()) 1232 Nodes.insert(ChildN.getNode()); 1233 1234 removeFromWorklist(N); 1235 DAG.DeleteNode(N); 1236 } else { 1237 AddToWorklist(N); 1238 } 1239 } while (!Nodes.empty()); 1240 return true; 1241 } 1242 1243 //===----------------------------------------------------------------------===// 1244 // Main DAG Combiner implementation 1245 //===----------------------------------------------------------------------===// 1246 1247 void DAGCombiner::Run(CombineLevel AtLevel) { 1248 // set the instance variables, so that the various visit routines may use it. 1249 Level = AtLevel; 1250 LegalOperations = Level >= AfterLegalizeVectorOps; 1251 LegalTypes = Level >= AfterLegalizeTypes; 1252 1253 // Add all the dag nodes to the worklist. 1254 for (SDNode &Node : DAG.allnodes()) 1255 AddToWorklist(&Node); 1256 1257 // Create a dummy node (which is not added to allnodes), that adds a reference 1258 // to the root node, preventing it from being deleted, and tracking any 1259 // changes of the root. 1260 HandleSDNode Dummy(DAG.getRoot()); 1261 1262 // while the worklist isn't empty, find a node and 1263 // try and combine it. 1264 while (!WorklistMap.empty()) { 1265 SDNode *N; 1266 // The Worklist holds the SDNodes in order, but it may contain null entries. 1267 do { 1268 N = Worklist.pop_back_val(); 1269 } while (!N); 1270 1271 bool GoodWorklistEntry = WorklistMap.erase(N); 1272 (void)GoodWorklistEntry; 1273 assert(GoodWorklistEntry && 1274 "Found a worklist entry without a corresponding map entry!"); 1275 1276 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1277 // N is deleted from the DAG, since they too may now be dead or may have a 1278 // reduced number of uses, allowing other xforms. 1279 if (recursivelyDeleteUnusedNodes(N)) 1280 continue; 1281 1282 WorklistRemover DeadNodes(*this); 1283 1284 // If this combine is running after legalizing the DAG, re-legalize any 1285 // nodes pulled off the worklist. 1286 if (Level == AfterLegalizeDAG) { 1287 SmallSetVector<SDNode *, 16> UpdatedNodes; 1288 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1289 1290 for (SDNode *LN : UpdatedNodes) { 1291 AddToWorklist(LN); 1292 AddUsersToWorklist(LN); 1293 } 1294 if (!NIsValid) 1295 continue; 1296 } 1297 1298 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1299 1300 // Add any operands of the new node which have not yet been combined to the 1301 // worklist as well. Because the worklist uniques things already, this 1302 // won't repeatedly process the same operand. 1303 CombinedNodes.insert(N); 1304 for (const SDValue &ChildN : N->op_values()) 1305 if (!CombinedNodes.count(ChildN.getNode())) 1306 AddToWorklist(ChildN.getNode()); 1307 1308 SDValue RV = combine(N); 1309 1310 if (!RV.getNode()) 1311 continue; 1312 1313 ++NodesCombined; 1314 1315 // If we get back the same node we passed in, rather than a new node or 1316 // zero, we know that the node must have defined multiple values and 1317 // CombineTo was used. Since CombineTo takes care of the worklist 1318 // mechanics for us, we have no work to do in this case. 1319 if (RV.getNode() == N) 1320 continue; 1321 1322 assert(N->getOpcode() != ISD::DELETED_NODE && 1323 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1324 "Node was deleted but visit returned new node!"); 1325 1326 DEBUG(dbgs() << " ... into: "; 1327 RV.getNode()->dump(&DAG)); 1328 1329 // Transfer debug value. 1330 DAG.TransferDbgValues(SDValue(N, 0), RV); 1331 if (N->getNumValues() == RV.getNode()->getNumValues()) 1332 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1333 else { 1334 assert(N->getValueType(0) == RV.getValueType() && 1335 N->getNumValues() == 1 && "Type mismatch"); 1336 SDValue OpV = RV; 1337 DAG.ReplaceAllUsesWith(N, &OpV); 1338 } 1339 1340 // Push the new node and any users onto the worklist 1341 AddToWorklist(RV.getNode()); 1342 AddUsersToWorklist(RV.getNode()); 1343 1344 // Finally, if the node is now dead, remove it from the graph. The node 1345 // may not be dead if the replacement process recursively simplified to 1346 // something else needing this node. This will also take care of adding any 1347 // operands which have lost a user to the worklist. 1348 recursivelyDeleteUnusedNodes(N); 1349 } 1350 1351 // If the root changed (e.g. it was a dead load, update the root). 1352 DAG.setRoot(Dummy.getValue()); 1353 DAG.RemoveDeadNodes(); 1354 } 1355 1356 SDValue DAGCombiner::visit(SDNode *N) { 1357 switch (N->getOpcode()) { 1358 default: break; 1359 case ISD::TokenFactor: return visitTokenFactor(N); 1360 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1361 case ISD::ADD: return visitADD(N); 1362 case ISD::SUB: return visitSUB(N); 1363 case ISD::ADDC: return visitADDC(N); 1364 case ISD::SUBC: return visitSUBC(N); 1365 case ISD::ADDE: return visitADDE(N); 1366 case ISD::SUBE: return visitSUBE(N); 1367 case ISD::MUL: return visitMUL(N); 1368 case ISD::SDIV: return visitSDIV(N); 1369 case ISD::UDIV: return visitUDIV(N); 1370 case ISD::SREM: 1371 case ISD::UREM: return visitREM(N); 1372 case ISD::MULHU: return visitMULHU(N); 1373 case ISD::MULHS: return visitMULHS(N); 1374 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1375 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1376 case ISD::SMULO: return visitSMULO(N); 1377 case ISD::UMULO: return visitUMULO(N); 1378 case ISD::SMIN: 1379 case ISD::SMAX: 1380 case ISD::UMIN: 1381 case ISD::UMAX: return visitIMINMAX(N); 1382 case ISD::AND: return visitAND(N); 1383 case ISD::OR: return visitOR(N); 1384 case ISD::XOR: return visitXOR(N); 1385 case ISD::SHL: return visitSHL(N); 1386 case ISD::SRA: return visitSRA(N); 1387 case ISD::SRL: return visitSRL(N); 1388 case ISD::ROTR: 1389 case ISD::ROTL: return visitRotate(N); 1390 case ISD::BSWAP: return visitBSWAP(N); 1391 case ISD::CTLZ: return visitCTLZ(N); 1392 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1393 case ISD::CTTZ: return visitCTTZ(N); 1394 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1395 case ISD::CTPOP: return visitCTPOP(N); 1396 case ISD::SELECT: return visitSELECT(N); 1397 case ISD::VSELECT: return visitVSELECT(N); 1398 case ISD::SELECT_CC: return visitSELECT_CC(N); 1399 case ISD::SETCC: return visitSETCC(N); 1400 case ISD::SETCCE: return visitSETCCE(N); 1401 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1402 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1403 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1404 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1405 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1406 case ISD::TRUNCATE: return visitTRUNCATE(N); 1407 case ISD::BITCAST: return visitBITCAST(N); 1408 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1409 case ISD::FADD: return visitFADD(N); 1410 case ISD::FSUB: return visitFSUB(N); 1411 case ISD::FMUL: return visitFMUL(N); 1412 case ISD::FMA: return visitFMA(N); 1413 case ISD::FDIV: return visitFDIV(N); 1414 case ISD::FREM: return visitFREM(N); 1415 case ISD::FSQRT: return visitFSQRT(N); 1416 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1417 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1418 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1419 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1420 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1421 case ISD::FP_ROUND: return visitFP_ROUND(N); 1422 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1423 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1424 case ISD::FNEG: return visitFNEG(N); 1425 case ISD::FABS: return visitFABS(N); 1426 case ISD::FFLOOR: return visitFFLOOR(N); 1427 case ISD::FMINNUM: return visitFMINNUM(N); 1428 case ISD::FMAXNUM: return visitFMAXNUM(N); 1429 case ISD::FCEIL: return visitFCEIL(N); 1430 case ISD::FTRUNC: return visitFTRUNC(N); 1431 case ISD::BRCOND: return visitBRCOND(N); 1432 case ISD::BR_CC: return visitBR_CC(N); 1433 case ISD::LOAD: return visitLOAD(N); 1434 case ISD::STORE: return visitSTORE(N); 1435 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1436 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1437 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1438 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1439 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1440 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1441 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1442 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1443 case ISD::MGATHER: return visitMGATHER(N); 1444 case ISD::MLOAD: return visitMLOAD(N); 1445 case ISD::MSCATTER: return visitMSCATTER(N); 1446 case ISD::MSTORE: return visitMSTORE(N); 1447 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1448 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1449 } 1450 return SDValue(); 1451 } 1452 1453 SDValue DAGCombiner::combine(SDNode *N) { 1454 SDValue RV = visit(N); 1455 1456 // If nothing happened, try a target-specific DAG combine. 1457 if (!RV.getNode()) { 1458 assert(N->getOpcode() != ISD::DELETED_NODE && 1459 "Node was deleted but visit returned NULL!"); 1460 1461 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1462 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1463 1464 // Expose the DAG combiner to the target combiner impls. 1465 TargetLowering::DAGCombinerInfo 1466 DagCombineInfo(DAG, Level, false, this); 1467 1468 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1469 } 1470 } 1471 1472 // If nothing happened still, try promoting the operation. 1473 if (!RV.getNode()) { 1474 switch (N->getOpcode()) { 1475 default: break; 1476 case ISD::ADD: 1477 case ISD::SUB: 1478 case ISD::MUL: 1479 case ISD::AND: 1480 case ISD::OR: 1481 case ISD::XOR: 1482 RV = PromoteIntBinOp(SDValue(N, 0)); 1483 break; 1484 case ISD::SHL: 1485 case ISD::SRA: 1486 case ISD::SRL: 1487 RV = PromoteIntShiftOp(SDValue(N, 0)); 1488 break; 1489 case ISD::SIGN_EXTEND: 1490 case ISD::ZERO_EXTEND: 1491 case ISD::ANY_EXTEND: 1492 RV = PromoteExtend(SDValue(N, 0)); 1493 break; 1494 case ISD::LOAD: 1495 if (PromoteLoad(SDValue(N, 0))) 1496 RV = SDValue(N, 0); 1497 break; 1498 } 1499 } 1500 1501 // If N is a commutative binary node, try commuting it to enable more 1502 // sdisel CSE. 1503 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1504 N->getNumValues() == 1) { 1505 SDValue N0 = N->getOperand(0); 1506 SDValue N1 = N->getOperand(1); 1507 1508 // Constant operands are canonicalized to RHS. 1509 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1510 SDValue Ops[] = {N1, N0}; 1511 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1512 N->getFlags()); 1513 if (CSENode) 1514 return SDValue(CSENode, 0); 1515 } 1516 } 1517 1518 return RV; 1519 } 1520 1521 /// Given a node, return its input chain if it has one, otherwise return a null 1522 /// sd operand. 1523 static SDValue getInputChainForNode(SDNode *N) { 1524 if (unsigned NumOps = N->getNumOperands()) { 1525 if (N->getOperand(0).getValueType() == MVT::Other) 1526 return N->getOperand(0); 1527 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1528 return N->getOperand(NumOps-1); 1529 for (unsigned i = 1; i < NumOps-1; ++i) 1530 if (N->getOperand(i).getValueType() == MVT::Other) 1531 return N->getOperand(i); 1532 } 1533 return SDValue(); 1534 } 1535 1536 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1537 // If N has two operands, where one has an input chain equal to the other, 1538 // the 'other' chain is redundant. 1539 if (N->getNumOperands() == 2) { 1540 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1541 return N->getOperand(0); 1542 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1543 return N->getOperand(1); 1544 } 1545 1546 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1547 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1548 SmallPtrSet<SDNode*, 16> SeenOps; 1549 bool Changed = false; // If we should replace this token factor. 1550 1551 // Start out with this token factor. 1552 TFs.push_back(N); 1553 1554 // Iterate through token factors. The TFs grows when new token factors are 1555 // encountered. 1556 for (unsigned i = 0; i < TFs.size(); ++i) { 1557 SDNode *TF = TFs[i]; 1558 1559 // Check each of the operands. 1560 for (const SDValue &Op : TF->op_values()) { 1561 1562 switch (Op.getOpcode()) { 1563 case ISD::EntryToken: 1564 // Entry tokens don't need to be added to the list. They are 1565 // redundant. 1566 Changed = true; 1567 break; 1568 1569 case ISD::TokenFactor: 1570 if (Op.hasOneUse() && 1571 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1572 // Queue up for processing. 1573 TFs.push_back(Op.getNode()); 1574 // Clean up in case the token factor is removed. 1575 AddToWorklist(Op.getNode()); 1576 Changed = true; 1577 break; 1578 } 1579 // Fall thru 1580 1581 default: 1582 // Only add if it isn't already in the list. 1583 if (SeenOps.insert(Op.getNode()).second) 1584 Ops.push_back(Op); 1585 else 1586 Changed = true; 1587 break; 1588 } 1589 } 1590 } 1591 1592 SDValue Result; 1593 1594 // If we've changed things around then replace token factor. 1595 if (Changed) { 1596 if (Ops.empty()) { 1597 // The entry token is the only possible outcome. 1598 Result = DAG.getEntryNode(); 1599 } else { 1600 // New and improved token factor. 1601 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1602 } 1603 1604 // Add users to worklist if AA is enabled, since it may introduce 1605 // a lot of new chained token factors while removing memory deps. 1606 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1607 : DAG.getSubtarget().useAA(); 1608 return CombineTo(N, Result, UseAA /*add to worklist*/); 1609 } 1610 1611 return Result; 1612 } 1613 1614 /// MERGE_VALUES can always be eliminated. 1615 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1616 WorklistRemover DeadNodes(*this); 1617 // Replacing results may cause a different MERGE_VALUES to suddenly 1618 // be CSE'd with N, and carry its uses with it. Iterate until no 1619 // uses remain, to ensure that the node can be safely deleted. 1620 // First add the users of this node to the work list so that they 1621 // can be tried again once they have new operands. 1622 AddUsersToWorklist(N); 1623 do { 1624 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1625 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1626 } while (!N->use_empty()); 1627 deleteAndRecombine(N); 1628 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1629 } 1630 1631 static bool isNullConstant(SDValue V) { 1632 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1633 return Const != nullptr && Const->isNullValue(); 1634 } 1635 1636 static bool isNullFPConstant(SDValue V) { 1637 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 1638 return Const != nullptr && Const->isZero() && !Const->isNegative(); 1639 } 1640 1641 static bool isAllOnesConstant(SDValue V) { 1642 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1643 return Const != nullptr && Const->isAllOnesValue(); 1644 } 1645 1646 static bool isOneConstant(SDValue V) { 1647 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1648 return Const != nullptr && Const->isOne(); 1649 } 1650 1651 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a 1652 /// ContantSDNode pointer else nullptr. 1653 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1654 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1655 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1656 } 1657 1658 SDValue DAGCombiner::visitADD(SDNode *N) { 1659 SDValue N0 = N->getOperand(0); 1660 SDValue N1 = N->getOperand(1); 1661 EVT VT = N0.getValueType(); 1662 1663 // fold vector ops 1664 if (VT.isVector()) { 1665 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1666 return FoldedVOp; 1667 1668 // fold (add x, 0) -> x, vector edition 1669 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1670 return N0; 1671 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1672 return N1; 1673 } 1674 1675 // fold (add x, undef) -> undef 1676 if (N0.getOpcode() == ISD::UNDEF) 1677 return N0; 1678 if (N1.getOpcode() == ISD::UNDEF) 1679 return N1; 1680 // fold (add c1, c2) -> c1+c2 1681 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1682 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1683 if (N0C && N1C) 1684 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C); 1685 // canonicalize constant to RHS 1686 if (isConstantIntBuildVectorOrConstantInt(N0) && 1687 !isConstantIntBuildVectorOrConstantInt(N1)) 1688 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1689 // fold (add x, 0) -> x 1690 if (isNullConstant(N1)) 1691 return N0; 1692 // fold (add Sym, c) -> Sym+c 1693 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1694 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1695 GA->getOpcode() == ISD::GlobalAddress) 1696 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1697 GA->getOffset() + 1698 (uint64_t)N1C->getSExtValue()); 1699 // fold ((c1-A)+c2) -> (c1+c2)-A 1700 if (N1C && N0.getOpcode() == ISD::SUB) 1701 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1702 SDLoc DL(N); 1703 return DAG.getNode(ISD::SUB, DL, VT, 1704 DAG.getConstant(N1C->getAPIntValue()+ 1705 N0C->getAPIntValue(), DL, VT), 1706 N0.getOperand(1)); 1707 } 1708 // reassociate add 1709 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1710 return RADD; 1711 // fold ((0-A) + B) -> B-A 1712 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1713 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1714 // fold (A + (0-B)) -> A-B 1715 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1716 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1717 // fold (A+(B-A)) -> B 1718 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1719 return N1.getOperand(0); 1720 // fold ((B-A)+A) -> B 1721 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1722 return N0.getOperand(0); 1723 // fold (A+(B-(A+C))) to (B-C) 1724 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1725 N0 == N1.getOperand(1).getOperand(0)) 1726 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1727 N1.getOperand(1).getOperand(1)); 1728 // fold (A+(B-(C+A))) to (B-C) 1729 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1730 N0 == N1.getOperand(1).getOperand(1)) 1731 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1732 N1.getOperand(1).getOperand(0)); 1733 // fold (A+((B-A)+or-C)) to (B+or-C) 1734 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1735 N1.getOperand(0).getOpcode() == ISD::SUB && 1736 N0 == N1.getOperand(0).getOperand(1)) 1737 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1738 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1739 1740 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1741 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1742 SDValue N00 = N0.getOperand(0); 1743 SDValue N01 = N0.getOperand(1); 1744 SDValue N10 = N1.getOperand(0); 1745 SDValue N11 = N1.getOperand(1); 1746 1747 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1748 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1749 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1750 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1751 } 1752 1753 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1754 return SDValue(N, 0); 1755 1756 // fold (a+b) -> (a|b) iff a and b share no bits. 1757 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1758 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1)) 1759 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1760 1761 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1762 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1763 isNullConstant(N1.getOperand(0).getOperand(0))) 1764 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1765 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1766 N1.getOperand(0).getOperand(1), 1767 N1.getOperand(1))); 1768 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1769 isNullConstant(N0.getOperand(0).getOperand(0))) 1770 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1771 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1772 N0.getOperand(0).getOperand(1), 1773 N0.getOperand(1))); 1774 1775 if (N1.getOpcode() == ISD::AND) { 1776 SDValue AndOp0 = N1.getOperand(0); 1777 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1778 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1779 1780 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1781 // and similar xforms where the inner op is either ~0 or 0. 1782 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1783 SDLoc DL(N); 1784 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1785 } 1786 } 1787 1788 // add (sext i1), X -> sub X, (zext i1) 1789 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1790 N0.getOperand(0).getValueType() == MVT::i1 && 1791 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1792 SDLoc DL(N); 1793 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1794 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1795 } 1796 1797 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1798 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1799 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1800 if (TN->getVT() == MVT::i1) { 1801 SDLoc DL(N); 1802 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1803 DAG.getConstant(1, DL, VT)); 1804 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1805 } 1806 } 1807 1808 return SDValue(); 1809 } 1810 1811 SDValue DAGCombiner::visitADDC(SDNode *N) { 1812 SDValue N0 = N->getOperand(0); 1813 SDValue N1 = N->getOperand(1); 1814 EVT VT = N0.getValueType(); 1815 1816 // If the flag result is dead, turn this into an ADD. 1817 if (!N->hasAnyUseOfValue(1)) 1818 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1819 DAG.getNode(ISD::CARRY_FALSE, 1820 SDLoc(N), MVT::Glue)); 1821 1822 // canonicalize constant to RHS. 1823 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1824 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1825 if (N0C && !N1C) 1826 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1827 1828 // fold (addc x, 0) -> x + no carry out 1829 if (isNullConstant(N1)) 1830 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1831 SDLoc(N), MVT::Glue)); 1832 1833 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1834 APInt LHSZero, LHSOne; 1835 APInt RHSZero, RHSOne; 1836 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1837 1838 if (LHSZero.getBoolValue()) { 1839 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1840 1841 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1842 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1843 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1844 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1845 DAG.getNode(ISD::CARRY_FALSE, 1846 SDLoc(N), MVT::Glue)); 1847 } 1848 1849 return SDValue(); 1850 } 1851 1852 SDValue DAGCombiner::visitADDE(SDNode *N) { 1853 SDValue N0 = N->getOperand(0); 1854 SDValue N1 = N->getOperand(1); 1855 SDValue CarryIn = N->getOperand(2); 1856 1857 // canonicalize constant to RHS 1858 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1859 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1860 if (N0C && !N1C) 1861 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1862 N1, N0, CarryIn); 1863 1864 // fold (adde x, y, false) -> (addc x, y) 1865 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1866 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1867 1868 return SDValue(); 1869 } 1870 1871 // Since it may not be valid to emit a fold to zero for vector initializers 1872 // check if we can before folding. 1873 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1874 SelectionDAG &DAG, 1875 bool LegalOperations, bool LegalTypes) { 1876 if (!VT.isVector()) 1877 return DAG.getConstant(0, DL, VT); 1878 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1879 return DAG.getConstant(0, DL, VT); 1880 return SDValue(); 1881 } 1882 1883 SDValue DAGCombiner::visitSUB(SDNode *N) { 1884 SDValue N0 = N->getOperand(0); 1885 SDValue N1 = N->getOperand(1); 1886 EVT VT = N0.getValueType(); 1887 1888 // fold vector ops 1889 if (VT.isVector()) { 1890 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1891 return FoldedVOp; 1892 1893 // fold (sub x, 0) -> x, vector edition 1894 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1895 return N0; 1896 } 1897 1898 // fold (sub x, x) -> 0 1899 // FIXME: Refactor this and xor and other similar operations together. 1900 if (N0 == N1) 1901 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1902 // fold (sub c1, c2) -> c1-c2 1903 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1904 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1905 if (N0C && N1C) 1906 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C); 1907 // fold (sub x, c) -> (add x, -c) 1908 if (N1C) { 1909 SDLoc DL(N); 1910 return DAG.getNode(ISD::ADD, DL, VT, N0, 1911 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1912 } 1913 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1914 if (isAllOnesConstant(N0)) 1915 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1916 // fold A-(A-B) -> B 1917 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1918 return N1.getOperand(1); 1919 // fold (A+B)-A -> B 1920 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1921 return N0.getOperand(1); 1922 // fold (A+B)-B -> A 1923 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1924 return N0.getOperand(0); 1925 // fold C2-(A+C1) -> (C2-C1)-A 1926 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1927 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1928 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1929 SDLoc DL(N); 1930 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1931 DL, VT); 1932 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1933 N1.getOperand(0)); 1934 } 1935 // fold ((A+(B+or-C))-B) -> A+or-C 1936 if (N0.getOpcode() == ISD::ADD && 1937 (N0.getOperand(1).getOpcode() == ISD::SUB || 1938 N0.getOperand(1).getOpcode() == ISD::ADD) && 1939 N0.getOperand(1).getOperand(0) == N1) 1940 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1941 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1942 // fold ((A+(C+B))-B) -> A+C 1943 if (N0.getOpcode() == ISD::ADD && 1944 N0.getOperand(1).getOpcode() == ISD::ADD && 1945 N0.getOperand(1).getOperand(1) == N1) 1946 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1947 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1948 // fold ((A-(B-C))-C) -> A-B 1949 if (N0.getOpcode() == ISD::SUB && 1950 N0.getOperand(1).getOpcode() == ISD::SUB && 1951 N0.getOperand(1).getOperand(1) == N1) 1952 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1953 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1954 1955 // If either operand of a sub is undef, the result is undef 1956 if (N0.getOpcode() == ISD::UNDEF) 1957 return N0; 1958 if (N1.getOpcode() == ISD::UNDEF) 1959 return N1; 1960 1961 // If the relocation model supports it, consider symbol offsets. 1962 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1963 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1964 // fold (sub Sym, c) -> Sym-c 1965 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1966 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1967 GA->getOffset() - 1968 (uint64_t)N1C->getSExtValue()); 1969 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1970 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1971 if (GA->getGlobal() == GB->getGlobal()) 1972 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1973 SDLoc(N), VT); 1974 } 1975 1976 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1977 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1978 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1979 if (TN->getVT() == MVT::i1) { 1980 SDLoc DL(N); 1981 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1982 DAG.getConstant(1, DL, VT)); 1983 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1984 } 1985 } 1986 1987 return SDValue(); 1988 } 1989 1990 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1991 SDValue N0 = N->getOperand(0); 1992 SDValue N1 = N->getOperand(1); 1993 EVT VT = N0.getValueType(); 1994 SDLoc DL(N); 1995 1996 // If the flag result is dead, turn this into an SUB. 1997 if (!N->hasAnyUseOfValue(1)) 1998 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 1999 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2000 2001 // fold (subc x, x) -> 0 + no borrow 2002 if (N0 == N1) 2003 return CombineTo(N, DAG.getConstant(0, DL, VT), 2004 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2005 2006 // fold (subc x, 0) -> x + no borrow 2007 if (isNullConstant(N1)) 2008 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2009 2010 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2011 if (isAllOnesConstant(N0)) 2012 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2013 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2014 2015 return SDValue(); 2016 } 2017 2018 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2019 SDValue N0 = N->getOperand(0); 2020 SDValue N1 = N->getOperand(1); 2021 SDValue CarryIn = N->getOperand(2); 2022 2023 // fold (sube x, y, false) -> (subc x, y) 2024 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2025 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2026 2027 return SDValue(); 2028 } 2029 2030 SDValue DAGCombiner::visitMUL(SDNode *N) { 2031 SDValue N0 = N->getOperand(0); 2032 SDValue N1 = N->getOperand(1); 2033 EVT VT = N0.getValueType(); 2034 2035 // fold (mul x, undef) -> 0 2036 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2037 return DAG.getConstant(0, SDLoc(N), VT); 2038 2039 bool N0IsConst = false; 2040 bool N1IsConst = false; 2041 bool N1IsOpaqueConst = false; 2042 bool N0IsOpaqueConst = false; 2043 APInt ConstValue0, ConstValue1; 2044 // fold vector ops 2045 if (VT.isVector()) { 2046 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2047 return FoldedVOp; 2048 2049 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2050 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2051 } else { 2052 N0IsConst = isa<ConstantSDNode>(N0); 2053 if (N0IsConst) { 2054 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2055 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2056 } 2057 N1IsConst = isa<ConstantSDNode>(N1); 2058 if (N1IsConst) { 2059 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2060 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2061 } 2062 } 2063 2064 // fold (mul c1, c2) -> c1*c2 2065 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2066 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2067 N0.getNode(), N1.getNode()); 2068 2069 // canonicalize constant to RHS (vector doesn't have to splat) 2070 if (isConstantIntBuildVectorOrConstantInt(N0) && 2071 !isConstantIntBuildVectorOrConstantInt(N1)) 2072 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2073 // fold (mul x, 0) -> 0 2074 if (N1IsConst && ConstValue1 == 0) 2075 return N1; 2076 // We require a splat of the entire scalar bit width for non-contiguous 2077 // bit patterns. 2078 bool IsFullSplat = 2079 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2080 // fold (mul x, 1) -> x 2081 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2082 return N0; 2083 // fold (mul x, -1) -> 0-x 2084 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2085 SDLoc DL(N); 2086 return DAG.getNode(ISD::SUB, DL, VT, 2087 DAG.getConstant(0, DL, VT), N0); 2088 } 2089 // fold (mul x, (1 << c)) -> x << c 2090 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2091 IsFullSplat) { 2092 SDLoc DL(N); 2093 return DAG.getNode(ISD::SHL, DL, VT, N0, 2094 DAG.getConstant(ConstValue1.logBase2(), DL, 2095 getShiftAmountTy(N0.getValueType()))); 2096 } 2097 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2098 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2099 IsFullSplat) { 2100 unsigned Log2Val = (-ConstValue1).logBase2(); 2101 SDLoc DL(N); 2102 // FIXME: If the input is something that is easily negated (e.g. a 2103 // single-use add), we should put the negate there. 2104 return DAG.getNode(ISD::SUB, DL, VT, 2105 DAG.getConstant(0, DL, VT), 2106 DAG.getNode(ISD::SHL, DL, VT, N0, 2107 DAG.getConstant(Log2Val, DL, 2108 getShiftAmountTy(N0.getValueType())))); 2109 } 2110 2111 APInt Val; 2112 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2113 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2114 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2115 isa<ConstantSDNode>(N0.getOperand(1)))) { 2116 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2117 N1, N0.getOperand(1)); 2118 AddToWorklist(C3.getNode()); 2119 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2120 N0.getOperand(0), C3); 2121 } 2122 2123 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2124 // use. 2125 { 2126 SDValue Sh(nullptr,0), Y(nullptr,0); 2127 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2128 if (N0.getOpcode() == ISD::SHL && 2129 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2130 isa<ConstantSDNode>(N0.getOperand(1))) && 2131 N0.getNode()->hasOneUse()) { 2132 Sh = N0; Y = N1; 2133 } else if (N1.getOpcode() == ISD::SHL && 2134 isa<ConstantSDNode>(N1.getOperand(1)) && 2135 N1.getNode()->hasOneUse()) { 2136 Sh = N1; Y = N0; 2137 } 2138 2139 if (Sh.getNode()) { 2140 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2141 Sh.getOperand(0), Y); 2142 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2143 Mul, Sh.getOperand(1)); 2144 } 2145 } 2146 2147 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2148 if (isConstantIntBuildVectorOrConstantInt(N1) && 2149 N0.getOpcode() == ISD::ADD && 2150 isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2151 isMulAddWithConstProfitable(N, N0, N1)) 2152 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2153 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2154 N0.getOperand(0), N1), 2155 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2156 N0.getOperand(1), N1)); 2157 2158 // reassociate mul 2159 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2160 return RMUL; 2161 2162 return SDValue(); 2163 } 2164 2165 /// Return true if divmod libcall is available. 2166 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2167 const TargetLowering &TLI) { 2168 RTLIB::Libcall LC; 2169 switch (Node->getSimpleValueType(0).SimpleTy) { 2170 default: return false; // No libcall for vector types. 2171 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2172 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2173 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2174 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2175 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2176 } 2177 2178 return TLI.getLibcallName(LC) != nullptr; 2179 } 2180 2181 /// Issue divrem if both quotient and remainder are needed. 2182 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2183 if (Node->use_empty()) 2184 return SDValue(); // This is a dead node, leave it alone. 2185 2186 EVT VT = Node->getValueType(0); 2187 if (!TLI.isTypeLegal(VT)) 2188 return SDValue(); 2189 2190 unsigned Opcode = Node->getOpcode(); 2191 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2192 2193 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2194 // If DIVREM is going to get expanded into a libcall, 2195 // but there is no libcall available, then don't combine. 2196 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2197 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2198 return SDValue(); 2199 2200 // If div is legal, it's better to do the normal expansion 2201 unsigned OtherOpcode = 0; 2202 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2203 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2204 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2205 return SDValue(); 2206 } else { 2207 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2208 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2209 return SDValue(); 2210 } 2211 2212 SDValue Op0 = Node->getOperand(0); 2213 SDValue Op1 = Node->getOperand(1); 2214 SDValue combined; 2215 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2216 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2217 SDNode *User = *UI; 2218 if (User == Node || User->use_empty()) 2219 continue; 2220 // Convert the other matching node(s), too; 2221 // otherwise, the DIVREM may get target-legalized into something 2222 // target-specific that we won't be able to recognize. 2223 unsigned UserOpc = User->getOpcode(); 2224 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2225 User->getOperand(0) == Op0 && 2226 User->getOperand(1) == Op1) { 2227 if (!combined) { 2228 if (UserOpc == OtherOpcode) { 2229 SDVTList VTs = DAG.getVTList(VT, VT); 2230 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2231 } else if (UserOpc == DivRemOpc) { 2232 combined = SDValue(User, 0); 2233 } else { 2234 assert(UserOpc == Opcode); 2235 continue; 2236 } 2237 } 2238 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2239 CombineTo(User, combined); 2240 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2241 CombineTo(User, combined.getValue(1)); 2242 } 2243 } 2244 return combined; 2245 } 2246 2247 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2248 SDValue N0 = N->getOperand(0); 2249 SDValue N1 = N->getOperand(1); 2250 EVT VT = N->getValueType(0); 2251 2252 // fold vector ops 2253 if (VT.isVector()) 2254 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2255 return FoldedVOp; 2256 2257 SDLoc DL(N); 2258 2259 // fold (sdiv c1, c2) -> c1/c2 2260 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2261 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2262 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2263 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2264 // fold (sdiv X, 1) -> X 2265 if (N1C && N1C->isOne()) 2266 return N0; 2267 // fold (sdiv X, -1) -> 0-X 2268 if (N1C && N1C->isAllOnesValue()) 2269 return DAG.getNode(ISD::SUB, DL, VT, 2270 DAG.getConstant(0, DL, VT), N0); 2271 2272 // If we know the sign bits of both operands are zero, strength reduce to a 2273 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2274 if (!VT.isVector()) { 2275 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2276 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2277 } 2278 2279 // fold (sdiv X, pow2) -> simple ops after legalize 2280 // FIXME: We check for the exact bit here because the generic lowering gives 2281 // better results in that case. The target-specific lowering should learn how 2282 // to handle exact sdivs efficiently. 2283 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2284 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2285 (N1C->getAPIntValue().isPowerOf2() || 2286 (-N1C->getAPIntValue()).isPowerOf2())) { 2287 // Target-specific implementation of sdiv x, pow2. 2288 if (SDValue Res = BuildSDIVPow2(N)) 2289 return Res; 2290 2291 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2292 2293 // Splat the sign bit into the register 2294 SDValue SGN = 2295 DAG.getNode(ISD::SRA, DL, VT, N0, 2296 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2297 getShiftAmountTy(N0.getValueType()))); 2298 AddToWorklist(SGN.getNode()); 2299 2300 // Add (N0 < 0) ? abs2 - 1 : 0; 2301 SDValue SRL = 2302 DAG.getNode(ISD::SRL, DL, VT, SGN, 2303 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2304 getShiftAmountTy(SGN.getValueType()))); 2305 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2306 AddToWorklist(SRL.getNode()); 2307 AddToWorklist(ADD.getNode()); // Divide by pow2 2308 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2309 DAG.getConstant(lg2, DL, 2310 getShiftAmountTy(ADD.getValueType()))); 2311 2312 // If we're dividing by a positive value, we're done. Otherwise, we must 2313 // negate the result. 2314 if (N1C->getAPIntValue().isNonNegative()) 2315 return SRA; 2316 2317 AddToWorklist(SRA.getNode()); 2318 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2319 } 2320 2321 // If integer divide is expensive and we satisfy the requirements, emit an 2322 // alternate sequence. Targets may check function attributes for size/speed 2323 // trade-offs. 2324 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2325 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2326 if (SDValue Op = BuildSDIV(N)) 2327 return Op; 2328 2329 // sdiv, srem -> sdivrem 2330 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2331 // Otherwise, we break the simplification logic in visitREM(). 2332 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2333 if (SDValue DivRem = useDivRem(N)) 2334 return DivRem; 2335 2336 // undef / X -> 0 2337 if (N0.getOpcode() == ISD::UNDEF) 2338 return DAG.getConstant(0, DL, VT); 2339 // X / undef -> undef 2340 if (N1.getOpcode() == ISD::UNDEF) 2341 return N1; 2342 2343 return SDValue(); 2344 } 2345 2346 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2347 SDValue N0 = N->getOperand(0); 2348 SDValue N1 = N->getOperand(1); 2349 EVT VT = N->getValueType(0); 2350 2351 // fold vector ops 2352 if (VT.isVector()) 2353 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2354 return FoldedVOp; 2355 2356 SDLoc DL(N); 2357 2358 // fold (udiv c1, c2) -> c1/c2 2359 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2360 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2361 if (N0C && N1C) 2362 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2363 N0C, N1C)) 2364 return Folded; 2365 // fold (udiv x, (1 << c)) -> x >>u c 2366 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2367 return DAG.getNode(ISD::SRL, DL, VT, N0, 2368 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2369 getShiftAmountTy(N0.getValueType()))); 2370 2371 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2372 if (N1.getOpcode() == ISD::SHL) { 2373 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2374 if (SHC->getAPIntValue().isPowerOf2()) { 2375 EVT ADDVT = N1.getOperand(1).getValueType(); 2376 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2377 N1.getOperand(1), 2378 DAG.getConstant(SHC->getAPIntValue() 2379 .logBase2(), 2380 DL, ADDVT)); 2381 AddToWorklist(Add.getNode()); 2382 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2383 } 2384 } 2385 } 2386 2387 // fold (udiv x, c) -> alternate 2388 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2389 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2390 if (SDValue Op = BuildUDIV(N)) 2391 return Op; 2392 2393 // sdiv, srem -> sdivrem 2394 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2395 // Otherwise, we break the simplification logic in visitREM(). 2396 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2397 if (SDValue DivRem = useDivRem(N)) 2398 return DivRem; 2399 2400 // undef / X -> 0 2401 if (N0.getOpcode() == ISD::UNDEF) 2402 return DAG.getConstant(0, DL, VT); 2403 // X / undef -> undef 2404 if (N1.getOpcode() == ISD::UNDEF) 2405 return N1; 2406 2407 return SDValue(); 2408 } 2409 2410 // handles ISD::SREM and ISD::UREM 2411 SDValue DAGCombiner::visitREM(SDNode *N) { 2412 unsigned Opcode = N->getOpcode(); 2413 SDValue N0 = N->getOperand(0); 2414 SDValue N1 = N->getOperand(1); 2415 EVT VT = N->getValueType(0); 2416 bool isSigned = (Opcode == ISD::SREM); 2417 SDLoc DL(N); 2418 2419 // fold (rem c1, c2) -> c1%c2 2420 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2421 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2422 if (N0C && N1C) 2423 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2424 return Folded; 2425 2426 if (isSigned) { 2427 // If we know the sign bits of both operands are zero, strength reduce to a 2428 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2429 if (!VT.isVector()) { 2430 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2431 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2432 } 2433 } else { 2434 // fold (urem x, pow2) -> (and x, pow2-1) 2435 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2436 N1C->getAPIntValue().isPowerOf2()) { 2437 return DAG.getNode(ISD::AND, DL, VT, N0, 2438 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2439 } 2440 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2441 if (N1.getOpcode() == ISD::SHL) { 2442 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2443 if (SHC->getAPIntValue().isPowerOf2()) { 2444 SDValue Add = 2445 DAG.getNode(ISD::ADD, DL, VT, N1, 2446 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2447 VT)); 2448 AddToWorklist(Add.getNode()); 2449 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2450 } 2451 } 2452 } 2453 } 2454 2455 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2456 2457 // If X/C can be simplified by the division-by-constant logic, lower 2458 // X%C to the equivalent of X-X/C*C. 2459 // To avoid mangling nodes, this simplification requires that the combine() 2460 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2461 // against this by skipping the simplification if isIntDivCheap(). When 2462 // div is not cheap, combine will not return a DIVREM. Regardless, 2463 // checking cheapness here makes sense since the simplification results in 2464 // fatter code. 2465 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2466 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2467 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2468 AddToWorklist(Div.getNode()); 2469 SDValue OptimizedDiv = combine(Div.getNode()); 2470 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2471 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2472 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2473 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2474 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2475 AddToWorklist(Mul.getNode()); 2476 return Sub; 2477 } 2478 } 2479 2480 // sdiv, srem -> sdivrem 2481 if (SDValue DivRem = useDivRem(N)) 2482 return DivRem.getValue(1); 2483 2484 // undef % X -> 0 2485 if (N0.getOpcode() == ISD::UNDEF) 2486 return DAG.getConstant(0, DL, VT); 2487 // X % undef -> undef 2488 if (N1.getOpcode() == ISD::UNDEF) 2489 return N1; 2490 2491 return SDValue(); 2492 } 2493 2494 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2495 SDValue N0 = N->getOperand(0); 2496 SDValue N1 = N->getOperand(1); 2497 EVT VT = N->getValueType(0); 2498 SDLoc DL(N); 2499 2500 // fold (mulhs x, 0) -> 0 2501 if (isNullConstant(N1)) 2502 return N1; 2503 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2504 if (isOneConstant(N1)) { 2505 SDLoc DL(N); 2506 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2507 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2508 DL, 2509 getShiftAmountTy(N0.getValueType()))); 2510 } 2511 // fold (mulhs x, undef) -> 0 2512 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2513 return DAG.getConstant(0, SDLoc(N), VT); 2514 2515 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2516 // plus a shift. 2517 if (VT.isSimple() && !VT.isVector()) { 2518 MVT Simple = VT.getSimpleVT(); 2519 unsigned SimpleSize = Simple.getSizeInBits(); 2520 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2521 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2522 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2523 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2524 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2525 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2526 DAG.getConstant(SimpleSize, DL, 2527 getShiftAmountTy(N1.getValueType()))); 2528 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2529 } 2530 } 2531 2532 return SDValue(); 2533 } 2534 2535 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2536 SDValue N0 = N->getOperand(0); 2537 SDValue N1 = N->getOperand(1); 2538 EVT VT = N->getValueType(0); 2539 SDLoc DL(N); 2540 2541 // fold (mulhu x, 0) -> 0 2542 if (isNullConstant(N1)) 2543 return N1; 2544 // fold (mulhu x, 1) -> 0 2545 if (isOneConstant(N1)) 2546 return DAG.getConstant(0, DL, N0.getValueType()); 2547 // fold (mulhu x, undef) -> 0 2548 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2549 return DAG.getConstant(0, DL, VT); 2550 2551 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2552 // plus a shift. 2553 if (VT.isSimple() && !VT.isVector()) { 2554 MVT Simple = VT.getSimpleVT(); 2555 unsigned SimpleSize = Simple.getSizeInBits(); 2556 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2557 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2558 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2559 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2560 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2561 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2562 DAG.getConstant(SimpleSize, DL, 2563 getShiftAmountTy(N1.getValueType()))); 2564 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2565 } 2566 } 2567 2568 return SDValue(); 2569 } 2570 2571 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2572 /// give the opcodes for the two computations that are being performed. Return 2573 /// true if a simplification was made. 2574 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2575 unsigned HiOp) { 2576 // If the high half is not needed, just compute the low half. 2577 bool HiExists = N->hasAnyUseOfValue(1); 2578 if (!HiExists && 2579 (!LegalOperations || 2580 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2581 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2582 return CombineTo(N, Res, Res); 2583 } 2584 2585 // If the low half is not needed, just compute the high half. 2586 bool LoExists = N->hasAnyUseOfValue(0); 2587 if (!LoExists && 2588 (!LegalOperations || 2589 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2590 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2591 return CombineTo(N, Res, Res); 2592 } 2593 2594 // If both halves are used, return as it is. 2595 if (LoExists && HiExists) 2596 return SDValue(); 2597 2598 // If the two computed results can be simplified separately, separate them. 2599 if (LoExists) { 2600 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2601 AddToWorklist(Lo.getNode()); 2602 SDValue LoOpt = combine(Lo.getNode()); 2603 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2604 (!LegalOperations || 2605 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2606 return CombineTo(N, LoOpt, LoOpt); 2607 } 2608 2609 if (HiExists) { 2610 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2611 AddToWorklist(Hi.getNode()); 2612 SDValue HiOpt = combine(Hi.getNode()); 2613 if (HiOpt.getNode() && HiOpt != Hi && 2614 (!LegalOperations || 2615 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2616 return CombineTo(N, HiOpt, HiOpt); 2617 } 2618 2619 return SDValue(); 2620 } 2621 2622 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2623 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2624 return Res; 2625 2626 EVT VT = N->getValueType(0); 2627 SDLoc DL(N); 2628 2629 // If the type is twice as wide is legal, transform the mulhu to a wider 2630 // multiply plus a shift. 2631 if (VT.isSimple() && !VT.isVector()) { 2632 MVT Simple = VT.getSimpleVT(); 2633 unsigned SimpleSize = Simple.getSizeInBits(); 2634 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2635 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2636 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2637 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2638 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2639 // Compute the high part as N1. 2640 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2641 DAG.getConstant(SimpleSize, DL, 2642 getShiftAmountTy(Lo.getValueType()))); 2643 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2644 // Compute the low part as N0. 2645 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2646 return CombineTo(N, Lo, Hi); 2647 } 2648 } 2649 2650 return SDValue(); 2651 } 2652 2653 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2654 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2655 return Res; 2656 2657 EVT VT = N->getValueType(0); 2658 SDLoc DL(N); 2659 2660 // If the type is twice as wide is legal, transform the mulhu to a wider 2661 // multiply plus a shift. 2662 if (VT.isSimple() && !VT.isVector()) { 2663 MVT Simple = VT.getSimpleVT(); 2664 unsigned SimpleSize = Simple.getSizeInBits(); 2665 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2666 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2667 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2668 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2669 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2670 // Compute the high part as N1. 2671 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2672 DAG.getConstant(SimpleSize, DL, 2673 getShiftAmountTy(Lo.getValueType()))); 2674 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2675 // Compute the low part as N0. 2676 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2677 return CombineTo(N, Lo, Hi); 2678 } 2679 } 2680 2681 return SDValue(); 2682 } 2683 2684 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2685 // (smulo x, 2) -> (saddo x, x) 2686 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2687 if (C2->getAPIntValue() == 2) 2688 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2689 N->getOperand(0), N->getOperand(0)); 2690 2691 return SDValue(); 2692 } 2693 2694 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2695 // (umulo x, 2) -> (uaddo x, x) 2696 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2697 if (C2->getAPIntValue() == 2) 2698 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2699 N->getOperand(0), N->getOperand(0)); 2700 2701 return SDValue(); 2702 } 2703 2704 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2705 SDValue N0 = N->getOperand(0); 2706 SDValue N1 = N->getOperand(1); 2707 EVT VT = N0.getValueType(); 2708 2709 // fold vector ops 2710 if (VT.isVector()) 2711 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2712 return FoldedVOp; 2713 2714 // fold (add c1, c2) -> c1+c2 2715 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2716 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2717 if (N0C && N1C) 2718 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2719 2720 // canonicalize constant to RHS 2721 if (isConstantIntBuildVectorOrConstantInt(N0) && 2722 !isConstantIntBuildVectorOrConstantInt(N1)) 2723 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2724 2725 return SDValue(); 2726 } 2727 2728 /// If this is a binary operator with two operands of the same opcode, try to 2729 /// simplify it. 2730 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2731 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2732 EVT VT = N0.getValueType(); 2733 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2734 2735 // Bail early if none of these transforms apply. 2736 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2737 2738 // For each of OP in AND/OR/XOR: 2739 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2740 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2741 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2742 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2743 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2744 // 2745 // do not sink logical op inside of a vector extend, since it may combine 2746 // into a vsetcc. 2747 EVT Op0VT = N0.getOperand(0).getValueType(); 2748 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2749 N0.getOpcode() == ISD::SIGN_EXTEND || 2750 N0.getOpcode() == ISD::BSWAP || 2751 // Avoid infinite looping with PromoteIntBinOp. 2752 (N0.getOpcode() == ISD::ANY_EXTEND && 2753 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2754 (N0.getOpcode() == ISD::TRUNCATE && 2755 (!TLI.isZExtFree(VT, Op0VT) || 2756 !TLI.isTruncateFree(Op0VT, VT)) && 2757 TLI.isTypeLegal(Op0VT))) && 2758 !VT.isVector() && 2759 Op0VT == N1.getOperand(0).getValueType() && 2760 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2761 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2762 N0.getOperand(0).getValueType(), 2763 N0.getOperand(0), N1.getOperand(0)); 2764 AddToWorklist(ORNode.getNode()); 2765 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2766 } 2767 2768 // For each of OP in SHL/SRL/SRA/AND... 2769 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2770 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2771 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2772 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2773 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2774 N0.getOperand(1) == N1.getOperand(1)) { 2775 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2776 N0.getOperand(0).getValueType(), 2777 N0.getOperand(0), N1.getOperand(0)); 2778 AddToWorklist(ORNode.getNode()); 2779 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2780 ORNode, N0.getOperand(1)); 2781 } 2782 2783 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2784 // Only perform this optimization after type legalization and before 2785 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2786 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2787 // we don't want to undo this promotion. 2788 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2789 // on scalars. 2790 if ((N0.getOpcode() == ISD::BITCAST || 2791 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2792 Level == AfterLegalizeTypes) { 2793 SDValue In0 = N0.getOperand(0); 2794 SDValue In1 = N1.getOperand(0); 2795 EVT In0Ty = In0.getValueType(); 2796 EVT In1Ty = In1.getValueType(); 2797 SDLoc DL(N); 2798 // If both incoming values are integers, and the original types are the 2799 // same. 2800 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2801 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2802 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2803 AddToWorklist(Op.getNode()); 2804 return BC; 2805 } 2806 } 2807 2808 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2809 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2810 // If both shuffles use the same mask, and both shuffle within a single 2811 // vector, then it is worthwhile to move the swizzle after the operation. 2812 // The type-legalizer generates this pattern when loading illegal 2813 // vector types from memory. In many cases this allows additional shuffle 2814 // optimizations. 2815 // There are other cases where moving the shuffle after the xor/and/or 2816 // is profitable even if shuffles don't perform a swizzle. 2817 // If both shuffles use the same mask, and both shuffles have the same first 2818 // or second operand, then it might still be profitable to move the shuffle 2819 // after the xor/and/or operation. 2820 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2821 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2822 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2823 2824 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2825 "Inputs to shuffles are not the same type"); 2826 2827 // Check that both shuffles use the same mask. The masks are known to be of 2828 // the same length because the result vector type is the same. 2829 // Check also that shuffles have only one use to avoid introducing extra 2830 // instructions. 2831 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2832 SVN0->getMask().equals(SVN1->getMask())) { 2833 SDValue ShOp = N0->getOperand(1); 2834 2835 // Don't try to fold this node if it requires introducing a 2836 // build vector of all zeros that might be illegal at this stage. 2837 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2838 if (!LegalTypes) 2839 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2840 else 2841 ShOp = SDValue(); 2842 } 2843 2844 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2845 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2846 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2847 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2848 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2849 N0->getOperand(0), N1->getOperand(0)); 2850 AddToWorklist(NewNode.getNode()); 2851 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2852 &SVN0->getMask()[0]); 2853 } 2854 2855 // Don't try to fold this node if it requires introducing a 2856 // build vector of all zeros that might be illegal at this stage. 2857 ShOp = N0->getOperand(0); 2858 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2859 if (!LegalTypes) 2860 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2861 else 2862 ShOp = SDValue(); 2863 } 2864 2865 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2866 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2867 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2868 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2869 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2870 N0->getOperand(1), N1->getOperand(1)); 2871 AddToWorklist(NewNode.getNode()); 2872 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2873 &SVN0->getMask()[0]); 2874 } 2875 } 2876 } 2877 2878 return SDValue(); 2879 } 2880 2881 /// This contains all DAGCombine rules which reduce two values combined by 2882 /// an And operation to a single value. This makes them reusable in the context 2883 /// of visitSELECT(). Rules involving constants are not included as 2884 /// visitSELECT() already handles those cases. 2885 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2886 SDNode *LocReference) { 2887 EVT VT = N1.getValueType(); 2888 2889 // fold (and x, undef) -> 0 2890 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2891 return DAG.getConstant(0, SDLoc(LocReference), VT); 2892 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2893 SDValue LL, LR, RL, RR, CC0, CC1; 2894 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2895 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2896 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2897 2898 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2899 LL.getValueType().isInteger()) { 2900 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2901 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2902 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2903 LR.getValueType(), LL, RL); 2904 AddToWorklist(ORNode.getNode()); 2905 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2906 } 2907 if (isAllOnesConstant(LR)) { 2908 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2909 if (Op1 == ISD::SETEQ) { 2910 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2911 LR.getValueType(), LL, RL); 2912 AddToWorklist(ANDNode.getNode()); 2913 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2914 } 2915 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2916 if (Op1 == ISD::SETGT) { 2917 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2918 LR.getValueType(), LL, RL); 2919 AddToWorklist(ORNode.getNode()); 2920 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2921 } 2922 } 2923 } 2924 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2925 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2926 Op0 == Op1 && LL.getValueType().isInteger() && 2927 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2928 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2929 SDLoc DL(N0); 2930 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2931 LL, DAG.getConstant(1, DL, 2932 LL.getValueType())); 2933 AddToWorklist(ADDNode.getNode()); 2934 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2935 DAG.getConstant(2, DL, LL.getValueType()), 2936 ISD::SETUGE); 2937 } 2938 // canonicalize equivalent to ll == rl 2939 if (LL == RR && LR == RL) { 2940 Op1 = ISD::getSetCCSwappedOperands(Op1); 2941 std::swap(RL, RR); 2942 } 2943 if (LL == RL && LR == RR) { 2944 bool isInteger = LL.getValueType().isInteger(); 2945 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2946 if (Result != ISD::SETCC_INVALID && 2947 (!LegalOperations || 2948 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2949 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2950 EVT CCVT = getSetCCResultType(LL.getValueType()); 2951 if (N0.getValueType() == CCVT || 2952 (!LegalOperations && N0.getValueType() == MVT::i1)) 2953 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2954 LL, LR, Result); 2955 } 2956 } 2957 } 2958 2959 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2960 VT.getSizeInBits() <= 64) { 2961 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2962 APInt ADDC = ADDI->getAPIntValue(); 2963 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2964 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2965 // immediate for an add, but it is legal if its top c2 bits are set, 2966 // transform the ADD so the immediate doesn't need to be materialized 2967 // in a register. 2968 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2969 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2970 SRLI->getZExtValue()); 2971 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2972 ADDC |= Mask; 2973 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2974 SDLoc DL(N0); 2975 SDValue NewAdd = 2976 DAG.getNode(ISD::ADD, DL, VT, 2977 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2978 CombineTo(N0.getNode(), NewAdd); 2979 // Return N so it doesn't get rechecked! 2980 return SDValue(LocReference, 0); 2981 } 2982 } 2983 } 2984 } 2985 } 2986 } 2987 2988 return SDValue(); 2989 } 2990 2991 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 2992 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 2993 bool &NarrowLoad) { 2994 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 2995 2996 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 2997 return false; 2998 2999 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3000 LoadedVT = LoadN->getMemoryVT(); 3001 3002 if (ExtVT == LoadedVT && 3003 (!LegalOperations || 3004 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3005 // ZEXTLOAD will match without needing to change the size of the value being 3006 // loaded. 3007 NarrowLoad = false; 3008 return true; 3009 } 3010 3011 // Do not change the width of a volatile load. 3012 if (LoadN->isVolatile()) 3013 return false; 3014 3015 // Do not generate loads of non-round integer types since these can 3016 // be expensive (and would be wrong if the type is not byte sized). 3017 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3018 return false; 3019 3020 if (LegalOperations && 3021 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3022 return false; 3023 3024 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3025 return false; 3026 3027 NarrowLoad = true; 3028 return true; 3029 } 3030 3031 SDValue DAGCombiner::visitAND(SDNode *N) { 3032 SDValue N0 = N->getOperand(0); 3033 SDValue N1 = N->getOperand(1); 3034 EVT VT = N1.getValueType(); 3035 3036 // fold vector ops 3037 if (VT.isVector()) { 3038 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3039 return FoldedVOp; 3040 3041 // fold (and x, 0) -> 0, vector edition 3042 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3043 // do not return N0, because undef node may exist in N0 3044 return DAG.getConstant( 3045 APInt::getNullValue( 3046 N0.getValueType().getScalarType().getSizeInBits()), 3047 SDLoc(N), N0.getValueType()); 3048 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3049 // do not return N1, because undef node may exist in N1 3050 return DAG.getConstant( 3051 APInt::getNullValue( 3052 N1.getValueType().getScalarType().getSizeInBits()), 3053 SDLoc(N), N1.getValueType()); 3054 3055 // fold (and x, -1) -> x, vector edition 3056 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3057 return N1; 3058 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3059 return N0; 3060 } 3061 3062 // fold (and c1, c2) -> c1&c2 3063 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3064 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3065 if (N0C && N1C && !N1C->isOpaque()) 3066 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3067 // canonicalize constant to RHS 3068 if (isConstantIntBuildVectorOrConstantInt(N0) && 3069 !isConstantIntBuildVectorOrConstantInt(N1)) 3070 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3071 // fold (and x, -1) -> x 3072 if (isAllOnesConstant(N1)) 3073 return N0; 3074 // if (and x, c) is known to be zero, return 0 3075 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3076 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3077 APInt::getAllOnesValue(BitWidth))) 3078 return DAG.getConstant(0, SDLoc(N), VT); 3079 // reassociate and 3080 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3081 return RAND; 3082 // fold (and (or x, C), D) -> D if (C & D) == D 3083 if (N1C && N0.getOpcode() == ISD::OR) 3084 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3085 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3086 return N1; 3087 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3088 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3089 SDValue N0Op0 = N0.getOperand(0); 3090 APInt Mask = ~N1C->getAPIntValue(); 3091 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 3092 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3093 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3094 N0.getValueType(), N0Op0); 3095 3096 // Replace uses of the AND with uses of the Zero extend node. 3097 CombineTo(N, Zext); 3098 3099 // We actually want to replace all uses of the any_extend with the 3100 // zero_extend, to avoid duplicating things. This will later cause this 3101 // AND to be folded. 3102 CombineTo(N0.getNode(), Zext); 3103 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3104 } 3105 } 3106 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3107 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3108 // already be zero by virtue of the width of the base type of the load. 3109 // 3110 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3111 // more cases. 3112 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3113 N0.getOperand(0).getOpcode() == ISD::LOAD) || 3114 N0.getOpcode() == ISD::LOAD) { 3115 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3116 N0 : N0.getOperand(0) ); 3117 3118 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3119 // This can be a pure constant or a vector splat, in which case we treat the 3120 // vector as a scalar and use the splat value. 3121 APInt Constant = APInt::getNullValue(1); 3122 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3123 Constant = C->getAPIntValue(); 3124 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3125 APInt SplatValue, SplatUndef; 3126 unsigned SplatBitSize; 3127 bool HasAnyUndefs; 3128 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3129 SplatBitSize, HasAnyUndefs); 3130 if (IsSplat) { 3131 // Undef bits can contribute to a possible optimisation if set, so 3132 // set them. 3133 SplatValue |= SplatUndef; 3134 3135 // The splat value may be something like "0x00FFFFFF", which means 0 for 3136 // the first vector value and FF for the rest, repeating. We need a mask 3137 // that will apply equally to all members of the vector, so AND all the 3138 // lanes of the constant together. 3139 EVT VT = Vector->getValueType(0); 3140 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3141 3142 // If the splat value has been compressed to a bitlength lower 3143 // than the size of the vector lane, we need to re-expand it to 3144 // the lane size. 3145 if (BitWidth > SplatBitSize) 3146 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3147 SplatBitSize < BitWidth; 3148 SplatBitSize = SplatBitSize * 2) 3149 SplatValue |= SplatValue.shl(SplatBitSize); 3150 3151 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3152 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3153 if (SplatBitSize % BitWidth == 0) { 3154 Constant = APInt::getAllOnesValue(BitWidth); 3155 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3156 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3157 } 3158 } 3159 } 3160 3161 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3162 // actually legal and isn't going to get expanded, else this is a false 3163 // optimisation. 3164 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3165 Load->getValueType(0), 3166 Load->getMemoryVT()); 3167 3168 // Resize the constant to the same size as the original memory access before 3169 // extension. If it is still the AllOnesValue then this AND is completely 3170 // unneeded. 3171 Constant = 3172 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3173 3174 bool B; 3175 switch (Load->getExtensionType()) { 3176 default: B = false; break; 3177 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3178 case ISD::ZEXTLOAD: 3179 case ISD::NON_EXTLOAD: B = true; break; 3180 } 3181 3182 if (B && Constant.isAllOnesValue()) { 3183 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3184 // preserve semantics once we get rid of the AND. 3185 SDValue NewLoad(Load, 0); 3186 if (Load->getExtensionType() == ISD::EXTLOAD) { 3187 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3188 Load->getValueType(0), SDLoc(Load), 3189 Load->getChain(), Load->getBasePtr(), 3190 Load->getOffset(), Load->getMemoryVT(), 3191 Load->getMemOperand()); 3192 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3193 if (Load->getNumValues() == 3) { 3194 // PRE/POST_INC loads have 3 values. 3195 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3196 NewLoad.getValue(2) }; 3197 CombineTo(Load, To, 3, true); 3198 } else { 3199 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3200 } 3201 } 3202 3203 // Fold the AND away, taking care not to fold to the old load node if we 3204 // replaced it. 3205 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3206 3207 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3208 } 3209 } 3210 3211 // fold (and (load x), 255) -> (zextload x, i8) 3212 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3213 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3214 if (N1C && (N0.getOpcode() == ISD::LOAD || 3215 (N0.getOpcode() == ISD::ANY_EXTEND && 3216 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3217 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3218 LoadSDNode *LN0 = HasAnyExt 3219 ? cast<LoadSDNode>(N0.getOperand(0)) 3220 : cast<LoadSDNode>(N0); 3221 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3222 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3223 auto NarrowLoad = false; 3224 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3225 EVT ExtVT, LoadedVT; 3226 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3227 NarrowLoad)) { 3228 if (!NarrowLoad) { 3229 SDValue NewLoad = 3230 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3231 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3232 LN0->getMemOperand()); 3233 AddToWorklist(N); 3234 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3235 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3236 } else { 3237 EVT PtrType = LN0->getOperand(1).getValueType(); 3238 3239 unsigned Alignment = LN0->getAlignment(); 3240 SDValue NewPtr = LN0->getBasePtr(); 3241 3242 // For big endian targets, we need to add an offset to the pointer 3243 // to load the correct bytes. For little endian systems, we merely 3244 // need to read fewer bytes from the same pointer. 3245 if (DAG.getDataLayout().isBigEndian()) { 3246 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3247 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3248 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3249 SDLoc DL(LN0); 3250 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3251 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3252 Alignment = MinAlign(Alignment, PtrOff); 3253 } 3254 3255 AddToWorklist(NewPtr.getNode()); 3256 3257 SDValue Load = 3258 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3259 LN0->getChain(), NewPtr, 3260 LN0->getPointerInfo(), 3261 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3262 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3263 AddToWorklist(N); 3264 CombineTo(LN0, Load, Load.getValue(1)); 3265 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3266 } 3267 } 3268 } 3269 } 3270 3271 if (SDValue Combined = visitANDLike(N0, N1, N)) 3272 return Combined; 3273 3274 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3275 if (N0.getOpcode() == N1.getOpcode()) 3276 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3277 return Tmp; 3278 3279 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3280 // fold (and (sra)) -> (and (srl)) when possible. 3281 if (!VT.isVector() && 3282 SimplifyDemandedBits(SDValue(N, 0))) 3283 return SDValue(N, 0); 3284 3285 // fold (zext_inreg (extload x)) -> (zextload x) 3286 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3287 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3288 EVT MemVT = LN0->getMemoryVT(); 3289 // If we zero all the possible extended bits, then we can turn this into 3290 // a zextload if we are running before legalize or the operation is legal. 3291 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3292 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3293 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3294 ((!LegalOperations && !LN0->isVolatile()) || 3295 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3296 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3297 LN0->getChain(), LN0->getBasePtr(), 3298 MemVT, LN0->getMemOperand()); 3299 AddToWorklist(N); 3300 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3301 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3302 } 3303 } 3304 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3305 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3306 N0.hasOneUse()) { 3307 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3308 EVT MemVT = LN0->getMemoryVT(); 3309 // If we zero all the possible extended bits, then we can turn this into 3310 // a zextload if we are running before legalize or the operation is legal. 3311 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3312 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3313 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3314 ((!LegalOperations && !LN0->isVolatile()) || 3315 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3316 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3317 LN0->getChain(), LN0->getBasePtr(), 3318 MemVT, LN0->getMemOperand()); 3319 AddToWorklist(N); 3320 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3321 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3322 } 3323 } 3324 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3325 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3326 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3327 N0.getOperand(1), false); 3328 if (BSwap.getNode()) 3329 return BSwap; 3330 } 3331 3332 return SDValue(); 3333 } 3334 3335 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3336 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3337 bool DemandHighBits) { 3338 if (!LegalOperations) 3339 return SDValue(); 3340 3341 EVT VT = N->getValueType(0); 3342 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3343 return SDValue(); 3344 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3345 return SDValue(); 3346 3347 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3348 bool LookPassAnd0 = false; 3349 bool LookPassAnd1 = false; 3350 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3351 std::swap(N0, N1); 3352 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3353 std::swap(N0, N1); 3354 if (N0.getOpcode() == ISD::AND) { 3355 if (!N0.getNode()->hasOneUse()) 3356 return SDValue(); 3357 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3358 if (!N01C || N01C->getZExtValue() != 0xFF00) 3359 return SDValue(); 3360 N0 = N0.getOperand(0); 3361 LookPassAnd0 = true; 3362 } 3363 3364 if (N1.getOpcode() == ISD::AND) { 3365 if (!N1.getNode()->hasOneUse()) 3366 return SDValue(); 3367 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3368 if (!N11C || N11C->getZExtValue() != 0xFF) 3369 return SDValue(); 3370 N1 = N1.getOperand(0); 3371 LookPassAnd1 = true; 3372 } 3373 3374 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3375 std::swap(N0, N1); 3376 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3377 return SDValue(); 3378 if (!N0.getNode()->hasOneUse() || 3379 !N1.getNode()->hasOneUse()) 3380 return SDValue(); 3381 3382 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3383 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3384 if (!N01C || !N11C) 3385 return SDValue(); 3386 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3387 return SDValue(); 3388 3389 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3390 SDValue N00 = N0->getOperand(0); 3391 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3392 if (!N00.getNode()->hasOneUse()) 3393 return SDValue(); 3394 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3395 if (!N001C || N001C->getZExtValue() != 0xFF) 3396 return SDValue(); 3397 N00 = N00.getOperand(0); 3398 LookPassAnd0 = true; 3399 } 3400 3401 SDValue N10 = N1->getOperand(0); 3402 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3403 if (!N10.getNode()->hasOneUse()) 3404 return SDValue(); 3405 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3406 if (!N101C || N101C->getZExtValue() != 0xFF00) 3407 return SDValue(); 3408 N10 = N10.getOperand(0); 3409 LookPassAnd1 = true; 3410 } 3411 3412 if (N00 != N10) 3413 return SDValue(); 3414 3415 // Make sure everything beyond the low halfword gets set to zero since the SRL 3416 // 16 will clear the top bits. 3417 unsigned OpSizeInBits = VT.getSizeInBits(); 3418 if (DemandHighBits && OpSizeInBits > 16) { 3419 // If the left-shift isn't masked out then the only way this is a bswap is 3420 // if all bits beyond the low 8 are 0. In that case the entire pattern 3421 // reduces to a left shift anyway: leave it for other parts of the combiner. 3422 if (!LookPassAnd0) 3423 return SDValue(); 3424 3425 // However, if the right shift isn't masked out then it might be because 3426 // it's not needed. See if we can spot that too. 3427 if (!LookPassAnd1 && 3428 !DAG.MaskedValueIsZero( 3429 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3430 return SDValue(); 3431 } 3432 3433 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3434 if (OpSizeInBits > 16) { 3435 SDLoc DL(N); 3436 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3437 DAG.getConstant(OpSizeInBits - 16, DL, 3438 getShiftAmountTy(VT))); 3439 } 3440 return Res; 3441 } 3442 3443 /// Return true if the specified node is an element that makes up a 32-bit 3444 /// packed halfword byteswap. 3445 /// ((x & 0x000000ff) << 8) | 3446 /// ((x & 0x0000ff00) >> 8) | 3447 /// ((x & 0x00ff0000) << 8) | 3448 /// ((x & 0xff000000) >> 8) 3449 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3450 if (!N.getNode()->hasOneUse()) 3451 return false; 3452 3453 unsigned Opc = N.getOpcode(); 3454 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3455 return false; 3456 3457 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3458 if (!N1C) 3459 return false; 3460 3461 unsigned Num; 3462 switch (N1C->getZExtValue()) { 3463 default: 3464 return false; 3465 case 0xFF: Num = 0; break; 3466 case 0xFF00: Num = 1; break; 3467 case 0xFF0000: Num = 2; break; 3468 case 0xFF000000: Num = 3; break; 3469 } 3470 3471 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3472 SDValue N0 = N.getOperand(0); 3473 if (Opc == ISD::AND) { 3474 if (Num == 0 || Num == 2) { 3475 // (x >> 8) & 0xff 3476 // (x >> 8) & 0xff0000 3477 if (N0.getOpcode() != ISD::SRL) 3478 return false; 3479 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3480 if (!C || C->getZExtValue() != 8) 3481 return false; 3482 } else { 3483 // (x << 8) & 0xff00 3484 // (x << 8) & 0xff000000 3485 if (N0.getOpcode() != ISD::SHL) 3486 return false; 3487 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3488 if (!C || C->getZExtValue() != 8) 3489 return false; 3490 } 3491 } else if (Opc == ISD::SHL) { 3492 // (x & 0xff) << 8 3493 // (x & 0xff0000) << 8 3494 if (Num != 0 && Num != 2) 3495 return false; 3496 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3497 if (!C || C->getZExtValue() != 8) 3498 return false; 3499 } else { // Opc == ISD::SRL 3500 // (x & 0xff00) >> 8 3501 // (x & 0xff000000) >> 8 3502 if (Num != 1 && Num != 3) 3503 return false; 3504 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3505 if (!C || C->getZExtValue() != 8) 3506 return false; 3507 } 3508 3509 if (Parts[Num]) 3510 return false; 3511 3512 Parts[Num] = N0.getOperand(0).getNode(); 3513 return true; 3514 } 3515 3516 /// Match a 32-bit packed halfword bswap. That is 3517 /// ((x & 0x000000ff) << 8) | 3518 /// ((x & 0x0000ff00) >> 8) | 3519 /// ((x & 0x00ff0000) << 8) | 3520 /// ((x & 0xff000000) >> 8) 3521 /// => (rotl (bswap x), 16) 3522 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3523 if (!LegalOperations) 3524 return SDValue(); 3525 3526 EVT VT = N->getValueType(0); 3527 if (VT != MVT::i32) 3528 return SDValue(); 3529 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3530 return SDValue(); 3531 3532 // Look for either 3533 // (or (or (and), (and)), (or (and), (and))) 3534 // (or (or (or (and), (and)), (and)), (and)) 3535 if (N0.getOpcode() != ISD::OR) 3536 return SDValue(); 3537 SDValue N00 = N0.getOperand(0); 3538 SDValue N01 = N0.getOperand(1); 3539 SDNode *Parts[4] = {}; 3540 3541 if (N1.getOpcode() == ISD::OR && 3542 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3543 // (or (or (and), (and)), (or (and), (and))) 3544 SDValue N000 = N00.getOperand(0); 3545 if (!isBSwapHWordElement(N000, Parts)) 3546 return SDValue(); 3547 3548 SDValue N001 = N00.getOperand(1); 3549 if (!isBSwapHWordElement(N001, Parts)) 3550 return SDValue(); 3551 SDValue N010 = N01.getOperand(0); 3552 if (!isBSwapHWordElement(N010, Parts)) 3553 return SDValue(); 3554 SDValue N011 = N01.getOperand(1); 3555 if (!isBSwapHWordElement(N011, Parts)) 3556 return SDValue(); 3557 } else { 3558 // (or (or (or (and), (and)), (and)), (and)) 3559 if (!isBSwapHWordElement(N1, Parts)) 3560 return SDValue(); 3561 if (!isBSwapHWordElement(N01, Parts)) 3562 return SDValue(); 3563 if (N00.getOpcode() != ISD::OR) 3564 return SDValue(); 3565 SDValue N000 = N00.getOperand(0); 3566 if (!isBSwapHWordElement(N000, Parts)) 3567 return SDValue(); 3568 SDValue N001 = N00.getOperand(1); 3569 if (!isBSwapHWordElement(N001, Parts)) 3570 return SDValue(); 3571 } 3572 3573 // Make sure the parts are all coming from the same node. 3574 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3575 return SDValue(); 3576 3577 SDLoc DL(N); 3578 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3579 SDValue(Parts[0], 0)); 3580 3581 // Result of the bswap should be rotated by 16. If it's not legal, then 3582 // do (x << 16) | (x >> 16). 3583 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3584 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3585 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3586 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3587 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3588 return DAG.getNode(ISD::OR, DL, VT, 3589 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3590 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3591 } 3592 3593 /// This contains all DAGCombine rules which reduce two values combined by 3594 /// an Or operation to a single value \see visitANDLike(). 3595 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3596 EVT VT = N1.getValueType(); 3597 // fold (or x, undef) -> -1 3598 if (!LegalOperations && 3599 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3600 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3601 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3602 SDLoc(LocReference), VT); 3603 } 3604 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3605 SDValue LL, LR, RL, RR, CC0, CC1; 3606 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3607 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3608 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3609 3610 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3611 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3612 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3613 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3614 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3615 LR.getValueType(), LL, RL); 3616 AddToWorklist(ORNode.getNode()); 3617 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3618 } 3619 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3620 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3621 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3622 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3623 LR.getValueType(), LL, RL); 3624 AddToWorklist(ANDNode.getNode()); 3625 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3626 } 3627 } 3628 // canonicalize equivalent to ll == rl 3629 if (LL == RR && LR == RL) { 3630 Op1 = ISD::getSetCCSwappedOperands(Op1); 3631 std::swap(RL, RR); 3632 } 3633 if (LL == RL && LR == RR) { 3634 bool isInteger = LL.getValueType().isInteger(); 3635 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3636 if (Result != ISD::SETCC_INVALID && 3637 (!LegalOperations || 3638 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3639 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3640 EVT CCVT = getSetCCResultType(LL.getValueType()); 3641 if (N0.getValueType() == CCVT || 3642 (!LegalOperations && N0.getValueType() == MVT::i1)) 3643 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3644 LL, LR, Result); 3645 } 3646 } 3647 } 3648 3649 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3650 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3651 // Don't increase # computations. 3652 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3653 // We can only do this xform if we know that bits from X that are set in C2 3654 // but not in C1 are already zero. Likewise for Y. 3655 if (const ConstantSDNode *N0O1C = 3656 getAsNonOpaqueConstant(N0.getOperand(1))) { 3657 if (const ConstantSDNode *N1O1C = 3658 getAsNonOpaqueConstant(N1.getOperand(1))) { 3659 // We can only do this xform if we know that bits from X that are set in 3660 // C2 but not in C1 are already zero. Likewise for Y. 3661 const APInt &LHSMask = N0O1C->getAPIntValue(); 3662 const APInt &RHSMask = N1O1C->getAPIntValue(); 3663 3664 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3665 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3666 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3667 N0.getOperand(0), N1.getOperand(0)); 3668 SDLoc DL(LocReference); 3669 return DAG.getNode(ISD::AND, DL, VT, X, 3670 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3671 } 3672 } 3673 } 3674 } 3675 3676 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3677 if (N0.getOpcode() == ISD::AND && 3678 N1.getOpcode() == ISD::AND && 3679 N0.getOperand(0) == N1.getOperand(0) && 3680 // Don't increase # computations. 3681 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3682 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3683 N0.getOperand(1), N1.getOperand(1)); 3684 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3685 } 3686 3687 return SDValue(); 3688 } 3689 3690 SDValue DAGCombiner::visitOR(SDNode *N) { 3691 SDValue N0 = N->getOperand(0); 3692 SDValue N1 = N->getOperand(1); 3693 EVT VT = N1.getValueType(); 3694 3695 // fold vector ops 3696 if (VT.isVector()) { 3697 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3698 return FoldedVOp; 3699 3700 // fold (or x, 0) -> x, vector edition 3701 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3702 return N1; 3703 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3704 return N0; 3705 3706 // fold (or x, -1) -> -1, vector edition 3707 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3708 // do not return N0, because undef node may exist in N0 3709 return DAG.getConstant( 3710 APInt::getAllOnesValue( 3711 N0.getValueType().getScalarType().getSizeInBits()), 3712 SDLoc(N), N0.getValueType()); 3713 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3714 // do not return N1, because undef node may exist in N1 3715 return DAG.getConstant( 3716 APInt::getAllOnesValue( 3717 N1.getValueType().getScalarType().getSizeInBits()), 3718 SDLoc(N), N1.getValueType()); 3719 3720 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3721 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3722 // Do this only if the resulting shuffle is legal. 3723 if (isa<ShuffleVectorSDNode>(N0) && 3724 isa<ShuffleVectorSDNode>(N1) && 3725 // Avoid folding a node with illegal type. 3726 TLI.isTypeLegal(VT) && 3727 N0->getOperand(1) == N1->getOperand(1) && 3728 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3729 bool CanFold = true; 3730 unsigned NumElts = VT.getVectorNumElements(); 3731 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3732 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3733 // We construct two shuffle masks: 3734 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3735 // and N1 as the second operand. 3736 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3737 // and N0 as the second operand. 3738 // We do this because OR is commutable and therefore there might be 3739 // two ways to fold this node into a shuffle. 3740 SmallVector<int,4> Mask1; 3741 SmallVector<int,4> Mask2; 3742 3743 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3744 int M0 = SV0->getMaskElt(i); 3745 int M1 = SV1->getMaskElt(i); 3746 3747 // Both shuffle indexes are undef. Propagate Undef. 3748 if (M0 < 0 && M1 < 0) { 3749 Mask1.push_back(M0); 3750 Mask2.push_back(M0); 3751 continue; 3752 } 3753 3754 if (M0 < 0 || M1 < 0 || 3755 (M0 < (int)NumElts && M1 < (int)NumElts) || 3756 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3757 CanFold = false; 3758 break; 3759 } 3760 3761 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3762 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3763 } 3764 3765 if (CanFold) { 3766 // Fold this sequence only if the resulting shuffle is 'legal'. 3767 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3768 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3769 N1->getOperand(0), &Mask1[0]); 3770 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3771 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3772 N0->getOperand(0), &Mask2[0]); 3773 } 3774 } 3775 } 3776 3777 // fold (or c1, c2) -> c1|c2 3778 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3779 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3780 if (N0C && N1C && !N1C->isOpaque()) 3781 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3782 // canonicalize constant to RHS 3783 if (isConstantIntBuildVectorOrConstantInt(N0) && 3784 !isConstantIntBuildVectorOrConstantInt(N1)) 3785 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3786 // fold (or x, 0) -> x 3787 if (isNullConstant(N1)) 3788 return N0; 3789 // fold (or x, -1) -> -1 3790 if (isAllOnesConstant(N1)) 3791 return N1; 3792 // fold (or x, c) -> c iff (x & ~c) == 0 3793 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3794 return N1; 3795 3796 if (SDValue Combined = visitORLike(N0, N1, N)) 3797 return Combined; 3798 3799 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3800 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3801 return BSwap; 3802 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3803 return BSwap; 3804 3805 // reassociate or 3806 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3807 return ROR; 3808 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3809 // iff (c1 & c2) == 0. 3810 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3811 isa<ConstantSDNode>(N0.getOperand(1))) { 3812 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3813 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3814 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3815 N1C, C1)) 3816 return DAG.getNode( 3817 ISD::AND, SDLoc(N), VT, 3818 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3819 return SDValue(); 3820 } 3821 } 3822 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3823 if (N0.getOpcode() == N1.getOpcode()) 3824 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3825 return Tmp; 3826 3827 // See if this is some rotate idiom. 3828 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3829 return SDValue(Rot, 0); 3830 3831 // Simplify the operands using demanded-bits information. 3832 if (!VT.isVector() && 3833 SimplifyDemandedBits(SDValue(N, 0))) 3834 return SDValue(N, 0); 3835 3836 return SDValue(); 3837 } 3838 3839 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3840 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3841 if (Op.getOpcode() == ISD::AND) { 3842 if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3843 Mask = Op.getOperand(1); 3844 Op = Op.getOperand(0); 3845 } else { 3846 return false; 3847 } 3848 } 3849 3850 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3851 Shift = Op; 3852 return true; 3853 } 3854 3855 return false; 3856 } 3857 3858 // Return true if we can prove that, whenever Neg and Pos are both in the 3859 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 3860 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3861 // 3862 // (or (shift1 X, Neg), (shift2 X, Pos)) 3863 // 3864 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3865 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 3866 // to consider shift amounts with defined behavior. 3867 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 3868 // If EltSize is a power of 2 then: 3869 // 3870 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 3871 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 3872 // 3873 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 3874 // for the stronger condition: 3875 // 3876 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 3877 // 3878 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 3879 // we can just replace Neg with Neg' for the rest of the function. 3880 // 3881 // In other cases we check for the even stronger condition: 3882 // 3883 // Neg == EltSize - Pos [B] 3884 // 3885 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3886 // behavior if Pos == 0 (and consequently Neg == EltSize). 3887 // 3888 // We could actually use [A] whenever EltSize is a power of 2, but the 3889 // only extra cases that it would match are those uninteresting ones 3890 // where Neg and Pos are never in range at the same time. E.g. for 3891 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3892 // as well as (sub 32, Pos), but: 3893 // 3894 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3895 // 3896 // always invokes undefined behavior for 32-bit X. 3897 // 3898 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 3899 unsigned MaskLoBits = 0; 3900 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 3901 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 3902 if (NegC->getAPIntValue() == EltSize - 1) { 3903 Neg = Neg.getOperand(0); 3904 MaskLoBits = Log2_64(EltSize); 3905 } 3906 } 3907 } 3908 3909 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3910 if (Neg.getOpcode() != ISD::SUB) 3911 return 0; 3912 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 3913 if (!NegC) 3914 return 0; 3915 SDValue NegOp1 = Neg.getOperand(1); 3916 3917 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 3918 // Pos'. The truncation is redundant for the purpose of the equality. 3919 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 3920 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3921 if (PosC->getAPIntValue() == EltSize - 1) 3922 Pos = Pos.getOperand(0); 3923 3924 // The condition we need is now: 3925 // 3926 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 3927 // 3928 // If NegOp1 == Pos then we need: 3929 // 3930 // EltSize & Mask == NegC & Mask 3931 // 3932 // (because "x & Mask" is a truncation and distributes through subtraction). 3933 APInt Width; 3934 if (Pos == NegOp1) 3935 Width = NegC->getAPIntValue(); 3936 3937 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3938 // Then the condition we want to prove becomes: 3939 // 3940 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 3941 // 3942 // which, again because "x & Mask" is a truncation, becomes: 3943 // 3944 // NegC & Mask == (EltSize - PosC) & Mask 3945 // EltSize & Mask == (NegC + PosC) & Mask 3946 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 3947 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3948 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 3949 else 3950 return false; 3951 } else 3952 return false; 3953 3954 // Now we just need to check that EltSize & Mask == Width & Mask. 3955 if (MaskLoBits) 3956 // EltSize & Mask is 0 since Mask is EltSize - 1. 3957 return Width.getLoBits(MaskLoBits) == 0; 3958 return Width == EltSize; 3959 } 3960 3961 // A subroutine of MatchRotate used once we have found an OR of two opposite 3962 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3963 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3964 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3965 // Neg with outer conversions stripped away. 3966 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3967 SDValue Neg, SDValue InnerPos, 3968 SDValue InnerNeg, unsigned PosOpcode, 3969 unsigned NegOpcode, SDLoc DL) { 3970 // fold (or (shl x, (*ext y)), 3971 // (srl x, (*ext (sub 32, y)))) -> 3972 // (rotl x, y) or (rotr x, (sub 32, y)) 3973 // 3974 // fold (or (shl x, (*ext (sub 32, y))), 3975 // (srl x, (*ext y))) -> 3976 // (rotr x, y) or (rotl x, (sub 32, y)) 3977 EVT VT = Shifted.getValueType(); 3978 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 3979 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3980 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3981 HasPos ? Pos : Neg).getNode(); 3982 } 3983 3984 return nullptr; 3985 } 3986 3987 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3988 // idioms for rotate, and if the target supports rotation instructions, generate 3989 // a rot[lr]. 3990 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3991 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3992 EVT VT = LHS.getValueType(); 3993 if (!TLI.isTypeLegal(VT)) return nullptr; 3994 3995 // The target must have at least one rotate flavor. 3996 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3997 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3998 if (!HasROTL && !HasROTR) return nullptr; 3999 4000 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4001 SDValue LHSShift; // The shift. 4002 SDValue LHSMask; // AND value if any. 4003 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4004 return nullptr; // Not part of a rotate. 4005 4006 SDValue RHSShift; // The shift. 4007 SDValue RHSMask; // AND value if any. 4008 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4009 return nullptr; // Not part of a rotate. 4010 4011 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4012 return nullptr; // Not shifting the same value. 4013 4014 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4015 return nullptr; // Shifts must disagree. 4016 4017 // Canonicalize shl to left side in a shl/srl pair. 4018 if (RHSShift.getOpcode() == ISD::SHL) { 4019 std::swap(LHS, RHS); 4020 std::swap(LHSShift, RHSShift); 4021 std::swap(LHSMask, RHSMask); 4022 } 4023 4024 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4025 SDValue LHSShiftArg = LHSShift.getOperand(0); 4026 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4027 SDValue RHSShiftArg = RHSShift.getOperand(0); 4028 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4029 4030 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4031 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4032 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4033 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4034 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4035 if ((LShVal + RShVal) != EltSizeInBits) 4036 return nullptr; 4037 4038 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4039 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4040 4041 // If there is an AND of either shifted operand, apply it to the result. 4042 if (LHSMask.getNode() || RHSMask.getNode()) { 4043 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4044 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4045 4046 if (LHSMask.getNode()) { 4047 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4048 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4049 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4050 DAG.getConstant(RHSBits, DL, VT))); 4051 } 4052 if (RHSMask.getNode()) { 4053 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4054 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4055 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4056 DAG.getConstant(LHSBits, DL, VT))); 4057 } 4058 4059 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4060 } 4061 4062 return Rot.getNode(); 4063 } 4064 4065 // If there is a mask here, and we have a variable shift, we can't be sure 4066 // that we're masking out the right stuff. 4067 if (LHSMask.getNode() || RHSMask.getNode()) 4068 return nullptr; 4069 4070 // If the shift amount is sign/zext/any-extended just peel it off. 4071 SDValue LExtOp0 = LHSShiftAmt; 4072 SDValue RExtOp0 = RHSShiftAmt; 4073 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4074 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4075 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4076 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4077 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4078 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4079 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4080 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4081 LExtOp0 = LHSShiftAmt.getOperand(0); 4082 RExtOp0 = RHSShiftAmt.getOperand(0); 4083 } 4084 4085 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4086 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4087 if (TryL) 4088 return TryL; 4089 4090 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4091 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4092 if (TryR) 4093 return TryR; 4094 4095 return nullptr; 4096 } 4097 4098 SDValue DAGCombiner::visitXOR(SDNode *N) { 4099 SDValue N0 = N->getOperand(0); 4100 SDValue N1 = N->getOperand(1); 4101 EVT VT = N0.getValueType(); 4102 4103 // fold vector ops 4104 if (VT.isVector()) { 4105 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4106 return FoldedVOp; 4107 4108 // fold (xor x, 0) -> x, vector edition 4109 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4110 return N1; 4111 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4112 return N0; 4113 } 4114 4115 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4116 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 4117 return DAG.getConstant(0, SDLoc(N), VT); 4118 // fold (xor x, undef) -> undef 4119 if (N0.getOpcode() == ISD::UNDEF) 4120 return N0; 4121 if (N1.getOpcode() == ISD::UNDEF) 4122 return N1; 4123 // fold (xor c1, c2) -> c1^c2 4124 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4125 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4126 if (N0C && N1C) 4127 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4128 // canonicalize constant to RHS 4129 if (isConstantIntBuildVectorOrConstantInt(N0) && 4130 !isConstantIntBuildVectorOrConstantInt(N1)) 4131 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4132 // fold (xor x, 0) -> x 4133 if (isNullConstant(N1)) 4134 return N0; 4135 // reassociate xor 4136 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4137 return RXOR; 4138 4139 // fold !(x cc y) -> (x !cc y) 4140 SDValue LHS, RHS, CC; 4141 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4142 bool isInt = LHS.getValueType().isInteger(); 4143 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4144 isInt); 4145 4146 if (!LegalOperations || 4147 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4148 switch (N0.getOpcode()) { 4149 default: 4150 llvm_unreachable("Unhandled SetCC Equivalent!"); 4151 case ISD::SETCC: 4152 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4153 case ISD::SELECT_CC: 4154 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4155 N0.getOperand(3), NotCC); 4156 } 4157 } 4158 } 4159 4160 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4161 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4162 N0.getNode()->hasOneUse() && 4163 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4164 SDValue V = N0.getOperand(0); 4165 SDLoc DL(N0); 4166 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4167 DAG.getConstant(1, DL, V.getValueType())); 4168 AddToWorklist(V.getNode()); 4169 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4170 } 4171 4172 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4173 if (isOneConstant(N1) && VT == MVT::i1 && 4174 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4175 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4176 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4177 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4178 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4179 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4180 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4181 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4182 } 4183 } 4184 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4185 if (isAllOnesConstant(N1) && 4186 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4187 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4188 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4189 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4190 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4191 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4192 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4193 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4194 } 4195 } 4196 // fold (xor (and x, y), y) -> (and (not x), y) 4197 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4198 N0->getOperand(1) == N1) { 4199 SDValue X = N0->getOperand(0); 4200 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4201 AddToWorklist(NotX.getNode()); 4202 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4203 } 4204 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4205 if (N1C && N0.getOpcode() == ISD::XOR) { 4206 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4207 SDLoc DL(N); 4208 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4209 DAG.getConstant(N1C->getAPIntValue() ^ 4210 N00C->getAPIntValue(), DL, VT)); 4211 } 4212 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4213 SDLoc DL(N); 4214 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4215 DAG.getConstant(N1C->getAPIntValue() ^ 4216 N01C->getAPIntValue(), DL, VT)); 4217 } 4218 } 4219 // fold (xor x, x) -> 0 4220 if (N0 == N1) 4221 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4222 4223 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4224 // Here is a concrete example of this equivalence: 4225 // i16 x == 14 4226 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4227 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4228 // 4229 // => 4230 // 4231 // i16 ~1 == 0b1111111111111110 4232 // i16 rol(~1, 14) == 0b1011111111111111 4233 // 4234 // Some additional tips to help conceptualize this transform: 4235 // - Try to see the operation as placing a single zero in a value of all ones. 4236 // - There exists no value for x which would allow the result to contain zero. 4237 // - Values of x larger than the bitwidth are undefined and do not require a 4238 // consistent result. 4239 // - Pushing the zero left requires shifting one bits in from the right. 4240 // A rotate left of ~1 is a nice way of achieving the desired result. 4241 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4242 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4243 SDLoc DL(N); 4244 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4245 N0.getOperand(1)); 4246 } 4247 4248 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4249 if (N0.getOpcode() == N1.getOpcode()) 4250 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4251 return Tmp; 4252 4253 // Simplify the expression using non-local knowledge. 4254 if (!VT.isVector() && 4255 SimplifyDemandedBits(SDValue(N, 0))) 4256 return SDValue(N, 0); 4257 4258 return SDValue(); 4259 } 4260 4261 /// Handle transforms common to the three shifts, when the shift amount is a 4262 /// constant. 4263 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4264 SDNode *LHS = N->getOperand(0).getNode(); 4265 if (!LHS->hasOneUse()) return SDValue(); 4266 4267 // We want to pull some binops through shifts, so that we have (and (shift)) 4268 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4269 // thing happens with address calculations, so it's important to canonicalize 4270 // it. 4271 bool HighBitSet = false; // Can we transform this if the high bit is set? 4272 4273 switch (LHS->getOpcode()) { 4274 default: return SDValue(); 4275 case ISD::OR: 4276 case ISD::XOR: 4277 HighBitSet = false; // We can only transform sra if the high bit is clear. 4278 break; 4279 case ISD::AND: 4280 HighBitSet = true; // We can only transform sra if the high bit is set. 4281 break; 4282 case ISD::ADD: 4283 if (N->getOpcode() != ISD::SHL) 4284 return SDValue(); // only shl(add) not sr[al](add). 4285 HighBitSet = false; // We can only transform sra if the high bit is clear. 4286 break; 4287 } 4288 4289 // We require the RHS of the binop to be a constant and not opaque as well. 4290 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4291 if (!BinOpCst) return SDValue(); 4292 4293 // FIXME: disable this unless the input to the binop is a shift by a constant. 4294 // If it is not a shift, it pessimizes some common cases like: 4295 // 4296 // void foo(int *X, int i) { X[i & 1235] = 1; } 4297 // int bar(int *X, int i) { return X[i & 255]; } 4298 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4299 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4300 BinOpLHSVal->getOpcode() != ISD::SRA && 4301 BinOpLHSVal->getOpcode() != ISD::SRL) || 4302 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4303 return SDValue(); 4304 4305 EVT VT = N->getValueType(0); 4306 4307 // If this is a signed shift right, and the high bit is modified by the 4308 // logical operation, do not perform the transformation. The highBitSet 4309 // boolean indicates the value of the high bit of the constant which would 4310 // cause it to be modified for this operation. 4311 if (N->getOpcode() == ISD::SRA) { 4312 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4313 if (BinOpRHSSignSet != HighBitSet) 4314 return SDValue(); 4315 } 4316 4317 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4318 return SDValue(); 4319 4320 // Fold the constants, shifting the binop RHS by the shift amount. 4321 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4322 N->getValueType(0), 4323 LHS->getOperand(1), N->getOperand(1)); 4324 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4325 4326 // Create the new shift. 4327 SDValue NewShift = DAG.getNode(N->getOpcode(), 4328 SDLoc(LHS->getOperand(0)), 4329 VT, LHS->getOperand(0), N->getOperand(1)); 4330 4331 // Create the new binop. 4332 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4333 } 4334 4335 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4336 assert(N->getOpcode() == ISD::TRUNCATE); 4337 assert(N->getOperand(0).getOpcode() == ISD::AND); 4338 4339 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4340 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4341 SDValue N01 = N->getOperand(0).getOperand(1); 4342 4343 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4344 if (!N01C->isOpaque()) { 4345 EVT TruncVT = N->getValueType(0); 4346 SDValue N00 = N->getOperand(0).getOperand(0); 4347 APInt TruncC = N01C->getAPIntValue(); 4348 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4349 SDLoc DL(N); 4350 4351 return DAG.getNode(ISD::AND, DL, TruncVT, 4352 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4353 DAG.getConstant(TruncC, DL, TruncVT)); 4354 } 4355 } 4356 } 4357 4358 return SDValue(); 4359 } 4360 4361 SDValue DAGCombiner::visitRotate(SDNode *N) { 4362 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4363 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4364 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4365 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4366 if (NewOp1.getNode()) 4367 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4368 N->getOperand(0), NewOp1); 4369 } 4370 return SDValue(); 4371 } 4372 4373 SDValue DAGCombiner::visitSHL(SDNode *N) { 4374 SDValue N0 = N->getOperand(0); 4375 SDValue N1 = N->getOperand(1); 4376 EVT VT = N0.getValueType(); 4377 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4378 4379 // fold vector ops 4380 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4381 if (VT.isVector()) { 4382 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4383 return FoldedVOp; 4384 4385 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4386 // If setcc produces all-one true value then: 4387 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4388 if (N1CV && N1CV->isConstant()) { 4389 if (N0.getOpcode() == ISD::AND) { 4390 SDValue N00 = N0->getOperand(0); 4391 SDValue N01 = N0->getOperand(1); 4392 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4393 4394 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4395 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4396 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4397 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4398 N01CV, N1CV)) 4399 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4400 } 4401 } else { 4402 N1C = isConstOrConstSplat(N1); 4403 } 4404 } 4405 } 4406 4407 // fold (shl c1, c2) -> c1<<c2 4408 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4409 if (N0C && N1C && !N1C->isOpaque()) 4410 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4411 // fold (shl 0, x) -> 0 4412 if (isNullConstant(N0)) 4413 return N0; 4414 // fold (shl x, c >= size(x)) -> undef 4415 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4416 return DAG.getUNDEF(VT); 4417 // fold (shl x, 0) -> x 4418 if (N1C && N1C->isNullValue()) 4419 return N0; 4420 // fold (shl undef, x) -> 0 4421 if (N0.getOpcode() == ISD::UNDEF) 4422 return DAG.getConstant(0, SDLoc(N), VT); 4423 // if (shl x, c) is known to be zero, return 0 4424 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4425 APInt::getAllOnesValue(OpSizeInBits))) 4426 return DAG.getConstant(0, SDLoc(N), VT); 4427 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4428 if (N1.getOpcode() == ISD::TRUNCATE && 4429 N1.getOperand(0).getOpcode() == ISD::AND) { 4430 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4431 if (NewOp1.getNode()) 4432 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4433 } 4434 4435 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4436 return SDValue(N, 0); 4437 4438 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4439 if (N1C && N0.getOpcode() == ISD::SHL) { 4440 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4441 uint64_t c1 = N0C1->getZExtValue(); 4442 uint64_t c2 = N1C->getZExtValue(); 4443 SDLoc DL(N); 4444 if (c1 + c2 >= OpSizeInBits) 4445 return DAG.getConstant(0, DL, VT); 4446 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4447 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4448 } 4449 } 4450 4451 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4452 // For this to be valid, the second form must not preserve any of the bits 4453 // that are shifted out by the inner shift in the first form. This means 4454 // the outer shift size must be >= the number of bits added by the ext. 4455 // As a corollary, we don't care what kind of ext it is. 4456 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4457 N0.getOpcode() == ISD::ANY_EXTEND || 4458 N0.getOpcode() == ISD::SIGN_EXTEND) && 4459 N0.getOperand(0).getOpcode() == ISD::SHL) { 4460 SDValue N0Op0 = N0.getOperand(0); 4461 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4462 uint64_t c1 = N0Op0C1->getZExtValue(); 4463 uint64_t c2 = N1C->getZExtValue(); 4464 EVT InnerShiftVT = N0Op0.getValueType(); 4465 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4466 if (c2 >= OpSizeInBits - InnerShiftSize) { 4467 SDLoc DL(N0); 4468 if (c1 + c2 >= OpSizeInBits) 4469 return DAG.getConstant(0, DL, VT); 4470 return DAG.getNode(ISD::SHL, DL, VT, 4471 DAG.getNode(N0.getOpcode(), DL, VT, 4472 N0Op0->getOperand(0)), 4473 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4474 } 4475 } 4476 } 4477 4478 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4479 // Only fold this if the inner zext has no other uses to avoid increasing 4480 // the total number of instructions. 4481 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4482 N0.getOperand(0).getOpcode() == ISD::SRL) { 4483 SDValue N0Op0 = N0.getOperand(0); 4484 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4485 uint64_t c1 = N0Op0C1->getZExtValue(); 4486 if (c1 < VT.getScalarSizeInBits()) { 4487 uint64_t c2 = N1C->getZExtValue(); 4488 if (c1 == c2) { 4489 SDValue NewOp0 = N0.getOperand(0); 4490 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4491 SDLoc DL(N); 4492 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4493 NewOp0, 4494 DAG.getConstant(c2, DL, CountVT)); 4495 AddToWorklist(NewSHL.getNode()); 4496 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4497 } 4498 } 4499 } 4500 } 4501 4502 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4503 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4504 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4505 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4506 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4507 uint64_t C1 = N0C1->getZExtValue(); 4508 uint64_t C2 = N1C->getZExtValue(); 4509 SDLoc DL(N); 4510 if (C1 <= C2) 4511 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4512 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4513 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4514 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4515 } 4516 } 4517 4518 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4519 // (and (srl x, (sub c1, c2), MASK) 4520 // Only fold this if the inner shift has no other uses -- if it does, folding 4521 // this will increase the total number of instructions. 4522 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4523 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4524 uint64_t c1 = N0C1->getZExtValue(); 4525 if (c1 < OpSizeInBits) { 4526 uint64_t c2 = N1C->getZExtValue(); 4527 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4528 SDValue Shift; 4529 if (c2 > c1) { 4530 Mask = Mask.shl(c2 - c1); 4531 SDLoc DL(N); 4532 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4533 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4534 } else { 4535 Mask = Mask.lshr(c1 - c2); 4536 SDLoc DL(N); 4537 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4538 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4539 } 4540 SDLoc DL(N0); 4541 return DAG.getNode(ISD::AND, DL, VT, Shift, 4542 DAG.getConstant(Mask, DL, VT)); 4543 } 4544 } 4545 } 4546 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4547 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4548 unsigned BitSize = VT.getScalarSizeInBits(); 4549 SDLoc DL(N); 4550 SDValue HiBitsMask = 4551 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4552 BitSize - N1C->getZExtValue()), 4553 DL, VT); 4554 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4555 HiBitsMask); 4556 } 4557 4558 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4559 // Variant of version done on multiply, except mul by a power of 2 is turned 4560 // into a shift. 4561 APInt Val; 4562 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4563 (isa<ConstantSDNode>(N0.getOperand(1)) || 4564 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4565 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4566 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4567 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4568 } 4569 4570 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4571 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4572 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4573 if (SDValue Folded = 4574 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4575 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4576 } 4577 } 4578 4579 if (N1C && !N1C->isOpaque()) 4580 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4581 return NewSHL; 4582 4583 return SDValue(); 4584 } 4585 4586 SDValue DAGCombiner::visitSRA(SDNode *N) { 4587 SDValue N0 = N->getOperand(0); 4588 SDValue N1 = N->getOperand(1); 4589 EVT VT = N0.getValueType(); 4590 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4591 4592 // fold vector ops 4593 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4594 if (VT.isVector()) { 4595 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4596 return FoldedVOp; 4597 4598 N1C = isConstOrConstSplat(N1); 4599 } 4600 4601 // fold (sra c1, c2) -> (sra c1, c2) 4602 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4603 if (N0C && N1C && !N1C->isOpaque()) 4604 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4605 // fold (sra 0, x) -> 0 4606 if (isNullConstant(N0)) 4607 return N0; 4608 // fold (sra -1, x) -> -1 4609 if (isAllOnesConstant(N0)) 4610 return N0; 4611 // fold (sra x, (setge c, size(x))) -> undef 4612 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4613 return DAG.getUNDEF(VT); 4614 // fold (sra x, 0) -> x 4615 if (N1C && N1C->isNullValue()) 4616 return N0; 4617 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4618 // sext_inreg. 4619 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4620 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4621 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4622 if (VT.isVector()) 4623 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4624 ExtVT, VT.getVectorNumElements()); 4625 if ((!LegalOperations || 4626 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4627 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4628 N0.getOperand(0), DAG.getValueType(ExtVT)); 4629 } 4630 4631 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4632 if (N1C && N0.getOpcode() == ISD::SRA) { 4633 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4634 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4635 if (Sum >= OpSizeInBits) 4636 Sum = OpSizeInBits - 1; 4637 SDLoc DL(N); 4638 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4639 DAG.getConstant(Sum, DL, N1.getValueType())); 4640 } 4641 } 4642 4643 // fold (sra (shl X, m), (sub result_size, n)) 4644 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4645 // result_size - n != m. 4646 // If truncate is free for the target sext(shl) is likely to result in better 4647 // code. 4648 if (N0.getOpcode() == ISD::SHL && N1C) { 4649 // Get the two constanst of the shifts, CN0 = m, CN = n. 4650 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4651 if (N01C) { 4652 LLVMContext &Ctx = *DAG.getContext(); 4653 // Determine what the truncate's result bitsize and type would be. 4654 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4655 4656 if (VT.isVector()) 4657 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4658 4659 // Determine the residual right-shift amount. 4660 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4661 4662 // If the shift is not a no-op (in which case this should be just a sign 4663 // extend already), the truncated to type is legal, sign_extend is legal 4664 // on that type, and the truncate to that type is both legal and free, 4665 // perform the transform. 4666 if ((ShiftAmt > 0) && 4667 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4668 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4669 TLI.isTruncateFree(VT, TruncVT)) { 4670 4671 SDLoc DL(N); 4672 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4673 getShiftAmountTy(N0.getOperand(0).getValueType())); 4674 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4675 N0.getOperand(0), Amt); 4676 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4677 Shift); 4678 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4679 N->getValueType(0), Trunc); 4680 } 4681 } 4682 } 4683 4684 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4685 if (N1.getOpcode() == ISD::TRUNCATE && 4686 N1.getOperand(0).getOpcode() == ISD::AND) { 4687 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4688 if (NewOp1.getNode()) 4689 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4690 } 4691 4692 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4693 // if c1 is equal to the number of bits the trunc removes 4694 if (N0.getOpcode() == ISD::TRUNCATE && 4695 (N0.getOperand(0).getOpcode() == ISD::SRL || 4696 N0.getOperand(0).getOpcode() == ISD::SRA) && 4697 N0.getOperand(0).hasOneUse() && 4698 N0.getOperand(0).getOperand(1).hasOneUse() && 4699 N1C) { 4700 SDValue N0Op0 = N0.getOperand(0); 4701 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4702 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4703 EVT LargeVT = N0Op0.getValueType(); 4704 4705 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4706 SDLoc DL(N); 4707 SDValue Amt = 4708 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4709 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4710 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4711 N0Op0.getOperand(0), Amt); 4712 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4713 } 4714 } 4715 } 4716 4717 // Simplify, based on bits shifted out of the LHS. 4718 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4719 return SDValue(N, 0); 4720 4721 4722 // If the sign bit is known to be zero, switch this to a SRL. 4723 if (DAG.SignBitIsZero(N0)) 4724 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4725 4726 if (N1C && !N1C->isOpaque()) 4727 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4728 return NewSRA; 4729 4730 return SDValue(); 4731 } 4732 4733 SDValue DAGCombiner::visitSRL(SDNode *N) { 4734 SDValue N0 = N->getOperand(0); 4735 SDValue N1 = N->getOperand(1); 4736 EVT VT = N0.getValueType(); 4737 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4738 4739 // fold vector ops 4740 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4741 if (VT.isVector()) { 4742 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4743 return FoldedVOp; 4744 4745 N1C = isConstOrConstSplat(N1); 4746 } 4747 4748 // fold (srl c1, c2) -> c1 >>u c2 4749 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4750 if (N0C && N1C && !N1C->isOpaque()) 4751 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4752 // fold (srl 0, x) -> 0 4753 if (isNullConstant(N0)) 4754 return N0; 4755 // fold (srl x, c >= size(x)) -> undef 4756 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4757 return DAG.getUNDEF(VT); 4758 // fold (srl x, 0) -> x 4759 if (N1C && N1C->isNullValue()) 4760 return N0; 4761 // if (srl x, c) is known to be zero, return 0 4762 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4763 APInt::getAllOnesValue(OpSizeInBits))) 4764 return DAG.getConstant(0, SDLoc(N), VT); 4765 4766 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4767 if (N1C && N0.getOpcode() == ISD::SRL) { 4768 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4769 uint64_t c1 = N01C->getZExtValue(); 4770 uint64_t c2 = N1C->getZExtValue(); 4771 SDLoc DL(N); 4772 if (c1 + c2 >= OpSizeInBits) 4773 return DAG.getConstant(0, DL, VT); 4774 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4775 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4776 } 4777 } 4778 4779 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4780 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4781 N0.getOperand(0).getOpcode() == ISD::SRL && 4782 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4783 uint64_t c1 = 4784 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4785 uint64_t c2 = N1C->getZExtValue(); 4786 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4787 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4788 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4789 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4790 if (c1 + OpSizeInBits == InnerShiftSize) { 4791 SDLoc DL(N0); 4792 if (c1 + c2 >= InnerShiftSize) 4793 return DAG.getConstant(0, DL, VT); 4794 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4795 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4796 N0.getOperand(0)->getOperand(0), 4797 DAG.getConstant(c1 + c2, DL, 4798 ShiftCountVT))); 4799 } 4800 } 4801 4802 // fold (srl (shl x, c), c) -> (and x, cst2) 4803 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4804 unsigned BitSize = N0.getScalarValueSizeInBits(); 4805 if (BitSize <= 64) { 4806 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4807 SDLoc DL(N); 4808 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4809 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4810 } 4811 } 4812 4813 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4814 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4815 // Shifting in all undef bits? 4816 EVT SmallVT = N0.getOperand(0).getValueType(); 4817 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4818 if (N1C->getZExtValue() >= BitSize) 4819 return DAG.getUNDEF(VT); 4820 4821 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4822 uint64_t ShiftAmt = N1C->getZExtValue(); 4823 SDLoc DL0(N0); 4824 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4825 N0.getOperand(0), 4826 DAG.getConstant(ShiftAmt, DL0, 4827 getShiftAmountTy(SmallVT))); 4828 AddToWorklist(SmallShift.getNode()); 4829 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4830 SDLoc DL(N); 4831 return DAG.getNode(ISD::AND, DL, VT, 4832 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4833 DAG.getConstant(Mask, DL, VT)); 4834 } 4835 } 4836 4837 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4838 // bit, which is unmodified by sra. 4839 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4840 if (N0.getOpcode() == ISD::SRA) 4841 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4842 } 4843 4844 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4845 if (N1C && N0.getOpcode() == ISD::CTLZ && 4846 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4847 APInt KnownZero, KnownOne; 4848 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4849 4850 // If any of the input bits are KnownOne, then the input couldn't be all 4851 // zeros, thus the result of the srl will always be zero. 4852 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4853 4854 // If all of the bits input the to ctlz node are known to be zero, then 4855 // the result of the ctlz is "32" and the result of the shift is one. 4856 APInt UnknownBits = ~KnownZero; 4857 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4858 4859 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4860 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4861 // Okay, we know that only that the single bit specified by UnknownBits 4862 // could be set on input to the CTLZ node. If this bit is set, the SRL 4863 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4864 // to an SRL/XOR pair, which is likely to simplify more. 4865 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4866 SDValue Op = N0.getOperand(0); 4867 4868 if (ShAmt) { 4869 SDLoc DL(N0); 4870 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4871 DAG.getConstant(ShAmt, DL, 4872 getShiftAmountTy(Op.getValueType()))); 4873 AddToWorklist(Op.getNode()); 4874 } 4875 4876 SDLoc DL(N); 4877 return DAG.getNode(ISD::XOR, DL, VT, 4878 Op, DAG.getConstant(1, DL, VT)); 4879 } 4880 } 4881 4882 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4883 if (N1.getOpcode() == ISD::TRUNCATE && 4884 N1.getOperand(0).getOpcode() == ISD::AND) { 4885 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4886 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4887 } 4888 4889 // fold operands of srl based on knowledge that the low bits are not 4890 // demanded. 4891 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4892 return SDValue(N, 0); 4893 4894 if (N1C && !N1C->isOpaque()) 4895 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4896 return NewSRL; 4897 4898 // Attempt to convert a srl of a load into a narrower zero-extending load. 4899 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4900 return NarrowLoad; 4901 4902 // Here is a common situation. We want to optimize: 4903 // 4904 // %a = ... 4905 // %b = and i32 %a, 2 4906 // %c = srl i32 %b, 1 4907 // brcond i32 %c ... 4908 // 4909 // into 4910 // 4911 // %a = ... 4912 // %b = and %a, 2 4913 // %c = setcc eq %b, 0 4914 // brcond %c ... 4915 // 4916 // However when after the source operand of SRL is optimized into AND, the SRL 4917 // itself may not be optimized further. Look for it and add the BRCOND into 4918 // the worklist. 4919 if (N->hasOneUse()) { 4920 SDNode *Use = *N->use_begin(); 4921 if (Use->getOpcode() == ISD::BRCOND) 4922 AddToWorklist(Use); 4923 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4924 // Also look pass the truncate. 4925 Use = *Use->use_begin(); 4926 if (Use->getOpcode() == ISD::BRCOND) 4927 AddToWorklist(Use); 4928 } 4929 } 4930 4931 return SDValue(); 4932 } 4933 4934 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4935 SDValue N0 = N->getOperand(0); 4936 EVT VT = N->getValueType(0); 4937 4938 // fold (bswap c1) -> c2 4939 if (isConstantIntBuildVectorOrConstantInt(N0)) 4940 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4941 // fold (bswap (bswap x)) -> x 4942 if (N0.getOpcode() == ISD::BSWAP) 4943 return N0->getOperand(0); 4944 return SDValue(); 4945 } 4946 4947 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4948 SDValue N0 = N->getOperand(0); 4949 EVT VT = N->getValueType(0); 4950 4951 // fold (ctlz c1) -> c2 4952 if (isConstantIntBuildVectorOrConstantInt(N0)) 4953 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4954 return SDValue(); 4955 } 4956 4957 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4958 SDValue N0 = N->getOperand(0); 4959 EVT VT = N->getValueType(0); 4960 4961 // fold (ctlz_zero_undef c1) -> c2 4962 if (isConstantIntBuildVectorOrConstantInt(N0)) 4963 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4964 return SDValue(); 4965 } 4966 4967 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4968 SDValue N0 = N->getOperand(0); 4969 EVT VT = N->getValueType(0); 4970 4971 // fold (cttz c1) -> c2 4972 if (isConstantIntBuildVectorOrConstantInt(N0)) 4973 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4974 return SDValue(); 4975 } 4976 4977 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4978 SDValue N0 = N->getOperand(0); 4979 EVT VT = N->getValueType(0); 4980 4981 // fold (cttz_zero_undef c1) -> c2 4982 if (isConstantIntBuildVectorOrConstantInt(N0)) 4983 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4984 return SDValue(); 4985 } 4986 4987 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4988 SDValue N0 = N->getOperand(0); 4989 EVT VT = N->getValueType(0); 4990 4991 // fold (ctpop c1) -> c2 4992 if (isConstantIntBuildVectorOrConstantInt(N0)) 4993 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4994 return SDValue(); 4995 } 4996 4997 4998 /// \brief Generate Min/Max node 4999 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 5000 SDValue True, SDValue False, 5001 ISD::CondCode CC, const TargetLowering &TLI, 5002 SelectionDAG &DAG) { 5003 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5004 return SDValue(); 5005 5006 switch (CC) { 5007 case ISD::SETOLT: 5008 case ISD::SETOLE: 5009 case ISD::SETLT: 5010 case ISD::SETLE: 5011 case ISD::SETULT: 5012 case ISD::SETULE: { 5013 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5014 if (TLI.isOperationLegal(Opcode, VT)) 5015 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5016 return SDValue(); 5017 } 5018 case ISD::SETOGT: 5019 case ISD::SETOGE: 5020 case ISD::SETGT: 5021 case ISD::SETGE: 5022 case ISD::SETUGT: 5023 case ISD::SETUGE: { 5024 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5025 if (TLI.isOperationLegal(Opcode, VT)) 5026 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5027 return SDValue(); 5028 } 5029 default: 5030 return SDValue(); 5031 } 5032 } 5033 5034 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5035 SDValue N0 = N->getOperand(0); 5036 SDValue N1 = N->getOperand(1); 5037 SDValue N2 = N->getOperand(2); 5038 EVT VT = N->getValueType(0); 5039 EVT VT0 = N0.getValueType(); 5040 5041 // fold (select C, X, X) -> X 5042 if (N1 == N2) 5043 return N1; 5044 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5045 // fold (select true, X, Y) -> X 5046 // fold (select false, X, Y) -> Y 5047 return !N0C->isNullValue() ? N1 : N2; 5048 } 5049 // fold (select C, 1, X) -> (or C, X) 5050 if (VT == MVT::i1 && isOneConstant(N1)) 5051 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5052 // fold (select C, 0, 1) -> (xor C, 1) 5053 // We can't do this reliably if integer based booleans have different contents 5054 // to floating point based booleans. This is because we can't tell whether we 5055 // have an integer-based boolean or a floating-point-based boolean unless we 5056 // can find the SETCC that produced it and inspect its operands. This is 5057 // fairly easy if C is the SETCC node, but it can potentially be 5058 // undiscoverable (or not reasonably discoverable). For example, it could be 5059 // in another basic block or it could require searching a complicated 5060 // expression. 5061 if (VT.isInteger() && 5062 (VT0 == MVT::i1 || (VT0.isInteger() && 5063 TLI.getBooleanContents(false, false) == 5064 TLI.getBooleanContents(false, true) && 5065 TLI.getBooleanContents(false, false) == 5066 TargetLowering::ZeroOrOneBooleanContent)) && 5067 isNullConstant(N1) && isOneConstant(N2)) { 5068 SDValue XORNode; 5069 if (VT == VT0) { 5070 SDLoc DL(N); 5071 return DAG.getNode(ISD::XOR, DL, VT0, 5072 N0, DAG.getConstant(1, DL, VT0)); 5073 } 5074 SDLoc DL0(N0); 5075 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5076 N0, DAG.getConstant(1, DL0, VT0)); 5077 AddToWorklist(XORNode.getNode()); 5078 if (VT.bitsGT(VT0)) 5079 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5080 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5081 } 5082 // fold (select C, 0, X) -> (and (not C), X) 5083 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5084 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5085 AddToWorklist(NOTNode.getNode()); 5086 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5087 } 5088 // fold (select C, X, 1) -> (or (not C), X) 5089 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5090 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5091 AddToWorklist(NOTNode.getNode()); 5092 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5093 } 5094 // fold (select C, X, 0) -> (and C, X) 5095 if (VT == MVT::i1 && isNullConstant(N2)) 5096 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5097 // fold (select X, X, Y) -> (or X, Y) 5098 // fold (select X, 1, Y) -> (or X, Y) 5099 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5100 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5101 // fold (select X, Y, X) -> (and X, Y) 5102 // fold (select X, Y, 0) -> (and X, Y) 5103 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5104 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5105 5106 // If we can fold this based on the true/false value, do so. 5107 if (SimplifySelectOps(N, N1, N2)) 5108 return SDValue(N, 0); // Don't revisit N. 5109 5110 if (VT0 == MVT::i1) { 5111 // The code in this block deals with the following 2 equivalences: 5112 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5113 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5114 // The target can specify its prefered form with the 5115 // shouldNormalizeToSelectSequence() callback. However we always transform 5116 // to the right anyway if we find the inner select exists in the DAG anyway 5117 // and we always transform to the left side if we know that we can further 5118 // optimize the combination of the conditions. 5119 bool normalizeToSequence 5120 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5121 // select (and Cond0, Cond1), X, Y 5122 // -> select Cond0, (select Cond1, X, Y), Y 5123 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5124 SDValue Cond0 = N0->getOperand(0); 5125 SDValue Cond1 = N0->getOperand(1); 5126 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5127 N1.getValueType(), Cond1, N1, N2); 5128 if (normalizeToSequence || !InnerSelect.use_empty()) 5129 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5130 InnerSelect, N2); 5131 } 5132 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5133 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5134 SDValue Cond0 = N0->getOperand(0); 5135 SDValue Cond1 = N0->getOperand(1); 5136 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5137 N1.getValueType(), Cond1, N1, N2); 5138 if (normalizeToSequence || !InnerSelect.use_empty()) 5139 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5140 InnerSelect); 5141 } 5142 5143 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5144 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5145 SDValue N1_0 = N1->getOperand(0); 5146 SDValue N1_1 = N1->getOperand(1); 5147 SDValue N1_2 = N1->getOperand(2); 5148 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5149 // Create the actual and node if we can generate good code for it. 5150 if (!normalizeToSequence) { 5151 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5152 N0, N1_0); 5153 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5154 N1_1, N2); 5155 } 5156 // Otherwise see if we can optimize the "and" to a better pattern. 5157 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5158 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5159 N1_1, N2); 5160 } 5161 } 5162 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5163 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5164 SDValue N2_0 = N2->getOperand(0); 5165 SDValue N2_1 = N2->getOperand(1); 5166 SDValue N2_2 = N2->getOperand(2); 5167 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5168 // Create the actual or node if we can generate good code for it. 5169 if (!normalizeToSequence) { 5170 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5171 N0, N2_0); 5172 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5173 N1, N2_2); 5174 } 5175 // Otherwise see if we can optimize to a better pattern. 5176 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5177 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5178 N1, N2_2); 5179 } 5180 } 5181 } 5182 5183 // fold selects based on a setcc into other things, such as min/max/abs 5184 if (N0.getOpcode() == ISD::SETCC) { 5185 // select x, y (fcmp lt x, y) -> fminnum x, y 5186 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5187 // 5188 // This is OK if we don't care about what happens if either operand is a 5189 // NaN. 5190 // 5191 5192 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5193 // no signed zeros as well as no nans. 5194 const TargetOptions &Options = DAG.getTarget().Options; 5195 if (Options.UnsafeFPMath && 5196 VT.isFloatingPoint() && N0.hasOneUse() && 5197 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5198 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5199 5200 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5201 N0.getOperand(1), N1, N2, CC, 5202 TLI, DAG)) 5203 return FMinMax; 5204 } 5205 5206 if ((!LegalOperations && 5207 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5208 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5209 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5210 N0.getOperand(0), N0.getOperand(1), 5211 N1, N2, N0.getOperand(2)); 5212 return SimplifySelect(SDLoc(N), N0, N1, N2); 5213 } 5214 5215 return SDValue(); 5216 } 5217 5218 static 5219 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5220 SDLoc DL(N); 5221 EVT LoVT, HiVT; 5222 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5223 5224 // Split the inputs. 5225 SDValue Lo, Hi, LL, LH, RL, RH; 5226 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5227 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5228 5229 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5230 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5231 5232 return std::make_pair(Lo, Hi); 5233 } 5234 5235 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5236 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5237 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5238 SDLoc dl(N); 5239 SDValue Cond = N->getOperand(0); 5240 SDValue LHS = N->getOperand(1); 5241 SDValue RHS = N->getOperand(2); 5242 EVT VT = N->getValueType(0); 5243 int NumElems = VT.getVectorNumElements(); 5244 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5245 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5246 Cond.getOpcode() == ISD::BUILD_VECTOR); 5247 5248 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5249 // binary ones here. 5250 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5251 return SDValue(); 5252 5253 // We're sure we have an even number of elements due to the 5254 // concat_vectors we have as arguments to vselect. 5255 // Skip BV elements until we find one that's not an UNDEF 5256 // After we find an UNDEF element, keep looping until we get to half the 5257 // length of the BV and see if all the non-undef nodes are the same. 5258 ConstantSDNode *BottomHalf = nullptr; 5259 for (int i = 0; i < NumElems / 2; ++i) { 5260 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5261 continue; 5262 5263 if (BottomHalf == nullptr) 5264 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5265 else if (Cond->getOperand(i).getNode() != BottomHalf) 5266 return SDValue(); 5267 } 5268 5269 // Do the same for the second half of the BuildVector 5270 ConstantSDNode *TopHalf = nullptr; 5271 for (int i = NumElems / 2; i < NumElems; ++i) { 5272 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5273 continue; 5274 5275 if (TopHalf == nullptr) 5276 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5277 else if (Cond->getOperand(i).getNode() != TopHalf) 5278 return SDValue(); 5279 } 5280 5281 assert(TopHalf && BottomHalf && 5282 "One half of the selector was all UNDEFs and the other was all the " 5283 "same value. This should have been addressed before this function."); 5284 return DAG.getNode( 5285 ISD::CONCAT_VECTORS, dl, VT, 5286 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5287 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5288 } 5289 5290 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5291 5292 if (Level >= AfterLegalizeTypes) 5293 return SDValue(); 5294 5295 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5296 SDValue Mask = MSC->getMask(); 5297 SDValue Data = MSC->getValue(); 5298 SDLoc DL(N); 5299 5300 // If the MSCATTER data type requires splitting and the mask is provided by a 5301 // SETCC, then split both nodes and its operands before legalization. This 5302 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5303 // and enables future optimizations (e.g. min/max pattern matching on X86). 5304 if (Mask.getOpcode() != ISD::SETCC) 5305 return SDValue(); 5306 5307 // Check if any splitting is required. 5308 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5309 TargetLowering::TypeSplitVector) 5310 return SDValue(); 5311 SDValue MaskLo, MaskHi, Lo, Hi; 5312 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5313 5314 EVT LoVT, HiVT; 5315 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5316 5317 SDValue Chain = MSC->getChain(); 5318 5319 EVT MemoryVT = MSC->getMemoryVT(); 5320 unsigned Alignment = MSC->getOriginalAlignment(); 5321 5322 EVT LoMemVT, HiMemVT; 5323 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5324 5325 SDValue DataLo, DataHi; 5326 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5327 5328 SDValue BasePtr = MSC->getBasePtr(); 5329 SDValue IndexLo, IndexHi; 5330 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5331 5332 MachineMemOperand *MMO = DAG.getMachineFunction(). 5333 getMachineMemOperand(MSC->getPointerInfo(), 5334 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5335 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5336 5337 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5338 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5339 DL, OpsLo, MMO); 5340 5341 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5342 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5343 DL, OpsHi, MMO); 5344 5345 AddToWorklist(Lo.getNode()); 5346 AddToWorklist(Hi.getNode()); 5347 5348 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5349 } 5350 5351 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5352 5353 if (Level >= AfterLegalizeTypes) 5354 return SDValue(); 5355 5356 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5357 SDValue Mask = MST->getMask(); 5358 SDValue Data = MST->getValue(); 5359 SDLoc DL(N); 5360 5361 // If the MSTORE data type requires splitting and the mask is provided by a 5362 // SETCC, then split both nodes and its operands before legalization. This 5363 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5364 // and enables future optimizations (e.g. min/max pattern matching on X86). 5365 if (Mask.getOpcode() == ISD::SETCC) { 5366 5367 // Check if any splitting is required. 5368 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5369 TargetLowering::TypeSplitVector) 5370 return SDValue(); 5371 5372 SDValue MaskLo, MaskHi, Lo, Hi; 5373 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5374 5375 EVT LoVT, HiVT; 5376 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5377 5378 SDValue Chain = MST->getChain(); 5379 SDValue Ptr = MST->getBasePtr(); 5380 5381 EVT MemoryVT = MST->getMemoryVT(); 5382 unsigned Alignment = MST->getOriginalAlignment(); 5383 5384 // if Alignment is equal to the vector size, 5385 // take the half of it for the second part 5386 unsigned SecondHalfAlignment = 5387 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5388 Alignment/2 : Alignment; 5389 5390 EVT LoMemVT, HiMemVT; 5391 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5392 5393 SDValue DataLo, DataHi; 5394 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5395 5396 MachineMemOperand *MMO = DAG.getMachineFunction(). 5397 getMachineMemOperand(MST->getPointerInfo(), 5398 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5399 Alignment, MST->getAAInfo(), MST->getRanges()); 5400 5401 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5402 MST->isTruncatingStore()); 5403 5404 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5405 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5406 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5407 5408 MMO = DAG.getMachineFunction(). 5409 getMachineMemOperand(MST->getPointerInfo(), 5410 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5411 SecondHalfAlignment, MST->getAAInfo(), 5412 MST->getRanges()); 5413 5414 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5415 MST->isTruncatingStore()); 5416 5417 AddToWorklist(Lo.getNode()); 5418 AddToWorklist(Hi.getNode()); 5419 5420 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5421 } 5422 return SDValue(); 5423 } 5424 5425 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5426 5427 if (Level >= AfterLegalizeTypes) 5428 return SDValue(); 5429 5430 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5431 SDValue Mask = MGT->getMask(); 5432 SDLoc DL(N); 5433 5434 // If the MGATHER result requires splitting and the mask is provided by a 5435 // SETCC, then split both nodes and its operands before legalization. This 5436 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5437 // and enables future optimizations (e.g. min/max pattern matching on X86). 5438 5439 if (Mask.getOpcode() != ISD::SETCC) 5440 return SDValue(); 5441 5442 EVT VT = N->getValueType(0); 5443 5444 // Check if any splitting is required. 5445 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5446 TargetLowering::TypeSplitVector) 5447 return SDValue(); 5448 5449 SDValue MaskLo, MaskHi, Lo, Hi; 5450 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5451 5452 SDValue Src0 = MGT->getValue(); 5453 SDValue Src0Lo, Src0Hi; 5454 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5455 5456 EVT LoVT, HiVT; 5457 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5458 5459 SDValue Chain = MGT->getChain(); 5460 EVT MemoryVT = MGT->getMemoryVT(); 5461 unsigned Alignment = MGT->getOriginalAlignment(); 5462 5463 EVT LoMemVT, HiMemVT; 5464 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5465 5466 SDValue BasePtr = MGT->getBasePtr(); 5467 SDValue Index = MGT->getIndex(); 5468 SDValue IndexLo, IndexHi; 5469 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5470 5471 MachineMemOperand *MMO = DAG.getMachineFunction(). 5472 getMachineMemOperand(MGT->getPointerInfo(), 5473 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5474 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5475 5476 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5477 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5478 MMO); 5479 5480 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5481 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5482 MMO); 5483 5484 AddToWorklist(Lo.getNode()); 5485 AddToWorklist(Hi.getNode()); 5486 5487 // Build a factor node to remember that this load is independent of the 5488 // other one. 5489 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5490 Hi.getValue(1)); 5491 5492 // Legalized the chain result - switch anything that used the old chain to 5493 // use the new one. 5494 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5495 5496 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5497 5498 SDValue RetOps[] = { GatherRes, Chain }; 5499 return DAG.getMergeValues(RetOps, DL); 5500 } 5501 5502 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5503 5504 if (Level >= AfterLegalizeTypes) 5505 return SDValue(); 5506 5507 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5508 SDValue Mask = MLD->getMask(); 5509 SDLoc DL(N); 5510 5511 // If the MLOAD result requires splitting and the mask is provided by a 5512 // SETCC, then split both nodes and its operands before legalization. This 5513 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5514 // and enables future optimizations (e.g. min/max pattern matching on X86). 5515 5516 if (Mask.getOpcode() == ISD::SETCC) { 5517 EVT VT = N->getValueType(0); 5518 5519 // Check if any splitting is required. 5520 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5521 TargetLowering::TypeSplitVector) 5522 return SDValue(); 5523 5524 SDValue MaskLo, MaskHi, Lo, Hi; 5525 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5526 5527 SDValue Src0 = MLD->getSrc0(); 5528 SDValue Src0Lo, Src0Hi; 5529 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5530 5531 EVT LoVT, HiVT; 5532 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5533 5534 SDValue Chain = MLD->getChain(); 5535 SDValue Ptr = MLD->getBasePtr(); 5536 EVT MemoryVT = MLD->getMemoryVT(); 5537 unsigned Alignment = MLD->getOriginalAlignment(); 5538 5539 // if Alignment is equal to the vector size, 5540 // take the half of it for the second part 5541 unsigned SecondHalfAlignment = 5542 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5543 Alignment/2 : Alignment; 5544 5545 EVT LoMemVT, HiMemVT; 5546 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5547 5548 MachineMemOperand *MMO = DAG.getMachineFunction(). 5549 getMachineMemOperand(MLD->getPointerInfo(), 5550 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5551 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5552 5553 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5554 ISD::NON_EXTLOAD); 5555 5556 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5557 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5558 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5559 5560 MMO = DAG.getMachineFunction(). 5561 getMachineMemOperand(MLD->getPointerInfo(), 5562 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5563 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5564 5565 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5566 ISD::NON_EXTLOAD); 5567 5568 AddToWorklist(Lo.getNode()); 5569 AddToWorklist(Hi.getNode()); 5570 5571 // Build a factor node to remember that this load is independent of the 5572 // other one. 5573 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5574 Hi.getValue(1)); 5575 5576 // Legalized the chain result - switch anything that used the old chain to 5577 // use the new one. 5578 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5579 5580 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5581 5582 SDValue RetOps[] = { LoadRes, Chain }; 5583 return DAG.getMergeValues(RetOps, DL); 5584 } 5585 return SDValue(); 5586 } 5587 5588 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5589 SDValue N0 = N->getOperand(0); 5590 SDValue N1 = N->getOperand(1); 5591 SDValue N2 = N->getOperand(2); 5592 SDLoc DL(N); 5593 5594 // Canonicalize integer abs. 5595 // vselect (setg[te] X, 0), X, -X -> 5596 // vselect (setgt X, -1), X, -X -> 5597 // vselect (setl[te] X, 0), -X, X -> 5598 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5599 if (N0.getOpcode() == ISD::SETCC) { 5600 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5601 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5602 bool isAbs = false; 5603 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5604 5605 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5606 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5607 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5608 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5609 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5610 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5611 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5612 5613 if (isAbs) { 5614 EVT VT = LHS.getValueType(); 5615 SDValue Shift = DAG.getNode( 5616 ISD::SRA, DL, VT, LHS, 5617 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5618 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5619 AddToWorklist(Shift.getNode()); 5620 AddToWorklist(Add.getNode()); 5621 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5622 } 5623 } 5624 5625 if (SimplifySelectOps(N, N1, N2)) 5626 return SDValue(N, 0); // Don't revisit N. 5627 5628 // If the VSELECT result requires splitting and the mask is provided by a 5629 // SETCC, then split both nodes and its operands before legalization. This 5630 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5631 // and enables future optimizations (e.g. min/max pattern matching on X86). 5632 if (N0.getOpcode() == ISD::SETCC) { 5633 EVT VT = N->getValueType(0); 5634 5635 // Check if any splitting is required. 5636 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5637 TargetLowering::TypeSplitVector) 5638 return SDValue(); 5639 5640 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5641 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5642 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5643 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5644 5645 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5646 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5647 5648 // Add the new VSELECT nodes to the work list in case they need to be split 5649 // again. 5650 AddToWorklist(Lo.getNode()); 5651 AddToWorklist(Hi.getNode()); 5652 5653 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5654 } 5655 5656 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5657 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5658 return N1; 5659 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5660 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5661 return N2; 5662 5663 // The ConvertSelectToConcatVector function is assuming both the above 5664 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5665 // and addressed. 5666 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5667 N2.getOpcode() == ISD::CONCAT_VECTORS && 5668 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5669 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5670 return CV; 5671 } 5672 5673 return SDValue(); 5674 } 5675 5676 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5677 SDValue N0 = N->getOperand(0); 5678 SDValue N1 = N->getOperand(1); 5679 SDValue N2 = N->getOperand(2); 5680 SDValue N3 = N->getOperand(3); 5681 SDValue N4 = N->getOperand(4); 5682 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5683 5684 // fold select_cc lhs, rhs, x, x, cc -> x 5685 if (N2 == N3) 5686 return N2; 5687 5688 // Determine if the condition we're dealing with is constant 5689 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5690 N0, N1, CC, SDLoc(N), false); 5691 if (SCC.getNode()) { 5692 AddToWorklist(SCC.getNode()); 5693 5694 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5695 if (!SCCC->isNullValue()) 5696 return N2; // cond always true -> true val 5697 else 5698 return N3; // cond always false -> false val 5699 } else if (SCC->getOpcode() == ISD::UNDEF) { 5700 // When the condition is UNDEF, just return the first operand. This is 5701 // coherent the DAG creation, no setcc node is created in this case 5702 return N2; 5703 } else if (SCC.getOpcode() == ISD::SETCC) { 5704 // Fold to a simpler select_cc 5705 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5706 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5707 SCC.getOperand(2)); 5708 } 5709 } 5710 5711 // If we can fold this based on the true/false value, do so. 5712 if (SimplifySelectOps(N, N2, N3)) 5713 return SDValue(N, 0); // Don't revisit N. 5714 5715 // fold select_cc into other things, such as min/max/abs 5716 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5717 } 5718 5719 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5720 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5721 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5722 SDLoc(N)); 5723 } 5724 5725 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5726 SDValue LHS = N->getOperand(0); 5727 SDValue RHS = N->getOperand(1); 5728 SDValue Carry = N->getOperand(2); 5729 SDValue Cond = N->getOperand(3); 5730 5731 // If Carry is false, fold to a regular SETCC. 5732 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5733 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5734 5735 return SDValue(); 5736 } 5737 5738 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5739 /// a build_vector of constants. 5740 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5741 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5742 /// Vector extends are not folded if operations are legal; this is to 5743 /// avoid introducing illegal build_vector dag nodes. 5744 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5745 SelectionDAG &DAG, bool LegalTypes, 5746 bool LegalOperations) { 5747 unsigned Opcode = N->getOpcode(); 5748 SDValue N0 = N->getOperand(0); 5749 EVT VT = N->getValueType(0); 5750 5751 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5752 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5753 && "Expected EXTEND dag node in input!"); 5754 5755 // fold (sext c1) -> c1 5756 // fold (zext c1) -> c1 5757 // fold (aext c1) -> c1 5758 if (isa<ConstantSDNode>(N0)) 5759 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5760 5761 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5762 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5763 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5764 EVT SVT = VT.getScalarType(); 5765 if (!(VT.isVector() && 5766 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5767 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5768 return nullptr; 5769 5770 // We can fold this node into a build_vector. 5771 unsigned VTBits = SVT.getSizeInBits(); 5772 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5773 SmallVector<SDValue, 8> Elts; 5774 unsigned NumElts = VT.getVectorNumElements(); 5775 SDLoc DL(N); 5776 5777 for (unsigned i=0; i != NumElts; ++i) { 5778 SDValue Op = N0->getOperand(i); 5779 if (Op->getOpcode() == ISD::UNDEF) { 5780 Elts.push_back(DAG.getUNDEF(SVT)); 5781 continue; 5782 } 5783 5784 SDLoc DL(Op); 5785 // Get the constant value and if needed trunc it to the size of the type. 5786 // Nodes like build_vector might have constants wider than the scalar type. 5787 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5788 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5789 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5790 else 5791 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5792 } 5793 5794 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5795 } 5796 5797 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5798 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5799 // transformation. Returns true if extension are possible and the above 5800 // mentioned transformation is profitable. 5801 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5802 unsigned ExtOpc, 5803 SmallVectorImpl<SDNode *> &ExtendNodes, 5804 const TargetLowering &TLI) { 5805 bool HasCopyToRegUses = false; 5806 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5807 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5808 UE = N0.getNode()->use_end(); 5809 UI != UE; ++UI) { 5810 SDNode *User = *UI; 5811 if (User == N) 5812 continue; 5813 if (UI.getUse().getResNo() != N0.getResNo()) 5814 continue; 5815 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5816 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5817 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5818 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5819 // Sign bits will be lost after a zext. 5820 return false; 5821 bool Add = false; 5822 for (unsigned i = 0; i != 2; ++i) { 5823 SDValue UseOp = User->getOperand(i); 5824 if (UseOp == N0) 5825 continue; 5826 if (!isa<ConstantSDNode>(UseOp)) 5827 return false; 5828 Add = true; 5829 } 5830 if (Add) 5831 ExtendNodes.push_back(User); 5832 continue; 5833 } 5834 // If truncates aren't free and there are users we can't 5835 // extend, it isn't worthwhile. 5836 if (!isTruncFree) 5837 return false; 5838 // Remember if this value is live-out. 5839 if (User->getOpcode() == ISD::CopyToReg) 5840 HasCopyToRegUses = true; 5841 } 5842 5843 if (HasCopyToRegUses) { 5844 bool BothLiveOut = false; 5845 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5846 UI != UE; ++UI) { 5847 SDUse &Use = UI.getUse(); 5848 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5849 BothLiveOut = true; 5850 break; 5851 } 5852 } 5853 if (BothLiveOut) 5854 // Both unextended and extended values are live out. There had better be 5855 // a good reason for the transformation. 5856 return ExtendNodes.size(); 5857 } 5858 return true; 5859 } 5860 5861 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5862 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5863 ISD::NodeType ExtType) { 5864 // Extend SetCC uses if necessary. 5865 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5866 SDNode *SetCC = SetCCs[i]; 5867 SmallVector<SDValue, 4> Ops; 5868 5869 for (unsigned j = 0; j != 2; ++j) { 5870 SDValue SOp = SetCC->getOperand(j); 5871 if (SOp == Trunc) 5872 Ops.push_back(ExtLoad); 5873 else 5874 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5875 } 5876 5877 Ops.push_back(SetCC->getOperand(2)); 5878 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5879 } 5880 } 5881 5882 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5883 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5884 SDValue N0 = N->getOperand(0); 5885 EVT DstVT = N->getValueType(0); 5886 EVT SrcVT = N0.getValueType(); 5887 5888 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5889 N->getOpcode() == ISD::ZERO_EXTEND) && 5890 "Unexpected node type (not an extend)!"); 5891 5892 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5893 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5894 // (v8i32 (sext (v8i16 (load x)))) 5895 // into: 5896 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5897 // (v4i32 (sextload (x + 16))))) 5898 // Where uses of the original load, i.e.: 5899 // (v8i16 (load x)) 5900 // are replaced with: 5901 // (v8i16 (truncate 5902 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5903 // (v4i32 (sextload (x + 16))))))) 5904 // 5905 // This combine is only applicable to illegal, but splittable, vectors. 5906 // All legal types, and illegal non-vector types, are handled elsewhere. 5907 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5908 // 5909 if (N0->getOpcode() != ISD::LOAD) 5910 return SDValue(); 5911 5912 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5913 5914 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5915 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5916 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5917 return SDValue(); 5918 5919 SmallVector<SDNode *, 4> SetCCs; 5920 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5921 return SDValue(); 5922 5923 ISD::LoadExtType ExtType = 5924 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5925 5926 // Try to split the vector types to get down to legal types. 5927 EVT SplitSrcVT = SrcVT; 5928 EVT SplitDstVT = DstVT; 5929 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5930 SplitSrcVT.getVectorNumElements() > 1) { 5931 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5932 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5933 } 5934 5935 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5936 return SDValue(); 5937 5938 SDLoc DL(N); 5939 const unsigned NumSplits = 5940 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5941 const unsigned Stride = SplitSrcVT.getStoreSize(); 5942 SmallVector<SDValue, 4> Loads; 5943 SmallVector<SDValue, 4> Chains; 5944 5945 SDValue BasePtr = LN0->getBasePtr(); 5946 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5947 const unsigned Offset = Idx * Stride; 5948 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5949 5950 SDValue SplitLoad = DAG.getExtLoad( 5951 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5952 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5953 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5954 Align, LN0->getAAInfo()); 5955 5956 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5957 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5958 5959 Loads.push_back(SplitLoad.getValue(0)); 5960 Chains.push_back(SplitLoad.getValue(1)); 5961 } 5962 5963 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5964 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5965 5966 CombineTo(N, NewValue); 5967 5968 // Replace uses of the original load (before extension) 5969 // with a truncate of the concatenated sextloaded vectors. 5970 SDValue Trunc = 5971 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5972 CombineTo(N0.getNode(), Trunc, NewChain); 5973 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5974 (ISD::NodeType)N->getOpcode()); 5975 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5976 } 5977 5978 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5979 SDValue N0 = N->getOperand(0); 5980 EVT VT = N->getValueType(0); 5981 5982 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5983 LegalOperations)) 5984 return SDValue(Res, 0); 5985 5986 // fold (sext (sext x)) -> (sext x) 5987 // fold (sext (aext x)) -> (sext x) 5988 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5989 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5990 N0.getOperand(0)); 5991 5992 if (N0.getOpcode() == ISD::TRUNCATE) { 5993 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5994 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5995 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 5996 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5997 if (NarrowLoad.getNode() != N0.getNode()) { 5998 CombineTo(N0.getNode(), NarrowLoad); 5999 // CombineTo deleted the truncate, if needed, but not what's under it. 6000 AddToWorklist(oye); 6001 } 6002 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6003 } 6004 6005 // See if the value being truncated is already sign extended. If so, just 6006 // eliminate the trunc/sext pair. 6007 SDValue Op = N0.getOperand(0); 6008 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 6009 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 6010 unsigned DestBits = VT.getScalarType().getSizeInBits(); 6011 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6012 6013 if (OpBits == DestBits) { 6014 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6015 // bits, it is already ready. 6016 if (NumSignBits > DestBits-MidBits) 6017 return Op; 6018 } else if (OpBits < DestBits) { 6019 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6020 // bits, just sext from i32. 6021 if (NumSignBits > OpBits-MidBits) 6022 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 6023 } else { 6024 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6025 // bits, just truncate to i32. 6026 if (NumSignBits > OpBits-MidBits) 6027 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6028 } 6029 6030 // fold (sext (truncate x)) -> (sextinreg x). 6031 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6032 N0.getValueType())) { 6033 if (OpBits < DestBits) 6034 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6035 else if (OpBits > DestBits) 6036 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6037 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6038 DAG.getValueType(N0.getValueType())); 6039 } 6040 } 6041 6042 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6043 // Only generate vector extloads when 1) they're legal, and 2) they are 6044 // deemed desirable by the target. 6045 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6046 ((!LegalOperations && !VT.isVector() && 6047 !cast<LoadSDNode>(N0)->isVolatile()) || 6048 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6049 bool DoXform = true; 6050 SmallVector<SDNode*, 4> SetCCs; 6051 if (!N0.hasOneUse()) 6052 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6053 if (VT.isVector()) 6054 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6055 if (DoXform) { 6056 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6057 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6058 LN0->getChain(), 6059 LN0->getBasePtr(), N0.getValueType(), 6060 LN0->getMemOperand()); 6061 CombineTo(N, ExtLoad); 6062 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6063 N0.getValueType(), ExtLoad); 6064 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6065 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6066 ISD::SIGN_EXTEND); 6067 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6068 } 6069 } 6070 6071 // fold (sext (load x)) to multiple smaller sextloads. 6072 // Only on illegal but splittable vectors. 6073 if (SDValue ExtLoad = CombineExtLoad(N)) 6074 return ExtLoad; 6075 6076 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6077 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6078 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6079 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6080 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6081 EVT MemVT = LN0->getMemoryVT(); 6082 if ((!LegalOperations && !LN0->isVolatile()) || 6083 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6084 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6085 LN0->getChain(), 6086 LN0->getBasePtr(), MemVT, 6087 LN0->getMemOperand()); 6088 CombineTo(N, ExtLoad); 6089 CombineTo(N0.getNode(), 6090 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6091 N0.getValueType(), ExtLoad), 6092 ExtLoad.getValue(1)); 6093 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6094 } 6095 } 6096 6097 // fold (sext (and/or/xor (load x), cst)) -> 6098 // (and/or/xor (sextload x), (sext cst)) 6099 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6100 N0.getOpcode() == ISD::XOR) && 6101 isa<LoadSDNode>(N0.getOperand(0)) && 6102 N0.getOperand(1).getOpcode() == ISD::Constant && 6103 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6104 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6105 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6106 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6107 bool DoXform = true; 6108 SmallVector<SDNode*, 4> SetCCs; 6109 if (!N0.hasOneUse()) 6110 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6111 SetCCs, TLI); 6112 if (DoXform) { 6113 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6114 LN0->getChain(), LN0->getBasePtr(), 6115 LN0->getMemoryVT(), 6116 LN0->getMemOperand()); 6117 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6118 Mask = Mask.sext(VT.getSizeInBits()); 6119 SDLoc DL(N); 6120 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6121 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6122 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6123 SDLoc(N0.getOperand(0)), 6124 N0.getOperand(0).getValueType(), ExtLoad); 6125 CombineTo(N, And); 6126 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6127 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6128 ISD::SIGN_EXTEND); 6129 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6130 } 6131 } 6132 } 6133 6134 if (N0.getOpcode() == ISD::SETCC) { 6135 EVT N0VT = N0.getOperand(0).getValueType(); 6136 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6137 // Only do this before legalize for now. 6138 if (VT.isVector() && !LegalOperations && 6139 TLI.getBooleanContents(N0VT) == 6140 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6141 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6142 // of the same size as the compared operands. Only optimize sext(setcc()) 6143 // if this is the case. 6144 EVT SVT = getSetCCResultType(N0VT); 6145 6146 // We know that the # elements of the results is the same as the 6147 // # elements of the compare (and the # elements of the compare result 6148 // for that matter). Check to see that they are the same size. If so, 6149 // we know that the element size of the sext'd result matches the 6150 // element size of the compare operands. 6151 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6152 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6153 N0.getOperand(1), 6154 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6155 6156 // If the desired elements are smaller or larger than the source 6157 // elements we can use a matching integer vector type and then 6158 // truncate/sign extend 6159 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6160 if (SVT == MatchingVectorType) { 6161 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6162 N0.getOperand(0), N0.getOperand(1), 6163 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6164 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6165 } 6166 } 6167 6168 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6169 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6170 SDLoc DL(N); 6171 SDValue NegOne = 6172 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6173 SDValue SCC = 6174 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6175 NegOne, DAG.getConstant(0, DL, VT), 6176 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6177 if (SCC.getNode()) return SCC; 6178 6179 if (!VT.isVector()) { 6180 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6181 if (!LegalOperations || 6182 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6183 SDLoc DL(N); 6184 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6185 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6186 N0.getOperand(0), N0.getOperand(1), CC); 6187 return DAG.getSelect(DL, VT, SetCC, 6188 NegOne, DAG.getConstant(0, DL, VT)); 6189 } 6190 } 6191 } 6192 6193 // fold (sext x) -> (zext x) if the sign bit is known zero. 6194 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6195 DAG.SignBitIsZero(N0)) 6196 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6197 6198 return SDValue(); 6199 } 6200 6201 // isTruncateOf - If N is a truncate of some other value, return true, record 6202 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6203 // This function computes KnownZero to avoid a duplicated call to 6204 // computeKnownBits in the caller. 6205 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6206 APInt &KnownZero) { 6207 APInt KnownOne; 6208 if (N->getOpcode() == ISD::TRUNCATE) { 6209 Op = N->getOperand(0); 6210 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6211 return true; 6212 } 6213 6214 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6215 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6216 return false; 6217 6218 SDValue Op0 = N->getOperand(0); 6219 SDValue Op1 = N->getOperand(1); 6220 assert(Op0.getValueType() == Op1.getValueType()); 6221 6222 if (isNullConstant(Op0)) 6223 Op = Op1; 6224 else if (isNullConstant(Op1)) 6225 Op = Op0; 6226 else 6227 return false; 6228 6229 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6230 6231 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6232 return false; 6233 6234 return true; 6235 } 6236 6237 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6238 SDValue N0 = N->getOperand(0); 6239 EVT VT = N->getValueType(0); 6240 6241 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6242 LegalOperations)) 6243 return SDValue(Res, 0); 6244 6245 // fold (zext (zext x)) -> (zext x) 6246 // fold (zext (aext x)) -> (zext x) 6247 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6248 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6249 N0.getOperand(0)); 6250 6251 // fold (zext (truncate x)) -> (zext x) or 6252 // (zext (truncate x)) -> (truncate x) 6253 // This is valid when the truncated bits of x are already zero. 6254 // FIXME: We should extend this to work for vectors too. 6255 SDValue Op; 6256 APInt KnownZero; 6257 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6258 APInt TruncatedBits = 6259 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6260 APInt(Op.getValueSizeInBits(), 0) : 6261 APInt::getBitsSet(Op.getValueSizeInBits(), 6262 N0.getValueSizeInBits(), 6263 std::min(Op.getValueSizeInBits(), 6264 VT.getSizeInBits())); 6265 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6266 if (VT.bitsGT(Op.getValueType())) 6267 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6268 if (VT.bitsLT(Op.getValueType())) 6269 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6270 6271 return Op; 6272 } 6273 } 6274 6275 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6276 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6277 if (N0.getOpcode() == ISD::TRUNCATE) { 6278 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6279 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6280 if (NarrowLoad.getNode() != N0.getNode()) { 6281 CombineTo(N0.getNode(), NarrowLoad); 6282 // CombineTo deleted the truncate, if needed, but not what's under it. 6283 AddToWorklist(oye); 6284 } 6285 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6286 } 6287 } 6288 6289 // fold (zext (truncate x)) -> (and x, mask) 6290 if (N0.getOpcode() == ISD::TRUNCATE) { 6291 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6292 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6293 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6294 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6295 if (NarrowLoad.getNode() != N0.getNode()) { 6296 CombineTo(N0.getNode(), NarrowLoad); 6297 // CombineTo deleted the truncate, if needed, but not what's under it. 6298 AddToWorklist(oye); 6299 } 6300 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6301 } 6302 6303 EVT SrcVT = N0.getOperand(0).getValueType(); 6304 EVT MinVT = N0.getValueType(); 6305 6306 // Try to mask before the extension to avoid having to generate a larger mask, 6307 // possibly over several sub-vectors. 6308 if (SrcVT.bitsLT(VT)) { 6309 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6310 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6311 SDValue Op = N0.getOperand(0); 6312 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6313 AddToWorklist(Op.getNode()); 6314 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6315 } 6316 } 6317 6318 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6319 SDValue Op = N0.getOperand(0); 6320 if (SrcVT.bitsLT(VT)) { 6321 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6322 AddToWorklist(Op.getNode()); 6323 } else if (SrcVT.bitsGT(VT)) { 6324 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6325 AddToWorklist(Op.getNode()); 6326 } 6327 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6328 } 6329 } 6330 6331 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6332 // if either of the casts is not free. 6333 if (N0.getOpcode() == ISD::AND && 6334 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6335 N0.getOperand(1).getOpcode() == ISD::Constant && 6336 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6337 N0.getValueType()) || 6338 !TLI.isZExtFree(N0.getValueType(), VT))) { 6339 SDValue X = N0.getOperand(0).getOperand(0); 6340 if (X.getValueType().bitsLT(VT)) { 6341 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6342 } else if (X.getValueType().bitsGT(VT)) { 6343 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6344 } 6345 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6346 Mask = Mask.zext(VT.getSizeInBits()); 6347 SDLoc DL(N); 6348 return DAG.getNode(ISD::AND, DL, VT, 6349 X, DAG.getConstant(Mask, DL, VT)); 6350 } 6351 6352 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6353 // Only generate vector extloads when 1) they're legal, and 2) they are 6354 // deemed desirable by the target. 6355 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6356 ((!LegalOperations && !VT.isVector() && 6357 !cast<LoadSDNode>(N0)->isVolatile()) || 6358 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6359 bool DoXform = true; 6360 SmallVector<SDNode*, 4> SetCCs; 6361 if (!N0.hasOneUse()) 6362 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6363 if (VT.isVector()) 6364 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6365 if (DoXform) { 6366 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6367 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6368 LN0->getChain(), 6369 LN0->getBasePtr(), N0.getValueType(), 6370 LN0->getMemOperand()); 6371 CombineTo(N, ExtLoad); 6372 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6373 N0.getValueType(), ExtLoad); 6374 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6375 6376 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6377 ISD::ZERO_EXTEND); 6378 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6379 } 6380 } 6381 6382 // fold (zext (load x)) to multiple smaller zextloads. 6383 // Only on illegal but splittable vectors. 6384 if (SDValue ExtLoad = CombineExtLoad(N)) 6385 return ExtLoad; 6386 6387 // fold (zext (and/or/xor (load x), cst)) -> 6388 // (and/or/xor (zextload x), (zext cst)) 6389 // Unless (and (load x) cst) will match as a zextload already and has 6390 // additional users. 6391 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6392 N0.getOpcode() == ISD::XOR) && 6393 isa<LoadSDNode>(N0.getOperand(0)) && 6394 N0.getOperand(1).getOpcode() == ISD::Constant && 6395 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6396 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6397 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6398 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6399 bool DoXform = true; 6400 SmallVector<SDNode*, 4> SetCCs; 6401 if (!N0.hasOneUse()) { 6402 if (N0.getOpcode() == ISD::AND) { 6403 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6404 auto NarrowLoad = false; 6405 EVT LoadResultTy = AndC->getValueType(0); 6406 EVT ExtVT, LoadedVT; 6407 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6408 NarrowLoad)) 6409 DoXform = false; 6410 } 6411 if (DoXform) 6412 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6413 ISD::ZERO_EXTEND, SetCCs, TLI); 6414 } 6415 if (DoXform) { 6416 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6417 LN0->getChain(), LN0->getBasePtr(), 6418 LN0->getMemoryVT(), 6419 LN0->getMemOperand()); 6420 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6421 Mask = Mask.zext(VT.getSizeInBits()); 6422 SDLoc DL(N); 6423 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6424 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6425 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6426 SDLoc(N0.getOperand(0)), 6427 N0.getOperand(0).getValueType(), ExtLoad); 6428 CombineTo(N, And); 6429 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6430 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6431 ISD::ZERO_EXTEND); 6432 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6433 } 6434 } 6435 } 6436 6437 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6438 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6439 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6440 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6441 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6442 EVT MemVT = LN0->getMemoryVT(); 6443 if ((!LegalOperations && !LN0->isVolatile()) || 6444 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6445 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6446 LN0->getChain(), 6447 LN0->getBasePtr(), MemVT, 6448 LN0->getMemOperand()); 6449 CombineTo(N, ExtLoad); 6450 CombineTo(N0.getNode(), 6451 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6452 ExtLoad), 6453 ExtLoad.getValue(1)); 6454 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6455 } 6456 } 6457 6458 if (N0.getOpcode() == ISD::SETCC) { 6459 if (!LegalOperations && VT.isVector() && 6460 N0.getValueType().getVectorElementType() == MVT::i1) { 6461 EVT N0VT = N0.getOperand(0).getValueType(); 6462 if (getSetCCResultType(N0VT) == N0.getValueType()) 6463 return SDValue(); 6464 6465 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6466 // Only do this before legalize for now. 6467 EVT EltVT = VT.getVectorElementType(); 6468 SDLoc DL(N); 6469 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 6470 DAG.getConstant(1, DL, EltVT)); 6471 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6472 // We know that the # elements of the results is the same as the 6473 // # elements of the compare (and the # elements of the compare result 6474 // for that matter). Check to see that they are the same size. If so, 6475 // we know that the element size of the sext'd result matches the 6476 // element size of the compare operands. 6477 return DAG.getNode(ISD::AND, DL, VT, 6478 DAG.getSetCC(DL, VT, N0.getOperand(0), 6479 N0.getOperand(1), 6480 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6481 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 6482 OneOps)); 6483 6484 // If the desired elements are smaller or larger than the source 6485 // elements we can use a matching integer vector type and then 6486 // truncate/sign extend 6487 EVT MatchingElementType = 6488 EVT::getIntegerVT(*DAG.getContext(), 6489 N0VT.getScalarType().getSizeInBits()); 6490 EVT MatchingVectorType = 6491 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6492 N0VT.getVectorNumElements()); 6493 SDValue VsetCC = 6494 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6495 N0.getOperand(1), 6496 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6497 return DAG.getNode(ISD::AND, DL, VT, 6498 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6499 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps)); 6500 } 6501 6502 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6503 SDLoc DL(N); 6504 SDValue SCC = 6505 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6506 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6507 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6508 if (SCC.getNode()) return SCC; 6509 } 6510 6511 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6512 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6513 isa<ConstantSDNode>(N0.getOperand(1)) && 6514 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6515 N0.hasOneUse()) { 6516 SDValue ShAmt = N0.getOperand(1); 6517 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6518 if (N0.getOpcode() == ISD::SHL) { 6519 SDValue InnerZExt = N0.getOperand(0); 6520 // If the original shl may be shifting out bits, do not perform this 6521 // transformation. 6522 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6523 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6524 if (ShAmtVal > KnownZeroBits) 6525 return SDValue(); 6526 } 6527 6528 SDLoc DL(N); 6529 6530 // Ensure that the shift amount is wide enough for the shifted value. 6531 if (VT.getSizeInBits() >= 256) 6532 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6533 6534 return DAG.getNode(N0.getOpcode(), DL, VT, 6535 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6536 ShAmt); 6537 } 6538 6539 return SDValue(); 6540 } 6541 6542 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6543 SDValue N0 = N->getOperand(0); 6544 EVT VT = N->getValueType(0); 6545 6546 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6547 LegalOperations)) 6548 return SDValue(Res, 0); 6549 6550 // fold (aext (aext x)) -> (aext x) 6551 // fold (aext (zext x)) -> (zext x) 6552 // fold (aext (sext x)) -> (sext x) 6553 if (N0.getOpcode() == ISD::ANY_EXTEND || 6554 N0.getOpcode() == ISD::ZERO_EXTEND || 6555 N0.getOpcode() == ISD::SIGN_EXTEND) 6556 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6557 6558 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6559 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6560 if (N0.getOpcode() == ISD::TRUNCATE) { 6561 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6562 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6563 if (NarrowLoad.getNode() != N0.getNode()) { 6564 CombineTo(N0.getNode(), NarrowLoad); 6565 // CombineTo deleted the truncate, if needed, but not what's under it. 6566 AddToWorklist(oye); 6567 } 6568 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6569 } 6570 } 6571 6572 // fold (aext (truncate x)) 6573 if (N0.getOpcode() == ISD::TRUNCATE) { 6574 SDValue TruncOp = N0.getOperand(0); 6575 if (TruncOp.getValueType() == VT) 6576 return TruncOp; // x iff x size == zext size. 6577 if (TruncOp.getValueType().bitsGT(VT)) 6578 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6579 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6580 } 6581 6582 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6583 // if the trunc is not free. 6584 if (N0.getOpcode() == ISD::AND && 6585 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6586 N0.getOperand(1).getOpcode() == ISD::Constant && 6587 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6588 N0.getValueType())) { 6589 SDValue X = N0.getOperand(0).getOperand(0); 6590 if (X.getValueType().bitsLT(VT)) { 6591 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6592 } else if (X.getValueType().bitsGT(VT)) { 6593 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6594 } 6595 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6596 Mask = Mask.zext(VT.getSizeInBits()); 6597 SDLoc DL(N); 6598 return DAG.getNode(ISD::AND, DL, VT, 6599 X, DAG.getConstant(Mask, DL, VT)); 6600 } 6601 6602 // fold (aext (load x)) -> (aext (truncate (extload x))) 6603 // None of the supported targets knows how to perform load and any_ext 6604 // on vectors in one instruction. We only perform this transformation on 6605 // scalars. 6606 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6607 ISD::isUNINDEXEDLoad(N0.getNode()) && 6608 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6609 bool DoXform = true; 6610 SmallVector<SDNode*, 4> SetCCs; 6611 if (!N0.hasOneUse()) 6612 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6613 if (DoXform) { 6614 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6615 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6616 LN0->getChain(), 6617 LN0->getBasePtr(), N0.getValueType(), 6618 LN0->getMemOperand()); 6619 CombineTo(N, ExtLoad); 6620 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6621 N0.getValueType(), ExtLoad); 6622 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6623 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6624 ISD::ANY_EXTEND); 6625 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6626 } 6627 } 6628 6629 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6630 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6631 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6632 if (N0.getOpcode() == ISD::LOAD && 6633 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6634 N0.hasOneUse()) { 6635 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6636 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6637 EVT MemVT = LN0->getMemoryVT(); 6638 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6639 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6640 VT, LN0->getChain(), LN0->getBasePtr(), 6641 MemVT, LN0->getMemOperand()); 6642 CombineTo(N, ExtLoad); 6643 CombineTo(N0.getNode(), 6644 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6645 N0.getValueType(), ExtLoad), 6646 ExtLoad.getValue(1)); 6647 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6648 } 6649 } 6650 6651 if (N0.getOpcode() == ISD::SETCC) { 6652 // For vectors: 6653 // aext(setcc) -> vsetcc 6654 // aext(setcc) -> truncate(vsetcc) 6655 // aext(setcc) -> aext(vsetcc) 6656 // Only do this before legalize for now. 6657 if (VT.isVector() && !LegalOperations) { 6658 EVT N0VT = N0.getOperand(0).getValueType(); 6659 // We know that the # elements of the results is the same as the 6660 // # elements of the compare (and the # elements of the compare result 6661 // for that matter). Check to see that they are the same size. If so, 6662 // we know that the element size of the sext'd result matches the 6663 // element size of the compare operands. 6664 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6665 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6666 N0.getOperand(1), 6667 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6668 // If the desired elements are smaller or larger than the source 6669 // elements we can use a matching integer vector type and then 6670 // truncate/any extend 6671 else { 6672 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6673 SDValue VsetCC = 6674 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6675 N0.getOperand(1), 6676 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6677 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6678 } 6679 } 6680 6681 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6682 SDLoc DL(N); 6683 SDValue SCC = 6684 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6685 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6686 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6687 if (SCC.getNode()) 6688 return SCC; 6689 } 6690 6691 return SDValue(); 6692 } 6693 6694 /// See if the specified operand can be simplified with the knowledge that only 6695 /// the bits specified by Mask are used. If so, return the simpler operand, 6696 /// otherwise return a null SDValue. 6697 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6698 switch (V.getOpcode()) { 6699 default: break; 6700 case ISD::Constant: { 6701 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6702 assert(CV && "Const value should be ConstSDNode."); 6703 const APInt &CVal = CV->getAPIntValue(); 6704 APInt NewVal = CVal & Mask; 6705 if (NewVal != CVal) 6706 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6707 break; 6708 } 6709 case ISD::OR: 6710 case ISD::XOR: 6711 // If the LHS or RHS don't contribute bits to the or, drop them. 6712 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6713 return V.getOperand(1); 6714 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6715 return V.getOperand(0); 6716 break; 6717 case ISD::SRL: 6718 // Only look at single-use SRLs. 6719 if (!V.getNode()->hasOneUse()) 6720 break; 6721 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6722 // See if we can recursively simplify the LHS. 6723 unsigned Amt = RHSC->getZExtValue(); 6724 6725 // Watch out for shift count overflow though. 6726 if (Amt >= Mask.getBitWidth()) break; 6727 APInt NewMask = Mask << Amt; 6728 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6729 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6730 SimplifyLHS, V.getOperand(1)); 6731 } 6732 } 6733 return SDValue(); 6734 } 6735 6736 /// If the result of a wider load is shifted to right of N bits and then 6737 /// truncated to a narrower type and where N is a multiple of number of bits of 6738 /// the narrower type, transform it to a narrower load from address + N / num of 6739 /// bits of new type. If the result is to be extended, also fold the extension 6740 /// to form a extending load. 6741 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6742 unsigned Opc = N->getOpcode(); 6743 6744 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6745 SDValue N0 = N->getOperand(0); 6746 EVT VT = N->getValueType(0); 6747 EVT ExtVT = VT; 6748 6749 // This transformation isn't valid for vector loads. 6750 if (VT.isVector()) 6751 return SDValue(); 6752 6753 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6754 // extended to VT. 6755 if (Opc == ISD::SIGN_EXTEND_INREG) { 6756 ExtType = ISD::SEXTLOAD; 6757 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6758 } else if (Opc == ISD::SRL) { 6759 // Another special-case: SRL is basically zero-extending a narrower value. 6760 ExtType = ISD::ZEXTLOAD; 6761 N0 = SDValue(N, 0); 6762 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6763 if (!N01) return SDValue(); 6764 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6765 VT.getSizeInBits() - N01->getZExtValue()); 6766 } 6767 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6768 return SDValue(); 6769 6770 unsigned EVTBits = ExtVT.getSizeInBits(); 6771 6772 // Do not generate loads of non-round integer types since these can 6773 // be expensive (and would be wrong if the type is not byte sized). 6774 if (!ExtVT.isRound()) 6775 return SDValue(); 6776 6777 unsigned ShAmt = 0; 6778 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6779 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6780 ShAmt = N01->getZExtValue(); 6781 // Is the shift amount a multiple of size of VT? 6782 if ((ShAmt & (EVTBits-1)) == 0) { 6783 N0 = N0.getOperand(0); 6784 // Is the load width a multiple of size of VT? 6785 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6786 return SDValue(); 6787 } 6788 6789 // At this point, we must have a load or else we can't do the transform. 6790 if (!isa<LoadSDNode>(N0)) return SDValue(); 6791 6792 // Because a SRL must be assumed to *need* to zero-extend the high bits 6793 // (as opposed to anyext the high bits), we can't combine the zextload 6794 // lowering of SRL and an sextload. 6795 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6796 return SDValue(); 6797 6798 // If the shift amount is larger than the input type then we're not 6799 // accessing any of the loaded bytes. If the load was a zextload/extload 6800 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6801 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6802 return SDValue(); 6803 } 6804 } 6805 6806 // If the load is shifted left (and the result isn't shifted back right), 6807 // we can fold the truncate through the shift. 6808 unsigned ShLeftAmt = 0; 6809 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6810 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6811 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6812 ShLeftAmt = N01->getZExtValue(); 6813 N0 = N0.getOperand(0); 6814 } 6815 } 6816 6817 // If we haven't found a load, we can't narrow it. Don't transform one with 6818 // multiple uses, this would require adding a new load. 6819 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6820 return SDValue(); 6821 6822 // Don't change the width of a volatile load. 6823 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6824 if (LN0->isVolatile()) 6825 return SDValue(); 6826 6827 // Verify that we are actually reducing a load width here. 6828 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6829 return SDValue(); 6830 6831 // For the transform to be legal, the load must produce only two values 6832 // (the value loaded and the chain). Don't transform a pre-increment 6833 // load, for example, which produces an extra value. Otherwise the 6834 // transformation is not equivalent, and the downstream logic to replace 6835 // uses gets things wrong. 6836 if (LN0->getNumValues() > 2) 6837 return SDValue(); 6838 6839 // If the load that we're shrinking is an extload and we're not just 6840 // discarding the extension we can't simply shrink the load. Bail. 6841 // TODO: It would be possible to merge the extensions in some cases. 6842 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6843 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6844 return SDValue(); 6845 6846 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6847 return SDValue(); 6848 6849 EVT PtrType = N0.getOperand(1).getValueType(); 6850 6851 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6852 // It's not possible to generate a constant of extended or untyped type. 6853 return SDValue(); 6854 6855 // For big endian targets, we need to adjust the offset to the pointer to 6856 // load the correct bytes. 6857 if (DAG.getDataLayout().isBigEndian()) { 6858 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6859 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6860 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6861 } 6862 6863 uint64_t PtrOff = ShAmt / 8; 6864 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6865 SDLoc DL(LN0); 6866 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6867 PtrType, LN0->getBasePtr(), 6868 DAG.getConstant(PtrOff, DL, PtrType)); 6869 AddToWorklist(NewPtr.getNode()); 6870 6871 SDValue Load; 6872 if (ExtType == ISD::NON_EXTLOAD) 6873 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6874 LN0->getPointerInfo().getWithOffset(PtrOff), 6875 LN0->isVolatile(), LN0->isNonTemporal(), 6876 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6877 else 6878 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6879 LN0->getPointerInfo().getWithOffset(PtrOff), 6880 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6881 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6882 6883 // Replace the old load's chain with the new load's chain. 6884 WorklistRemover DeadNodes(*this); 6885 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6886 6887 // Shift the result left, if we've swallowed a left shift. 6888 SDValue Result = Load; 6889 if (ShLeftAmt != 0) { 6890 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6891 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6892 ShImmTy = VT; 6893 // If the shift amount is as large as the result size (but, presumably, 6894 // no larger than the source) then the useful bits of the result are 6895 // zero; we can't simply return the shortened shift, because the result 6896 // of that operation is undefined. 6897 SDLoc DL(N0); 6898 if (ShLeftAmt >= VT.getSizeInBits()) 6899 Result = DAG.getConstant(0, DL, VT); 6900 else 6901 Result = DAG.getNode(ISD::SHL, DL, VT, 6902 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6903 } 6904 6905 // Return the new loaded value. 6906 return Result; 6907 } 6908 6909 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6910 SDValue N0 = N->getOperand(0); 6911 SDValue N1 = N->getOperand(1); 6912 EVT VT = N->getValueType(0); 6913 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6914 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6915 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6916 6917 if (N0.isUndef()) 6918 return DAG.getUNDEF(VT); 6919 6920 // fold (sext_in_reg c1) -> c1 6921 if (isConstantIntBuildVectorOrConstantInt(N0)) 6922 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6923 6924 // If the input is already sign extended, just drop the extension. 6925 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6926 return N0; 6927 6928 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6929 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6930 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6931 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6932 N0.getOperand(0), N1); 6933 6934 // fold (sext_in_reg (sext x)) -> (sext x) 6935 // fold (sext_in_reg (aext x)) -> (sext x) 6936 // if x is small enough. 6937 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6938 SDValue N00 = N0.getOperand(0); 6939 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6940 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6941 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6942 } 6943 6944 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6945 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6946 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6947 6948 // fold operands of sext_in_reg based on knowledge that the top bits are not 6949 // demanded. 6950 if (SimplifyDemandedBits(SDValue(N, 0))) 6951 return SDValue(N, 0); 6952 6953 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6954 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6955 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6956 return NarrowLoad; 6957 6958 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6959 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6960 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6961 if (N0.getOpcode() == ISD::SRL) { 6962 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6963 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6964 // We can turn this into an SRA iff the input to the SRL is already sign 6965 // extended enough. 6966 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6967 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6968 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6969 N0.getOperand(0), N0.getOperand(1)); 6970 } 6971 } 6972 6973 // fold (sext_inreg (extload x)) -> (sextload x) 6974 if (ISD::isEXTLoad(N0.getNode()) && 6975 ISD::isUNINDEXEDLoad(N0.getNode()) && 6976 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6977 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6978 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6979 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6980 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6981 LN0->getChain(), 6982 LN0->getBasePtr(), EVT, 6983 LN0->getMemOperand()); 6984 CombineTo(N, ExtLoad); 6985 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6986 AddToWorklist(ExtLoad.getNode()); 6987 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6988 } 6989 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6990 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6991 N0.hasOneUse() && 6992 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6993 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6994 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6995 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6996 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6997 LN0->getChain(), 6998 LN0->getBasePtr(), EVT, 6999 LN0->getMemOperand()); 7000 CombineTo(N, ExtLoad); 7001 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7002 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7003 } 7004 7005 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7006 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7007 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7008 N0.getOperand(1), false); 7009 if (BSwap.getNode()) 7010 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7011 BSwap, N1); 7012 } 7013 7014 return SDValue(); 7015 } 7016 7017 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7018 SDValue N0 = N->getOperand(0); 7019 EVT VT = N->getValueType(0); 7020 7021 if (N0.getOpcode() == ISD::UNDEF) 7022 return DAG.getUNDEF(VT); 7023 7024 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7025 LegalOperations)) 7026 return SDValue(Res, 0); 7027 7028 return SDValue(); 7029 } 7030 7031 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7032 SDValue N0 = N->getOperand(0); 7033 EVT VT = N->getValueType(0); 7034 bool isLE = DAG.getDataLayout().isLittleEndian(); 7035 7036 // noop truncate 7037 if (N0.getValueType() == N->getValueType(0)) 7038 return N0; 7039 // fold (truncate c1) -> c1 7040 if (isConstantIntBuildVectorOrConstantInt(N0)) 7041 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7042 // fold (truncate (truncate x)) -> (truncate x) 7043 if (N0.getOpcode() == ISD::TRUNCATE) 7044 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7045 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7046 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7047 N0.getOpcode() == ISD::SIGN_EXTEND || 7048 N0.getOpcode() == ISD::ANY_EXTEND) { 7049 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7050 // if the source is smaller than the dest, we still need an extend 7051 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 7052 N0.getOperand(0)); 7053 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7054 // if the source is larger than the dest, than we just need the truncate 7055 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7056 // if the source and dest are the same type, we can drop both the extend 7057 // and the truncate. 7058 return N0.getOperand(0); 7059 } 7060 7061 // Fold extract-and-trunc into a narrow extract. For example: 7062 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7063 // i32 y = TRUNCATE(i64 x) 7064 // -- becomes -- 7065 // v16i8 b = BITCAST (v2i64 val) 7066 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7067 // 7068 // Note: We only run this optimization after type legalization (which often 7069 // creates this pattern) and before operation legalization after which 7070 // we need to be more careful about the vector instructions that we generate. 7071 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7072 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7073 7074 EVT VecTy = N0.getOperand(0).getValueType(); 7075 EVT ExTy = N0.getValueType(); 7076 EVT TrTy = N->getValueType(0); 7077 7078 unsigned NumElem = VecTy.getVectorNumElements(); 7079 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7080 7081 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7082 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7083 7084 SDValue EltNo = N0->getOperand(1); 7085 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7086 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7087 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7088 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7089 7090 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 7091 NVT, N0.getOperand(0)); 7092 7093 SDLoc DL(N); 7094 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 7095 DL, TrTy, V, 7096 DAG.getConstant(Index, DL, IndexTy)); 7097 } 7098 } 7099 7100 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7101 if (N0.getOpcode() == ISD::SELECT) { 7102 EVT SrcVT = N0.getValueType(); 7103 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7104 TLI.isTruncateFree(SrcVT, VT)) { 7105 SDLoc SL(N0); 7106 SDValue Cond = N0.getOperand(0); 7107 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7108 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7109 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7110 } 7111 } 7112 7113 // Fold a series of buildvector, bitcast, and truncate if possible. 7114 // For example fold 7115 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7116 // (2xi32 (buildvector x, y)). 7117 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7118 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7119 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7120 N0.getOperand(0).hasOneUse()) { 7121 7122 SDValue BuildVect = N0.getOperand(0); 7123 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7124 EVT TruncVecEltTy = VT.getVectorElementType(); 7125 7126 // Check that the element types match. 7127 if (BuildVectEltTy == TruncVecEltTy) { 7128 // Now we only need to compute the offset of the truncated elements. 7129 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7130 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7131 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7132 7133 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7134 "Invalid number of elements"); 7135 7136 SmallVector<SDValue, 8> Opnds; 7137 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7138 Opnds.push_back(BuildVect.getOperand(i)); 7139 7140 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 7141 } 7142 } 7143 7144 // See if we can simplify the input to this truncate through knowledge that 7145 // only the low bits are being used. 7146 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7147 // Currently we only perform this optimization on scalars because vectors 7148 // may have different active low bits. 7149 if (!VT.isVector()) { 7150 SDValue Shorter = 7151 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7152 VT.getSizeInBits())); 7153 if (Shorter.getNode()) 7154 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7155 } 7156 // fold (truncate (load x)) -> (smaller load x) 7157 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7158 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7159 if (SDValue Reduced = ReduceLoadWidth(N)) 7160 return Reduced; 7161 7162 // Handle the case where the load remains an extending load even 7163 // after truncation. 7164 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7165 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7166 if (!LN0->isVolatile() && 7167 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7168 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7169 VT, LN0->getChain(), LN0->getBasePtr(), 7170 LN0->getMemoryVT(), 7171 LN0->getMemOperand()); 7172 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7173 return NewLoad; 7174 } 7175 } 7176 } 7177 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7178 // where ... are all 'undef'. 7179 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7180 SmallVector<EVT, 8> VTs; 7181 SDValue V; 7182 unsigned Idx = 0; 7183 unsigned NumDefs = 0; 7184 7185 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7186 SDValue X = N0.getOperand(i); 7187 if (X.getOpcode() != ISD::UNDEF) { 7188 V = X; 7189 Idx = i; 7190 NumDefs++; 7191 } 7192 // Stop if more than one members are non-undef. 7193 if (NumDefs > 1) 7194 break; 7195 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7196 VT.getVectorElementType(), 7197 X.getValueType().getVectorNumElements())); 7198 } 7199 7200 if (NumDefs == 0) 7201 return DAG.getUNDEF(VT); 7202 7203 if (NumDefs == 1) { 7204 assert(V.getNode() && "The single defined operand is empty!"); 7205 SmallVector<SDValue, 8> Opnds; 7206 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7207 if (i != Idx) { 7208 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7209 continue; 7210 } 7211 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7212 AddToWorklist(NV.getNode()); 7213 Opnds.push_back(NV); 7214 } 7215 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7216 } 7217 } 7218 7219 // Simplify the operands using demanded-bits information. 7220 if (!VT.isVector() && 7221 SimplifyDemandedBits(SDValue(N, 0))) 7222 return SDValue(N, 0); 7223 7224 return SDValue(); 7225 } 7226 7227 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7228 SDValue Elt = N->getOperand(i); 7229 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7230 return Elt.getNode(); 7231 return Elt.getOperand(Elt.getResNo()).getNode(); 7232 } 7233 7234 /// build_pair (load, load) -> load 7235 /// if load locations are consecutive. 7236 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7237 assert(N->getOpcode() == ISD::BUILD_PAIR); 7238 7239 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7240 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7241 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7242 LD1->getAddressSpace() != LD2->getAddressSpace()) 7243 return SDValue(); 7244 EVT LD1VT = LD1->getValueType(0); 7245 7246 if (ISD::isNON_EXTLoad(LD2) && 7247 LD2->hasOneUse() && 7248 // If both are volatile this would reduce the number of volatile loads. 7249 // If one is volatile it might be ok, but play conservative and bail out. 7250 !LD1->isVolatile() && 7251 !LD2->isVolatile() && 7252 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 7253 unsigned Align = LD1->getAlignment(); 7254 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7255 VT.getTypeForEVT(*DAG.getContext())); 7256 7257 if (NewAlign <= Align && 7258 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7259 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7260 LD1->getBasePtr(), LD1->getPointerInfo(), 7261 false, false, false, Align); 7262 } 7263 7264 return SDValue(); 7265 } 7266 7267 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7268 SDValue N0 = N->getOperand(0); 7269 EVT VT = N->getValueType(0); 7270 7271 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7272 // Only do this before legalize, since afterward the target may be depending 7273 // on the bitconvert. 7274 // First check to see if this is all constant. 7275 if (!LegalTypes && 7276 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7277 VT.isVector()) { 7278 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7279 7280 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7281 assert(!DestEltVT.isVector() && 7282 "Element type of vector ValueType must not be vector!"); 7283 if (isSimple) 7284 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7285 } 7286 7287 // If the input is a constant, let getNode fold it. 7288 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7289 // If we can't allow illegal operations, we need to check that this is just 7290 // a fp -> int or int -> conversion and that the resulting operation will 7291 // be legal. 7292 if (!LegalOperations || 7293 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7294 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7295 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7296 TLI.isOperationLegal(ISD::Constant, VT))) 7297 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7298 } 7299 7300 // (conv (conv x, t1), t2) -> (conv x, t2) 7301 if (N0.getOpcode() == ISD::BITCAST) 7302 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7303 N0.getOperand(0)); 7304 7305 // fold (conv (load x)) -> (load (conv*)x) 7306 // If the resultant load doesn't need a higher alignment than the original! 7307 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7308 // Do not change the width of a volatile load. 7309 !cast<LoadSDNode>(N0)->isVolatile() && 7310 // Do not remove the cast if the types differ in endian layout. 7311 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7312 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7313 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7314 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7315 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7316 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 7317 VT.getTypeForEVT(*DAG.getContext())); 7318 unsigned OrigAlign = LN0->getAlignment(); 7319 7320 if (Align <= OrigAlign) { 7321 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7322 LN0->getBasePtr(), LN0->getPointerInfo(), 7323 LN0->isVolatile(), LN0->isNonTemporal(), 7324 LN0->isInvariant(), OrigAlign, 7325 LN0->getAAInfo()); 7326 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7327 return Load; 7328 } 7329 } 7330 7331 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7332 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7333 // This often reduces constant pool loads. 7334 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7335 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7336 N0.getNode()->hasOneUse() && VT.isInteger() && 7337 !VT.isVector() && !N0.getValueType().isVector()) { 7338 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7339 N0.getOperand(0)); 7340 AddToWorklist(NewConv.getNode()); 7341 7342 SDLoc DL(N); 7343 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7344 if (N0.getOpcode() == ISD::FNEG) 7345 return DAG.getNode(ISD::XOR, DL, VT, 7346 NewConv, DAG.getConstant(SignBit, DL, VT)); 7347 assert(N0.getOpcode() == ISD::FABS); 7348 return DAG.getNode(ISD::AND, DL, VT, 7349 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7350 } 7351 7352 // fold (bitconvert (fcopysign cst, x)) -> 7353 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7354 // Note that we don't handle (copysign x, cst) because this can always be 7355 // folded to an fneg or fabs. 7356 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7357 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7358 VT.isInteger() && !VT.isVector()) { 7359 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7360 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7361 if (isTypeLegal(IntXVT)) { 7362 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7363 IntXVT, N0.getOperand(1)); 7364 AddToWorklist(X.getNode()); 7365 7366 // If X has a different width than the result/lhs, sext it or truncate it. 7367 unsigned VTWidth = VT.getSizeInBits(); 7368 if (OrigXWidth < VTWidth) { 7369 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7370 AddToWorklist(X.getNode()); 7371 } else if (OrigXWidth > VTWidth) { 7372 // To get the sign bit in the right place, we have to shift it right 7373 // before truncating. 7374 SDLoc DL(X); 7375 X = DAG.getNode(ISD::SRL, DL, 7376 X.getValueType(), X, 7377 DAG.getConstant(OrigXWidth-VTWidth, DL, 7378 X.getValueType())); 7379 AddToWorklist(X.getNode()); 7380 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7381 AddToWorklist(X.getNode()); 7382 } 7383 7384 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7385 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7386 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7387 AddToWorklist(X.getNode()); 7388 7389 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7390 VT, N0.getOperand(0)); 7391 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7392 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7393 AddToWorklist(Cst.getNode()); 7394 7395 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7396 } 7397 } 7398 7399 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7400 if (N0.getOpcode() == ISD::BUILD_PAIR) 7401 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7402 return CombineLD; 7403 7404 // Remove double bitcasts from shuffles - this is often a legacy of 7405 // XformToShuffleWithZero being used to combine bitmaskings (of 7406 // float vectors bitcast to integer vectors) into shuffles. 7407 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7408 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7409 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7410 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7411 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7412 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7413 7414 // If operands are a bitcast, peek through if it casts the original VT. 7415 // If operands are a constant, just bitcast back to original VT. 7416 auto PeekThroughBitcast = [&](SDValue Op) { 7417 if (Op.getOpcode() == ISD::BITCAST && 7418 Op.getOperand(0).getValueType() == VT) 7419 return SDValue(Op.getOperand(0)); 7420 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7421 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7422 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7423 return SDValue(); 7424 }; 7425 7426 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7427 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7428 if (!(SV0 && SV1)) 7429 return SDValue(); 7430 7431 int MaskScale = 7432 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7433 SmallVector<int, 8> NewMask; 7434 for (int M : SVN->getMask()) 7435 for (int i = 0; i != MaskScale; ++i) 7436 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7437 7438 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7439 if (!LegalMask) { 7440 std::swap(SV0, SV1); 7441 ShuffleVectorSDNode::commuteMask(NewMask); 7442 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7443 } 7444 7445 if (LegalMask) 7446 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7447 } 7448 7449 return SDValue(); 7450 } 7451 7452 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7453 EVT VT = N->getValueType(0); 7454 return CombineConsecutiveLoads(N, VT); 7455 } 7456 7457 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7458 /// operands. DstEltVT indicates the destination element value type. 7459 SDValue DAGCombiner:: 7460 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7461 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7462 7463 // If this is already the right type, we're done. 7464 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7465 7466 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7467 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7468 7469 // If this is a conversion of N elements of one type to N elements of another 7470 // type, convert each element. This handles FP<->INT cases. 7471 if (SrcBitSize == DstBitSize) { 7472 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7473 BV->getValueType(0).getVectorNumElements()); 7474 7475 // Due to the FP element handling below calling this routine recursively, 7476 // we can end up with a scalar-to-vector node here. 7477 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7478 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7479 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7480 DstEltVT, BV->getOperand(0))); 7481 7482 SmallVector<SDValue, 8> Ops; 7483 for (SDValue Op : BV->op_values()) { 7484 // If the vector element type is not legal, the BUILD_VECTOR operands 7485 // are promoted and implicitly truncated. Make that explicit here. 7486 if (Op.getValueType() != SrcEltVT) 7487 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7488 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7489 DstEltVT, Op)); 7490 AddToWorklist(Ops.back().getNode()); 7491 } 7492 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7493 } 7494 7495 // Otherwise, we're growing or shrinking the elements. To avoid having to 7496 // handle annoying details of growing/shrinking FP values, we convert them to 7497 // int first. 7498 if (SrcEltVT.isFloatingPoint()) { 7499 // Convert the input float vector to a int vector where the elements are the 7500 // same sizes. 7501 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7502 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7503 SrcEltVT = IntVT; 7504 } 7505 7506 // Now we know the input is an integer vector. If the output is a FP type, 7507 // convert to integer first, then to FP of the right size. 7508 if (DstEltVT.isFloatingPoint()) { 7509 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7510 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7511 7512 // Next, convert to FP elements of the same size. 7513 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7514 } 7515 7516 SDLoc DL(BV); 7517 7518 // Okay, we know the src/dst types are both integers of differing types. 7519 // Handling growing first. 7520 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7521 if (SrcBitSize < DstBitSize) { 7522 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7523 7524 SmallVector<SDValue, 8> Ops; 7525 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7526 i += NumInputsPerOutput) { 7527 bool isLE = DAG.getDataLayout().isLittleEndian(); 7528 APInt NewBits = APInt(DstBitSize, 0); 7529 bool EltIsUndef = true; 7530 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7531 // Shift the previously computed bits over. 7532 NewBits <<= SrcBitSize; 7533 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7534 if (Op.getOpcode() == ISD::UNDEF) continue; 7535 EltIsUndef = false; 7536 7537 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7538 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7539 } 7540 7541 if (EltIsUndef) 7542 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7543 else 7544 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7545 } 7546 7547 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7548 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7549 } 7550 7551 // Finally, this must be the case where we are shrinking elements: each input 7552 // turns into multiple outputs. 7553 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7554 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7555 NumOutputsPerInput*BV->getNumOperands()); 7556 SmallVector<SDValue, 8> Ops; 7557 7558 for (const SDValue &Op : BV->op_values()) { 7559 if (Op.getOpcode() == ISD::UNDEF) { 7560 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7561 continue; 7562 } 7563 7564 APInt OpVal = cast<ConstantSDNode>(Op)-> 7565 getAPIntValue().zextOrTrunc(SrcBitSize); 7566 7567 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7568 APInt ThisVal = OpVal.trunc(DstBitSize); 7569 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7570 OpVal = OpVal.lshr(DstBitSize); 7571 } 7572 7573 // For big endian targets, swap the order of the pieces of each element. 7574 if (DAG.getDataLayout().isBigEndian()) 7575 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7576 } 7577 7578 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7579 } 7580 7581 /// Try to perform FMA combining on a given FADD node. 7582 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7583 SDValue N0 = N->getOperand(0); 7584 SDValue N1 = N->getOperand(1); 7585 EVT VT = N->getValueType(0); 7586 SDLoc SL(N); 7587 7588 const TargetOptions &Options = DAG.getTarget().Options; 7589 bool AllowFusion = 7590 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7591 7592 // Floating-point multiply-add with intermediate rounding. 7593 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7594 7595 // Floating-point multiply-add without intermediate rounding. 7596 bool HasFMA = 7597 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7598 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7599 7600 // No valid opcode, do not combine. 7601 if (!HasFMAD && !HasFMA) 7602 return SDValue(); 7603 7604 // Always prefer FMAD to FMA for precision. 7605 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7606 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7607 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7608 7609 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7610 // prefer to fold the multiply with fewer uses. 7611 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7612 N1.getOpcode() == ISD::FMUL) { 7613 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7614 std::swap(N0, N1); 7615 } 7616 7617 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7618 if (N0.getOpcode() == ISD::FMUL && 7619 (Aggressive || N0->hasOneUse())) { 7620 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7621 N0.getOperand(0), N0.getOperand(1), N1); 7622 } 7623 7624 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7625 // Note: Commutes FADD operands. 7626 if (N1.getOpcode() == ISD::FMUL && 7627 (Aggressive || N1->hasOneUse())) { 7628 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7629 N1.getOperand(0), N1.getOperand(1), N0); 7630 } 7631 7632 // Look through FP_EXTEND nodes to do more combining. 7633 if (AllowFusion && LookThroughFPExt) { 7634 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7635 if (N0.getOpcode() == ISD::FP_EXTEND) { 7636 SDValue N00 = N0.getOperand(0); 7637 if (N00.getOpcode() == ISD::FMUL) 7638 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7639 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7640 N00.getOperand(0)), 7641 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7642 N00.getOperand(1)), N1); 7643 } 7644 7645 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7646 // Note: Commutes FADD operands. 7647 if (N1.getOpcode() == ISD::FP_EXTEND) { 7648 SDValue N10 = N1.getOperand(0); 7649 if (N10.getOpcode() == ISD::FMUL) 7650 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7651 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7652 N10.getOperand(0)), 7653 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7654 N10.getOperand(1)), N0); 7655 } 7656 } 7657 7658 // More folding opportunities when target permits. 7659 if ((AllowFusion || HasFMAD) && Aggressive) { 7660 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7661 if (N0.getOpcode() == PreferredFusedOpcode && 7662 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7663 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7664 N0.getOperand(0), N0.getOperand(1), 7665 DAG.getNode(PreferredFusedOpcode, SL, VT, 7666 N0.getOperand(2).getOperand(0), 7667 N0.getOperand(2).getOperand(1), 7668 N1)); 7669 } 7670 7671 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7672 if (N1->getOpcode() == PreferredFusedOpcode && 7673 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7674 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7675 N1.getOperand(0), N1.getOperand(1), 7676 DAG.getNode(PreferredFusedOpcode, SL, VT, 7677 N1.getOperand(2).getOperand(0), 7678 N1.getOperand(2).getOperand(1), 7679 N0)); 7680 } 7681 7682 if (AllowFusion && LookThroughFPExt) { 7683 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7684 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7685 auto FoldFAddFMAFPExtFMul = [&] ( 7686 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7687 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7688 DAG.getNode(PreferredFusedOpcode, SL, VT, 7689 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7690 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7691 Z)); 7692 }; 7693 if (N0.getOpcode() == PreferredFusedOpcode) { 7694 SDValue N02 = N0.getOperand(2); 7695 if (N02.getOpcode() == ISD::FP_EXTEND) { 7696 SDValue N020 = N02.getOperand(0); 7697 if (N020.getOpcode() == ISD::FMUL) 7698 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7699 N020.getOperand(0), N020.getOperand(1), 7700 N1); 7701 } 7702 } 7703 7704 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7705 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7706 // FIXME: This turns two single-precision and one double-precision 7707 // operation into two double-precision operations, which might not be 7708 // interesting for all targets, especially GPUs. 7709 auto FoldFAddFPExtFMAFMul = [&] ( 7710 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7711 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7712 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7713 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7714 DAG.getNode(PreferredFusedOpcode, SL, VT, 7715 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7716 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7717 Z)); 7718 }; 7719 if (N0.getOpcode() == ISD::FP_EXTEND) { 7720 SDValue N00 = N0.getOperand(0); 7721 if (N00.getOpcode() == PreferredFusedOpcode) { 7722 SDValue N002 = N00.getOperand(2); 7723 if (N002.getOpcode() == ISD::FMUL) 7724 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7725 N002.getOperand(0), N002.getOperand(1), 7726 N1); 7727 } 7728 } 7729 7730 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7731 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7732 if (N1.getOpcode() == PreferredFusedOpcode) { 7733 SDValue N12 = N1.getOperand(2); 7734 if (N12.getOpcode() == ISD::FP_EXTEND) { 7735 SDValue N120 = N12.getOperand(0); 7736 if (N120.getOpcode() == ISD::FMUL) 7737 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7738 N120.getOperand(0), N120.getOperand(1), 7739 N0); 7740 } 7741 } 7742 7743 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7744 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7745 // FIXME: This turns two single-precision and one double-precision 7746 // operation into two double-precision operations, which might not be 7747 // interesting for all targets, especially GPUs. 7748 if (N1.getOpcode() == ISD::FP_EXTEND) { 7749 SDValue N10 = N1.getOperand(0); 7750 if (N10.getOpcode() == PreferredFusedOpcode) { 7751 SDValue N102 = N10.getOperand(2); 7752 if (N102.getOpcode() == ISD::FMUL) 7753 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7754 N102.getOperand(0), N102.getOperand(1), 7755 N0); 7756 } 7757 } 7758 } 7759 } 7760 7761 return SDValue(); 7762 } 7763 7764 /// Try to perform FMA combining on a given FSUB node. 7765 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7766 SDValue N0 = N->getOperand(0); 7767 SDValue N1 = N->getOperand(1); 7768 EVT VT = N->getValueType(0); 7769 SDLoc SL(N); 7770 7771 const TargetOptions &Options = DAG.getTarget().Options; 7772 bool AllowFusion = 7773 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7774 7775 // Floating-point multiply-add with intermediate rounding. 7776 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7777 7778 // Floating-point multiply-add without intermediate rounding. 7779 bool HasFMA = 7780 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7781 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7782 7783 // No valid opcode, do not combine. 7784 if (!HasFMAD && !HasFMA) 7785 return SDValue(); 7786 7787 // Always prefer FMAD to FMA for precision. 7788 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7789 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7790 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7791 7792 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7793 if (N0.getOpcode() == ISD::FMUL && 7794 (Aggressive || N0->hasOneUse())) { 7795 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7796 N0.getOperand(0), N0.getOperand(1), 7797 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7798 } 7799 7800 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7801 // Note: Commutes FSUB operands. 7802 if (N1.getOpcode() == ISD::FMUL && 7803 (Aggressive || N1->hasOneUse())) 7804 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7805 DAG.getNode(ISD::FNEG, SL, VT, 7806 N1.getOperand(0)), 7807 N1.getOperand(1), N0); 7808 7809 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7810 if (N0.getOpcode() == ISD::FNEG && 7811 N0.getOperand(0).getOpcode() == ISD::FMUL && 7812 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7813 SDValue N00 = N0.getOperand(0).getOperand(0); 7814 SDValue N01 = N0.getOperand(0).getOperand(1); 7815 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7816 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7817 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7818 } 7819 7820 // Look through FP_EXTEND nodes to do more combining. 7821 if (AllowFusion && LookThroughFPExt) { 7822 // fold (fsub (fpext (fmul x, y)), z) 7823 // -> (fma (fpext x), (fpext y), (fneg z)) 7824 if (N0.getOpcode() == ISD::FP_EXTEND) { 7825 SDValue N00 = N0.getOperand(0); 7826 if (N00.getOpcode() == ISD::FMUL) 7827 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7828 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7829 N00.getOperand(0)), 7830 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7831 N00.getOperand(1)), 7832 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7833 } 7834 7835 // fold (fsub x, (fpext (fmul y, z))) 7836 // -> (fma (fneg (fpext y)), (fpext z), x) 7837 // Note: Commutes FSUB operands. 7838 if (N1.getOpcode() == ISD::FP_EXTEND) { 7839 SDValue N10 = N1.getOperand(0); 7840 if (N10.getOpcode() == ISD::FMUL) 7841 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7842 DAG.getNode(ISD::FNEG, SL, VT, 7843 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7844 N10.getOperand(0))), 7845 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7846 N10.getOperand(1)), 7847 N0); 7848 } 7849 7850 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7851 // -> (fneg (fma (fpext x), (fpext y), z)) 7852 // Note: This could be removed with appropriate canonicalization of the 7853 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7854 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7855 // from implementing the canonicalization in visitFSUB. 7856 if (N0.getOpcode() == ISD::FP_EXTEND) { 7857 SDValue N00 = N0.getOperand(0); 7858 if (N00.getOpcode() == ISD::FNEG) { 7859 SDValue N000 = N00.getOperand(0); 7860 if (N000.getOpcode() == ISD::FMUL) { 7861 return DAG.getNode(ISD::FNEG, SL, VT, 7862 DAG.getNode(PreferredFusedOpcode, SL, VT, 7863 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7864 N000.getOperand(0)), 7865 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7866 N000.getOperand(1)), 7867 N1)); 7868 } 7869 } 7870 } 7871 7872 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7873 // -> (fneg (fma (fpext x)), (fpext y), z) 7874 // Note: This could be removed with appropriate canonicalization of the 7875 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7876 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7877 // from implementing the canonicalization in visitFSUB. 7878 if (N0.getOpcode() == ISD::FNEG) { 7879 SDValue N00 = N0.getOperand(0); 7880 if (N00.getOpcode() == ISD::FP_EXTEND) { 7881 SDValue N000 = N00.getOperand(0); 7882 if (N000.getOpcode() == ISD::FMUL) { 7883 return DAG.getNode(ISD::FNEG, SL, VT, 7884 DAG.getNode(PreferredFusedOpcode, SL, VT, 7885 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7886 N000.getOperand(0)), 7887 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7888 N000.getOperand(1)), 7889 N1)); 7890 } 7891 } 7892 } 7893 7894 } 7895 7896 // More folding opportunities when target permits. 7897 if ((AllowFusion || HasFMAD) && Aggressive) { 7898 // fold (fsub (fma x, y, (fmul u, v)), z) 7899 // -> (fma x, y (fma u, v, (fneg z))) 7900 if (N0.getOpcode() == PreferredFusedOpcode && 7901 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7902 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7903 N0.getOperand(0), N0.getOperand(1), 7904 DAG.getNode(PreferredFusedOpcode, SL, VT, 7905 N0.getOperand(2).getOperand(0), 7906 N0.getOperand(2).getOperand(1), 7907 DAG.getNode(ISD::FNEG, SL, VT, 7908 N1))); 7909 } 7910 7911 // fold (fsub x, (fma y, z, (fmul u, v))) 7912 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7913 if (N1.getOpcode() == PreferredFusedOpcode && 7914 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7915 SDValue N20 = N1.getOperand(2).getOperand(0); 7916 SDValue N21 = N1.getOperand(2).getOperand(1); 7917 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7918 DAG.getNode(ISD::FNEG, SL, VT, 7919 N1.getOperand(0)), 7920 N1.getOperand(1), 7921 DAG.getNode(PreferredFusedOpcode, SL, VT, 7922 DAG.getNode(ISD::FNEG, SL, VT, N20), 7923 7924 N21, N0)); 7925 } 7926 7927 if (AllowFusion && LookThroughFPExt) { 7928 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7929 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 7930 if (N0.getOpcode() == PreferredFusedOpcode) { 7931 SDValue N02 = N0.getOperand(2); 7932 if (N02.getOpcode() == ISD::FP_EXTEND) { 7933 SDValue N020 = N02.getOperand(0); 7934 if (N020.getOpcode() == ISD::FMUL) 7935 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7936 N0.getOperand(0), N0.getOperand(1), 7937 DAG.getNode(PreferredFusedOpcode, SL, VT, 7938 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7939 N020.getOperand(0)), 7940 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7941 N020.getOperand(1)), 7942 DAG.getNode(ISD::FNEG, SL, VT, 7943 N1))); 7944 } 7945 } 7946 7947 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 7948 // -> (fma (fpext x), (fpext y), 7949 // (fma (fpext u), (fpext v), (fneg z))) 7950 // FIXME: This turns two single-precision and one double-precision 7951 // operation into two double-precision operations, which might not be 7952 // interesting for all targets, especially GPUs. 7953 if (N0.getOpcode() == ISD::FP_EXTEND) { 7954 SDValue N00 = N0.getOperand(0); 7955 if (N00.getOpcode() == PreferredFusedOpcode) { 7956 SDValue N002 = N00.getOperand(2); 7957 if (N002.getOpcode() == ISD::FMUL) 7958 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7959 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7960 N00.getOperand(0)), 7961 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7962 N00.getOperand(1)), 7963 DAG.getNode(PreferredFusedOpcode, SL, VT, 7964 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7965 N002.getOperand(0)), 7966 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7967 N002.getOperand(1)), 7968 DAG.getNode(ISD::FNEG, SL, VT, 7969 N1))); 7970 } 7971 } 7972 7973 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 7974 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 7975 if (N1.getOpcode() == PreferredFusedOpcode && 7976 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 7977 SDValue N120 = N1.getOperand(2).getOperand(0); 7978 if (N120.getOpcode() == ISD::FMUL) { 7979 SDValue N1200 = N120.getOperand(0); 7980 SDValue N1201 = N120.getOperand(1); 7981 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7982 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 7983 N1.getOperand(1), 7984 DAG.getNode(PreferredFusedOpcode, SL, VT, 7985 DAG.getNode(ISD::FNEG, SL, VT, 7986 DAG.getNode(ISD::FP_EXTEND, SL, 7987 VT, N1200)), 7988 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7989 N1201), 7990 N0)); 7991 } 7992 } 7993 7994 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 7995 // -> (fma (fneg (fpext y)), (fpext z), 7996 // (fma (fneg (fpext u)), (fpext v), x)) 7997 // FIXME: This turns two single-precision and one double-precision 7998 // operation into two double-precision operations, which might not be 7999 // interesting for all targets, especially GPUs. 8000 if (N1.getOpcode() == ISD::FP_EXTEND && 8001 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8002 SDValue N100 = N1.getOperand(0).getOperand(0); 8003 SDValue N101 = N1.getOperand(0).getOperand(1); 8004 SDValue N102 = N1.getOperand(0).getOperand(2); 8005 if (N102.getOpcode() == ISD::FMUL) { 8006 SDValue N1020 = N102.getOperand(0); 8007 SDValue N1021 = N102.getOperand(1); 8008 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8009 DAG.getNode(ISD::FNEG, SL, VT, 8010 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8011 N100)), 8012 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8013 DAG.getNode(PreferredFusedOpcode, SL, VT, 8014 DAG.getNode(ISD::FNEG, SL, VT, 8015 DAG.getNode(ISD::FP_EXTEND, SL, 8016 VT, N1020)), 8017 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8018 N1021), 8019 N0)); 8020 } 8021 } 8022 } 8023 } 8024 8025 return SDValue(); 8026 } 8027 8028 /// Try to perform FMA combining on a given FMUL node. 8029 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 8030 SDValue N0 = N->getOperand(0); 8031 SDValue N1 = N->getOperand(1); 8032 EVT VT = N->getValueType(0); 8033 SDLoc SL(N); 8034 8035 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8036 8037 const TargetOptions &Options = DAG.getTarget().Options; 8038 bool AllowFusion = 8039 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8040 8041 // Floating-point multiply-add with intermediate rounding. 8042 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8043 8044 // Floating-point multiply-add without intermediate rounding. 8045 bool HasFMA = 8046 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8047 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8048 8049 // No valid opcode, do not combine. 8050 if (!HasFMAD && !HasFMA) 8051 return SDValue(); 8052 8053 // Always prefer FMAD to FMA for precision. 8054 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8055 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8056 8057 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8058 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8059 auto FuseFADD = [&](SDValue X, SDValue Y) { 8060 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8061 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8062 if (XC1 && XC1->isExactlyValue(+1.0)) 8063 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8064 if (XC1 && XC1->isExactlyValue(-1.0)) 8065 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8066 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8067 } 8068 return SDValue(); 8069 }; 8070 8071 if (SDValue FMA = FuseFADD(N0, N1)) 8072 return FMA; 8073 if (SDValue FMA = FuseFADD(N1, N0)) 8074 return FMA; 8075 8076 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8077 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8078 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8079 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8080 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8081 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8082 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8083 if (XC0 && XC0->isExactlyValue(+1.0)) 8084 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8085 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8086 Y); 8087 if (XC0 && XC0->isExactlyValue(-1.0)) 8088 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8089 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8090 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8091 8092 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8093 if (XC1 && XC1->isExactlyValue(+1.0)) 8094 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8095 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8096 if (XC1 && XC1->isExactlyValue(-1.0)) 8097 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8098 } 8099 return SDValue(); 8100 }; 8101 8102 if (SDValue FMA = FuseFSUB(N0, N1)) 8103 return FMA; 8104 if (SDValue FMA = FuseFSUB(N1, N0)) 8105 return FMA; 8106 8107 return SDValue(); 8108 } 8109 8110 SDValue DAGCombiner::visitFADD(SDNode *N) { 8111 SDValue N0 = N->getOperand(0); 8112 SDValue N1 = N->getOperand(1); 8113 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8114 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8115 EVT VT = N->getValueType(0); 8116 SDLoc DL(N); 8117 const TargetOptions &Options = DAG.getTarget().Options; 8118 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8119 8120 // fold vector ops 8121 if (VT.isVector()) 8122 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8123 return FoldedVOp; 8124 8125 // fold (fadd c1, c2) -> c1 + c2 8126 if (N0CFP && N1CFP) 8127 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8128 8129 // canonicalize constant to RHS 8130 if (N0CFP && !N1CFP) 8131 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8132 8133 // fold (fadd A, (fneg B)) -> (fsub A, B) 8134 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8135 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8136 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8137 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8138 8139 // fold (fadd (fneg A), B) -> (fsub B, A) 8140 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8141 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8142 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8143 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8144 8145 // If 'unsafe math' is enabled, fold lots of things. 8146 if (Options.UnsafeFPMath) { 8147 // No FP constant should be created after legalization as Instruction 8148 // Selection pass has a hard time dealing with FP constants. 8149 bool AllowNewConst = (Level < AfterLegalizeDAG); 8150 8151 // fold (fadd A, 0) -> A 8152 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8153 if (N1C->isZero()) 8154 return N0; 8155 8156 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8157 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8158 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8159 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8160 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8161 Flags), 8162 Flags); 8163 8164 // If allowed, fold (fadd (fneg x), x) -> 0.0 8165 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8166 return DAG.getConstantFP(0.0, DL, VT); 8167 8168 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8169 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8170 return DAG.getConstantFP(0.0, DL, VT); 8171 8172 // We can fold chains of FADD's of the same value into multiplications. 8173 // This transform is not safe in general because we are reducing the number 8174 // of rounding steps. 8175 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8176 if (N0.getOpcode() == ISD::FMUL) { 8177 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8178 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8179 8180 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8181 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8182 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8183 DAG.getConstantFP(1.0, DL, VT), Flags); 8184 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8185 } 8186 8187 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8188 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8189 N1.getOperand(0) == N1.getOperand(1) && 8190 N0.getOperand(0) == N1.getOperand(0)) { 8191 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8192 DAG.getConstantFP(2.0, DL, VT), Flags); 8193 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8194 } 8195 } 8196 8197 if (N1.getOpcode() == ISD::FMUL) { 8198 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8199 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8200 8201 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8202 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8203 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8204 DAG.getConstantFP(1.0, DL, VT), Flags); 8205 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8206 } 8207 8208 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8209 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8210 N0.getOperand(0) == N0.getOperand(1) && 8211 N1.getOperand(0) == N0.getOperand(0)) { 8212 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8213 DAG.getConstantFP(2.0, DL, VT), Flags); 8214 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8215 } 8216 } 8217 8218 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8219 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8220 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8221 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8222 (N0.getOperand(0) == N1)) { 8223 return DAG.getNode(ISD::FMUL, DL, VT, 8224 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8225 } 8226 } 8227 8228 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8229 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8230 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8231 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8232 N1.getOperand(0) == N0) { 8233 return DAG.getNode(ISD::FMUL, DL, VT, 8234 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8235 } 8236 } 8237 8238 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8239 if (AllowNewConst && 8240 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8241 N0.getOperand(0) == N0.getOperand(1) && 8242 N1.getOperand(0) == N1.getOperand(1) && 8243 N0.getOperand(0) == N1.getOperand(0)) { 8244 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8245 DAG.getConstantFP(4.0, DL, VT), Flags); 8246 } 8247 } 8248 } // enable-unsafe-fp-math 8249 8250 // FADD -> FMA combines: 8251 if (SDValue Fused = visitFADDForFMACombine(N)) { 8252 AddToWorklist(Fused.getNode()); 8253 return Fused; 8254 } 8255 8256 return SDValue(); 8257 } 8258 8259 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8260 SDValue N0 = N->getOperand(0); 8261 SDValue N1 = N->getOperand(1); 8262 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8263 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8264 EVT VT = N->getValueType(0); 8265 SDLoc dl(N); 8266 const TargetOptions &Options = DAG.getTarget().Options; 8267 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8268 8269 // fold vector ops 8270 if (VT.isVector()) 8271 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8272 return FoldedVOp; 8273 8274 // fold (fsub c1, c2) -> c1-c2 8275 if (N0CFP && N1CFP) 8276 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8277 8278 // fold (fsub A, (fneg B)) -> (fadd A, B) 8279 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8280 return DAG.getNode(ISD::FADD, dl, VT, N0, 8281 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8282 8283 // If 'unsafe math' is enabled, fold lots of things. 8284 if (Options.UnsafeFPMath) { 8285 // (fsub A, 0) -> A 8286 if (N1CFP && N1CFP->isZero()) 8287 return N0; 8288 8289 // (fsub 0, B) -> -B 8290 if (N0CFP && N0CFP->isZero()) { 8291 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8292 return GetNegatedExpression(N1, DAG, LegalOperations); 8293 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8294 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8295 } 8296 8297 // (fsub x, x) -> 0.0 8298 if (N0 == N1) 8299 return DAG.getConstantFP(0.0f, dl, VT); 8300 8301 // (fsub x, (fadd x, y)) -> (fneg y) 8302 // (fsub x, (fadd y, x)) -> (fneg y) 8303 if (N1.getOpcode() == ISD::FADD) { 8304 SDValue N10 = N1->getOperand(0); 8305 SDValue N11 = N1->getOperand(1); 8306 8307 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8308 return GetNegatedExpression(N11, DAG, LegalOperations); 8309 8310 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8311 return GetNegatedExpression(N10, DAG, LegalOperations); 8312 } 8313 } 8314 8315 // FSUB -> FMA combines: 8316 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8317 AddToWorklist(Fused.getNode()); 8318 return Fused; 8319 } 8320 8321 return SDValue(); 8322 } 8323 8324 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8325 SDValue N0 = N->getOperand(0); 8326 SDValue N1 = N->getOperand(1); 8327 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8328 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8329 EVT VT = N->getValueType(0); 8330 SDLoc DL(N); 8331 const TargetOptions &Options = DAG.getTarget().Options; 8332 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8333 8334 // fold vector ops 8335 if (VT.isVector()) { 8336 // This just handles C1 * C2 for vectors. Other vector folds are below. 8337 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8338 return FoldedVOp; 8339 } 8340 8341 // fold (fmul c1, c2) -> c1*c2 8342 if (N0CFP && N1CFP) 8343 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8344 8345 // canonicalize constant to RHS 8346 if (isConstantFPBuildVectorOrConstantFP(N0) && 8347 !isConstantFPBuildVectorOrConstantFP(N1)) 8348 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8349 8350 // fold (fmul A, 1.0) -> A 8351 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8352 return N0; 8353 8354 if (Options.UnsafeFPMath) { 8355 // fold (fmul A, 0) -> 0 8356 if (N1CFP && N1CFP->isZero()) 8357 return N1; 8358 8359 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8360 if (N0.getOpcode() == ISD::FMUL) { 8361 // Fold scalars or any vector constants (not just splats). 8362 // This fold is done in general by InstCombine, but extra fmul insts 8363 // may have been generated during lowering. 8364 SDValue N00 = N0.getOperand(0); 8365 SDValue N01 = N0.getOperand(1); 8366 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8367 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8368 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8369 8370 // Check 1: Make sure that the first operand of the inner multiply is NOT 8371 // a constant. Otherwise, we may induce infinite looping. 8372 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8373 // Check 2: Make sure that the second operand of the inner multiply and 8374 // the second operand of the outer multiply are constants. 8375 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8376 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8377 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8378 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8379 } 8380 } 8381 } 8382 8383 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8384 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8385 // during an early run of DAGCombiner can prevent folding with fmuls 8386 // inserted during lowering. 8387 if (N0.getOpcode() == ISD::FADD && 8388 (N0.getOperand(0) == N0.getOperand(1)) && 8389 N0.hasOneUse()) { 8390 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8391 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8392 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8393 } 8394 } 8395 8396 // fold (fmul X, 2.0) -> (fadd X, X) 8397 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8398 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8399 8400 // fold (fmul X, -1.0) -> (fneg X) 8401 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8402 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8403 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8404 8405 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8406 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8407 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8408 // Both can be negated for free, check to see if at least one is cheaper 8409 // negated. 8410 if (LHSNeg == 2 || RHSNeg == 2) 8411 return DAG.getNode(ISD::FMUL, DL, VT, 8412 GetNegatedExpression(N0, DAG, LegalOperations), 8413 GetNegatedExpression(N1, DAG, LegalOperations), 8414 Flags); 8415 } 8416 } 8417 8418 // FMUL -> FMA combines: 8419 if (SDValue Fused = visitFMULForFMACombine(N)) { 8420 AddToWorklist(Fused.getNode()); 8421 return Fused; 8422 } 8423 8424 return SDValue(); 8425 } 8426 8427 SDValue DAGCombiner::visitFMA(SDNode *N) { 8428 SDValue N0 = N->getOperand(0); 8429 SDValue N1 = N->getOperand(1); 8430 SDValue N2 = N->getOperand(2); 8431 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8432 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8433 EVT VT = N->getValueType(0); 8434 SDLoc dl(N); 8435 const TargetOptions &Options = DAG.getTarget().Options; 8436 8437 // Constant fold FMA. 8438 if (isa<ConstantFPSDNode>(N0) && 8439 isa<ConstantFPSDNode>(N1) && 8440 isa<ConstantFPSDNode>(N2)) { 8441 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8442 } 8443 8444 if (Options.UnsafeFPMath) { 8445 if (N0CFP && N0CFP->isZero()) 8446 return N2; 8447 if (N1CFP && N1CFP->isZero()) 8448 return N2; 8449 } 8450 // TODO: The FMA node should have flags that propagate to these nodes. 8451 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8452 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8453 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8454 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8455 8456 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8457 if (isConstantFPBuildVectorOrConstantFP(N0) && 8458 !isConstantFPBuildVectorOrConstantFP(N1)) 8459 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8460 8461 // TODO: FMA nodes should have flags that propagate to the created nodes. 8462 // For now, create a Flags object for use with all unsafe math transforms. 8463 SDNodeFlags Flags; 8464 Flags.setUnsafeAlgebra(true); 8465 8466 if (Options.UnsafeFPMath) { 8467 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8468 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8469 isConstantFPBuildVectorOrConstantFP(N1) && 8470 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8471 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8472 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8473 &Flags), &Flags); 8474 } 8475 8476 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8477 if (N0.getOpcode() == ISD::FMUL && 8478 isConstantFPBuildVectorOrConstantFP(N1) && 8479 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8480 return DAG.getNode(ISD::FMA, dl, VT, 8481 N0.getOperand(0), 8482 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8483 &Flags), 8484 N2); 8485 } 8486 } 8487 8488 // (fma x, 1, y) -> (fadd x, y) 8489 // (fma x, -1, y) -> (fadd (fneg x), y) 8490 if (N1CFP) { 8491 if (N1CFP->isExactlyValue(1.0)) 8492 // TODO: The FMA node should have flags that propagate to this node. 8493 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8494 8495 if (N1CFP->isExactlyValue(-1.0) && 8496 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8497 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8498 AddToWorklist(RHSNeg.getNode()); 8499 // TODO: The FMA node should have flags that propagate to this node. 8500 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8501 } 8502 } 8503 8504 if (Options.UnsafeFPMath) { 8505 // (fma x, c, x) -> (fmul x, (c+1)) 8506 if (N1CFP && N0 == N2) { 8507 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8508 DAG.getNode(ISD::FADD, dl, VT, 8509 N1, DAG.getConstantFP(1.0, dl, VT), 8510 &Flags), &Flags); 8511 } 8512 8513 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8514 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8515 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8516 DAG.getNode(ISD::FADD, dl, VT, 8517 N1, DAG.getConstantFP(-1.0, dl, VT), 8518 &Flags), &Flags); 8519 } 8520 } 8521 8522 return SDValue(); 8523 } 8524 8525 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8526 // reciprocal. 8527 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8528 // Notice that this is not always beneficial. One reason is different target 8529 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8530 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8531 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8532 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8533 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8534 const SDNodeFlags *Flags = N->getFlags(); 8535 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8536 return SDValue(); 8537 8538 // Skip if current node is a reciprocal. 8539 SDValue N0 = N->getOperand(0); 8540 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8541 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8542 return SDValue(); 8543 8544 // Exit early if the target does not want this transform or if there can't 8545 // possibly be enough uses of the divisor to make the transform worthwhile. 8546 SDValue N1 = N->getOperand(1); 8547 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8548 if (!MinUses || N1->use_size() < MinUses) 8549 return SDValue(); 8550 8551 // Find all FDIV users of the same divisor. 8552 // Use a set because duplicates may be present in the user list. 8553 SetVector<SDNode *> Users; 8554 for (auto *U : N1->uses()) { 8555 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8556 // This division is eligible for optimization only if global unsafe math 8557 // is enabled or if this division allows reciprocal formation. 8558 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8559 Users.insert(U); 8560 } 8561 } 8562 8563 // Now that we have the actual number of divisor uses, make sure it meets 8564 // the minimum threshold specified by the target. 8565 if (Users.size() < MinUses) 8566 return SDValue(); 8567 8568 EVT VT = N->getValueType(0); 8569 SDLoc DL(N); 8570 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8571 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8572 8573 // Dividend / Divisor -> Dividend * Reciprocal 8574 for (auto *U : Users) { 8575 SDValue Dividend = U->getOperand(0); 8576 if (Dividend != FPOne) { 8577 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8578 Reciprocal, Flags); 8579 CombineTo(U, NewNode); 8580 } else if (U != Reciprocal.getNode()) { 8581 // In the absence of fast-math-flags, this user node is always the 8582 // same node as Reciprocal, but with FMF they may be different nodes. 8583 CombineTo(U, Reciprocal); 8584 } 8585 } 8586 return SDValue(N, 0); // N was replaced. 8587 } 8588 8589 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8590 SDValue N0 = N->getOperand(0); 8591 SDValue N1 = N->getOperand(1); 8592 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8593 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8594 EVT VT = N->getValueType(0); 8595 SDLoc DL(N); 8596 const TargetOptions &Options = DAG.getTarget().Options; 8597 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8598 8599 // fold vector ops 8600 if (VT.isVector()) 8601 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8602 return FoldedVOp; 8603 8604 // fold (fdiv c1, c2) -> c1/c2 8605 if (N0CFP && N1CFP) 8606 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8607 8608 if (Options.UnsafeFPMath) { 8609 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8610 if (N1CFP) { 8611 // Compute the reciprocal 1.0 / c2. 8612 APFloat N1APF = N1CFP->getValueAPF(); 8613 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8614 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8615 // Only do the transform if the reciprocal is a legal fp immediate that 8616 // isn't too nasty (eg NaN, denormal, ...). 8617 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8618 (!LegalOperations || 8619 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8620 // backend)... we should handle this gracefully after Legalize. 8621 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8622 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8623 TLI.isFPImmLegal(Recip, VT))) 8624 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8625 DAG.getConstantFP(Recip, DL, VT), Flags); 8626 } 8627 8628 // If this FDIV is part of a reciprocal square root, it may be folded 8629 // into a target-specific square root estimate instruction. 8630 if (N1.getOpcode() == ISD::FSQRT) { 8631 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) { 8632 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8633 } 8634 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8635 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8636 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8637 Flags)) { 8638 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8639 AddToWorklist(RV.getNode()); 8640 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8641 } 8642 } else if (N1.getOpcode() == ISD::FP_ROUND && 8643 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8644 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8645 Flags)) { 8646 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8647 AddToWorklist(RV.getNode()); 8648 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8649 } 8650 } else if (N1.getOpcode() == ISD::FMUL) { 8651 // Look through an FMUL. Even though this won't remove the FDIV directly, 8652 // it's still worthwhile to get rid of the FSQRT if possible. 8653 SDValue SqrtOp; 8654 SDValue OtherOp; 8655 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8656 SqrtOp = N1.getOperand(0); 8657 OtherOp = N1.getOperand(1); 8658 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8659 SqrtOp = N1.getOperand(1); 8660 OtherOp = N1.getOperand(0); 8661 } 8662 if (SqrtOp.getNode()) { 8663 // We found a FSQRT, so try to make this fold: 8664 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8665 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8666 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8667 AddToWorklist(RV.getNode()); 8668 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8669 } 8670 } 8671 } 8672 8673 // Fold into a reciprocal estimate and multiply instead of a real divide. 8674 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8675 AddToWorklist(RV.getNode()); 8676 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8677 } 8678 } 8679 8680 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8681 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8682 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8683 // Both can be negated for free, check to see if at least one is cheaper 8684 // negated. 8685 if (LHSNeg == 2 || RHSNeg == 2) 8686 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8687 GetNegatedExpression(N0, DAG, LegalOperations), 8688 GetNegatedExpression(N1, DAG, LegalOperations), 8689 Flags); 8690 } 8691 } 8692 8693 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8694 return CombineRepeatedDivisors; 8695 8696 return SDValue(); 8697 } 8698 8699 SDValue DAGCombiner::visitFREM(SDNode *N) { 8700 SDValue N0 = N->getOperand(0); 8701 SDValue N1 = N->getOperand(1); 8702 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8703 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8704 EVT VT = N->getValueType(0); 8705 8706 // fold (frem c1, c2) -> fmod(c1,c2) 8707 if (N0CFP && N1CFP) 8708 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8709 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8710 8711 return SDValue(); 8712 } 8713 8714 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8715 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8716 return SDValue(); 8717 8718 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8719 // For now, create a Flags object for use with all unsafe math transforms. 8720 SDNodeFlags Flags; 8721 Flags.setUnsafeAlgebra(true); 8722 8723 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8724 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags); 8725 if (!RV) 8726 return SDValue(); 8727 8728 EVT VT = RV.getValueType(); 8729 SDLoc DL(N); 8730 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags); 8731 AddToWorklist(RV.getNode()); 8732 8733 // Unfortunately, RV is now NaN if the input was exactly 0. 8734 // Select out this case and force the answer to 0. 8735 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8736 EVT CCVT = getSetCCResultType(VT); 8737 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ); 8738 AddToWorklist(ZeroCmp.getNode()); 8739 AddToWorklist(RV.getNode()); 8740 8741 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 8742 ZeroCmp, Zero, RV); 8743 } 8744 8745 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8746 SDValue N0 = N->getOperand(0); 8747 SDValue N1 = N->getOperand(1); 8748 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8749 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8750 EVT VT = N->getValueType(0); 8751 8752 if (N0CFP && N1CFP) // Constant fold 8753 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8754 8755 if (N1CFP) { 8756 const APFloat& V = N1CFP->getValueAPF(); 8757 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8758 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8759 if (!V.isNegative()) { 8760 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8761 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8762 } else { 8763 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8764 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8765 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8766 } 8767 } 8768 8769 // copysign(fabs(x), y) -> copysign(x, y) 8770 // copysign(fneg(x), y) -> copysign(x, y) 8771 // copysign(copysign(x,z), y) -> copysign(x, y) 8772 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8773 N0.getOpcode() == ISD::FCOPYSIGN) 8774 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8775 N0.getOperand(0), N1); 8776 8777 // copysign(x, abs(y)) -> abs(x) 8778 if (N1.getOpcode() == ISD::FABS) 8779 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8780 8781 // copysign(x, copysign(y,z)) -> copysign(x, z) 8782 if (N1.getOpcode() == ISD::FCOPYSIGN) 8783 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8784 N0, N1.getOperand(1)); 8785 8786 // copysign(x, fp_extend(y)) -> copysign(x, y) 8787 // copysign(x, fp_round(y)) -> copysign(x, y) 8788 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 8789 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8790 N0, N1.getOperand(0)); 8791 8792 return SDValue(); 8793 } 8794 8795 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8796 SDValue N0 = N->getOperand(0); 8797 EVT VT = N->getValueType(0); 8798 EVT OpVT = N0.getValueType(); 8799 8800 // fold (sint_to_fp c1) -> c1fp 8801 if (isConstantIntBuildVectorOrConstantInt(N0) && 8802 // ...but only if the target supports immediate floating-point values 8803 (!LegalOperations || 8804 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8805 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8806 8807 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8808 // but UINT_TO_FP is legal on this target, try to convert. 8809 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8810 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8811 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8812 if (DAG.SignBitIsZero(N0)) 8813 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8814 } 8815 8816 // The next optimizations are desirable only if SELECT_CC can be lowered. 8817 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8818 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8819 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8820 !VT.isVector() && 8821 (!LegalOperations || 8822 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8823 SDLoc DL(N); 8824 SDValue Ops[] = 8825 { N0.getOperand(0), N0.getOperand(1), 8826 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8827 N0.getOperand(2) }; 8828 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8829 } 8830 8831 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8832 // (select_cc x, y, 1.0, 0.0,, cc) 8833 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8834 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8835 (!LegalOperations || 8836 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8837 SDLoc DL(N); 8838 SDValue Ops[] = 8839 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8840 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8841 N0.getOperand(0).getOperand(2) }; 8842 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8843 } 8844 } 8845 8846 return SDValue(); 8847 } 8848 8849 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8850 SDValue N0 = N->getOperand(0); 8851 EVT VT = N->getValueType(0); 8852 EVT OpVT = N0.getValueType(); 8853 8854 // fold (uint_to_fp c1) -> c1fp 8855 if (isConstantIntBuildVectorOrConstantInt(N0) && 8856 // ...but only if the target supports immediate floating-point values 8857 (!LegalOperations || 8858 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8859 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8860 8861 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8862 // but SINT_TO_FP is legal on this target, try to convert. 8863 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8864 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8865 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8866 if (DAG.SignBitIsZero(N0)) 8867 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8868 } 8869 8870 // The next optimizations are desirable only if SELECT_CC can be lowered. 8871 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8872 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8873 8874 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8875 (!LegalOperations || 8876 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8877 SDLoc DL(N); 8878 SDValue Ops[] = 8879 { N0.getOperand(0), N0.getOperand(1), 8880 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8881 N0.getOperand(2) }; 8882 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8883 } 8884 } 8885 8886 return SDValue(); 8887 } 8888 8889 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8890 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8891 SDValue N0 = N->getOperand(0); 8892 EVT VT = N->getValueType(0); 8893 8894 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8895 return SDValue(); 8896 8897 SDValue Src = N0.getOperand(0); 8898 EVT SrcVT = Src.getValueType(); 8899 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8900 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8901 8902 // We can safely assume the conversion won't overflow the output range, 8903 // because (for example) (uint8_t)18293.f is undefined behavior. 8904 8905 // Since we can assume the conversion won't overflow, our decision as to 8906 // whether the input will fit in the float should depend on the minimum 8907 // of the input range and output range. 8908 8909 // This means this is also safe for a signed input and unsigned output, since 8910 // a negative input would lead to undefined behavior. 8911 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8912 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8913 unsigned ActualSize = std::min(InputSize, OutputSize); 8914 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8915 8916 // We can only fold away the float conversion if the input range can be 8917 // represented exactly in the float range. 8918 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8919 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8920 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8921 : ISD::ZERO_EXTEND; 8922 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8923 } 8924 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8925 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8926 if (SrcVT == VT) 8927 return Src; 8928 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 8929 } 8930 return SDValue(); 8931 } 8932 8933 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8934 SDValue N0 = N->getOperand(0); 8935 EVT VT = N->getValueType(0); 8936 8937 // fold (fp_to_sint c1fp) -> c1 8938 if (isConstantFPBuildVectorOrConstantFP(N0)) 8939 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8940 8941 return FoldIntToFPToInt(N, DAG); 8942 } 8943 8944 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 8945 SDValue N0 = N->getOperand(0); 8946 EVT VT = N->getValueType(0); 8947 8948 // fold (fp_to_uint c1fp) -> c1 8949 if (isConstantFPBuildVectorOrConstantFP(N0)) 8950 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 8951 8952 return FoldIntToFPToInt(N, DAG); 8953 } 8954 8955 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 8956 SDValue N0 = N->getOperand(0); 8957 SDValue N1 = N->getOperand(1); 8958 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8959 EVT VT = N->getValueType(0); 8960 8961 // fold (fp_round c1fp) -> c1fp 8962 if (N0CFP) 8963 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 8964 8965 // fold (fp_round (fp_extend x)) -> x 8966 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 8967 return N0.getOperand(0); 8968 8969 // fold (fp_round (fp_round x)) -> (fp_round x) 8970 if (N0.getOpcode() == ISD::FP_ROUND) { 8971 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 8972 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 8973 // If the first fp_round isn't a value preserving truncation, it might 8974 // introduce a tie in the second fp_round, that wouldn't occur in the 8975 // single-step fp_round we want to fold to. 8976 // In other words, double rounding isn't the same as rounding. 8977 // Also, this is a value preserving truncation iff both fp_round's are. 8978 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 8979 SDLoc DL(N); 8980 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 8981 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 8982 } 8983 } 8984 8985 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 8986 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 8987 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 8988 N0.getOperand(0), N1); 8989 AddToWorklist(Tmp.getNode()); 8990 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8991 Tmp, N0.getOperand(1)); 8992 } 8993 8994 return SDValue(); 8995 } 8996 8997 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 8998 SDValue N0 = N->getOperand(0); 8999 EVT VT = N->getValueType(0); 9000 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9001 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9002 9003 // fold (fp_round_inreg c1fp) -> c1fp 9004 if (N0CFP && isTypeLegal(EVT)) { 9005 SDLoc DL(N); 9006 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9007 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9008 } 9009 9010 return SDValue(); 9011 } 9012 9013 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9014 SDValue N0 = N->getOperand(0); 9015 EVT VT = N->getValueType(0); 9016 9017 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9018 if (N->hasOneUse() && 9019 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9020 return SDValue(); 9021 9022 // fold (fp_extend c1fp) -> c1fp 9023 if (isConstantFPBuildVectorOrConstantFP(N0)) 9024 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9025 9026 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9027 if (N0.getOpcode() == ISD::FP16_TO_FP && 9028 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9029 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9030 9031 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9032 // value of X. 9033 if (N0.getOpcode() == ISD::FP_ROUND 9034 && N0.getNode()->getConstantOperandVal(1) == 1) { 9035 SDValue In = N0.getOperand(0); 9036 if (In.getValueType() == VT) return In; 9037 if (VT.bitsLT(In.getValueType())) 9038 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9039 In, N0.getOperand(1)); 9040 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9041 } 9042 9043 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9044 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9045 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9046 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9047 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9048 LN0->getChain(), 9049 LN0->getBasePtr(), N0.getValueType(), 9050 LN0->getMemOperand()); 9051 CombineTo(N, ExtLoad); 9052 CombineTo(N0.getNode(), 9053 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9054 N0.getValueType(), ExtLoad, 9055 DAG.getIntPtrConstant(1, SDLoc(N0))), 9056 ExtLoad.getValue(1)); 9057 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9058 } 9059 9060 return SDValue(); 9061 } 9062 9063 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9064 SDValue N0 = N->getOperand(0); 9065 EVT VT = N->getValueType(0); 9066 9067 // fold (fceil c1) -> fceil(c1) 9068 if (isConstantFPBuildVectorOrConstantFP(N0)) 9069 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9070 9071 return SDValue(); 9072 } 9073 9074 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9075 SDValue N0 = N->getOperand(0); 9076 EVT VT = N->getValueType(0); 9077 9078 // fold (ftrunc c1) -> ftrunc(c1) 9079 if (isConstantFPBuildVectorOrConstantFP(N0)) 9080 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9081 9082 return SDValue(); 9083 } 9084 9085 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9086 SDValue N0 = N->getOperand(0); 9087 EVT VT = N->getValueType(0); 9088 9089 // fold (ffloor c1) -> ffloor(c1) 9090 if (isConstantFPBuildVectorOrConstantFP(N0)) 9091 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9092 9093 return SDValue(); 9094 } 9095 9096 // FIXME: FNEG and FABS have a lot in common; refactor. 9097 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9098 SDValue N0 = N->getOperand(0); 9099 EVT VT = N->getValueType(0); 9100 9101 // Constant fold FNEG. 9102 if (isConstantFPBuildVectorOrConstantFP(N0)) 9103 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9104 9105 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9106 &DAG.getTarget().Options)) 9107 return GetNegatedExpression(N0, DAG, LegalOperations); 9108 9109 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9110 // constant pool values. 9111 if (!TLI.isFNegFree(VT) && 9112 N0.getOpcode() == ISD::BITCAST && 9113 N0.getNode()->hasOneUse()) { 9114 SDValue Int = N0.getOperand(0); 9115 EVT IntVT = Int.getValueType(); 9116 if (IntVT.isInteger() && !IntVT.isVector()) { 9117 APInt SignMask; 9118 if (N0.getValueType().isVector()) { 9119 // For a vector, get a mask such as 0x80... per scalar element 9120 // and splat it. 9121 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9122 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9123 } else { 9124 // For a scalar, just generate 0x80... 9125 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9126 } 9127 SDLoc DL0(N0); 9128 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9129 DAG.getConstant(SignMask, DL0, IntVT)); 9130 AddToWorklist(Int.getNode()); 9131 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 9132 } 9133 } 9134 9135 // (fneg (fmul c, x)) -> (fmul -c, x) 9136 if (N0.getOpcode() == ISD::FMUL && 9137 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9138 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9139 if (CFP1) { 9140 APFloat CVal = CFP1->getValueAPF(); 9141 CVal.changeSign(); 9142 if (Level >= AfterLegalizeDAG && 9143 (TLI.isFPImmLegal(CVal, VT) || 9144 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9145 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9146 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9147 N0.getOperand(1)), 9148 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9149 } 9150 } 9151 9152 return SDValue(); 9153 } 9154 9155 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9156 SDValue N0 = N->getOperand(0); 9157 SDValue N1 = N->getOperand(1); 9158 EVT VT = N->getValueType(0); 9159 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9160 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9161 9162 if (N0CFP && N1CFP) { 9163 const APFloat &C0 = N0CFP->getValueAPF(); 9164 const APFloat &C1 = N1CFP->getValueAPF(); 9165 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9166 } 9167 9168 // Canonicalize to constant on RHS. 9169 if (isConstantFPBuildVectorOrConstantFP(N0) && 9170 !isConstantFPBuildVectorOrConstantFP(N1)) 9171 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9172 9173 return SDValue(); 9174 } 9175 9176 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9177 SDValue N0 = N->getOperand(0); 9178 SDValue N1 = N->getOperand(1); 9179 EVT VT = N->getValueType(0); 9180 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9181 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9182 9183 if (N0CFP && N1CFP) { 9184 const APFloat &C0 = N0CFP->getValueAPF(); 9185 const APFloat &C1 = N1CFP->getValueAPF(); 9186 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9187 } 9188 9189 // Canonicalize to constant on RHS. 9190 if (isConstantFPBuildVectorOrConstantFP(N0) && 9191 !isConstantFPBuildVectorOrConstantFP(N1)) 9192 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9193 9194 return SDValue(); 9195 } 9196 9197 SDValue DAGCombiner::visitFABS(SDNode *N) { 9198 SDValue N0 = N->getOperand(0); 9199 EVT VT = N->getValueType(0); 9200 9201 // fold (fabs c1) -> fabs(c1) 9202 if (isConstantFPBuildVectorOrConstantFP(N0)) 9203 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9204 9205 // fold (fabs (fabs x)) -> (fabs x) 9206 if (N0.getOpcode() == ISD::FABS) 9207 return N->getOperand(0); 9208 9209 // fold (fabs (fneg x)) -> (fabs x) 9210 // fold (fabs (fcopysign x, y)) -> (fabs x) 9211 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9212 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9213 9214 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9215 // constant pool values. 9216 if (!TLI.isFAbsFree(VT) && 9217 N0.getOpcode() == ISD::BITCAST && 9218 N0.getNode()->hasOneUse()) { 9219 SDValue Int = N0.getOperand(0); 9220 EVT IntVT = Int.getValueType(); 9221 if (IntVT.isInteger() && !IntVT.isVector()) { 9222 APInt SignMask; 9223 if (N0.getValueType().isVector()) { 9224 // For a vector, get a mask such as 0x7f... per scalar element 9225 // and splat it. 9226 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9227 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9228 } else { 9229 // For a scalar, just generate 0x7f... 9230 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9231 } 9232 SDLoc DL(N0); 9233 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9234 DAG.getConstant(SignMask, DL, IntVT)); 9235 AddToWorklist(Int.getNode()); 9236 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 9237 } 9238 } 9239 9240 return SDValue(); 9241 } 9242 9243 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9244 SDValue Chain = N->getOperand(0); 9245 SDValue N1 = N->getOperand(1); 9246 SDValue N2 = N->getOperand(2); 9247 9248 // If N is a constant we could fold this into a fallthrough or unconditional 9249 // branch. However that doesn't happen very often in normal code, because 9250 // Instcombine/SimplifyCFG should have handled the available opportunities. 9251 // If we did this folding here, it would be necessary to update the 9252 // MachineBasicBlock CFG, which is awkward. 9253 9254 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9255 // on the target. 9256 if (N1.getOpcode() == ISD::SETCC && 9257 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9258 N1.getOperand(0).getValueType())) { 9259 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9260 Chain, N1.getOperand(2), 9261 N1.getOperand(0), N1.getOperand(1), N2); 9262 } 9263 9264 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9265 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9266 (N1.getOperand(0).hasOneUse() && 9267 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9268 SDNode *Trunc = nullptr; 9269 if (N1.getOpcode() == ISD::TRUNCATE) { 9270 // Look pass the truncate. 9271 Trunc = N1.getNode(); 9272 N1 = N1.getOperand(0); 9273 } 9274 9275 // Match this pattern so that we can generate simpler code: 9276 // 9277 // %a = ... 9278 // %b = and i32 %a, 2 9279 // %c = srl i32 %b, 1 9280 // brcond i32 %c ... 9281 // 9282 // into 9283 // 9284 // %a = ... 9285 // %b = and i32 %a, 2 9286 // %c = setcc eq %b, 0 9287 // brcond %c ... 9288 // 9289 // This applies only when the AND constant value has one bit set and the 9290 // SRL constant is equal to the log2 of the AND constant. The back-end is 9291 // smart enough to convert the result into a TEST/JMP sequence. 9292 SDValue Op0 = N1.getOperand(0); 9293 SDValue Op1 = N1.getOperand(1); 9294 9295 if (Op0.getOpcode() == ISD::AND && 9296 Op1.getOpcode() == ISD::Constant) { 9297 SDValue AndOp1 = Op0.getOperand(1); 9298 9299 if (AndOp1.getOpcode() == ISD::Constant) { 9300 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9301 9302 if (AndConst.isPowerOf2() && 9303 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9304 SDLoc DL(N); 9305 SDValue SetCC = 9306 DAG.getSetCC(DL, 9307 getSetCCResultType(Op0.getValueType()), 9308 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9309 ISD::SETNE); 9310 9311 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9312 MVT::Other, Chain, SetCC, N2); 9313 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9314 // will convert it back to (X & C1) >> C2. 9315 CombineTo(N, NewBRCond, false); 9316 // Truncate is dead. 9317 if (Trunc) 9318 deleteAndRecombine(Trunc); 9319 // Replace the uses of SRL with SETCC 9320 WorklistRemover DeadNodes(*this); 9321 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9322 deleteAndRecombine(N1.getNode()); 9323 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9324 } 9325 } 9326 } 9327 9328 if (Trunc) 9329 // Restore N1 if the above transformation doesn't match. 9330 N1 = N->getOperand(1); 9331 } 9332 9333 // Transform br(xor(x, y)) -> br(x != y) 9334 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9335 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9336 SDNode *TheXor = N1.getNode(); 9337 SDValue Op0 = TheXor->getOperand(0); 9338 SDValue Op1 = TheXor->getOperand(1); 9339 if (Op0.getOpcode() == Op1.getOpcode()) { 9340 // Avoid missing important xor optimizations. 9341 if (SDValue Tmp = visitXOR(TheXor)) { 9342 if (Tmp.getNode() != TheXor) { 9343 DEBUG(dbgs() << "\nReplacing.8 "; 9344 TheXor->dump(&DAG); 9345 dbgs() << "\nWith: "; 9346 Tmp.getNode()->dump(&DAG); 9347 dbgs() << '\n'); 9348 WorklistRemover DeadNodes(*this); 9349 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9350 deleteAndRecombine(TheXor); 9351 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9352 MVT::Other, Chain, Tmp, N2); 9353 } 9354 9355 // visitXOR has changed XOR's operands or replaced the XOR completely, 9356 // bail out. 9357 return SDValue(N, 0); 9358 } 9359 } 9360 9361 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9362 bool Equal = false; 9363 if (isOneConstant(Op0) && Op0.hasOneUse() && 9364 Op0.getOpcode() == ISD::XOR) { 9365 TheXor = Op0.getNode(); 9366 Equal = true; 9367 } 9368 9369 EVT SetCCVT = N1.getValueType(); 9370 if (LegalTypes) 9371 SetCCVT = getSetCCResultType(SetCCVT); 9372 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9373 SetCCVT, 9374 Op0, Op1, 9375 Equal ? ISD::SETEQ : ISD::SETNE); 9376 // Replace the uses of XOR with SETCC 9377 WorklistRemover DeadNodes(*this); 9378 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9379 deleteAndRecombine(N1.getNode()); 9380 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9381 MVT::Other, Chain, SetCC, N2); 9382 } 9383 } 9384 9385 return SDValue(); 9386 } 9387 9388 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9389 // 9390 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9391 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9392 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9393 9394 // If N is a constant we could fold this into a fallthrough or unconditional 9395 // branch. However that doesn't happen very often in normal code, because 9396 // Instcombine/SimplifyCFG should have handled the available opportunities. 9397 // If we did this folding here, it would be necessary to update the 9398 // MachineBasicBlock CFG, which is awkward. 9399 9400 // Use SimplifySetCC to simplify SETCC's. 9401 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9402 CondLHS, CondRHS, CC->get(), SDLoc(N), 9403 false); 9404 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9405 9406 // fold to a simpler setcc 9407 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9408 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9409 N->getOperand(0), Simp.getOperand(2), 9410 Simp.getOperand(0), Simp.getOperand(1), 9411 N->getOperand(4)); 9412 9413 return SDValue(); 9414 } 9415 9416 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9417 /// and that N may be folded in the load / store addressing mode. 9418 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9419 SelectionDAG &DAG, 9420 const TargetLowering &TLI) { 9421 EVT VT; 9422 unsigned AS; 9423 9424 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9425 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9426 return false; 9427 VT = LD->getMemoryVT(); 9428 AS = LD->getAddressSpace(); 9429 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9430 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9431 return false; 9432 VT = ST->getMemoryVT(); 9433 AS = ST->getAddressSpace(); 9434 } else 9435 return false; 9436 9437 TargetLowering::AddrMode AM; 9438 if (N->getOpcode() == ISD::ADD) { 9439 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9440 if (Offset) 9441 // [reg +/- imm] 9442 AM.BaseOffs = Offset->getSExtValue(); 9443 else 9444 // [reg +/- reg] 9445 AM.Scale = 1; 9446 } else if (N->getOpcode() == ISD::SUB) { 9447 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9448 if (Offset) 9449 // [reg +/- imm] 9450 AM.BaseOffs = -Offset->getSExtValue(); 9451 else 9452 // [reg +/- reg] 9453 AM.Scale = 1; 9454 } else 9455 return false; 9456 9457 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9458 VT.getTypeForEVT(*DAG.getContext()), AS); 9459 } 9460 9461 /// Try turning a load/store into a pre-indexed load/store when the base 9462 /// pointer is an add or subtract and it has other uses besides the load/store. 9463 /// After the transformation, the new indexed load/store has effectively folded 9464 /// the add/subtract in and all of its other uses are redirected to the 9465 /// new load/store. 9466 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9467 if (Level < AfterLegalizeDAG) 9468 return false; 9469 9470 bool isLoad = true; 9471 SDValue Ptr; 9472 EVT VT; 9473 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9474 if (LD->isIndexed()) 9475 return false; 9476 VT = LD->getMemoryVT(); 9477 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9478 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9479 return false; 9480 Ptr = LD->getBasePtr(); 9481 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9482 if (ST->isIndexed()) 9483 return false; 9484 VT = ST->getMemoryVT(); 9485 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9486 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9487 return false; 9488 Ptr = ST->getBasePtr(); 9489 isLoad = false; 9490 } else { 9491 return false; 9492 } 9493 9494 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9495 // out. There is no reason to make this a preinc/predec. 9496 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9497 Ptr.getNode()->hasOneUse()) 9498 return false; 9499 9500 // Ask the target to do addressing mode selection. 9501 SDValue BasePtr; 9502 SDValue Offset; 9503 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9504 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9505 return false; 9506 9507 // Backends without true r+i pre-indexed forms may need to pass a 9508 // constant base with a variable offset so that constant coercion 9509 // will work with the patterns in canonical form. 9510 bool Swapped = false; 9511 if (isa<ConstantSDNode>(BasePtr)) { 9512 std::swap(BasePtr, Offset); 9513 Swapped = true; 9514 } 9515 9516 // Don't create a indexed load / store with zero offset. 9517 if (isNullConstant(Offset)) 9518 return false; 9519 9520 // Try turning it into a pre-indexed load / store except when: 9521 // 1) The new base ptr is a frame index. 9522 // 2) If N is a store and the new base ptr is either the same as or is a 9523 // predecessor of the value being stored. 9524 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9525 // that would create a cycle. 9526 // 4) All uses are load / store ops that use it as old base ptr. 9527 9528 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9529 // (plus the implicit offset) to a register to preinc anyway. 9530 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9531 return false; 9532 9533 // Check #2. 9534 if (!isLoad) { 9535 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9536 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9537 return false; 9538 } 9539 9540 // If the offset is a constant, there may be other adds of constants that 9541 // can be folded with this one. We should do this to avoid having to keep 9542 // a copy of the original base pointer. 9543 SmallVector<SDNode *, 16> OtherUses; 9544 if (isa<ConstantSDNode>(Offset)) 9545 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9546 UE = BasePtr.getNode()->use_end(); 9547 UI != UE; ++UI) { 9548 SDUse &Use = UI.getUse(); 9549 // Skip the use that is Ptr and uses of other results from BasePtr's 9550 // node (important for nodes that return multiple results). 9551 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9552 continue; 9553 9554 if (Use.getUser()->isPredecessorOf(N)) 9555 continue; 9556 9557 if (Use.getUser()->getOpcode() != ISD::ADD && 9558 Use.getUser()->getOpcode() != ISD::SUB) { 9559 OtherUses.clear(); 9560 break; 9561 } 9562 9563 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9564 if (!isa<ConstantSDNode>(Op1)) { 9565 OtherUses.clear(); 9566 break; 9567 } 9568 9569 // FIXME: In some cases, we can be smarter about this. 9570 if (Op1.getValueType() != Offset.getValueType()) { 9571 OtherUses.clear(); 9572 break; 9573 } 9574 9575 OtherUses.push_back(Use.getUser()); 9576 } 9577 9578 if (Swapped) 9579 std::swap(BasePtr, Offset); 9580 9581 // Now check for #3 and #4. 9582 bool RealUse = false; 9583 9584 // Caches for hasPredecessorHelper 9585 SmallPtrSet<const SDNode *, 32> Visited; 9586 SmallVector<const SDNode *, 16> Worklist; 9587 9588 for (SDNode *Use : Ptr.getNode()->uses()) { 9589 if (Use == N) 9590 continue; 9591 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 9592 return false; 9593 9594 // If Ptr may be folded in addressing mode of other use, then it's 9595 // not profitable to do this transformation. 9596 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9597 RealUse = true; 9598 } 9599 9600 if (!RealUse) 9601 return false; 9602 9603 SDValue Result; 9604 if (isLoad) 9605 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9606 BasePtr, Offset, AM); 9607 else 9608 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9609 BasePtr, Offset, AM); 9610 ++PreIndexedNodes; 9611 ++NodesCombined; 9612 DEBUG(dbgs() << "\nReplacing.4 "; 9613 N->dump(&DAG); 9614 dbgs() << "\nWith: "; 9615 Result.getNode()->dump(&DAG); 9616 dbgs() << '\n'); 9617 WorklistRemover DeadNodes(*this); 9618 if (isLoad) { 9619 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9620 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9621 } else { 9622 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9623 } 9624 9625 // Finally, since the node is now dead, remove it from the graph. 9626 deleteAndRecombine(N); 9627 9628 if (Swapped) 9629 std::swap(BasePtr, Offset); 9630 9631 // Replace other uses of BasePtr that can be updated to use Ptr 9632 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9633 unsigned OffsetIdx = 1; 9634 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9635 OffsetIdx = 0; 9636 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9637 BasePtr.getNode() && "Expected BasePtr operand"); 9638 9639 // We need to replace ptr0 in the following expression: 9640 // x0 * offset0 + y0 * ptr0 = t0 9641 // knowing that 9642 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9643 // 9644 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9645 // indexed load/store and the expresion that needs to be re-written. 9646 // 9647 // Therefore, we have: 9648 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9649 9650 ConstantSDNode *CN = 9651 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9652 int X0, X1, Y0, Y1; 9653 APInt Offset0 = CN->getAPIntValue(); 9654 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9655 9656 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9657 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9658 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9659 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9660 9661 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9662 9663 APInt CNV = Offset0; 9664 if (X0 < 0) CNV = -CNV; 9665 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9666 else CNV = CNV - Offset1; 9667 9668 SDLoc DL(OtherUses[i]); 9669 9670 // We can now generate the new expression. 9671 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9672 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9673 9674 SDValue NewUse = DAG.getNode(Opcode, 9675 DL, 9676 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9677 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9678 deleteAndRecombine(OtherUses[i]); 9679 } 9680 9681 // Replace the uses of Ptr with uses of the updated base value. 9682 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9683 deleteAndRecombine(Ptr.getNode()); 9684 9685 return true; 9686 } 9687 9688 /// Try to combine a load/store with a add/sub of the base pointer node into a 9689 /// post-indexed load/store. The transformation folded the add/subtract into the 9690 /// new indexed load/store effectively and all of its uses are redirected to the 9691 /// new load/store. 9692 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9693 if (Level < AfterLegalizeDAG) 9694 return false; 9695 9696 bool isLoad = true; 9697 SDValue Ptr; 9698 EVT VT; 9699 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9700 if (LD->isIndexed()) 9701 return false; 9702 VT = LD->getMemoryVT(); 9703 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9704 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9705 return false; 9706 Ptr = LD->getBasePtr(); 9707 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9708 if (ST->isIndexed()) 9709 return false; 9710 VT = ST->getMemoryVT(); 9711 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9712 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9713 return false; 9714 Ptr = ST->getBasePtr(); 9715 isLoad = false; 9716 } else { 9717 return false; 9718 } 9719 9720 if (Ptr.getNode()->hasOneUse()) 9721 return false; 9722 9723 for (SDNode *Op : Ptr.getNode()->uses()) { 9724 if (Op == N || 9725 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9726 continue; 9727 9728 SDValue BasePtr; 9729 SDValue Offset; 9730 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9731 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9732 // Don't create a indexed load / store with zero offset. 9733 if (isNullConstant(Offset)) 9734 continue; 9735 9736 // Try turning it into a post-indexed load / store except when 9737 // 1) All uses are load / store ops that use it as base ptr (and 9738 // it may be folded as addressing mmode). 9739 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9740 // nor a successor of N. Otherwise, if Op is folded that would 9741 // create a cycle. 9742 9743 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9744 continue; 9745 9746 // Check for #1. 9747 bool TryNext = false; 9748 for (SDNode *Use : BasePtr.getNode()->uses()) { 9749 if (Use == Ptr.getNode()) 9750 continue; 9751 9752 // If all the uses are load / store addresses, then don't do the 9753 // transformation. 9754 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9755 bool RealUse = false; 9756 for (SDNode *UseUse : Use->uses()) { 9757 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9758 RealUse = true; 9759 } 9760 9761 if (!RealUse) { 9762 TryNext = true; 9763 break; 9764 } 9765 } 9766 } 9767 9768 if (TryNext) 9769 continue; 9770 9771 // Check for #2 9772 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9773 SDValue Result = isLoad 9774 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9775 BasePtr, Offset, AM) 9776 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9777 BasePtr, Offset, AM); 9778 ++PostIndexedNodes; 9779 ++NodesCombined; 9780 DEBUG(dbgs() << "\nReplacing.5 "; 9781 N->dump(&DAG); 9782 dbgs() << "\nWith: "; 9783 Result.getNode()->dump(&DAG); 9784 dbgs() << '\n'); 9785 WorklistRemover DeadNodes(*this); 9786 if (isLoad) { 9787 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9788 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9789 } else { 9790 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9791 } 9792 9793 // Finally, since the node is now dead, remove it from the graph. 9794 deleteAndRecombine(N); 9795 9796 // Replace the uses of Use with uses of the updated base value. 9797 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9798 Result.getValue(isLoad ? 1 : 0)); 9799 deleteAndRecombine(Op); 9800 return true; 9801 } 9802 } 9803 } 9804 9805 return false; 9806 } 9807 9808 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9809 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9810 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9811 assert(AM != ISD::UNINDEXED); 9812 SDValue BP = LD->getOperand(1); 9813 SDValue Inc = LD->getOperand(2); 9814 9815 // Some backends use TargetConstants for load offsets, but don't expect 9816 // TargetConstants in general ADD nodes. We can convert these constants into 9817 // regular Constants (if the constant is not opaque). 9818 assert((Inc.getOpcode() != ISD::TargetConstant || 9819 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9820 "Cannot split out indexing using opaque target constants"); 9821 if (Inc.getOpcode() == ISD::TargetConstant) { 9822 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9823 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9824 ConstInc->getValueType(0)); 9825 } 9826 9827 unsigned Opc = 9828 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9829 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9830 } 9831 9832 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9833 LoadSDNode *LD = cast<LoadSDNode>(N); 9834 SDValue Chain = LD->getChain(); 9835 SDValue Ptr = LD->getBasePtr(); 9836 9837 // If load is not volatile and there are no uses of the loaded value (and 9838 // the updated indexed value in case of indexed loads), change uses of the 9839 // chain value into uses of the chain input (i.e. delete the dead load). 9840 if (!LD->isVolatile()) { 9841 if (N->getValueType(1) == MVT::Other) { 9842 // Unindexed loads. 9843 if (!N->hasAnyUseOfValue(0)) { 9844 // It's not safe to use the two value CombineTo variant here. e.g. 9845 // v1, chain2 = load chain1, loc 9846 // v2, chain3 = load chain2, loc 9847 // v3 = add v2, c 9848 // Now we replace use of chain2 with chain1. This makes the second load 9849 // isomorphic to the one we are deleting, and thus makes this load live. 9850 DEBUG(dbgs() << "\nReplacing.6 "; 9851 N->dump(&DAG); 9852 dbgs() << "\nWith chain: "; 9853 Chain.getNode()->dump(&DAG); 9854 dbgs() << "\n"); 9855 WorklistRemover DeadNodes(*this); 9856 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9857 9858 if (N->use_empty()) 9859 deleteAndRecombine(N); 9860 9861 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9862 } 9863 } else { 9864 // Indexed loads. 9865 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9866 9867 // If this load has an opaque TargetConstant offset, then we cannot split 9868 // the indexing into an add/sub directly (that TargetConstant may not be 9869 // valid for a different type of node, and we cannot convert an opaque 9870 // target constant into a regular constant). 9871 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9872 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9873 9874 if (!N->hasAnyUseOfValue(0) && 9875 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9876 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9877 SDValue Index; 9878 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9879 Index = SplitIndexingFromLoad(LD); 9880 // Try to fold the base pointer arithmetic into subsequent loads and 9881 // stores. 9882 AddUsersToWorklist(N); 9883 } else 9884 Index = DAG.getUNDEF(N->getValueType(1)); 9885 DEBUG(dbgs() << "\nReplacing.7 "; 9886 N->dump(&DAG); 9887 dbgs() << "\nWith: "; 9888 Undef.getNode()->dump(&DAG); 9889 dbgs() << " and 2 other values\n"); 9890 WorklistRemover DeadNodes(*this); 9891 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9892 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9893 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9894 deleteAndRecombine(N); 9895 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9896 } 9897 } 9898 } 9899 9900 // If this load is directly stored, replace the load value with the stored 9901 // value. 9902 // TODO: Handle store large -> read small portion. 9903 // TODO: Handle TRUNCSTORE/LOADEXT 9904 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9905 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9906 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9907 if (PrevST->getBasePtr() == Ptr && 9908 PrevST->getValue().getValueType() == N->getValueType(0)) 9909 return CombineTo(N, Chain.getOperand(1), Chain); 9910 } 9911 } 9912 9913 // Try to infer better alignment information than the load already has. 9914 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9915 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9916 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9917 SDValue NewLoad = 9918 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9919 LD->getValueType(0), 9920 Chain, Ptr, LD->getPointerInfo(), 9921 LD->getMemoryVT(), 9922 LD->isVolatile(), LD->isNonTemporal(), 9923 LD->isInvariant(), Align, LD->getAAInfo()); 9924 if (NewLoad.getNode() != N) 9925 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9926 } 9927 } 9928 } 9929 9930 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 9931 : DAG.getSubtarget().useAA(); 9932 #ifndef NDEBUG 9933 if (CombinerAAOnlyFunc.getNumOccurrences() && 9934 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9935 UseAA = false; 9936 #endif 9937 if (UseAA && LD->isUnindexed()) { 9938 // Walk up chain skipping non-aliasing memory nodes. 9939 SDValue BetterChain = FindBetterChain(N, Chain); 9940 9941 // If there is a better chain. 9942 if (Chain != BetterChain) { 9943 SDValue ReplLoad; 9944 9945 // Replace the chain to void dependency. 9946 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 9947 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 9948 BetterChain, Ptr, LD->getMemOperand()); 9949 } else { 9950 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 9951 LD->getValueType(0), 9952 BetterChain, Ptr, LD->getMemoryVT(), 9953 LD->getMemOperand()); 9954 } 9955 9956 // Create token factor to keep old chain connected. 9957 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9958 MVT::Other, Chain, ReplLoad.getValue(1)); 9959 9960 // Make sure the new and old chains are cleaned up. 9961 AddToWorklist(Token.getNode()); 9962 9963 // Replace uses with load result and token factor. Don't add users 9964 // to work list. 9965 return CombineTo(N, ReplLoad.getValue(0), Token, false); 9966 } 9967 } 9968 9969 // Try transforming N to an indexed load. 9970 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9971 return SDValue(N, 0); 9972 9973 // Try to slice up N to more direct loads if the slices are mapped to 9974 // different register banks or pairing can take place. 9975 if (SliceUpLoad(N)) 9976 return SDValue(N, 0); 9977 9978 return SDValue(); 9979 } 9980 9981 namespace { 9982 /// \brief Helper structure used to slice a load in smaller loads. 9983 /// Basically a slice is obtained from the following sequence: 9984 /// Origin = load Ty1, Base 9985 /// Shift = srl Ty1 Origin, CstTy Amount 9986 /// Inst = trunc Shift to Ty2 9987 /// 9988 /// Then, it will be rewriten into: 9989 /// Slice = load SliceTy, Base + SliceOffset 9990 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 9991 /// 9992 /// SliceTy is deduced from the number of bits that are actually used to 9993 /// build Inst. 9994 struct LoadedSlice { 9995 /// \brief Helper structure used to compute the cost of a slice. 9996 struct Cost { 9997 /// Are we optimizing for code size. 9998 bool ForCodeSize; 9999 /// Various cost. 10000 unsigned Loads; 10001 unsigned Truncates; 10002 unsigned CrossRegisterBanksCopies; 10003 unsigned ZExts; 10004 unsigned Shift; 10005 10006 Cost(bool ForCodeSize = false) 10007 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10008 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10009 10010 /// \brief Get the cost of one isolated slice. 10011 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10012 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10013 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10014 EVT TruncType = LS.Inst->getValueType(0); 10015 EVT LoadedType = LS.getLoadedType(); 10016 if (TruncType != LoadedType && 10017 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10018 ZExts = 1; 10019 } 10020 10021 /// \brief Account for slicing gain in the current cost. 10022 /// Slicing provide a few gains like removing a shift or a 10023 /// truncate. This method allows to grow the cost of the original 10024 /// load with the gain from this slice. 10025 void addSliceGain(const LoadedSlice &LS) { 10026 // Each slice saves a truncate. 10027 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10028 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10029 LS.Inst->getValueType(0))) 10030 ++Truncates; 10031 // If there is a shift amount, this slice gets rid of it. 10032 if (LS.Shift) 10033 ++Shift; 10034 // If this slice can merge a cross register bank copy, account for it. 10035 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10036 ++CrossRegisterBanksCopies; 10037 } 10038 10039 Cost &operator+=(const Cost &RHS) { 10040 Loads += RHS.Loads; 10041 Truncates += RHS.Truncates; 10042 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10043 ZExts += RHS.ZExts; 10044 Shift += RHS.Shift; 10045 return *this; 10046 } 10047 10048 bool operator==(const Cost &RHS) const { 10049 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10050 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10051 ZExts == RHS.ZExts && Shift == RHS.Shift; 10052 } 10053 10054 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10055 10056 bool operator<(const Cost &RHS) const { 10057 // Assume cross register banks copies are as expensive as loads. 10058 // FIXME: Do we want some more target hooks? 10059 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10060 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10061 // Unless we are optimizing for code size, consider the 10062 // expensive operation first. 10063 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10064 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10065 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10066 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10067 } 10068 10069 bool operator>(const Cost &RHS) const { return RHS < *this; } 10070 10071 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10072 10073 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10074 }; 10075 // The last instruction that represent the slice. This should be a 10076 // truncate instruction. 10077 SDNode *Inst; 10078 // The original load instruction. 10079 LoadSDNode *Origin; 10080 // The right shift amount in bits from the original load. 10081 unsigned Shift; 10082 // The DAG from which Origin came from. 10083 // This is used to get some contextual information about legal types, etc. 10084 SelectionDAG *DAG; 10085 10086 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10087 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10088 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10089 10090 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10091 /// \return Result is \p BitWidth and has used bits set to 1 and 10092 /// not used bits set to 0. 10093 APInt getUsedBits() const { 10094 // Reproduce the trunc(lshr) sequence: 10095 // - Start from the truncated value. 10096 // - Zero extend to the desired bit width. 10097 // - Shift left. 10098 assert(Origin && "No original load to compare against."); 10099 unsigned BitWidth = Origin->getValueSizeInBits(0); 10100 assert(Inst && "This slice is not bound to an instruction"); 10101 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10102 "Extracted slice is bigger than the whole type!"); 10103 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10104 UsedBits.setAllBits(); 10105 UsedBits = UsedBits.zext(BitWidth); 10106 UsedBits <<= Shift; 10107 return UsedBits; 10108 } 10109 10110 /// \brief Get the size of the slice to be loaded in bytes. 10111 unsigned getLoadedSize() const { 10112 unsigned SliceSize = getUsedBits().countPopulation(); 10113 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10114 return SliceSize / 8; 10115 } 10116 10117 /// \brief Get the type that will be loaded for this slice. 10118 /// Note: This may not be the final type for the slice. 10119 EVT getLoadedType() const { 10120 assert(DAG && "Missing context"); 10121 LLVMContext &Ctxt = *DAG->getContext(); 10122 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10123 } 10124 10125 /// \brief Get the alignment of the load used for this slice. 10126 unsigned getAlignment() const { 10127 unsigned Alignment = Origin->getAlignment(); 10128 unsigned Offset = getOffsetFromBase(); 10129 if (Offset != 0) 10130 Alignment = MinAlign(Alignment, Alignment + Offset); 10131 return Alignment; 10132 } 10133 10134 /// \brief Check if this slice can be rewritten with legal operations. 10135 bool isLegal() const { 10136 // An invalid slice is not legal. 10137 if (!Origin || !Inst || !DAG) 10138 return false; 10139 10140 // Offsets are for indexed load only, we do not handle that. 10141 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 10142 return false; 10143 10144 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10145 10146 // Check that the type is legal. 10147 EVT SliceType = getLoadedType(); 10148 if (!TLI.isTypeLegal(SliceType)) 10149 return false; 10150 10151 // Check that the load is legal for this type. 10152 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10153 return false; 10154 10155 // Check that the offset can be computed. 10156 // 1. Check its type. 10157 EVT PtrType = Origin->getBasePtr().getValueType(); 10158 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10159 return false; 10160 10161 // 2. Check that it fits in the immediate. 10162 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10163 return false; 10164 10165 // 3. Check that the computation is legal. 10166 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10167 return false; 10168 10169 // Check that the zext is legal if it needs one. 10170 EVT TruncateType = Inst->getValueType(0); 10171 if (TruncateType != SliceType && 10172 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10173 return false; 10174 10175 return true; 10176 } 10177 10178 /// \brief Get the offset in bytes of this slice in the original chunk of 10179 /// bits. 10180 /// \pre DAG != nullptr. 10181 uint64_t getOffsetFromBase() const { 10182 assert(DAG && "Missing context."); 10183 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10184 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10185 uint64_t Offset = Shift / 8; 10186 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10187 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10188 "The size of the original loaded type is not a multiple of a" 10189 " byte."); 10190 // If Offset is bigger than TySizeInBytes, it means we are loading all 10191 // zeros. This should have been optimized before in the process. 10192 assert(TySizeInBytes > Offset && 10193 "Invalid shift amount for given loaded size"); 10194 if (IsBigEndian) 10195 Offset = TySizeInBytes - Offset - getLoadedSize(); 10196 return Offset; 10197 } 10198 10199 /// \brief Generate the sequence of instructions to load the slice 10200 /// represented by this object and redirect the uses of this slice to 10201 /// this new sequence of instructions. 10202 /// \pre this->Inst && this->Origin are valid Instructions and this 10203 /// object passed the legal check: LoadedSlice::isLegal returned true. 10204 /// \return The last instruction of the sequence used to load the slice. 10205 SDValue loadSlice() const { 10206 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10207 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10208 SDValue BaseAddr = OldBaseAddr; 10209 // Get the offset in that chunk of bytes w.r.t. the endianess. 10210 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10211 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10212 if (Offset) { 10213 // BaseAddr = BaseAddr + Offset. 10214 EVT ArithType = BaseAddr.getValueType(); 10215 SDLoc DL(Origin); 10216 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10217 DAG->getConstant(Offset, DL, ArithType)); 10218 } 10219 10220 // Create the type of the loaded slice according to its size. 10221 EVT SliceType = getLoadedType(); 10222 10223 // Create the load for the slice. 10224 SDValue LastInst = DAG->getLoad( 10225 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10226 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 10227 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 10228 // If the final type is not the same as the loaded type, this means that 10229 // we have to pad with zero. Create a zero extend for that. 10230 EVT FinalType = Inst->getValueType(0); 10231 if (SliceType != FinalType) 10232 LastInst = 10233 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10234 return LastInst; 10235 } 10236 10237 /// \brief Check if this slice can be merged with an expensive cross register 10238 /// bank copy. E.g., 10239 /// i = load i32 10240 /// f = bitcast i32 i to float 10241 bool canMergeExpensiveCrossRegisterBankCopy() const { 10242 if (!Inst || !Inst->hasOneUse()) 10243 return false; 10244 SDNode *Use = *Inst->use_begin(); 10245 if (Use->getOpcode() != ISD::BITCAST) 10246 return false; 10247 assert(DAG && "Missing context"); 10248 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10249 EVT ResVT = Use->getValueType(0); 10250 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10251 const TargetRegisterClass *ArgRC = 10252 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10253 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10254 return false; 10255 10256 // At this point, we know that we perform a cross-register-bank copy. 10257 // Check if it is expensive. 10258 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10259 // Assume bitcasts are cheap, unless both register classes do not 10260 // explicitly share a common sub class. 10261 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10262 return false; 10263 10264 // Check if it will be merged with the load. 10265 // 1. Check the alignment constraint. 10266 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10267 ResVT.getTypeForEVT(*DAG->getContext())); 10268 10269 if (RequiredAlignment > getAlignment()) 10270 return false; 10271 10272 // 2. Check that the load is a legal operation for that type. 10273 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10274 return false; 10275 10276 // 3. Check that we do not have a zext in the way. 10277 if (Inst->getValueType(0) != getLoadedType()) 10278 return false; 10279 10280 return true; 10281 } 10282 }; 10283 } 10284 10285 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10286 /// \p UsedBits looks like 0..0 1..1 0..0. 10287 static bool areUsedBitsDense(const APInt &UsedBits) { 10288 // If all the bits are one, this is dense! 10289 if (UsedBits.isAllOnesValue()) 10290 return true; 10291 10292 // Get rid of the unused bits on the right. 10293 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10294 // Get rid of the unused bits on the left. 10295 if (NarrowedUsedBits.countLeadingZeros()) 10296 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10297 // Check that the chunk of bits is completely used. 10298 return NarrowedUsedBits.isAllOnesValue(); 10299 } 10300 10301 /// \brief Check whether or not \p First and \p Second are next to each other 10302 /// in memory. This means that there is no hole between the bits loaded 10303 /// by \p First and the bits loaded by \p Second. 10304 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10305 const LoadedSlice &Second) { 10306 assert(First.Origin == Second.Origin && First.Origin && 10307 "Unable to match different memory origins."); 10308 APInt UsedBits = First.getUsedBits(); 10309 assert((UsedBits & Second.getUsedBits()) == 0 && 10310 "Slices are not supposed to overlap."); 10311 UsedBits |= Second.getUsedBits(); 10312 return areUsedBitsDense(UsedBits); 10313 } 10314 10315 /// \brief Adjust the \p GlobalLSCost according to the target 10316 /// paring capabilities and the layout of the slices. 10317 /// \pre \p GlobalLSCost should account for at least as many loads as 10318 /// there is in the slices in \p LoadedSlices. 10319 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10320 LoadedSlice::Cost &GlobalLSCost) { 10321 unsigned NumberOfSlices = LoadedSlices.size(); 10322 // If there is less than 2 elements, no pairing is possible. 10323 if (NumberOfSlices < 2) 10324 return; 10325 10326 // Sort the slices so that elements that are likely to be next to each 10327 // other in memory are next to each other in the list. 10328 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10329 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10330 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10331 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10332 }); 10333 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10334 // First (resp. Second) is the first (resp. Second) potentially candidate 10335 // to be placed in a paired load. 10336 const LoadedSlice *First = nullptr; 10337 const LoadedSlice *Second = nullptr; 10338 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10339 // Set the beginning of the pair. 10340 First = Second) { 10341 10342 Second = &LoadedSlices[CurrSlice]; 10343 10344 // If First is NULL, it means we start a new pair. 10345 // Get to the next slice. 10346 if (!First) 10347 continue; 10348 10349 EVT LoadedType = First->getLoadedType(); 10350 10351 // If the types of the slices are different, we cannot pair them. 10352 if (LoadedType != Second->getLoadedType()) 10353 continue; 10354 10355 // Check if the target supplies paired loads for this type. 10356 unsigned RequiredAlignment = 0; 10357 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10358 // move to the next pair, this type is hopeless. 10359 Second = nullptr; 10360 continue; 10361 } 10362 // Check if we meet the alignment requirement. 10363 if (RequiredAlignment > First->getAlignment()) 10364 continue; 10365 10366 // Check that both loads are next to each other in memory. 10367 if (!areSlicesNextToEachOther(*First, *Second)) 10368 continue; 10369 10370 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10371 --GlobalLSCost.Loads; 10372 // Move to the next pair. 10373 Second = nullptr; 10374 } 10375 } 10376 10377 /// \brief Check the profitability of all involved LoadedSlice. 10378 /// Currently, it is considered profitable if there is exactly two 10379 /// involved slices (1) which are (2) next to each other in memory, and 10380 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10381 /// 10382 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10383 /// the elements themselves. 10384 /// 10385 /// FIXME: When the cost model will be mature enough, we can relax 10386 /// constraints (1) and (2). 10387 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10388 const APInt &UsedBits, bool ForCodeSize) { 10389 unsigned NumberOfSlices = LoadedSlices.size(); 10390 if (StressLoadSlicing) 10391 return NumberOfSlices > 1; 10392 10393 // Check (1). 10394 if (NumberOfSlices != 2) 10395 return false; 10396 10397 // Check (2). 10398 if (!areUsedBitsDense(UsedBits)) 10399 return false; 10400 10401 // Check (3). 10402 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10403 // The original code has one big load. 10404 OrigCost.Loads = 1; 10405 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10406 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10407 // Accumulate the cost of all the slices. 10408 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10409 GlobalSlicingCost += SliceCost; 10410 10411 // Account as cost in the original configuration the gain obtained 10412 // with the current slices. 10413 OrigCost.addSliceGain(LS); 10414 } 10415 10416 // If the target supports paired load, adjust the cost accordingly. 10417 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10418 return OrigCost > GlobalSlicingCost; 10419 } 10420 10421 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10422 /// operations, split it in the various pieces being extracted. 10423 /// 10424 /// This sort of thing is introduced by SROA. 10425 /// This slicing takes care not to insert overlapping loads. 10426 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10427 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10428 if (Level < AfterLegalizeDAG) 10429 return false; 10430 10431 LoadSDNode *LD = cast<LoadSDNode>(N); 10432 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10433 !LD->getValueType(0).isInteger()) 10434 return false; 10435 10436 // Keep track of already used bits to detect overlapping values. 10437 // In that case, we will just abort the transformation. 10438 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10439 10440 SmallVector<LoadedSlice, 4> LoadedSlices; 10441 10442 // Check if this load is used as several smaller chunks of bits. 10443 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10444 // of computation for each trunc. 10445 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10446 UI != UIEnd; ++UI) { 10447 // Skip the uses of the chain. 10448 if (UI.getUse().getResNo() != 0) 10449 continue; 10450 10451 SDNode *User = *UI; 10452 unsigned Shift = 0; 10453 10454 // Check if this is a trunc(lshr). 10455 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10456 isa<ConstantSDNode>(User->getOperand(1))) { 10457 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10458 User = *User->use_begin(); 10459 } 10460 10461 // At this point, User is a Truncate, iff we encountered, trunc or 10462 // trunc(lshr). 10463 if (User->getOpcode() != ISD::TRUNCATE) 10464 return false; 10465 10466 // The width of the type must be a power of 2 and greater than 8-bits. 10467 // Otherwise the load cannot be represented in LLVM IR. 10468 // Moreover, if we shifted with a non-8-bits multiple, the slice 10469 // will be across several bytes. We do not support that. 10470 unsigned Width = User->getValueSizeInBits(0); 10471 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10472 return 0; 10473 10474 // Build the slice for this chain of computations. 10475 LoadedSlice LS(User, LD, Shift, &DAG); 10476 APInt CurrentUsedBits = LS.getUsedBits(); 10477 10478 // Check if this slice overlaps with another. 10479 if ((CurrentUsedBits & UsedBits) != 0) 10480 return false; 10481 // Update the bits used globally. 10482 UsedBits |= CurrentUsedBits; 10483 10484 // Check if the new slice would be legal. 10485 if (!LS.isLegal()) 10486 return false; 10487 10488 // Record the slice. 10489 LoadedSlices.push_back(LS); 10490 } 10491 10492 // Abort slicing if it does not seem to be profitable. 10493 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10494 return false; 10495 10496 ++SlicedLoads; 10497 10498 // Rewrite each chain to use an independent load. 10499 // By construction, each chain can be represented by a unique load. 10500 10501 // Prepare the argument for the new token factor for all the slices. 10502 SmallVector<SDValue, 8> ArgChains; 10503 for (SmallVectorImpl<LoadedSlice>::const_iterator 10504 LSIt = LoadedSlices.begin(), 10505 LSItEnd = LoadedSlices.end(); 10506 LSIt != LSItEnd; ++LSIt) { 10507 SDValue SliceInst = LSIt->loadSlice(); 10508 CombineTo(LSIt->Inst, SliceInst, true); 10509 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10510 SliceInst = SliceInst.getOperand(0); 10511 assert(SliceInst->getOpcode() == ISD::LOAD && 10512 "It takes more than a zext to get to the loaded slice!!"); 10513 ArgChains.push_back(SliceInst.getValue(1)); 10514 } 10515 10516 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10517 ArgChains); 10518 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10519 return true; 10520 } 10521 10522 /// Check to see if V is (and load (ptr), imm), where the load is having 10523 /// specific bytes cleared out. If so, return the byte size being masked out 10524 /// and the shift amount. 10525 static std::pair<unsigned, unsigned> 10526 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10527 std::pair<unsigned, unsigned> Result(0, 0); 10528 10529 // Check for the structure we're looking for. 10530 if (V->getOpcode() != ISD::AND || 10531 !isa<ConstantSDNode>(V->getOperand(1)) || 10532 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10533 return Result; 10534 10535 // Check the chain and pointer. 10536 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10537 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10538 10539 // The store should be chained directly to the load or be an operand of a 10540 // tokenfactor. 10541 if (LD == Chain.getNode()) 10542 ; // ok. 10543 else if (Chain->getOpcode() != ISD::TokenFactor) 10544 return Result; // Fail. 10545 else { 10546 bool isOk = false; 10547 for (const SDValue &ChainOp : Chain->op_values()) 10548 if (ChainOp.getNode() == LD) { 10549 isOk = true; 10550 break; 10551 } 10552 if (!isOk) return Result; 10553 } 10554 10555 // This only handles simple types. 10556 if (V.getValueType() != MVT::i16 && 10557 V.getValueType() != MVT::i32 && 10558 V.getValueType() != MVT::i64) 10559 return Result; 10560 10561 // Check the constant mask. Invert it so that the bits being masked out are 10562 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10563 // follow the sign bit for uniformity. 10564 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10565 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10566 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10567 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10568 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10569 if (NotMaskLZ == 64) return Result; // All zero mask. 10570 10571 // See if we have a continuous run of bits. If so, we have 0*1+0* 10572 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10573 return Result; 10574 10575 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10576 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10577 NotMaskLZ -= 64-V.getValueSizeInBits(); 10578 10579 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10580 switch (MaskedBytes) { 10581 case 1: 10582 case 2: 10583 case 4: break; 10584 default: return Result; // All one mask, or 5-byte mask. 10585 } 10586 10587 // Verify that the first bit starts at a multiple of mask so that the access 10588 // is aligned the same as the access width. 10589 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10590 10591 Result.first = MaskedBytes; 10592 Result.second = NotMaskTZ/8; 10593 return Result; 10594 } 10595 10596 10597 /// Check to see if IVal is something that provides a value as specified by 10598 /// MaskInfo. If so, replace the specified store with a narrower store of 10599 /// truncated IVal. 10600 static SDNode * 10601 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10602 SDValue IVal, StoreSDNode *St, 10603 DAGCombiner *DC) { 10604 unsigned NumBytes = MaskInfo.first; 10605 unsigned ByteShift = MaskInfo.second; 10606 SelectionDAG &DAG = DC->getDAG(); 10607 10608 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10609 // that uses this. If not, this is not a replacement. 10610 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10611 ByteShift*8, (ByteShift+NumBytes)*8); 10612 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10613 10614 // Check that it is legal on the target to do this. It is legal if the new 10615 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10616 // legalization. 10617 MVT VT = MVT::getIntegerVT(NumBytes*8); 10618 if (!DC->isTypeLegal(VT)) 10619 return nullptr; 10620 10621 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10622 // shifted by ByteShift and truncated down to NumBytes. 10623 if (ByteShift) { 10624 SDLoc DL(IVal); 10625 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10626 DAG.getConstant(ByteShift*8, DL, 10627 DC->getShiftAmountTy(IVal.getValueType()))); 10628 } 10629 10630 // Figure out the offset for the store and the alignment of the access. 10631 unsigned StOffset; 10632 unsigned NewAlign = St->getAlignment(); 10633 10634 if (DAG.getDataLayout().isLittleEndian()) 10635 StOffset = ByteShift; 10636 else 10637 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10638 10639 SDValue Ptr = St->getBasePtr(); 10640 if (StOffset) { 10641 SDLoc DL(IVal); 10642 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10643 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10644 NewAlign = MinAlign(NewAlign, StOffset); 10645 } 10646 10647 // Truncate down to the new size. 10648 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10649 10650 ++OpsNarrowed; 10651 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10652 St->getPointerInfo().getWithOffset(StOffset), 10653 false, false, NewAlign).getNode(); 10654 } 10655 10656 10657 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10658 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10659 /// narrowing the load and store if it would end up being a win for performance 10660 /// or code size. 10661 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10662 StoreSDNode *ST = cast<StoreSDNode>(N); 10663 if (ST->isVolatile()) 10664 return SDValue(); 10665 10666 SDValue Chain = ST->getChain(); 10667 SDValue Value = ST->getValue(); 10668 SDValue Ptr = ST->getBasePtr(); 10669 EVT VT = Value.getValueType(); 10670 10671 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10672 return SDValue(); 10673 10674 unsigned Opc = Value.getOpcode(); 10675 10676 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10677 // is a byte mask indicating a consecutive number of bytes, check to see if 10678 // Y is known to provide just those bytes. If so, we try to replace the 10679 // load + replace + store sequence with a single (narrower) store, which makes 10680 // the load dead. 10681 if (Opc == ISD::OR) { 10682 std::pair<unsigned, unsigned> MaskedLoad; 10683 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10684 if (MaskedLoad.first) 10685 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10686 Value.getOperand(1), ST,this)) 10687 return SDValue(NewST, 0); 10688 10689 // Or is commutative, so try swapping X and Y. 10690 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10691 if (MaskedLoad.first) 10692 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10693 Value.getOperand(0), ST,this)) 10694 return SDValue(NewST, 0); 10695 } 10696 10697 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10698 Value.getOperand(1).getOpcode() != ISD::Constant) 10699 return SDValue(); 10700 10701 SDValue N0 = Value.getOperand(0); 10702 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10703 Chain == SDValue(N0.getNode(), 1)) { 10704 LoadSDNode *LD = cast<LoadSDNode>(N0); 10705 if (LD->getBasePtr() != Ptr || 10706 LD->getPointerInfo().getAddrSpace() != 10707 ST->getPointerInfo().getAddrSpace()) 10708 return SDValue(); 10709 10710 // Find the type to narrow it the load / op / store to. 10711 SDValue N1 = Value.getOperand(1); 10712 unsigned BitWidth = N1.getValueSizeInBits(); 10713 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10714 if (Opc == ISD::AND) 10715 Imm ^= APInt::getAllOnesValue(BitWidth); 10716 if (Imm == 0 || Imm.isAllOnesValue()) 10717 return SDValue(); 10718 unsigned ShAmt = Imm.countTrailingZeros(); 10719 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10720 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10721 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10722 // The narrowing should be profitable, the load/store operation should be 10723 // legal (or custom) and the store size should be equal to the NewVT width. 10724 while (NewBW < BitWidth && 10725 (NewVT.getStoreSizeInBits() != NewBW || 10726 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10727 !TLI.isNarrowingProfitable(VT, NewVT))) { 10728 NewBW = NextPowerOf2(NewBW); 10729 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10730 } 10731 if (NewBW >= BitWidth) 10732 return SDValue(); 10733 10734 // If the lsb changed does not start at the type bitwidth boundary, 10735 // start at the previous one. 10736 if (ShAmt % NewBW) 10737 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10738 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10739 std::min(BitWidth, ShAmt + NewBW)); 10740 if ((Imm & Mask) == Imm) { 10741 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10742 if (Opc == ISD::AND) 10743 NewImm ^= APInt::getAllOnesValue(NewBW); 10744 uint64_t PtrOff = ShAmt / 8; 10745 // For big endian targets, we need to adjust the offset to the pointer to 10746 // load the correct bytes. 10747 if (DAG.getDataLayout().isBigEndian()) 10748 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10749 10750 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10751 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10752 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10753 return SDValue(); 10754 10755 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10756 Ptr.getValueType(), Ptr, 10757 DAG.getConstant(PtrOff, SDLoc(LD), 10758 Ptr.getValueType())); 10759 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10760 LD->getChain(), NewPtr, 10761 LD->getPointerInfo().getWithOffset(PtrOff), 10762 LD->isVolatile(), LD->isNonTemporal(), 10763 LD->isInvariant(), NewAlign, 10764 LD->getAAInfo()); 10765 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10766 DAG.getConstant(NewImm, SDLoc(Value), 10767 NewVT)); 10768 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10769 NewVal, NewPtr, 10770 ST->getPointerInfo().getWithOffset(PtrOff), 10771 false, false, NewAlign); 10772 10773 AddToWorklist(NewPtr.getNode()); 10774 AddToWorklist(NewLD.getNode()); 10775 AddToWorklist(NewVal.getNode()); 10776 WorklistRemover DeadNodes(*this); 10777 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10778 ++OpsNarrowed; 10779 return NewST; 10780 } 10781 } 10782 10783 return SDValue(); 10784 } 10785 10786 /// For a given floating point load / store pair, if the load value isn't used 10787 /// by any other operations, then consider transforming the pair to integer 10788 /// load / store operations if the target deems the transformation profitable. 10789 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10790 StoreSDNode *ST = cast<StoreSDNode>(N); 10791 SDValue Chain = ST->getChain(); 10792 SDValue Value = ST->getValue(); 10793 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10794 Value.hasOneUse() && 10795 Chain == SDValue(Value.getNode(), 1)) { 10796 LoadSDNode *LD = cast<LoadSDNode>(Value); 10797 EVT VT = LD->getMemoryVT(); 10798 if (!VT.isFloatingPoint() || 10799 VT != ST->getMemoryVT() || 10800 LD->isNonTemporal() || 10801 ST->isNonTemporal() || 10802 LD->getPointerInfo().getAddrSpace() != 0 || 10803 ST->getPointerInfo().getAddrSpace() != 0) 10804 return SDValue(); 10805 10806 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10807 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10808 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10809 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10810 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10811 return SDValue(); 10812 10813 unsigned LDAlign = LD->getAlignment(); 10814 unsigned STAlign = ST->getAlignment(); 10815 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10816 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 10817 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10818 return SDValue(); 10819 10820 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10821 LD->getChain(), LD->getBasePtr(), 10822 LD->getPointerInfo(), 10823 false, false, false, LDAlign); 10824 10825 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10826 NewLD, ST->getBasePtr(), 10827 ST->getPointerInfo(), 10828 false, false, STAlign); 10829 10830 AddToWorklist(NewLD.getNode()); 10831 AddToWorklist(NewST.getNode()); 10832 WorklistRemover DeadNodes(*this); 10833 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10834 ++LdStFP2Int; 10835 return NewST; 10836 } 10837 10838 return SDValue(); 10839 } 10840 10841 namespace { 10842 /// Helper struct to parse and store a memory address as base + index + offset. 10843 /// We ignore sign extensions when it is safe to do so. 10844 /// The following two expressions are not equivalent. To differentiate we need 10845 /// to store whether there was a sign extension involved in the index 10846 /// computation. 10847 /// (load (i64 add (i64 copyfromreg %c) 10848 /// (i64 signextend (add (i8 load %index) 10849 /// (i8 1)))) 10850 /// vs 10851 /// 10852 /// (load (i64 add (i64 copyfromreg %c) 10853 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10854 /// (i32 1))))) 10855 struct BaseIndexOffset { 10856 SDValue Base; 10857 SDValue Index; 10858 int64_t Offset; 10859 bool IsIndexSignExt; 10860 10861 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10862 10863 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10864 bool IsIndexSignExt) : 10865 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10866 10867 bool equalBaseIndex(const BaseIndexOffset &Other) { 10868 return Other.Base == Base && Other.Index == Index && 10869 Other.IsIndexSignExt == IsIndexSignExt; 10870 } 10871 10872 /// Parses tree in Ptr for base, index, offset addresses. 10873 static BaseIndexOffset match(SDValue Ptr) { 10874 bool IsIndexSignExt = false; 10875 10876 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10877 // instruction, then it could be just the BASE or everything else we don't 10878 // know how to handle. Just use Ptr as BASE and give up. 10879 if (Ptr->getOpcode() != ISD::ADD) 10880 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10881 10882 // We know that we have at least an ADD instruction. Try to pattern match 10883 // the simple case of BASE + OFFSET. 10884 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10885 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10886 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10887 IsIndexSignExt); 10888 } 10889 10890 // Inside a loop the current BASE pointer is calculated using an ADD and a 10891 // MUL instruction. In this case Ptr is the actual BASE pointer. 10892 // (i64 add (i64 %array_ptr) 10893 // (i64 mul (i64 %induction_var) 10894 // (i64 %element_size))) 10895 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10896 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10897 10898 // Look at Base + Index + Offset cases. 10899 SDValue Base = Ptr->getOperand(0); 10900 SDValue IndexOffset = Ptr->getOperand(1); 10901 10902 // Skip signextends. 10903 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10904 IndexOffset = IndexOffset->getOperand(0); 10905 IsIndexSignExt = true; 10906 } 10907 10908 // Either the case of Base + Index (no offset) or something else. 10909 if (IndexOffset->getOpcode() != ISD::ADD) 10910 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10911 10912 // Now we have the case of Base + Index + offset. 10913 SDValue Index = IndexOffset->getOperand(0); 10914 SDValue Offset = IndexOffset->getOperand(1); 10915 10916 if (!isa<ConstantSDNode>(Offset)) 10917 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10918 10919 // Ignore signextends. 10920 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 10921 Index = Index->getOperand(0); 10922 IsIndexSignExt = true; 10923 } else IsIndexSignExt = false; 10924 10925 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 10926 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 10927 } 10928 }; 10929 } // namespace 10930 10931 // This is a helper function for visitMUL to check the profitability 10932 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 10933 // MulNode is the original multiply, AddNode is (add x, c1), 10934 // and ConstNode is c2. 10935 // 10936 // If the (add x, c1) has multiple uses, we could increase 10937 // the number of adds if we make this transformation. 10938 // It would only be worth doing this if we can remove a 10939 // multiply in the process. Check for that here. 10940 // To illustrate: 10941 // (A + c1) * c3 10942 // (A + c2) * c3 10943 // We're checking for cases where we have common "c3 * A" expressions. 10944 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 10945 SDValue &AddNode, 10946 SDValue &ConstNode) { 10947 APInt Val; 10948 10949 // If the add only has one use, this would be OK to do. 10950 if (AddNode.getNode()->hasOneUse()) 10951 return true; 10952 10953 // Walk all the users of the constant with which we're multiplying. 10954 for (SDNode *Use : ConstNode->uses()) { 10955 10956 if (Use == MulNode) // This use is the one we're on right now. Skip it. 10957 continue; 10958 10959 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 10960 SDNode *OtherOp; 10961 SDNode *MulVar = AddNode.getOperand(0).getNode(); 10962 10963 // OtherOp is what we're multiplying against the constant. 10964 if (Use->getOperand(0) == ConstNode) 10965 OtherOp = Use->getOperand(1).getNode(); 10966 else 10967 OtherOp = Use->getOperand(0).getNode(); 10968 10969 // Check to see if multiply is with the same operand of our "add". 10970 // 10971 // ConstNode = CONST 10972 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 10973 // ... 10974 // AddNode = (A + c1) <-- MulVar is A. 10975 // = AddNode * ConstNode <-- current visiting instruction. 10976 // 10977 // If we make this transformation, we will have a common 10978 // multiply (ConstNode * A) that we can save. 10979 if (OtherOp == MulVar) 10980 return true; 10981 10982 // Now check to see if a future expansion will give us a common 10983 // multiply. 10984 // 10985 // ConstNode = CONST 10986 // AddNode = (A + c1) 10987 // ... = AddNode * ConstNode <-- current visiting instruction. 10988 // ... 10989 // OtherOp = (A + c2) 10990 // Use = OtherOp * ConstNode <-- visiting Use. 10991 // 10992 // If we make this transformation, we will have a common 10993 // multiply (CONST * A) after we also do the same transformation 10994 // to the "t2" instruction. 10995 if (OtherOp->getOpcode() == ISD::ADD && 10996 isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 10997 OtherOp->getOperand(0).getNode() == MulVar) 10998 return true; 10999 } 11000 } 11001 11002 // Didn't find a case where this would be profitable. 11003 return false; 11004 } 11005 11006 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG, 11007 SDLoc SL, 11008 ArrayRef<MemOpLink> Stores, 11009 SmallVectorImpl<SDValue> &Chains, 11010 EVT Ty) const { 11011 SmallVector<SDValue, 8> BuildVector; 11012 11013 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11014 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11015 Chains.push_back(St->getChain()); 11016 BuildVector.push_back(St->getValue()); 11017 } 11018 11019 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector); 11020 } 11021 11022 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11023 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11024 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11025 // Make sure we have something to merge. 11026 if (NumStores < 2) 11027 return false; 11028 11029 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11030 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11031 unsigned LatestNodeUsed = 0; 11032 11033 for (unsigned i=0; i < NumStores; ++i) { 11034 // Find a chain for the new wide-store operand. Notice that some 11035 // of the store nodes that we found may not be selected for inclusion 11036 // in the wide store. The chain we use needs to be the chain of the 11037 // latest store node which is *used* and replaced by the wide store. 11038 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11039 LatestNodeUsed = i; 11040 } 11041 11042 SmallVector<SDValue, 8> Chains; 11043 11044 // The latest Node in the DAG. 11045 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11046 SDLoc DL(StoreNodes[0].MemNode); 11047 11048 SDValue StoredVal; 11049 if (UseVector) { 11050 bool IsVec = MemVT.isVector(); 11051 unsigned Elts = NumStores; 11052 if (IsVec) { 11053 // When merging vector stores, get the total number of elements. 11054 Elts *= MemVT.getVectorNumElements(); 11055 } 11056 // Get the type for the merged vector store. 11057 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11058 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11059 11060 if (IsConstantSrc) { 11061 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11062 } else { 11063 SmallVector<SDValue, 8> Ops; 11064 for (unsigned i = 0; i < NumStores; ++i) { 11065 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11066 SDValue Val = St->getValue(); 11067 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11068 if (Val.getValueType() != MemVT) 11069 return false; 11070 Ops.push_back(Val); 11071 Chains.push_back(St->getChain()); 11072 } 11073 11074 // Build the extracted vector elements back into a vector. 11075 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11076 DL, Ty, Ops); } 11077 } else { 11078 // We should always use a vector store when merging extracted vector 11079 // elements, so this path implies a store of constants. 11080 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11081 11082 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11083 APInt StoreInt(SizeInBits, 0); 11084 11085 // Construct a single integer constant which is made of the smaller 11086 // constant inputs. 11087 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11088 for (unsigned i = 0; i < NumStores; ++i) { 11089 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11090 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11091 Chains.push_back(St->getChain()); 11092 11093 SDValue Val = St->getValue(); 11094 StoreInt <<= ElementSizeBytes * 8; 11095 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11096 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11097 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11098 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11099 } else { 11100 llvm_unreachable("Invalid constant element type"); 11101 } 11102 } 11103 11104 // Create the new Load and Store operations. 11105 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11106 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11107 } 11108 11109 assert(!Chains.empty()); 11110 11111 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11112 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11113 FirstInChain->getBasePtr(), 11114 FirstInChain->getPointerInfo(), 11115 false, false, 11116 FirstInChain->getAlignment()); 11117 11118 // Replace the last store with the new store 11119 CombineTo(LatestOp, NewStore); 11120 // Erase all other stores. 11121 for (unsigned i = 0; i < NumStores; ++i) { 11122 if (StoreNodes[i].MemNode == LatestOp) 11123 continue; 11124 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11125 // ReplaceAllUsesWith will replace all uses that existed when it was 11126 // called, but graph optimizations may cause new ones to appear. For 11127 // example, the case in pr14333 looks like 11128 // 11129 // St's chain -> St -> another store -> X 11130 // 11131 // And the only difference from St to the other store is the chain. 11132 // When we change it's chain to be St's chain they become identical, 11133 // get CSEed and the net result is that X is now a use of St. 11134 // Since we know that St is redundant, just iterate. 11135 while (!St->use_empty()) 11136 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11137 deleteAndRecombine(St); 11138 } 11139 11140 return true; 11141 } 11142 11143 void DAGCombiner::getStoreMergeAndAliasCandidates( 11144 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11145 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11146 // This holds the base pointer, index, and the offset in bytes from the base 11147 // pointer. 11148 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 11149 11150 // We must have a base and an offset. 11151 if (!BasePtr.Base.getNode()) 11152 return; 11153 11154 // Do not handle stores to undef base pointers. 11155 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 11156 return; 11157 11158 // Walk up the chain and look for nodes with offsets from the same 11159 // base pointer. Stop when reaching an instruction with a different kind 11160 // or instruction which has a different base pointer. 11161 EVT MemVT = St->getMemoryVT(); 11162 unsigned Seq = 0; 11163 StoreSDNode *Index = St; 11164 11165 11166 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11167 : DAG.getSubtarget().useAA(); 11168 11169 if (UseAA) { 11170 // Look at other users of the same chain. Stores on the same chain do not 11171 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11172 // to be on the same chain, so don't bother looking at adjacent chains. 11173 11174 SDValue Chain = St->getChain(); 11175 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11176 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11177 if (I.getOperandNo() != 0) 11178 continue; 11179 11180 if (OtherST->isVolatile() || OtherST->isIndexed()) 11181 continue; 11182 11183 if (OtherST->getMemoryVT() != MemVT) 11184 continue; 11185 11186 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr()); 11187 11188 if (Ptr.equalBaseIndex(BasePtr)) 11189 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11190 } 11191 } 11192 11193 return; 11194 } 11195 11196 while (Index) { 11197 // If the chain has more than one use, then we can't reorder the mem ops. 11198 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11199 break; 11200 11201 // Find the base pointer and offset for this memory node. 11202 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 11203 11204 // Check that the base pointer is the same as the original one. 11205 if (!Ptr.equalBaseIndex(BasePtr)) 11206 break; 11207 11208 // The memory operands must not be volatile. 11209 if (Index->isVolatile() || Index->isIndexed()) 11210 break; 11211 11212 // No truncation. 11213 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 11214 if (St->isTruncatingStore()) 11215 break; 11216 11217 // The stored memory type must be the same. 11218 if (Index->getMemoryVT() != MemVT) 11219 break; 11220 11221 // We do not allow under-aligned stores in order to prevent 11222 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11223 // be irrelevant here; what MATTERS is that we not move memory 11224 // operations that potentially overlap past each-other. 11225 if (Index->getAlignment() < MemVT.getStoreSize()) 11226 break; 11227 11228 // We found a potential memory operand to merge. 11229 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11230 11231 // Find the next memory operand in the chain. If the next operand in the 11232 // chain is a store then move up and continue the scan with the next 11233 // memory operand. If the next operand is a load save it and use alias 11234 // information to check if it interferes with anything. 11235 SDNode *NextInChain = Index->getChain().getNode(); 11236 while (1) { 11237 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11238 // We found a store node. Use it for the next iteration. 11239 Index = STn; 11240 break; 11241 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11242 if (Ldn->isVolatile()) { 11243 Index = nullptr; 11244 break; 11245 } 11246 11247 // Save the load node for later. Continue the scan. 11248 AliasLoadNodes.push_back(Ldn); 11249 NextInChain = Ldn->getChain().getNode(); 11250 continue; 11251 } else { 11252 Index = nullptr; 11253 break; 11254 } 11255 } 11256 } 11257 } 11258 11259 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11260 if (OptLevel == CodeGenOpt::None) 11261 return false; 11262 11263 EVT MemVT = St->getMemoryVT(); 11264 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11265 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11266 Attribute::NoImplicitFloat); 11267 11268 // This function cannot currently deal with non-byte-sized memory sizes. 11269 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11270 return false; 11271 11272 if (!MemVT.isSimple()) 11273 return false; 11274 11275 // Perform an early exit check. Do not bother looking at stored values that 11276 // are not constants, loads, or extracted vector elements. 11277 SDValue StoredVal = St->getValue(); 11278 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11279 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11280 isa<ConstantFPSDNode>(StoredVal); 11281 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11282 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11283 11284 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11285 return false; 11286 11287 // Don't merge vectors into wider vectors if the source data comes from loads. 11288 // TODO: This restriction can be lifted by using logic similar to the 11289 // ExtractVecSrc case. 11290 if (MemVT.isVector() && IsLoadSrc) 11291 return false; 11292 11293 // Only look at ends of store sequences. 11294 SDValue Chain = SDValue(St, 0); 11295 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11296 return false; 11297 11298 // Save the LoadSDNodes that we find in the chain. 11299 // We need to make sure that these nodes do not interfere with 11300 // any of the store nodes. 11301 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11302 11303 // Save the StoreSDNodes that we find in the chain. 11304 SmallVector<MemOpLink, 8> StoreNodes; 11305 11306 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11307 11308 // Check if there is anything to merge. 11309 if (StoreNodes.size() < 2) 11310 return false; 11311 11312 // Sort the memory operands according to their distance from the 11313 // base pointer. As a secondary criteria: make sure stores coming 11314 // later in the code come first in the list. This is important for 11315 // the non-UseAA case, because we're merging stores into the FINAL 11316 // store along a chain which potentially contains aliasing stores. 11317 // Thus, if there are multiple stores to the same address, the last 11318 // one can be considered for merging but not the others. 11319 std::sort(StoreNodes.begin(), StoreNodes.end(), 11320 [](MemOpLink LHS, MemOpLink RHS) { 11321 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11322 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11323 LHS.SequenceNum < RHS.SequenceNum); 11324 }); 11325 11326 // Scan the memory operations on the chain and find the first non-consecutive 11327 // store memory address. 11328 unsigned LastConsecutiveStore = 0; 11329 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11330 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11331 11332 // Check that the addresses are consecutive starting from the second 11333 // element in the list of stores. 11334 if (i > 0) { 11335 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11336 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11337 break; 11338 } 11339 11340 bool Alias = false; 11341 // Check if this store interferes with any of the loads that we found. 11342 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 11343 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 11344 Alias = true; 11345 break; 11346 } 11347 // We found a load that alias with this store. Stop the sequence. 11348 if (Alias) 11349 break; 11350 11351 // Mark this node as useful. 11352 LastConsecutiveStore = i; 11353 } 11354 11355 // The node with the lowest store address. 11356 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11357 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11358 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11359 LLVMContext &Context = *DAG.getContext(); 11360 const DataLayout &DL = DAG.getDataLayout(); 11361 11362 // Store the constants into memory as one consecutive store. 11363 if (IsConstantSrc) { 11364 unsigned LastLegalType = 0; 11365 unsigned LastLegalVectorType = 0; 11366 bool NonZero = false; 11367 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11368 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11369 SDValue StoredVal = St->getValue(); 11370 11371 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11372 NonZero |= !C->isNullValue(); 11373 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11374 NonZero |= !C->getConstantFPValue()->isNullValue(); 11375 } else { 11376 // Non-constant. 11377 break; 11378 } 11379 11380 // Find a legal type for the constant store. 11381 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11382 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11383 bool IsFast; 11384 if (TLI.isTypeLegal(StoreTy) && 11385 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11386 FirstStoreAlign, &IsFast) && IsFast) { 11387 LastLegalType = i+1; 11388 // Or check whether a truncstore is legal. 11389 } else if (TLI.getTypeAction(Context, StoreTy) == 11390 TargetLowering::TypePromoteInteger) { 11391 EVT LegalizedStoredValueTy = 11392 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11393 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11394 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11395 FirstStoreAS, FirstStoreAlign, &IsFast) && 11396 IsFast) { 11397 LastLegalType = i + 1; 11398 } 11399 } 11400 11401 // We only use vectors if the constant is known to be zero or the target 11402 // allows it and the function is not marked with the noimplicitfloat 11403 // attribute. 11404 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11405 FirstStoreAS)) && 11406 !NoVectors) { 11407 // Find a legal type for the vector store. 11408 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11409 if (TLI.isTypeLegal(Ty) && 11410 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11411 FirstStoreAlign, &IsFast) && IsFast) 11412 LastLegalVectorType = i + 1; 11413 } 11414 } 11415 11416 // Check if we found a legal integer type to store. 11417 if (LastLegalType == 0 && LastLegalVectorType == 0) 11418 return false; 11419 11420 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11421 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11422 11423 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11424 true, UseVector); 11425 } 11426 11427 // When extracting multiple vector elements, try to store them 11428 // in one vector store rather than a sequence of scalar stores. 11429 if (IsExtractVecSrc) { 11430 unsigned NumStoresToMerge = 0; 11431 bool IsVec = MemVT.isVector(); 11432 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11433 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11434 unsigned StoreValOpcode = St->getValue().getOpcode(); 11435 // This restriction could be loosened. 11436 // Bail out if any stored values are not elements extracted from a vector. 11437 // It should be possible to handle mixed sources, but load sources need 11438 // more careful handling (see the block of code below that handles 11439 // consecutive loads). 11440 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11441 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11442 return false; 11443 11444 // Find a legal type for the vector store. 11445 unsigned Elts = i + 1; 11446 if (IsVec) { 11447 // When merging vector stores, get the total number of elements. 11448 Elts *= MemVT.getVectorNumElements(); 11449 } 11450 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11451 bool IsFast; 11452 if (TLI.isTypeLegal(Ty) && 11453 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11454 FirstStoreAlign, &IsFast) && IsFast) 11455 NumStoresToMerge = i + 1; 11456 } 11457 11458 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11459 false, true); 11460 } 11461 11462 // Below we handle the case of multiple consecutive stores that 11463 // come from multiple consecutive loads. We merge them into a single 11464 // wide load and a single wide store. 11465 11466 // Look for load nodes which are used by the stored values. 11467 SmallVector<MemOpLink, 8> LoadNodes; 11468 11469 // Find acceptable loads. Loads need to have the same chain (token factor), 11470 // must not be zext, volatile, indexed, and they must be consecutive. 11471 BaseIndexOffset LdBasePtr; 11472 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11473 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11474 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11475 if (!Ld) break; 11476 11477 // Loads must only have one use. 11478 if (!Ld->hasNUsesOfValue(1, 0)) 11479 break; 11480 11481 // The memory operands must not be volatile. 11482 if (Ld->isVolatile() || Ld->isIndexed()) 11483 break; 11484 11485 // We do not accept ext loads. 11486 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11487 break; 11488 11489 // The stored memory type must be the same. 11490 if (Ld->getMemoryVT() != MemVT) 11491 break; 11492 11493 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 11494 // If this is not the first ptr that we check. 11495 if (LdBasePtr.Base.getNode()) { 11496 // The base ptr must be the same. 11497 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11498 break; 11499 } else { 11500 // Check that all other base pointers are the same as this one. 11501 LdBasePtr = LdPtr; 11502 } 11503 11504 // We found a potential memory operand to merge. 11505 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11506 } 11507 11508 if (LoadNodes.size() < 2) 11509 return false; 11510 11511 // If we have load/store pair instructions and we only have two values, 11512 // don't bother. 11513 unsigned RequiredAlignment; 11514 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11515 St->getAlignment() >= RequiredAlignment) 11516 return false; 11517 11518 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11519 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11520 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11521 11522 // Scan the memory operations on the chain and find the first non-consecutive 11523 // load memory address. These variables hold the index in the store node 11524 // array. 11525 unsigned LastConsecutiveLoad = 0; 11526 // This variable refers to the size and not index in the array. 11527 unsigned LastLegalVectorType = 0; 11528 unsigned LastLegalIntegerType = 0; 11529 StartAddress = LoadNodes[0].OffsetFromBase; 11530 SDValue FirstChain = FirstLoad->getChain(); 11531 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11532 // All loads must share the same chain. 11533 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11534 break; 11535 11536 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11537 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11538 break; 11539 LastConsecutiveLoad = i; 11540 // Find a legal type for the vector store. 11541 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11542 bool IsFastSt, IsFastLd; 11543 if (TLI.isTypeLegal(StoreTy) && 11544 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11545 FirstStoreAlign, &IsFastSt) && IsFastSt && 11546 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11547 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11548 LastLegalVectorType = i + 1; 11549 } 11550 11551 // Find a legal type for the integer store. 11552 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11553 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11554 if (TLI.isTypeLegal(StoreTy) && 11555 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11556 FirstStoreAlign, &IsFastSt) && IsFastSt && 11557 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11558 FirstLoadAlign, &IsFastLd) && IsFastLd) 11559 LastLegalIntegerType = i + 1; 11560 // Or check whether a truncstore and extload is legal. 11561 else if (TLI.getTypeAction(Context, StoreTy) == 11562 TargetLowering::TypePromoteInteger) { 11563 EVT LegalizedStoredValueTy = 11564 TLI.getTypeToTransformTo(Context, StoreTy); 11565 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11566 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11567 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11568 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11569 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11570 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11571 IsFastSt && 11572 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11573 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11574 IsFastLd) 11575 LastLegalIntegerType = i+1; 11576 } 11577 } 11578 11579 // Only use vector types if the vector type is larger than the integer type. 11580 // If they are the same, use integers. 11581 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11582 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11583 11584 // We add +1 here because the LastXXX variables refer to location while 11585 // the NumElem refers to array/index size. 11586 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11587 NumElem = std::min(LastLegalType, NumElem); 11588 11589 if (NumElem < 2) 11590 return false; 11591 11592 // Collect the chains from all merged stores. 11593 SmallVector<SDValue, 8> MergeStoreChains; 11594 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11595 11596 // The latest Node in the DAG. 11597 unsigned LatestNodeUsed = 0; 11598 for (unsigned i=1; i<NumElem; ++i) { 11599 // Find a chain for the new wide-store operand. Notice that some 11600 // of the store nodes that we found may not be selected for inclusion 11601 // in the wide store. The chain we use needs to be the chain of the 11602 // latest store node which is *used* and replaced by the wide store. 11603 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11604 LatestNodeUsed = i; 11605 11606 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11607 } 11608 11609 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11610 11611 // Find if it is better to use vectors or integers to load and store 11612 // to memory. 11613 EVT JointMemOpVT; 11614 if (UseVectorTy) { 11615 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11616 } else { 11617 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11618 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11619 } 11620 11621 SDLoc LoadDL(LoadNodes[0].MemNode); 11622 SDLoc StoreDL(StoreNodes[0].MemNode); 11623 11624 // The merged loads are required to have the same incoming chain, so 11625 // using the first's chain is acceptable. 11626 SDValue NewLoad = DAG.getLoad( 11627 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11628 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11629 11630 SDValue NewStoreChain = 11631 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11632 11633 SDValue NewStore = DAG.getStore( 11634 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11635 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11636 11637 // Transfer chain users from old loads to the new load. 11638 for (unsigned i = 0; i < NumElem; ++i) { 11639 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11640 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11641 SDValue(NewLoad.getNode(), 1)); 11642 } 11643 11644 // Replace the last store with the new store. 11645 CombineTo(LatestOp, NewStore); 11646 // Erase all other stores. 11647 for (unsigned i = 0; i < NumElem ; ++i) { 11648 // Remove all Store nodes. 11649 if (StoreNodes[i].MemNode == LatestOp) 11650 continue; 11651 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11652 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11653 deleteAndRecombine(St); 11654 } 11655 11656 return true; 11657 } 11658 11659 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11660 SDLoc SL(ST); 11661 SDValue ReplStore; 11662 11663 // Replace the chain to avoid dependency. 11664 if (ST->isTruncatingStore()) { 11665 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11666 ST->getBasePtr(), ST->getMemoryVT(), 11667 ST->getMemOperand()); 11668 } else { 11669 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11670 ST->getMemOperand()); 11671 } 11672 11673 // Create token to keep both nodes around. 11674 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11675 MVT::Other, ST->getChain(), ReplStore); 11676 11677 // Make sure the new and old chains are cleaned up. 11678 AddToWorklist(Token.getNode()); 11679 11680 // Don't add users to work list. 11681 return CombineTo(ST, Token, false); 11682 } 11683 11684 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11685 SDValue Value = ST->getValue(); 11686 if (Value.getOpcode() == ISD::TargetConstantFP) 11687 return SDValue(); 11688 11689 SDLoc DL(ST); 11690 11691 SDValue Chain = ST->getChain(); 11692 SDValue Ptr = ST->getBasePtr(); 11693 11694 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11695 11696 // NOTE: If the original store is volatile, this transform must not increase 11697 // the number of stores. For example, on x86-32 an f64 can be stored in one 11698 // processor operation but an i64 (which is not legal) requires two. So the 11699 // transform should not be done in this case. 11700 11701 SDValue Tmp; 11702 switch (CFP->getSimpleValueType(0).SimpleTy) { 11703 default: 11704 llvm_unreachable("Unknown FP type"); 11705 case MVT::f16: // We don't do this for these yet. 11706 case MVT::f80: 11707 case MVT::f128: 11708 case MVT::ppcf128: 11709 return SDValue(); 11710 case MVT::f32: 11711 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11712 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11713 ; 11714 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11715 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11716 MVT::i32); 11717 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11718 } 11719 11720 return SDValue(); 11721 case MVT::f64: 11722 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11723 !ST->isVolatile()) || 11724 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11725 ; 11726 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11727 getZExtValue(), SDLoc(CFP), MVT::i64); 11728 return DAG.getStore(Chain, DL, Tmp, 11729 Ptr, ST->getMemOperand()); 11730 } 11731 11732 if (!ST->isVolatile() && 11733 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11734 // Many FP stores are not made apparent until after legalize, e.g. for 11735 // argument passing. Since this is so common, custom legalize the 11736 // 64-bit integer store into two 32-bit stores. 11737 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11738 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11739 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11740 if (DAG.getDataLayout().isBigEndian()) 11741 std::swap(Lo, Hi); 11742 11743 unsigned Alignment = ST->getAlignment(); 11744 bool isVolatile = ST->isVolatile(); 11745 bool isNonTemporal = ST->isNonTemporal(); 11746 AAMDNodes AAInfo = ST->getAAInfo(); 11747 11748 SDValue St0 = DAG.getStore(Chain, DL, Lo, 11749 Ptr, ST->getPointerInfo(), 11750 isVolatile, isNonTemporal, 11751 ST->getAlignment(), AAInfo); 11752 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11753 DAG.getConstant(4, DL, Ptr.getValueType())); 11754 Alignment = MinAlign(Alignment, 4U); 11755 SDValue St1 = DAG.getStore(Chain, DL, Hi, 11756 Ptr, ST->getPointerInfo().getWithOffset(4), 11757 isVolatile, isNonTemporal, 11758 Alignment, AAInfo); 11759 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11760 St0, St1); 11761 } 11762 11763 return SDValue(); 11764 } 11765 } 11766 11767 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11768 StoreSDNode *ST = cast<StoreSDNode>(N); 11769 SDValue Chain = ST->getChain(); 11770 SDValue Value = ST->getValue(); 11771 SDValue Ptr = ST->getBasePtr(); 11772 11773 // If this is a store of a bit convert, store the input value if the 11774 // resultant store does not need a higher alignment than the original. 11775 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11776 ST->isUnindexed()) { 11777 unsigned OrigAlign = ST->getAlignment(); 11778 EVT SVT = Value.getOperand(0).getValueType(); 11779 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 11780 SVT.getTypeForEVT(*DAG.getContext())); 11781 if (Align <= OrigAlign && 11782 ((!LegalOperations && !ST->isVolatile()) || 11783 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 11784 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11785 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11786 ST->isNonTemporal(), OrigAlign, 11787 ST->getAAInfo()); 11788 } 11789 11790 // Turn 'store undef, Ptr' -> nothing. 11791 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 11792 return Chain; 11793 11794 // Try to infer better alignment information than the store already has. 11795 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 11796 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11797 if (Align > ST->getAlignment()) { 11798 SDValue NewStore = 11799 DAG.getTruncStore(Chain, SDLoc(N), Value, 11800 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 11801 ST->isVolatile(), ST->isNonTemporal(), Align, 11802 ST->getAAInfo()); 11803 if (NewStore.getNode() != N) 11804 return CombineTo(ST, NewStore, true); 11805 } 11806 } 11807 } 11808 11809 // Try transforming a pair floating point load / store ops to integer 11810 // load / store ops. 11811 if (SDValue NewST = TransformFPLoadStorePair(N)) 11812 return NewST; 11813 11814 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11815 : DAG.getSubtarget().useAA(); 11816 #ifndef NDEBUG 11817 if (CombinerAAOnlyFunc.getNumOccurrences() && 11818 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11819 UseAA = false; 11820 #endif 11821 if (UseAA && ST->isUnindexed()) { 11822 // FIXME: We should do this even without AA enabled. AA will just allow 11823 // FindBetterChain to work in more situations. The problem with this is that 11824 // any combine that expects memory operations to be on consecutive chains 11825 // first needs to be updated to look for users of the same chain. 11826 11827 // Walk up chain skipping non-aliasing memory nodes, on this store and any 11828 // adjacent stores. 11829 if (findBetterNeighborChains(ST)) { 11830 // replaceStoreChain uses CombineTo, which handled all of the worklist 11831 // manipulation. Return the original node to not do anything else. 11832 return SDValue(ST, 0); 11833 } 11834 } 11835 11836 // Try transforming N to an indexed store. 11837 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11838 return SDValue(N, 0); 11839 11840 // FIXME: is there such a thing as a truncating indexed store? 11841 if (ST->isTruncatingStore() && ST->isUnindexed() && 11842 Value.getValueType().isInteger()) { 11843 // See if we can simplify the input to this truncstore with knowledge that 11844 // only the low bits are being used. For example: 11845 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 11846 SDValue Shorter = 11847 GetDemandedBits(Value, 11848 APInt::getLowBitsSet( 11849 Value.getValueType().getScalarType().getSizeInBits(), 11850 ST->getMemoryVT().getScalarType().getSizeInBits())); 11851 AddToWorklist(Value.getNode()); 11852 if (Shorter.getNode()) 11853 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 11854 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11855 11856 // Otherwise, see if we can simplify the operation with 11857 // SimplifyDemandedBits, which only works if the value has a single use. 11858 if (SimplifyDemandedBits(Value, 11859 APInt::getLowBitsSet( 11860 Value.getValueType().getScalarType().getSizeInBits(), 11861 ST->getMemoryVT().getScalarType().getSizeInBits()))) 11862 return SDValue(N, 0); 11863 } 11864 11865 // If this is a load followed by a store to the same location, then the store 11866 // is dead/noop. 11867 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 11868 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 11869 ST->isUnindexed() && !ST->isVolatile() && 11870 // There can't be any side effects between the load and store, such as 11871 // a call or store. 11872 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 11873 // The store is dead, remove it. 11874 return Chain; 11875 } 11876 } 11877 11878 // If this is a store followed by a store with the same value to the same 11879 // location, then the store is dead/noop. 11880 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 11881 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 11882 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 11883 ST1->isUnindexed() && !ST1->isVolatile()) { 11884 // The store is dead, remove it. 11885 return Chain; 11886 } 11887 } 11888 11889 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 11890 // truncating store. We can do this even if this is already a truncstore. 11891 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 11892 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 11893 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 11894 ST->getMemoryVT())) { 11895 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 11896 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11897 } 11898 11899 // Only perform this optimization before the types are legal, because we 11900 // don't want to perform this optimization on every DAGCombine invocation. 11901 if (!LegalTypes) { 11902 bool EverChanged = false; 11903 11904 do { 11905 // There can be multiple store sequences on the same chain. 11906 // Keep trying to merge store sequences until we are unable to do so 11907 // or until we merge the last store on the chain. 11908 bool Changed = MergeConsecutiveStores(ST); 11909 EverChanged |= Changed; 11910 if (!Changed) break; 11911 } while (ST->getOpcode() != ISD::DELETED_NODE); 11912 11913 if (EverChanged) 11914 return SDValue(N, 0); 11915 } 11916 11917 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 11918 // 11919 // Make sure to do this only after attempting to merge stores in order to 11920 // avoid changing the types of some subset of stores due to visit order, 11921 // preventing their merging. 11922 if (isa<ConstantFPSDNode>(Value)) { 11923 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 11924 return NewSt; 11925 } 11926 11927 return ReduceLoadOpStoreWidth(N); 11928 } 11929 11930 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 11931 SDValue InVec = N->getOperand(0); 11932 SDValue InVal = N->getOperand(1); 11933 SDValue EltNo = N->getOperand(2); 11934 SDLoc dl(N); 11935 11936 // If the inserted element is an UNDEF, just use the input vector. 11937 if (InVal.getOpcode() == ISD::UNDEF) 11938 return InVec; 11939 11940 EVT VT = InVec.getValueType(); 11941 11942 // If we can't generate a legal BUILD_VECTOR, exit 11943 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 11944 return SDValue(); 11945 11946 // Check that we know which element is being inserted 11947 if (!isa<ConstantSDNode>(EltNo)) 11948 return SDValue(); 11949 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11950 11951 // Canonicalize insert_vector_elt dag nodes. 11952 // Example: 11953 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 11954 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 11955 // 11956 // Do this only if the child insert_vector node has one use; also 11957 // do this only if indices are both constants and Idx1 < Idx0. 11958 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 11959 && isa<ConstantSDNode>(InVec.getOperand(2))) { 11960 unsigned OtherElt = 11961 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 11962 if (Elt < OtherElt) { 11963 // Swap nodes. 11964 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 11965 InVec.getOperand(0), InVal, EltNo); 11966 AddToWorklist(NewOp.getNode()); 11967 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 11968 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 11969 } 11970 } 11971 11972 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 11973 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 11974 // vector elements. 11975 SmallVector<SDValue, 8> Ops; 11976 // Do not combine these two vectors if the output vector will not replace 11977 // the input vector. 11978 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 11979 Ops.append(InVec.getNode()->op_begin(), 11980 InVec.getNode()->op_end()); 11981 } else if (InVec.getOpcode() == ISD::UNDEF) { 11982 unsigned NElts = VT.getVectorNumElements(); 11983 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 11984 } else { 11985 return SDValue(); 11986 } 11987 11988 // Insert the element 11989 if (Elt < Ops.size()) { 11990 // All the operands of BUILD_VECTOR must have the same type; 11991 // we enforce that here. 11992 EVT OpVT = Ops[0].getValueType(); 11993 if (InVal.getValueType() != OpVT) 11994 InVal = OpVT.bitsGT(InVal.getValueType()) ? 11995 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 11996 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 11997 Ops[Elt] = InVal; 11998 } 11999 12000 // Return the new vector 12001 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 12002 } 12003 12004 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12005 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12006 EVT ResultVT = EVE->getValueType(0); 12007 EVT VecEltVT = InVecVT.getVectorElementType(); 12008 unsigned Align = OriginalLoad->getAlignment(); 12009 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12010 VecEltVT.getTypeForEVT(*DAG.getContext())); 12011 12012 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12013 return SDValue(); 12014 12015 Align = NewAlign; 12016 12017 SDValue NewPtr = OriginalLoad->getBasePtr(); 12018 SDValue Offset; 12019 EVT PtrType = NewPtr.getValueType(); 12020 MachinePointerInfo MPI; 12021 SDLoc DL(EVE); 12022 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12023 int Elt = ConstEltNo->getZExtValue(); 12024 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12025 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12026 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12027 } else { 12028 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12029 Offset = DAG.getNode( 12030 ISD::MUL, DL, PtrType, Offset, 12031 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12032 MPI = OriginalLoad->getPointerInfo(); 12033 } 12034 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12035 12036 // The replacement we need to do here is a little tricky: we need to 12037 // replace an extractelement of a load with a load. 12038 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12039 // Note that this replacement assumes that the extractvalue is the only 12040 // use of the load; that's okay because we don't want to perform this 12041 // transformation in other cases anyway. 12042 SDValue Load; 12043 SDValue Chain; 12044 if (ResultVT.bitsGT(VecEltVT)) { 12045 // If the result type of vextract is wider than the load, then issue an 12046 // extending load instead. 12047 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12048 VecEltVT) 12049 ? ISD::ZEXTLOAD 12050 : ISD::EXTLOAD; 12051 Load = DAG.getExtLoad( 12052 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 12053 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12054 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12055 Chain = Load.getValue(1); 12056 } else { 12057 Load = DAG.getLoad( 12058 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 12059 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12060 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12061 Chain = Load.getValue(1); 12062 if (ResultVT.bitsLT(VecEltVT)) 12063 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12064 else 12065 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 12066 } 12067 WorklistRemover DeadNodes(*this); 12068 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12069 SDValue To[] = { Load, Chain }; 12070 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12071 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12072 // worklist explicitly as well. 12073 AddToWorklist(Load.getNode()); 12074 AddUsersToWorklist(Load.getNode()); // Add users too 12075 // Make sure to revisit this node to clean it up; it will usually be dead. 12076 AddToWorklist(EVE); 12077 ++OpsNarrowed; 12078 return SDValue(EVE, 0); 12079 } 12080 12081 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12082 // (vextract (scalar_to_vector val, 0) -> val 12083 SDValue InVec = N->getOperand(0); 12084 EVT VT = InVec.getValueType(); 12085 EVT NVT = N->getValueType(0); 12086 12087 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12088 // Check if the result type doesn't match the inserted element type. A 12089 // SCALAR_TO_VECTOR may truncate the inserted element and the 12090 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12091 SDValue InOp = InVec.getOperand(0); 12092 if (InOp.getValueType() != NVT) { 12093 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12094 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12095 } 12096 return InOp; 12097 } 12098 12099 SDValue EltNo = N->getOperand(1); 12100 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12101 12102 // extract_vector_elt (build_vector x, y), 1 -> y 12103 if (ConstEltNo && 12104 InVec.getOpcode() == ISD::BUILD_VECTOR && 12105 TLI.isTypeLegal(VT) && 12106 (InVec.hasOneUse() || 12107 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12108 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12109 EVT InEltVT = Elt.getValueType(); 12110 12111 // Sometimes build_vector's scalar input types do not match result type. 12112 if (NVT == InEltVT) 12113 return Elt; 12114 12115 // TODO: It may be useful to truncate if free if the build_vector implicitly 12116 // converts. 12117 } 12118 12119 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12120 // We only perform this optimization before the op legalization phase because 12121 // we may introduce new vector instructions which are not backed by TD 12122 // patterns. For example on AVX, extracting elements from a wide vector 12123 // without using extract_subvector. However, if we can find an underlying 12124 // scalar value, then we can always use that. 12125 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12126 int NumElem = VT.getVectorNumElements(); 12127 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12128 // Find the new index to extract from. 12129 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12130 12131 // Extracting an undef index is undef. 12132 if (OrigElt == -1) 12133 return DAG.getUNDEF(NVT); 12134 12135 // Select the right vector half to extract from. 12136 SDValue SVInVec; 12137 if (OrigElt < NumElem) { 12138 SVInVec = InVec->getOperand(0); 12139 } else { 12140 SVInVec = InVec->getOperand(1); 12141 OrigElt -= NumElem; 12142 } 12143 12144 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12145 SDValue InOp = SVInVec.getOperand(OrigElt); 12146 if (InOp.getValueType() != NVT) { 12147 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12148 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12149 } 12150 12151 return InOp; 12152 } 12153 12154 // FIXME: We should handle recursing on other vector shuffles and 12155 // scalar_to_vector here as well. 12156 12157 if (!LegalOperations) { 12158 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12159 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12160 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12161 } 12162 } 12163 12164 bool BCNumEltsChanged = false; 12165 EVT ExtVT = VT.getVectorElementType(); 12166 EVT LVT = ExtVT; 12167 12168 // If the result of load has to be truncated, then it's not necessarily 12169 // profitable. 12170 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12171 return SDValue(); 12172 12173 if (InVec.getOpcode() == ISD::BITCAST) { 12174 // Don't duplicate a load with other uses. 12175 if (!InVec.hasOneUse()) 12176 return SDValue(); 12177 12178 EVT BCVT = InVec.getOperand(0).getValueType(); 12179 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12180 return SDValue(); 12181 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12182 BCNumEltsChanged = true; 12183 InVec = InVec.getOperand(0); 12184 ExtVT = BCVT.getVectorElementType(); 12185 } 12186 12187 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12188 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12189 ISD::isNormalLoad(InVec.getNode()) && 12190 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12191 SDValue Index = N->getOperand(1); 12192 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 12193 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12194 OrigLoad); 12195 } 12196 12197 // Perform only after legalization to ensure build_vector / vector_shuffle 12198 // optimizations have already been done. 12199 if (!LegalOperations) return SDValue(); 12200 12201 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12202 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12203 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12204 12205 if (ConstEltNo) { 12206 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12207 12208 LoadSDNode *LN0 = nullptr; 12209 const ShuffleVectorSDNode *SVN = nullptr; 12210 if (ISD::isNormalLoad(InVec.getNode())) { 12211 LN0 = cast<LoadSDNode>(InVec); 12212 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12213 InVec.getOperand(0).getValueType() == ExtVT && 12214 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12215 // Don't duplicate a load with other uses. 12216 if (!InVec.hasOneUse()) 12217 return SDValue(); 12218 12219 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12220 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12221 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12222 // => 12223 // (load $addr+1*size) 12224 12225 // Don't duplicate a load with other uses. 12226 if (!InVec.hasOneUse()) 12227 return SDValue(); 12228 12229 // If the bit convert changed the number of elements, it is unsafe 12230 // to examine the mask. 12231 if (BCNumEltsChanged) 12232 return SDValue(); 12233 12234 // Select the input vector, guarding against out of range extract vector. 12235 unsigned NumElems = VT.getVectorNumElements(); 12236 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12237 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12238 12239 if (InVec.getOpcode() == ISD::BITCAST) { 12240 // Don't duplicate a load with other uses. 12241 if (!InVec.hasOneUse()) 12242 return SDValue(); 12243 12244 InVec = InVec.getOperand(0); 12245 } 12246 if (ISD::isNormalLoad(InVec.getNode())) { 12247 LN0 = cast<LoadSDNode>(InVec); 12248 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12249 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12250 } 12251 } 12252 12253 // Make sure we found a non-volatile load and the extractelement is 12254 // the only use. 12255 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12256 return SDValue(); 12257 12258 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12259 if (Elt == -1) 12260 return DAG.getUNDEF(LVT); 12261 12262 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12263 } 12264 12265 return SDValue(); 12266 } 12267 12268 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12269 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12270 // We perform this optimization post type-legalization because 12271 // the type-legalizer often scalarizes integer-promoted vectors. 12272 // Performing this optimization before may create bit-casts which 12273 // will be type-legalized to complex code sequences. 12274 // We perform this optimization only before the operation legalizer because we 12275 // may introduce illegal operations. 12276 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12277 return SDValue(); 12278 12279 unsigned NumInScalars = N->getNumOperands(); 12280 SDLoc dl(N); 12281 EVT VT = N->getValueType(0); 12282 12283 // Check to see if this is a BUILD_VECTOR of a bunch of values 12284 // which come from any_extend or zero_extend nodes. If so, we can create 12285 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12286 // optimizations. We do not handle sign-extend because we can't fill the sign 12287 // using shuffles. 12288 EVT SourceType = MVT::Other; 12289 bool AllAnyExt = true; 12290 12291 for (unsigned i = 0; i != NumInScalars; ++i) { 12292 SDValue In = N->getOperand(i); 12293 // Ignore undef inputs. 12294 if (In.getOpcode() == ISD::UNDEF) continue; 12295 12296 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12297 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12298 12299 // Abort if the element is not an extension. 12300 if (!ZeroExt && !AnyExt) { 12301 SourceType = MVT::Other; 12302 break; 12303 } 12304 12305 // The input is a ZeroExt or AnyExt. Check the original type. 12306 EVT InTy = In.getOperand(0).getValueType(); 12307 12308 // Check that all of the widened source types are the same. 12309 if (SourceType == MVT::Other) 12310 // First time. 12311 SourceType = InTy; 12312 else if (InTy != SourceType) { 12313 // Multiple income types. Abort. 12314 SourceType = MVT::Other; 12315 break; 12316 } 12317 12318 // Check if all of the extends are ANY_EXTENDs. 12319 AllAnyExt &= AnyExt; 12320 } 12321 12322 // In order to have valid types, all of the inputs must be extended from the 12323 // same source type and all of the inputs must be any or zero extend. 12324 // Scalar sizes must be a power of two. 12325 EVT OutScalarTy = VT.getScalarType(); 12326 bool ValidTypes = SourceType != MVT::Other && 12327 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12328 isPowerOf2_32(SourceType.getSizeInBits()); 12329 12330 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12331 // turn into a single shuffle instruction. 12332 if (!ValidTypes) 12333 return SDValue(); 12334 12335 bool isLE = DAG.getDataLayout().isLittleEndian(); 12336 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12337 assert(ElemRatio > 1 && "Invalid element size ratio"); 12338 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12339 DAG.getConstant(0, SDLoc(N), SourceType); 12340 12341 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12342 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12343 12344 // Populate the new build_vector 12345 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12346 SDValue Cast = N->getOperand(i); 12347 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12348 Cast.getOpcode() == ISD::ZERO_EXTEND || 12349 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 12350 SDValue In; 12351 if (Cast.getOpcode() == ISD::UNDEF) 12352 In = DAG.getUNDEF(SourceType); 12353 else 12354 In = Cast->getOperand(0); 12355 unsigned Index = isLE ? (i * ElemRatio) : 12356 (i * ElemRatio + (ElemRatio - 1)); 12357 12358 assert(Index < Ops.size() && "Invalid index"); 12359 Ops[Index] = In; 12360 } 12361 12362 // The type of the new BUILD_VECTOR node. 12363 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12364 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12365 "Invalid vector size"); 12366 // Check if the new vector type is legal. 12367 if (!isTypeLegal(VecVT)) return SDValue(); 12368 12369 // Make the new BUILD_VECTOR. 12370 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 12371 12372 // The new BUILD_VECTOR node has the potential to be further optimized. 12373 AddToWorklist(BV.getNode()); 12374 // Bitcast to the desired type. 12375 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12376 } 12377 12378 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12379 EVT VT = N->getValueType(0); 12380 12381 unsigned NumInScalars = N->getNumOperands(); 12382 SDLoc dl(N); 12383 12384 EVT SrcVT = MVT::Other; 12385 unsigned Opcode = ISD::DELETED_NODE; 12386 unsigned NumDefs = 0; 12387 12388 for (unsigned i = 0; i != NumInScalars; ++i) { 12389 SDValue In = N->getOperand(i); 12390 unsigned Opc = In.getOpcode(); 12391 12392 if (Opc == ISD::UNDEF) 12393 continue; 12394 12395 // If all scalar values are floats and converted from integers. 12396 if (Opcode == ISD::DELETED_NODE && 12397 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12398 Opcode = Opc; 12399 } 12400 12401 if (Opc != Opcode) 12402 return SDValue(); 12403 12404 EVT InVT = In.getOperand(0).getValueType(); 12405 12406 // If all scalar values are typed differently, bail out. It's chosen to 12407 // simplify BUILD_VECTOR of integer types. 12408 if (SrcVT == MVT::Other) 12409 SrcVT = InVT; 12410 if (SrcVT != InVT) 12411 return SDValue(); 12412 NumDefs++; 12413 } 12414 12415 // If the vector has just one element defined, it's not worth to fold it into 12416 // a vectorized one. 12417 if (NumDefs < 2) 12418 return SDValue(); 12419 12420 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12421 && "Should only handle conversion from integer to float."); 12422 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12423 12424 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12425 12426 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12427 return SDValue(); 12428 12429 // Just because the floating-point vector type is legal does not necessarily 12430 // mean that the corresponding integer vector type is. 12431 if (!isTypeLegal(NVT)) 12432 return SDValue(); 12433 12434 SmallVector<SDValue, 8> Opnds; 12435 for (unsigned i = 0; i != NumInScalars; ++i) { 12436 SDValue In = N->getOperand(i); 12437 12438 if (In.getOpcode() == ISD::UNDEF) 12439 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12440 else 12441 Opnds.push_back(In.getOperand(0)); 12442 } 12443 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 12444 AddToWorklist(BV.getNode()); 12445 12446 return DAG.getNode(Opcode, dl, VT, BV); 12447 } 12448 12449 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12450 unsigned NumInScalars = N->getNumOperands(); 12451 SDLoc dl(N); 12452 EVT VT = N->getValueType(0); 12453 12454 // A vector built entirely of undefs is undef. 12455 if (ISD::allOperandsUndef(N)) 12456 return DAG.getUNDEF(VT); 12457 12458 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12459 return V; 12460 12461 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12462 return V; 12463 12464 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12465 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12466 // at most two distinct vectors, turn this into a shuffle node. 12467 12468 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12469 if (!isTypeLegal(VT)) 12470 return SDValue(); 12471 12472 // May only combine to shuffle after legalize if shuffle is legal. 12473 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12474 return SDValue(); 12475 12476 SDValue VecIn1, VecIn2; 12477 bool UsesZeroVector = false; 12478 for (unsigned i = 0; i != NumInScalars; ++i) { 12479 SDValue Op = N->getOperand(i); 12480 // Ignore undef inputs. 12481 if (Op.getOpcode() == ISD::UNDEF) continue; 12482 12483 // See if we can combine this build_vector into a blend with a zero vector. 12484 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12485 UsesZeroVector = true; 12486 continue; 12487 } 12488 12489 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12490 // constant index, bail out. 12491 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12492 !isa<ConstantSDNode>(Op.getOperand(1))) { 12493 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12494 break; 12495 } 12496 12497 // We allow up to two distinct input vectors. 12498 SDValue ExtractedFromVec = Op.getOperand(0); 12499 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12500 continue; 12501 12502 if (!VecIn1.getNode()) { 12503 VecIn1 = ExtractedFromVec; 12504 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12505 VecIn2 = ExtractedFromVec; 12506 } else { 12507 // Too many inputs. 12508 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12509 break; 12510 } 12511 } 12512 12513 // If everything is good, we can make a shuffle operation. 12514 if (VecIn1.getNode()) { 12515 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12516 SmallVector<int, 8> Mask; 12517 for (unsigned i = 0; i != NumInScalars; ++i) { 12518 unsigned Opcode = N->getOperand(i).getOpcode(); 12519 if (Opcode == ISD::UNDEF) { 12520 Mask.push_back(-1); 12521 continue; 12522 } 12523 12524 // Operands can also be zero. 12525 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12526 assert(UsesZeroVector && 12527 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12528 "Unexpected node found!"); 12529 Mask.push_back(NumInScalars+i); 12530 continue; 12531 } 12532 12533 // If extracting from the first vector, just use the index directly. 12534 SDValue Extract = N->getOperand(i); 12535 SDValue ExtVal = Extract.getOperand(1); 12536 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12537 if (Extract.getOperand(0) == VecIn1) { 12538 Mask.push_back(ExtIndex); 12539 continue; 12540 } 12541 12542 // Otherwise, use InIdx + InputVecSize 12543 Mask.push_back(InNumElements + ExtIndex); 12544 } 12545 12546 // Avoid introducing illegal shuffles with zero. 12547 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12548 return SDValue(); 12549 12550 // We can't generate a shuffle node with mismatched input and output types. 12551 // Attempt to transform a single input vector to the correct type. 12552 if ((VT != VecIn1.getValueType())) { 12553 // If the input vector type has a different base type to the output 12554 // vector type, bail out. 12555 EVT VTElemType = VT.getVectorElementType(); 12556 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12557 (VecIn2.getNode() && 12558 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12559 return SDValue(); 12560 12561 // If the input vector is too small, widen it. 12562 // We only support widening of vectors which are half the size of the 12563 // output registers. For example XMM->YMM widening on X86 with AVX. 12564 EVT VecInT = VecIn1.getValueType(); 12565 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12566 // If we only have one small input, widen it by adding undef values. 12567 if (!VecIn2.getNode()) 12568 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12569 DAG.getUNDEF(VecIn1.getValueType())); 12570 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12571 // If we have two small inputs of the same type, try to concat them. 12572 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12573 VecIn2 = SDValue(nullptr, 0); 12574 } else 12575 return SDValue(); 12576 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12577 // If the input vector is too large, try to split it. 12578 // We don't support having two input vectors that are too large. 12579 // If the zero vector was used, we can not split the vector, 12580 // since we'd need 3 inputs. 12581 if (UsesZeroVector || VecIn2.getNode()) 12582 return SDValue(); 12583 12584 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12585 return SDValue(); 12586 12587 // Try to replace VecIn1 with two extract_subvectors 12588 // No need to update the masks, they should still be correct. 12589 VecIn2 = DAG.getNode( 12590 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12591 DAG.getConstant(VT.getVectorNumElements(), dl, 12592 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12593 VecIn1 = DAG.getNode( 12594 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12595 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12596 } else 12597 return SDValue(); 12598 } 12599 12600 if (UsesZeroVector) 12601 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12602 DAG.getConstantFP(0.0, dl, VT); 12603 else 12604 // If VecIn2 is unused then change it to undef. 12605 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12606 12607 // Check that we were able to transform all incoming values to the same 12608 // type. 12609 if (VecIn2.getValueType() != VecIn1.getValueType() || 12610 VecIn1.getValueType() != VT) 12611 return SDValue(); 12612 12613 // Return the new VECTOR_SHUFFLE node. 12614 SDValue Ops[2]; 12615 Ops[0] = VecIn1; 12616 Ops[1] = VecIn2; 12617 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12618 } 12619 12620 return SDValue(); 12621 } 12622 12623 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12624 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12625 EVT OpVT = N->getOperand(0).getValueType(); 12626 12627 // If the operands are legal vectors, leave them alone. 12628 if (TLI.isTypeLegal(OpVT)) 12629 return SDValue(); 12630 12631 SDLoc DL(N); 12632 EVT VT = N->getValueType(0); 12633 SmallVector<SDValue, 8> Ops; 12634 12635 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12636 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12637 12638 // Keep track of what we encounter. 12639 bool AnyInteger = false; 12640 bool AnyFP = false; 12641 for (const SDValue &Op : N->ops()) { 12642 if (ISD::BITCAST == Op.getOpcode() && 12643 !Op.getOperand(0).getValueType().isVector()) 12644 Ops.push_back(Op.getOperand(0)); 12645 else if (ISD::UNDEF == Op.getOpcode()) 12646 Ops.push_back(ScalarUndef); 12647 else 12648 return SDValue(); 12649 12650 // Note whether we encounter an integer or floating point scalar. 12651 // If it's neither, bail out, it could be something weird like x86mmx. 12652 EVT LastOpVT = Ops.back().getValueType(); 12653 if (LastOpVT.isFloatingPoint()) 12654 AnyFP = true; 12655 else if (LastOpVT.isInteger()) 12656 AnyInteger = true; 12657 else 12658 return SDValue(); 12659 } 12660 12661 // If any of the operands is a floating point scalar bitcast to a vector, 12662 // use floating point types throughout, and bitcast everything. 12663 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12664 if (AnyFP) { 12665 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12666 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12667 if (AnyInteger) { 12668 for (SDValue &Op : Ops) { 12669 if (Op.getValueType() == SVT) 12670 continue; 12671 if (Op.getOpcode() == ISD::UNDEF) 12672 Op = ScalarUndef; 12673 else 12674 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12675 } 12676 } 12677 } 12678 12679 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12680 VT.getSizeInBits() / SVT.getSizeInBits()); 12681 return DAG.getNode(ISD::BITCAST, DL, VT, 12682 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 12683 } 12684 12685 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12686 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12687 // most two distinct vectors the same size as the result, attempt to turn this 12688 // into a legal shuffle. 12689 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12690 EVT VT = N->getValueType(0); 12691 EVT OpVT = N->getOperand(0).getValueType(); 12692 int NumElts = VT.getVectorNumElements(); 12693 int NumOpElts = OpVT.getVectorNumElements(); 12694 12695 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12696 SmallVector<int, 8> Mask; 12697 12698 for (SDValue Op : N->ops()) { 12699 // Peek through any bitcast. 12700 while (Op.getOpcode() == ISD::BITCAST) 12701 Op = Op.getOperand(0); 12702 12703 // UNDEF nodes convert to UNDEF shuffle mask values. 12704 if (Op.getOpcode() == ISD::UNDEF) { 12705 Mask.append((unsigned)NumOpElts, -1); 12706 continue; 12707 } 12708 12709 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12710 return SDValue(); 12711 12712 // What vector are we extracting the subvector from and at what index? 12713 SDValue ExtVec = Op.getOperand(0); 12714 12715 // We want the EVT of the original extraction to correctly scale the 12716 // extraction index. 12717 EVT ExtVT = ExtVec.getValueType(); 12718 12719 // Peek through any bitcast. 12720 while (ExtVec.getOpcode() == ISD::BITCAST) 12721 ExtVec = ExtVec.getOperand(0); 12722 12723 // UNDEF nodes convert to UNDEF shuffle mask values. 12724 if (ExtVec.getOpcode() == ISD::UNDEF) { 12725 Mask.append((unsigned)NumOpElts, -1); 12726 continue; 12727 } 12728 12729 if (!isa<ConstantSDNode>(Op.getOperand(1))) 12730 return SDValue(); 12731 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 12732 12733 // Ensure that we are extracting a subvector from a vector the same 12734 // size as the result. 12735 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 12736 return SDValue(); 12737 12738 // Scale the subvector index to account for any bitcast. 12739 int NumExtElts = ExtVT.getVectorNumElements(); 12740 if (0 == (NumExtElts % NumElts)) 12741 ExtIdx /= (NumExtElts / NumElts); 12742 else if (0 == (NumElts % NumExtElts)) 12743 ExtIdx *= (NumElts / NumExtElts); 12744 else 12745 return SDValue(); 12746 12747 // At most we can reference 2 inputs in the final shuffle. 12748 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) { 12749 SV0 = ExtVec; 12750 for (int i = 0; i != NumOpElts; ++i) 12751 Mask.push_back(i + ExtIdx); 12752 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) { 12753 SV1 = ExtVec; 12754 for (int i = 0; i != NumOpElts; ++i) 12755 Mask.push_back(i + ExtIdx + NumElts); 12756 } else { 12757 return SDValue(); 12758 } 12759 } 12760 12761 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 12762 return SDValue(); 12763 12764 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 12765 DAG.getBitcast(VT, SV1), Mask); 12766 } 12767 12768 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12769 // If we only have one input vector, we don't need to do any concatenation. 12770 if (N->getNumOperands() == 1) 12771 return N->getOperand(0); 12772 12773 // Check if all of the operands are undefs. 12774 EVT VT = N->getValueType(0); 12775 if (ISD::allOperandsUndef(N)) 12776 return DAG.getUNDEF(VT); 12777 12778 // Optimize concat_vectors where all but the first of the vectors are undef. 12779 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 12780 return Op.getOpcode() == ISD::UNDEF; 12781 })) { 12782 SDValue In = N->getOperand(0); 12783 assert(In.getValueType().isVector() && "Must concat vectors"); 12784 12785 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 12786 if (In->getOpcode() == ISD::BITCAST && 12787 !In->getOperand(0)->getValueType(0).isVector()) { 12788 SDValue Scalar = In->getOperand(0); 12789 12790 // If the bitcast type isn't legal, it might be a trunc of a legal type; 12791 // look through the trunc so we can still do the transform: 12792 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 12793 if (Scalar->getOpcode() == ISD::TRUNCATE && 12794 !TLI.isTypeLegal(Scalar.getValueType()) && 12795 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 12796 Scalar = Scalar->getOperand(0); 12797 12798 EVT SclTy = Scalar->getValueType(0); 12799 12800 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 12801 return SDValue(); 12802 12803 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 12804 VT.getSizeInBits() / SclTy.getSizeInBits()); 12805 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 12806 return SDValue(); 12807 12808 SDLoc dl = SDLoc(N); 12809 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 12810 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 12811 } 12812 } 12813 12814 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 12815 // We have already tested above for an UNDEF only concatenation. 12816 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 12817 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 12818 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 12819 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 12820 }; 12821 bool AllBuildVectorsOrUndefs = 12822 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 12823 if (AllBuildVectorsOrUndefs) { 12824 SmallVector<SDValue, 8> Opnds; 12825 EVT SVT = VT.getScalarType(); 12826 12827 EVT MinVT = SVT; 12828 if (!SVT.isFloatingPoint()) { 12829 // If BUILD_VECTOR are from built from integer, they may have different 12830 // operand types. Get the smallest type and truncate all operands to it. 12831 bool FoundMinVT = false; 12832 for (const SDValue &Op : N->ops()) 12833 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12834 EVT OpSVT = Op.getOperand(0)->getValueType(0); 12835 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 12836 FoundMinVT = true; 12837 } 12838 assert(FoundMinVT && "Concat vector type mismatch"); 12839 } 12840 12841 for (const SDValue &Op : N->ops()) { 12842 EVT OpVT = Op.getValueType(); 12843 unsigned NumElts = OpVT.getVectorNumElements(); 12844 12845 if (ISD::UNDEF == Op.getOpcode()) 12846 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 12847 12848 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12849 if (SVT.isFloatingPoint()) { 12850 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 12851 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 12852 } else { 12853 for (unsigned i = 0; i != NumElts; ++i) 12854 Opnds.push_back( 12855 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 12856 } 12857 } 12858 } 12859 12860 assert(VT.getVectorNumElements() == Opnds.size() && 12861 "Concat vector type mismatch"); 12862 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 12863 } 12864 12865 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 12866 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 12867 return V; 12868 12869 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 12870 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 12871 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 12872 return V; 12873 12874 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 12875 // nodes often generate nop CONCAT_VECTOR nodes. 12876 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 12877 // place the incoming vectors at the exact same location. 12878 SDValue SingleSource = SDValue(); 12879 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 12880 12881 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12882 SDValue Op = N->getOperand(i); 12883 12884 if (Op.getOpcode() == ISD::UNDEF) 12885 continue; 12886 12887 // Check if this is the identity extract: 12888 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12889 return SDValue(); 12890 12891 // Find the single incoming vector for the extract_subvector. 12892 if (SingleSource.getNode()) { 12893 if (Op.getOperand(0) != SingleSource) 12894 return SDValue(); 12895 } else { 12896 SingleSource = Op.getOperand(0); 12897 12898 // Check the source type is the same as the type of the result. 12899 // If not, this concat may extend the vector, so we can not 12900 // optimize it away. 12901 if (SingleSource.getValueType() != N->getValueType(0)) 12902 return SDValue(); 12903 } 12904 12905 unsigned IdentityIndex = i * PartNumElem; 12906 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 12907 // The extract index must be constant. 12908 if (!CS) 12909 return SDValue(); 12910 12911 // Check that we are reading from the identity index. 12912 if (CS->getZExtValue() != IdentityIndex) 12913 return SDValue(); 12914 } 12915 12916 if (SingleSource.getNode()) 12917 return SingleSource; 12918 12919 return SDValue(); 12920 } 12921 12922 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 12923 EVT NVT = N->getValueType(0); 12924 SDValue V = N->getOperand(0); 12925 12926 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 12927 // Combine: 12928 // (extract_subvec (concat V1, V2, ...), i) 12929 // Into: 12930 // Vi if possible 12931 // Only operand 0 is checked as 'concat' assumes all inputs of the same 12932 // type. 12933 if (V->getOperand(0).getValueType() != NVT) 12934 return SDValue(); 12935 unsigned Idx = N->getConstantOperandVal(1); 12936 unsigned NumElems = NVT.getVectorNumElements(); 12937 assert((Idx % NumElems) == 0 && 12938 "IDX in concat is not a multiple of the result vector length."); 12939 return V->getOperand(Idx / NumElems); 12940 } 12941 12942 // Skip bitcasting 12943 if (V->getOpcode() == ISD::BITCAST) 12944 V = V.getOperand(0); 12945 12946 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 12947 SDLoc dl(N); 12948 // Handle only simple case where vector being inserted and vector 12949 // being extracted are of same type, and are half size of larger vectors. 12950 EVT BigVT = V->getOperand(0).getValueType(); 12951 EVT SmallVT = V->getOperand(1).getValueType(); 12952 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 12953 return SDValue(); 12954 12955 // Only handle cases where both indexes are constants with the same type. 12956 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12957 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12958 12959 if (InsIdx && ExtIdx && 12960 InsIdx->getValueType(0).getSizeInBits() <= 64 && 12961 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 12962 // Combine: 12963 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 12964 // Into: 12965 // indices are equal or bit offsets are equal => V1 12966 // otherwise => (extract_subvec V1, ExtIdx) 12967 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 12968 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 12969 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 12970 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 12971 DAG.getNode(ISD::BITCAST, dl, 12972 N->getOperand(0).getValueType(), 12973 V->getOperand(0)), N->getOperand(1)); 12974 } 12975 } 12976 12977 return SDValue(); 12978 } 12979 12980 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 12981 SDValue V, SelectionDAG &DAG) { 12982 SDLoc DL(V); 12983 EVT VT = V.getValueType(); 12984 12985 switch (V.getOpcode()) { 12986 default: 12987 return V; 12988 12989 case ISD::CONCAT_VECTORS: { 12990 EVT OpVT = V->getOperand(0).getValueType(); 12991 int OpSize = OpVT.getVectorNumElements(); 12992 SmallBitVector OpUsedElements(OpSize, false); 12993 bool FoundSimplification = false; 12994 SmallVector<SDValue, 4> NewOps; 12995 NewOps.reserve(V->getNumOperands()); 12996 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 12997 SDValue Op = V->getOperand(i); 12998 bool OpUsed = false; 12999 for (int j = 0; j < OpSize; ++j) 13000 if (UsedElements[i * OpSize + j]) { 13001 OpUsedElements[j] = true; 13002 OpUsed = true; 13003 } 13004 NewOps.push_back( 13005 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13006 : DAG.getUNDEF(OpVT)); 13007 FoundSimplification |= Op == NewOps.back(); 13008 OpUsedElements.reset(); 13009 } 13010 if (FoundSimplification) 13011 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13012 return V; 13013 } 13014 13015 case ISD::INSERT_SUBVECTOR: { 13016 SDValue BaseV = V->getOperand(0); 13017 SDValue SubV = V->getOperand(1); 13018 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13019 if (!IdxN) 13020 return V; 13021 13022 int SubSize = SubV.getValueType().getVectorNumElements(); 13023 int Idx = IdxN->getZExtValue(); 13024 bool SubVectorUsed = false; 13025 SmallBitVector SubUsedElements(SubSize, false); 13026 for (int i = 0; i < SubSize; ++i) 13027 if (UsedElements[i + Idx]) { 13028 SubVectorUsed = true; 13029 SubUsedElements[i] = true; 13030 UsedElements[i + Idx] = false; 13031 } 13032 13033 // Now recurse on both the base and sub vectors. 13034 SDValue SimplifiedSubV = 13035 SubVectorUsed 13036 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13037 : DAG.getUNDEF(SubV.getValueType()); 13038 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13039 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13040 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13041 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13042 return V; 13043 } 13044 } 13045 } 13046 13047 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13048 SDValue N1, SelectionDAG &DAG) { 13049 EVT VT = SVN->getValueType(0); 13050 int NumElts = VT.getVectorNumElements(); 13051 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13052 for (int M : SVN->getMask()) 13053 if (M >= 0 && M < NumElts) 13054 N0UsedElements[M] = true; 13055 else if (M >= NumElts) 13056 N1UsedElements[M - NumElts] = true; 13057 13058 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13059 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13060 if (S0 == N0 && S1 == N1) 13061 return SDValue(); 13062 13063 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13064 } 13065 13066 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13067 // or turn a shuffle of a single concat into simpler shuffle then concat. 13068 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13069 EVT VT = N->getValueType(0); 13070 unsigned NumElts = VT.getVectorNumElements(); 13071 13072 SDValue N0 = N->getOperand(0); 13073 SDValue N1 = N->getOperand(1); 13074 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13075 13076 SmallVector<SDValue, 4> Ops; 13077 EVT ConcatVT = N0.getOperand(0).getValueType(); 13078 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13079 unsigned NumConcats = NumElts / NumElemsPerConcat; 13080 13081 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13082 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13083 // half vector elements. 13084 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 13085 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13086 SVN->getMask().end(), [](int i) { return i == -1; })) { 13087 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13088 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13089 N1 = DAG.getUNDEF(ConcatVT); 13090 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13091 } 13092 13093 // Look at every vector that's inserted. We're looking for exact 13094 // subvector-sized copies from a concatenated vector 13095 for (unsigned I = 0; I != NumConcats; ++I) { 13096 // Make sure we're dealing with a copy. 13097 unsigned Begin = I * NumElemsPerConcat; 13098 bool AllUndef = true, NoUndef = true; 13099 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13100 if (SVN->getMaskElt(J) >= 0) 13101 AllUndef = false; 13102 else 13103 NoUndef = false; 13104 } 13105 13106 if (NoUndef) { 13107 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13108 return SDValue(); 13109 13110 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13111 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13112 return SDValue(); 13113 13114 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13115 if (FirstElt < N0.getNumOperands()) 13116 Ops.push_back(N0.getOperand(FirstElt)); 13117 else 13118 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13119 13120 } else if (AllUndef) { 13121 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13122 } else { // Mixed with general masks and undefs, can't do optimization. 13123 return SDValue(); 13124 } 13125 } 13126 13127 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13128 } 13129 13130 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13131 EVT VT = N->getValueType(0); 13132 unsigned NumElts = VT.getVectorNumElements(); 13133 13134 SDValue N0 = N->getOperand(0); 13135 SDValue N1 = N->getOperand(1); 13136 13137 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13138 13139 // Canonicalize shuffle undef, undef -> undef 13140 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 13141 return DAG.getUNDEF(VT); 13142 13143 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13144 13145 // Canonicalize shuffle v, v -> v, undef 13146 if (N0 == N1) { 13147 SmallVector<int, 8> NewMask; 13148 for (unsigned i = 0; i != NumElts; ++i) { 13149 int Idx = SVN->getMaskElt(i); 13150 if (Idx >= (int)NumElts) Idx -= NumElts; 13151 NewMask.push_back(Idx); 13152 } 13153 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 13154 &NewMask[0]); 13155 } 13156 13157 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13158 if (N0.getOpcode() == ISD::UNDEF) { 13159 SmallVector<int, 8> NewMask; 13160 for (unsigned i = 0; i != NumElts; ++i) { 13161 int Idx = SVN->getMaskElt(i); 13162 if (Idx >= 0) { 13163 if (Idx >= (int)NumElts) 13164 Idx -= NumElts; 13165 else 13166 Idx = -1; // remove reference to lhs 13167 } 13168 NewMask.push_back(Idx); 13169 } 13170 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 13171 &NewMask[0]); 13172 } 13173 13174 // Remove references to rhs if it is undef 13175 if (N1.getOpcode() == ISD::UNDEF) { 13176 bool Changed = false; 13177 SmallVector<int, 8> NewMask; 13178 for (unsigned i = 0; i != NumElts; ++i) { 13179 int Idx = SVN->getMaskElt(i); 13180 if (Idx >= (int)NumElts) { 13181 Idx = -1; 13182 Changed = true; 13183 } 13184 NewMask.push_back(Idx); 13185 } 13186 if (Changed) 13187 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 13188 } 13189 13190 // If it is a splat, check if the argument vector is another splat or a 13191 // build_vector. 13192 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13193 SDNode *V = N0.getNode(); 13194 13195 // If this is a bit convert that changes the element type of the vector but 13196 // not the number of vector elements, look through it. Be careful not to 13197 // look though conversions that change things like v4f32 to v2f64. 13198 if (V->getOpcode() == ISD::BITCAST) { 13199 SDValue ConvInput = V->getOperand(0); 13200 if (ConvInput.getValueType().isVector() && 13201 ConvInput.getValueType().getVectorNumElements() == NumElts) 13202 V = ConvInput.getNode(); 13203 } 13204 13205 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13206 assert(V->getNumOperands() == NumElts && 13207 "BUILD_VECTOR has wrong number of operands"); 13208 SDValue Base; 13209 bool AllSame = true; 13210 for (unsigned i = 0; i != NumElts; ++i) { 13211 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 13212 Base = V->getOperand(i); 13213 break; 13214 } 13215 } 13216 // Splat of <u, u, u, u>, return <u, u, u, u> 13217 if (!Base.getNode()) 13218 return N0; 13219 for (unsigned i = 0; i != NumElts; ++i) { 13220 if (V->getOperand(i) != Base) { 13221 AllSame = false; 13222 break; 13223 } 13224 } 13225 // Splat of <x, x, x, x>, return <x, x, x, x> 13226 if (AllSame) 13227 return N0; 13228 13229 // Canonicalize any other splat as a build_vector. 13230 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13231 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13232 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 13233 V->getValueType(0), Ops); 13234 13235 // We may have jumped through bitcasts, so the type of the 13236 // BUILD_VECTOR may not match the type of the shuffle. 13237 if (V->getValueType(0) != VT) 13238 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 13239 return NewBV; 13240 } 13241 } 13242 13243 // There are various patterns used to build up a vector from smaller vectors, 13244 // subvectors, or elements. Scan chains of these and replace unused insertions 13245 // or components with undef. 13246 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13247 return S; 13248 13249 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13250 Level < AfterLegalizeVectorOps && 13251 (N1.getOpcode() == ISD::UNDEF || 13252 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13253 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13254 SDValue V = partitionShuffleOfConcats(N, DAG); 13255 13256 if (V.getNode()) 13257 return V; 13258 } 13259 13260 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13261 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13262 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13263 SmallVector<SDValue, 8> Ops; 13264 for (int M : SVN->getMask()) { 13265 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13266 if (M >= 0) { 13267 int Idx = M % NumElts; 13268 SDValue &S = (M < (int)NumElts ? N0 : N1); 13269 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13270 Op = S.getOperand(Idx); 13271 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13272 if (Idx == 0) 13273 Op = S.getOperand(0); 13274 } else { 13275 // Operand can't be combined - bail out. 13276 break; 13277 } 13278 } 13279 Ops.push_back(Op); 13280 } 13281 if (Ops.size() == VT.getVectorNumElements()) { 13282 // BUILD_VECTOR requires all inputs to be of the same type, find the 13283 // maximum type and extend them all. 13284 EVT SVT = VT.getScalarType(); 13285 if (SVT.isInteger()) 13286 for (SDValue &Op : Ops) 13287 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13288 if (SVT != VT.getScalarType()) 13289 for (SDValue &Op : Ops) 13290 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13291 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13292 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13293 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 13294 } 13295 } 13296 13297 // If this shuffle only has a single input that is a bitcasted shuffle, 13298 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13299 // back to their original types. 13300 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13301 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 13302 TLI.isTypeLegal(VT)) { 13303 13304 // Peek through the bitcast only if there is one user. 13305 SDValue BC0 = N0; 13306 while (BC0.getOpcode() == ISD::BITCAST) { 13307 if (!BC0.hasOneUse()) 13308 break; 13309 BC0 = BC0.getOperand(0); 13310 } 13311 13312 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13313 if (Scale == 1) 13314 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13315 13316 SmallVector<int, 8> NewMask; 13317 for (int M : Mask) 13318 for (int s = 0; s != Scale; ++s) 13319 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13320 return NewMask; 13321 }; 13322 13323 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13324 EVT SVT = VT.getScalarType(); 13325 EVT InnerVT = BC0->getValueType(0); 13326 EVT InnerSVT = InnerVT.getScalarType(); 13327 13328 // Determine which shuffle works with the smaller scalar type. 13329 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13330 EVT ScaleSVT = ScaleVT.getScalarType(); 13331 13332 if (TLI.isTypeLegal(ScaleVT) && 13333 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13334 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13335 13336 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13337 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13338 13339 // Scale the shuffle masks to the smaller scalar type. 13340 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13341 SmallVector<int, 8> InnerMask = 13342 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13343 SmallVector<int, 8> OuterMask = 13344 ScaleShuffleMask(SVN->getMask(), OuterScale); 13345 13346 // Merge the shuffle masks. 13347 SmallVector<int, 8> NewMask; 13348 for (int M : OuterMask) 13349 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13350 13351 // Test for shuffle mask legality over both commutations. 13352 SDValue SV0 = BC0->getOperand(0); 13353 SDValue SV1 = BC0->getOperand(1); 13354 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13355 if (!LegalMask) { 13356 std::swap(SV0, SV1); 13357 ShuffleVectorSDNode::commuteMask(NewMask); 13358 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13359 } 13360 13361 if (LegalMask) { 13362 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 13363 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 13364 return DAG.getNode( 13365 ISD::BITCAST, SDLoc(N), VT, 13366 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13367 } 13368 } 13369 } 13370 } 13371 13372 // Canonicalize shuffles according to rules: 13373 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13374 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13375 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13376 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13377 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13378 TLI.isTypeLegal(VT)) { 13379 // The incoming shuffle must be of the same type as the result of the 13380 // current shuffle. 13381 assert(N1->getOperand(0).getValueType() == VT && 13382 "Shuffle types don't match"); 13383 13384 SDValue SV0 = N1->getOperand(0); 13385 SDValue SV1 = N1->getOperand(1); 13386 bool HasSameOp0 = N0 == SV0; 13387 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 13388 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13389 // Commute the operands of this shuffle so that next rule 13390 // will trigger. 13391 return DAG.getCommutedVectorShuffle(*SVN); 13392 } 13393 13394 // Try to fold according to rules: 13395 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13396 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13397 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13398 // Don't try to fold shuffles with illegal type. 13399 // Only fold if this shuffle is the only user of the other shuffle. 13400 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13401 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13402 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13403 13404 // The incoming shuffle must be of the same type as the result of the 13405 // current shuffle. 13406 assert(OtherSV->getOperand(0).getValueType() == VT && 13407 "Shuffle types don't match"); 13408 13409 SDValue SV0, SV1; 13410 SmallVector<int, 4> Mask; 13411 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13412 // operand, and SV1 as the second operand. 13413 for (unsigned i = 0; i != NumElts; ++i) { 13414 int Idx = SVN->getMaskElt(i); 13415 if (Idx < 0) { 13416 // Propagate Undef. 13417 Mask.push_back(Idx); 13418 continue; 13419 } 13420 13421 SDValue CurrentVec; 13422 if (Idx < (int)NumElts) { 13423 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13424 // shuffle mask to identify which vector is actually referenced. 13425 Idx = OtherSV->getMaskElt(Idx); 13426 if (Idx < 0) { 13427 // Propagate Undef. 13428 Mask.push_back(Idx); 13429 continue; 13430 } 13431 13432 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13433 : OtherSV->getOperand(1); 13434 } else { 13435 // This shuffle index references an element within N1. 13436 CurrentVec = N1; 13437 } 13438 13439 // Simple case where 'CurrentVec' is UNDEF. 13440 if (CurrentVec.getOpcode() == ISD::UNDEF) { 13441 Mask.push_back(-1); 13442 continue; 13443 } 13444 13445 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13446 // will be the first or second operand of the combined shuffle. 13447 Idx = Idx % NumElts; 13448 if (!SV0.getNode() || SV0 == CurrentVec) { 13449 // Ok. CurrentVec is the left hand side. 13450 // Update the mask accordingly. 13451 SV0 = CurrentVec; 13452 Mask.push_back(Idx); 13453 continue; 13454 } 13455 13456 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13457 if (SV1.getNode() && SV1 != CurrentVec) 13458 return SDValue(); 13459 13460 // Ok. CurrentVec is the right hand side. 13461 // Update the mask accordingly. 13462 SV1 = CurrentVec; 13463 Mask.push_back(Idx + NumElts); 13464 } 13465 13466 // Check if all indices in Mask are Undef. In case, propagate Undef. 13467 bool isUndefMask = true; 13468 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13469 isUndefMask &= Mask[i] < 0; 13470 13471 if (isUndefMask) 13472 return DAG.getUNDEF(VT); 13473 13474 if (!SV0.getNode()) 13475 SV0 = DAG.getUNDEF(VT); 13476 if (!SV1.getNode()) 13477 SV1 = DAG.getUNDEF(VT); 13478 13479 // Avoid introducing shuffles with illegal mask. 13480 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13481 ShuffleVectorSDNode::commuteMask(Mask); 13482 13483 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13484 return SDValue(); 13485 13486 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13487 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13488 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13489 std::swap(SV0, SV1); 13490 } 13491 13492 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13493 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13494 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13495 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 13496 } 13497 13498 return SDValue(); 13499 } 13500 13501 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13502 SDValue InVal = N->getOperand(0); 13503 EVT VT = N->getValueType(0); 13504 13505 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13506 // with a VECTOR_SHUFFLE. 13507 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13508 SDValue InVec = InVal->getOperand(0); 13509 SDValue EltNo = InVal->getOperand(1); 13510 13511 // FIXME: We could support implicit truncation if the shuffle can be 13512 // scaled to a smaller vector scalar type. 13513 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13514 if (C0 && VT == InVec.getValueType() && 13515 VT.getScalarType() == InVal.getValueType()) { 13516 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13517 int Elt = C0->getZExtValue(); 13518 NewMask[0] = Elt; 13519 13520 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13521 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13522 NewMask); 13523 } 13524 } 13525 13526 return SDValue(); 13527 } 13528 13529 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13530 SDValue N0 = N->getOperand(0); 13531 SDValue N2 = N->getOperand(2); 13532 13533 // If the input vector is a concatenation, and the insert replaces 13534 // one of the halves, we can optimize into a single concat_vectors. 13535 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13536 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 13537 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13538 EVT VT = N->getValueType(0); 13539 13540 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13541 // (concat_vectors Z, Y) 13542 if (InsIdx == 0) 13543 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13544 N->getOperand(1), N0.getOperand(1)); 13545 13546 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13547 // (concat_vectors X, Z) 13548 if (InsIdx == VT.getVectorNumElements()/2) 13549 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13550 N0.getOperand(0), N->getOperand(1)); 13551 } 13552 13553 return SDValue(); 13554 } 13555 13556 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13557 SDValue N0 = N->getOperand(0); 13558 13559 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13560 if (N0->getOpcode() == ISD::FP16_TO_FP) 13561 return N0->getOperand(0); 13562 13563 return SDValue(); 13564 } 13565 13566 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13567 SDValue N0 = N->getOperand(0); 13568 13569 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13570 if (N0->getOpcode() == ISD::AND) { 13571 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13572 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13573 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13574 N0.getOperand(0)); 13575 } 13576 } 13577 13578 return SDValue(); 13579 } 13580 13581 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13582 /// with the destination vector and a zero vector. 13583 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13584 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13585 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13586 EVT VT = N->getValueType(0); 13587 SDValue LHS = N->getOperand(0); 13588 SDValue RHS = N->getOperand(1); 13589 SDLoc dl(N); 13590 13591 // Make sure we're not running after operation legalization where it 13592 // may have custom lowered the vector shuffles. 13593 if (LegalOperations) 13594 return SDValue(); 13595 13596 if (N->getOpcode() != ISD::AND) 13597 return SDValue(); 13598 13599 if (RHS.getOpcode() == ISD::BITCAST) 13600 RHS = RHS.getOperand(0); 13601 13602 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13603 return SDValue(); 13604 13605 EVT RVT = RHS.getValueType(); 13606 unsigned NumElts = RHS.getNumOperands(); 13607 13608 // Attempt to create a valid clear mask, splitting the mask into 13609 // sub elements and checking to see if each is 13610 // all zeros or all ones - suitable for shuffle masking. 13611 auto BuildClearMask = [&](int Split) { 13612 int NumSubElts = NumElts * Split; 13613 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13614 13615 SmallVector<int, 8> Indices; 13616 for (int i = 0; i != NumSubElts; ++i) { 13617 int EltIdx = i / Split; 13618 int SubIdx = i % Split; 13619 SDValue Elt = RHS.getOperand(EltIdx); 13620 if (Elt.getOpcode() == ISD::UNDEF) { 13621 Indices.push_back(-1); 13622 continue; 13623 } 13624 13625 APInt Bits; 13626 if (isa<ConstantSDNode>(Elt)) 13627 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13628 else if (isa<ConstantFPSDNode>(Elt)) 13629 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13630 else 13631 return SDValue(); 13632 13633 // Extract the sub element from the constant bit mask. 13634 if (DAG.getDataLayout().isBigEndian()) { 13635 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13636 } else { 13637 Bits = Bits.lshr(SubIdx * NumSubBits); 13638 } 13639 13640 if (Split > 1) 13641 Bits = Bits.trunc(NumSubBits); 13642 13643 if (Bits.isAllOnesValue()) 13644 Indices.push_back(i); 13645 else if (Bits == 0) 13646 Indices.push_back(i + NumSubElts); 13647 else 13648 return SDValue(); 13649 } 13650 13651 // Let's see if the target supports this vector_shuffle. 13652 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13653 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13654 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13655 return SDValue(); 13656 13657 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13658 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13659 DAG.getBitcast(ClearVT, LHS), 13660 Zero, &Indices[0])); 13661 }; 13662 13663 // Determine maximum split level (byte level masking). 13664 int MaxSplit = 1; 13665 if (RVT.getScalarSizeInBits() % 8 == 0) 13666 MaxSplit = RVT.getScalarSizeInBits() / 8; 13667 13668 for (int Split = 1; Split <= MaxSplit; ++Split) 13669 if (RVT.getScalarSizeInBits() % Split == 0) 13670 if (SDValue S = BuildClearMask(Split)) 13671 return S; 13672 13673 return SDValue(); 13674 } 13675 13676 /// Visit a binary vector operation, like ADD. 13677 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13678 assert(N->getValueType(0).isVector() && 13679 "SimplifyVBinOp only works on vectors!"); 13680 13681 SDValue LHS = N->getOperand(0); 13682 SDValue RHS = N->getOperand(1); 13683 SDValue Ops[] = {LHS, RHS}; 13684 13685 // See if we can constant fold the vector operation. 13686 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 13687 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 13688 return Fold; 13689 13690 // Try to convert a constant mask AND into a shuffle clear mask. 13691 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13692 return Shuffle; 13693 13694 // Type legalization might introduce new shuffles in the DAG. 13695 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13696 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13697 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13698 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13699 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 13700 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 13701 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13702 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13703 13704 if (SVN0->getMask().equals(SVN1->getMask())) { 13705 EVT VT = N->getValueType(0); 13706 SDValue UndefVector = LHS.getOperand(1); 13707 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13708 LHS.getOperand(0), RHS.getOperand(0), 13709 N->getFlags()); 13710 AddUsersToWorklist(N); 13711 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13712 &SVN0->getMask()[0]); 13713 } 13714 } 13715 13716 return SDValue(); 13717 } 13718 13719 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13720 SDValue N1, SDValue N2){ 13721 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13722 13723 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13724 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13725 13726 // If we got a simplified select_cc node back from SimplifySelectCC, then 13727 // break it down into a new SETCC node, and a new SELECT node, and then return 13728 // the SELECT node, since we were called with a SELECT node. 13729 if (SCC.getNode()) { 13730 // Check to see if we got a select_cc back (to turn into setcc/select). 13731 // Otherwise, just return whatever node we got back, like fabs. 13732 if (SCC.getOpcode() == ISD::SELECT_CC) { 13733 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13734 N0.getValueType(), 13735 SCC.getOperand(0), SCC.getOperand(1), 13736 SCC.getOperand(4)); 13737 AddToWorklist(SETCC.getNode()); 13738 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13739 SCC.getOperand(2), SCC.getOperand(3)); 13740 } 13741 13742 return SCC; 13743 } 13744 return SDValue(); 13745 } 13746 13747 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13748 /// being selected between, see if we can simplify the select. Callers of this 13749 /// should assume that TheSelect is deleted if this returns true. As such, they 13750 /// should return the appropriate thing (e.g. the node) back to the top-level of 13751 /// the DAG combiner loop to avoid it being looked at. 13752 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13753 SDValue RHS) { 13754 13755 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13756 // The select + setcc is redundant, because fsqrt returns NaN for X < -0. 13757 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13758 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13759 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13760 SDValue Sqrt = RHS; 13761 ISD::CondCode CC; 13762 SDValue CmpLHS; 13763 const ConstantFPSDNode *NegZero = nullptr; 13764 13765 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13766 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13767 CmpLHS = TheSelect->getOperand(0); 13768 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13769 } else { 13770 // SELECT or VSELECT 13771 SDValue Cmp = TheSelect->getOperand(0); 13772 if (Cmp.getOpcode() == ISD::SETCC) { 13773 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13774 CmpLHS = Cmp.getOperand(0); 13775 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13776 } 13777 } 13778 if (NegZero && NegZero->isNegative() && NegZero->isZero() && 13779 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13780 CC == ISD::SETULT || CC == ISD::SETLT)) { 13781 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13782 CombineTo(TheSelect, Sqrt); 13783 return true; 13784 } 13785 } 13786 } 13787 // Cannot simplify select with vector condition 13788 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 13789 13790 // If this is a select from two identical things, try to pull the operation 13791 // through the select. 13792 if (LHS.getOpcode() != RHS.getOpcode() || 13793 !LHS.hasOneUse() || !RHS.hasOneUse()) 13794 return false; 13795 13796 // If this is a load and the token chain is identical, replace the select 13797 // of two loads with a load through a select of the address to load from. 13798 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 13799 // constants have been dropped into the constant pool. 13800 if (LHS.getOpcode() == ISD::LOAD) { 13801 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 13802 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 13803 13804 // Token chains must be identical. 13805 if (LHS.getOperand(0) != RHS.getOperand(0) || 13806 // Do not let this transformation reduce the number of volatile loads. 13807 LLD->isVolatile() || RLD->isVolatile() || 13808 // FIXME: If either is a pre/post inc/dec load, 13809 // we'd need to split out the address adjustment. 13810 LLD->isIndexed() || RLD->isIndexed() || 13811 // If this is an EXTLOAD, the VT's must match. 13812 LLD->getMemoryVT() != RLD->getMemoryVT() || 13813 // If this is an EXTLOAD, the kind of extension must match. 13814 (LLD->getExtensionType() != RLD->getExtensionType() && 13815 // The only exception is if one of the extensions is anyext. 13816 LLD->getExtensionType() != ISD::EXTLOAD && 13817 RLD->getExtensionType() != ISD::EXTLOAD) || 13818 // FIXME: this discards src value information. This is 13819 // over-conservative. It would be beneficial to be able to remember 13820 // both potential memory locations. Since we are discarding 13821 // src value info, don't do the transformation if the memory 13822 // locations are not in the default address space. 13823 LLD->getPointerInfo().getAddrSpace() != 0 || 13824 RLD->getPointerInfo().getAddrSpace() != 0 || 13825 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 13826 LLD->getBasePtr().getValueType())) 13827 return false; 13828 13829 // Check that the select condition doesn't reach either load. If so, 13830 // folding this will induce a cycle into the DAG. If not, this is safe to 13831 // xform, so create a select of the addresses. 13832 SDValue Addr; 13833 if (TheSelect->getOpcode() == ISD::SELECT) { 13834 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 13835 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 13836 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 13837 return false; 13838 // The loads must not depend on one another. 13839 if (LLD->isPredecessorOf(RLD) || 13840 RLD->isPredecessorOf(LLD)) 13841 return false; 13842 Addr = DAG.getSelect(SDLoc(TheSelect), 13843 LLD->getBasePtr().getValueType(), 13844 TheSelect->getOperand(0), LLD->getBasePtr(), 13845 RLD->getBasePtr()); 13846 } else { // Otherwise SELECT_CC 13847 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 13848 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 13849 13850 if ((LLD->hasAnyUseOfValue(1) && 13851 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 13852 (RLD->hasAnyUseOfValue(1) && 13853 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 13854 return false; 13855 13856 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 13857 LLD->getBasePtr().getValueType(), 13858 TheSelect->getOperand(0), 13859 TheSelect->getOperand(1), 13860 LLD->getBasePtr(), RLD->getBasePtr(), 13861 TheSelect->getOperand(4)); 13862 } 13863 13864 SDValue Load; 13865 // It is safe to replace the two loads if they have different alignments, 13866 // but the new load must be the minimum (most restrictive) alignment of the 13867 // inputs. 13868 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 13869 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 13870 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 13871 Load = DAG.getLoad(TheSelect->getValueType(0), 13872 SDLoc(TheSelect), 13873 // FIXME: Discards pointer and AA info. 13874 LLD->getChain(), Addr, MachinePointerInfo(), 13875 LLD->isVolatile(), LLD->isNonTemporal(), 13876 isInvariant, Alignment); 13877 } else { 13878 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 13879 RLD->getExtensionType() : LLD->getExtensionType(), 13880 SDLoc(TheSelect), 13881 TheSelect->getValueType(0), 13882 // FIXME: Discards pointer and AA info. 13883 LLD->getChain(), Addr, MachinePointerInfo(), 13884 LLD->getMemoryVT(), LLD->isVolatile(), 13885 LLD->isNonTemporal(), isInvariant, Alignment); 13886 } 13887 13888 // Users of the select now use the result of the load. 13889 CombineTo(TheSelect, Load); 13890 13891 // Users of the old loads now use the new load's chain. We know the 13892 // old-load value is dead now. 13893 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 13894 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 13895 return true; 13896 } 13897 13898 return false; 13899 } 13900 13901 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 13902 /// where 'cond' is the comparison specified by CC. 13903 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 13904 SDValue N2, SDValue N3, 13905 ISD::CondCode CC, bool NotExtCompare) { 13906 // (x ? y : y) -> y. 13907 if (N2 == N3) return N2; 13908 13909 EVT VT = N2.getValueType(); 13910 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 13911 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 13912 13913 // Determine if the condition we're dealing with is constant 13914 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 13915 N0, N1, CC, DL, false); 13916 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 13917 13918 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 13919 // fold select_cc true, x, y -> x 13920 // fold select_cc false, x, y -> y 13921 return !SCCC->isNullValue() ? N2 : N3; 13922 } 13923 13924 // Check to see if we can simplify the select into an fabs node 13925 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 13926 // Allow either -0.0 or 0.0 13927 if (CFP->isZero()) { 13928 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 13929 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 13930 N0 == N2 && N3.getOpcode() == ISD::FNEG && 13931 N2 == N3.getOperand(0)) 13932 return DAG.getNode(ISD::FABS, DL, VT, N0); 13933 13934 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 13935 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 13936 N0 == N3 && N2.getOpcode() == ISD::FNEG && 13937 N2.getOperand(0) == N3) 13938 return DAG.getNode(ISD::FABS, DL, VT, N3); 13939 } 13940 } 13941 13942 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 13943 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 13944 // in it. This is a win when the constant is not otherwise available because 13945 // it replaces two constant pool loads with one. We only do this if the FP 13946 // type is known to be legal, because if it isn't, then we are before legalize 13947 // types an we want the other legalization to happen first (e.g. to avoid 13948 // messing with soft float) and if the ConstantFP is not legal, because if 13949 // it is legal, we may not need to store the FP constant in a constant pool. 13950 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 13951 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 13952 if (TLI.isTypeLegal(N2.getValueType()) && 13953 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 13954 TargetLowering::Legal && 13955 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 13956 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 13957 // If both constants have multiple uses, then we won't need to do an 13958 // extra load, they are likely around in registers for other users. 13959 (TV->hasOneUse() || FV->hasOneUse())) { 13960 Constant *Elts[] = { 13961 const_cast<ConstantFP*>(FV->getConstantFPValue()), 13962 const_cast<ConstantFP*>(TV->getConstantFPValue()) 13963 }; 13964 Type *FPTy = Elts[0]->getType(); 13965 const DataLayout &TD = DAG.getDataLayout(); 13966 13967 // Create a ConstantArray of the two constants. 13968 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 13969 SDValue CPIdx = 13970 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 13971 TD.getPrefTypeAlignment(FPTy)); 13972 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 13973 13974 // Get the offsets to the 0 and 1 element of the array so that we can 13975 // select between them. 13976 SDValue Zero = DAG.getIntPtrConstant(0, DL); 13977 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 13978 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 13979 13980 SDValue Cond = DAG.getSetCC(DL, 13981 getSetCCResultType(N0.getValueType()), 13982 N0, N1, CC); 13983 AddToWorklist(Cond.getNode()); 13984 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 13985 Cond, One, Zero); 13986 AddToWorklist(CstOffset.getNode()); 13987 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 13988 CstOffset); 13989 AddToWorklist(CPIdx.getNode()); 13990 return DAG.getLoad( 13991 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 13992 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 13993 false, false, false, Alignment); 13994 } 13995 } 13996 13997 // Check to see if we can perform the "gzip trick", transforming 13998 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 13999 if (isNullConstant(N3) && CC == ISD::SETLT && 14000 (isNullConstant(N1) || // (a < 0) ? b : 0 14001 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 14002 EVT XType = N0.getValueType(); 14003 EVT AType = N2.getValueType(); 14004 if (XType.bitsGE(AType)) { 14005 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 14006 // single-bit constant. 14007 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14008 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 14009 ShCtV = XType.getSizeInBits() - ShCtV - 1; 14010 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 14011 getShiftAmountTy(N0.getValueType())); 14012 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 14013 XType, N0, ShCt); 14014 AddToWorklist(Shift.getNode()); 14015 14016 if (XType.bitsGT(AType)) { 14017 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14018 AddToWorklist(Shift.getNode()); 14019 } 14020 14021 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14022 } 14023 14024 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 14025 XType, N0, 14026 DAG.getConstant(XType.getSizeInBits() - 1, 14027 SDLoc(N0), 14028 getShiftAmountTy(N0.getValueType()))); 14029 AddToWorklist(Shift.getNode()); 14030 14031 if (XType.bitsGT(AType)) { 14032 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14033 AddToWorklist(Shift.getNode()); 14034 } 14035 14036 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14037 } 14038 } 14039 14040 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14041 // where y is has a single bit set. 14042 // A plaintext description would be, we can turn the SELECT_CC into an AND 14043 // when the condition can be materialized as an all-ones register. Any 14044 // single bit-test can be materialized as an all-ones register with 14045 // shift-left and shift-right-arith. 14046 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14047 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14048 SDValue AndLHS = N0->getOperand(0); 14049 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14050 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14051 // Shift the tested bit over the sign bit. 14052 APInt AndMask = ConstAndRHS->getAPIntValue(); 14053 SDValue ShlAmt = 14054 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14055 getShiftAmountTy(AndLHS.getValueType())); 14056 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14057 14058 // Now arithmetic right shift it all the way over, so the result is either 14059 // all-ones, or zero. 14060 SDValue ShrAmt = 14061 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14062 getShiftAmountTy(Shl.getValueType())); 14063 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14064 14065 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14066 } 14067 } 14068 14069 // fold select C, 16, 0 -> shl C, 4 14070 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14071 TLI.getBooleanContents(N0.getValueType()) == 14072 TargetLowering::ZeroOrOneBooleanContent) { 14073 14074 // If the caller doesn't want us to simplify this into a zext of a compare, 14075 // don't do it. 14076 if (NotExtCompare && N2C->isOne()) 14077 return SDValue(); 14078 14079 // Get a SetCC of the condition 14080 // NOTE: Don't create a SETCC if it's not legal on this target. 14081 if (!LegalOperations || 14082 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14083 SDValue Temp, SCC; 14084 // cast from setcc result type to select result type 14085 if (LegalTypes) { 14086 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14087 N0, N1, CC); 14088 if (N2.getValueType().bitsLT(SCC.getValueType())) 14089 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14090 N2.getValueType()); 14091 else 14092 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14093 N2.getValueType(), SCC); 14094 } else { 14095 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14096 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14097 N2.getValueType(), SCC); 14098 } 14099 14100 AddToWorklist(SCC.getNode()); 14101 AddToWorklist(Temp.getNode()); 14102 14103 if (N2C->isOne()) 14104 return Temp; 14105 14106 // shl setcc result by log2 n2c 14107 return DAG.getNode( 14108 ISD::SHL, DL, N2.getValueType(), Temp, 14109 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14110 getShiftAmountTy(Temp.getValueType()))); 14111 } 14112 } 14113 14114 // Check to see if this is an integer abs. 14115 // select_cc setg[te] X, 0, X, -X -> 14116 // select_cc setgt X, -1, X, -X -> 14117 // select_cc setl[te] X, 0, -X, X -> 14118 // select_cc setlt X, 1, -X, X -> 14119 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14120 if (N1C) { 14121 ConstantSDNode *SubC = nullptr; 14122 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14123 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14124 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14125 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14126 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14127 (N1C->isOne() && CC == ISD::SETLT)) && 14128 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14129 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14130 14131 EVT XType = N0.getValueType(); 14132 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14133 SDLoc DL(N0); 14134 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14135 N0, 14136 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14137 getShiftAmountTy(N0.getValueType()))); 14138 SDValue Add = DAG.getNode(ISD::ADD, DL, 14139 XType, N0, Shift); 14140 AddToWorklist(Shift.getNode()); 14141 AddToWorklist(Add.getNode()); 14142 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14143 } 14144 } 14145 14146 return SDValue(); 14147 } 14148 14149 /// This is a stub for TargetLowering::SimplifySetCC. 14150 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 14151 SDValue N1, ISD::CondCode Cond, 14152 SDLoc DL, bool foldBooleans) { 14153 TargetLowering::DAGCombinerInfo 14154 DagCombineInfo(DAG, Level, false, this); 14155 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14156 } 14157 14158 /// Given an ISD::SDIV node expressing a divide by constant, return 14159 /// a DAG expression to select that will generate the same value by multiplying 14160 /// by a magic number. 14161 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14162 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14163 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14164 if (!C) 14165 return SDValue(); 14166 14167 // Avoid division by zero. 14168 if (C->isNullValue()) 14169 return SDValue(); 14170 14171 std::vector<SDNode*> Built; 14172 SDValue S = 14173 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14174 14175 for (SDNode *N : Built) 14176 AddToWorklist(N); 14177 return S; 14178 } 14179 14180 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14181 /// DAG expression that will generate the same value by right shifting. 14182 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14183 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14184 if (!C) 14185 return SDValue(); 14186 14187 // Avoid division by zero. 14188 if (C->isNullValue()) 14189 return SDValue(); 14190 14191 std::vector<SDNode *> Built; 14192 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14193 14194 for (SDNode *N : Built) 14195 AddToWorklist(N); 14196 return S; 14197 } 14198 14199 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14200 /// expression that will generate the same value by multiplying by a magic 14201 /// number. 14202 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14203 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14204 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14205 if (!C) 14206 return SDValue(); 14207 14208 // Avoid division by zero. 14209 if (C->isNullValue()) 14210 return SDValue(); 14211 14212 std::vector<SDNode*> Built; 14213 SDValue S = 14214 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14215 14216 for (SDNode *N : Built) 14217 AddToWorklist(N); 14218 return S; 14219 } 14220 14221 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14222 if (Level >= AfterLegalizeDAG) 14223 return SDValue(); 14224 14225 // Expose the DAG combiner to the target combiner implementations. 14226 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14227 14228 unsigned Iterations = 0; 14229 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14230 if (Iterations) { 14231 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14232 // For the reciprocal, we need to find the zero of the function: 14233 // F(X) = A X - 1 [which has a zero at X = 1/A] 14234 // => 14235 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14236 // does not require additional intermediate precision] 14237 EVT VT = Op.getValueType(); 14238 SDLoc DL(Op); 14239 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14240 14241 AddToWorklist(Est.getNode()); 14242 14243 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14244 for (unsigned i = 0; i < Iterations; ++i) { 14245 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14246 AddToWorklist(NewEst.getNode()); 14247 14248 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14249 AddToWorklist(NewEst.getNode()); 14250 14251 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14252 AddToWorklist(NewEst.getNode()); 14253 14254 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14255 AddToWorklist(Est.getNode()); 14256 } 14257 } 14258 return Est; 14259 } 14260 14261 return SDValue(); 14262 } 14263 14264 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14265 /// For the reciprocal sqrt, we need to find the zero of the function: 14266 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14267 /// => 14268 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14269 /// As a result, we precompute A/2 prior to the iteration loop. 14270 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 14271 unsigned Iterations, 14272 SDNodeFlags *Flags) { 14273 EVT VT = Arg.getValueType(); 14274 SDLoc DL(Arg); 14275 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14276 14277 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14278 // this entire sequence requires only one FP constant. 14279 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14280 AddToWorklist(HalfArg.getNode()); 14281 14282 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14283 AddToWorklist(HalfArg.getNode()); 14284 14285 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14286 for (unsigned i = 0; i < Iterations; ++i) { 14287 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14288 AddToWorklist(NewEst.getNode()); 14289 14290 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14291 AddToWorklist(NewEst.getNode()); 14292 14293 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14294 AddToWorklist(NewEst.getNode()); 14295 14296 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14297 AddToWorklist(Est.getNode()); 14298 } 14299 return Est; 14300 } 14301 14302 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14303 /// For the reciprocal sqrt, we need to find the zero of the function: 14304 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14305 /// => 14306 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14307 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 14308 unsigned Iterations, 14309 SDNodeFlags *Flags) { 14310 EVT VT = Arg.getValueType(); 14311 SDLoc DL(Arg); 14312 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14313 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14314 14315 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 14316 for (unsigned i = 0; i < Iterations; ++i) { 14317 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14318 AddToWorklist(HalfEst.getNode()); 14319 14320 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14321 AddToWorklist(Est.getNode()); 14322 14323 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14324 AddToWorklist(Est.getNode()); 14325 14326 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags); 14327 AddToWorklist(Est.getNode()); 14328 14329 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags); 14330 AddToWorklist(Est.getNode()); 14331 } 14332 return Est; 14333 } 14334 14335 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14336 if (Level >= AfterLegalizeDAG) 14337 return SDValue(); 14338 14339 // Expose the DAG combiner to the target combiner implementations. 14340 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14341 unsigned Iterations = 0; 14342 bool UseOneConstNR = false; 14343 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14344 AddToWorklist(Est.getNode()); 14345 if (Iterations) { 14346 Est = UseOneConstNR ? 14347 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) : 14348 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags); 14349 } 14350 return Est; 14351 } 14352 14353 return SDValue(); 14354 } 14355 14356 /// Return true if base is a frame index, which is known not to alias with 14357 /// anything but itself. Provides base object and offset as results. 14358 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14359 const GlobalValue *&GV, const void *&CV) { 14360 // Assume it is a primitive operation. 14361 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14362 14363 // If it's an adding a simple constant then integrate the offset. 14364 if (Base.getOpcode() == ISD::ADD) { 14365 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14366 Base = Base.getOperand(0); 14367 Offset += C->getZExtValue(); 14368 } 14369 } 14370 14371 // Return the underlying GlobalValue, and update the Offset. Return false 14372 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14373 // by multiple nodes with different offsets. 14374 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14375 GV = G->getGlobal(); 14376 Offset += G->getOffset(); 14377 return false; 14378 } 14379 14380 // Return the underlying Constant value, and update the Offset. Return false 14381 // for ConstantSDNodes since the same constant pool entry may be represented 14382 // by multiple nodes with different offsets. 14383 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14384 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14385 : (const void *)C->getConstVal(); 14386 Offset += C->getOffset(); 14387 return false; 14388 } 14389 // If it's any of the following then it can't alias with anything but itself. 14390 return isa<FrameIndexSDNode>(Base); 14391 } 14392 14393 /// Return true if there is any possibility that the two addresses overlap. 14394 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14395 // If they are the same then they must be aliases. 14396 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14397 14398 // If they are both volatile then they cannot be reordered. 14399 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14400 14401 // If one operation reads from invariant memory, and the other may store, they 14402 // cannot alias. These should really be checking the equivalent of mayWrite, 14403 // but it only matters for memory nodes other than load /store. 14404 if (Op0->isInvariant() && Op1->writeMem()) 14405 return false; 14406 14407 if (Op1->isInvariant() && Op0->writeMem()) 14408 return false; 14409 14410 // Gather base node and offset information. 14411 SDValue Base1, Base2; 14412 int64_t Offset1, Offset2; 14413 const GlobalValue *GV1, *GV2; 14414 const void *CV1, *CV2; 14415 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14416 Base1, Offset1, GV1, CV1); 14417 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14418 Base2, Offset2, GV2, CV2); 14419 14420 // If they have a same base address then check to see if they overlap. 14421 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14422 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14423 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14424 14425 // It is possible for different frame indices to alias each other, mostly 14426 // when tail call optimization reuses return address slots for arguments. 14427 // To catch this case, look up the actual index of frame indices to compute 14428 // the real alias relationship. 14429 if (isFrameIndex1 && isFrameIndex2) { 14430 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 14431 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14432 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14433 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14434 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14435 } 14436 14437 // Otherwise, if we know what the bases are, and they aren't identical, then 14438 // we know they cannot alias. 14439 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14440 return false; 14441 14442 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14443 // compared to the size and offset of the access, we may be able to prove they 14444 // do not alias. This check is conservative for now to catch cases created by 14445 // splitting vector types. 14446 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14447 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14448 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14449 Op1->getMemoryVT().getSizeInBits() >> 3) && 14450 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 14451 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14452 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14453 14454 // There is no overlap between these relatively aligned accesses of similar 14455 // size, return no alias. 14456 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14457 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14458 return false; 14459 } 14460 14461 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14462 ? CombinerGlobalAA 14463 : DAG.getSubtarget().useAA(); 14464 #ifndef NDEBUG 14465 if (CombinerAAOnlyFunc.getNumOccurrences() && 14466 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14467 UseAA = false; 14468 #endif 14469 if (UseAA && 14470 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14471 // Use alias analysis information. 14472 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14473 Op1->getSrcValueOffset()); 14474 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14475 Op0->getSrcValueOffset() - MinOffset; 14476 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14477 Op1->getSrcValueOffset() - MinOffset; 14478 AliasResult AAResult = 14479 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14480 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14481 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14482 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14483 if (AAResult == NoAlias) 14484 return false; 14485 } 14486 14487 // Otherwise we have to assume they alias. 14488 return true; 14489 } 14490 14491 /// Walk up chain skipping non-aliasing memory nodes, 14492 /// looking for aliasing nodes and adding them to the Aliases vector. 14493 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14494 SmallVectorImpl<SDValue> &Aliases) { 14495 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14496 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14497 14498 // Get alias information for node. 14499 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14500 14501 // Starting off. 14502 Chains.push_back(OriginalChain); 14503 unsigned Depth = 0; 14504 14505 // Look at each chain and determine if it is an alias. If so, add it to the 14506 // aliases list. If not, then continue up the chain looking for the next 14507 // candidate. 14508 while (!Chains.empty()) { 14509 SDValue Chain = Chains.pop_back_val(); 14510 14511 // For TokenFactor nodes, look at each operand and only continue up the 14512 // chain until we reach the depth limit. 14513 // 14514 // FIXME: The depth check could be made to return the last non-aliasing 14515 // chain we found before we hit a tokenfactor rather than the original 14516 // chain. 14517 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 14518 Aliases.clear(); 14519 Aliases.push_back(OriginalChain); 14520 return; 14521 } 14522 14523 // Don't bother if we've been before. 14524 if (!Visited.insert(Chain.getNode()).second) 14525 continue; 14526 14527 switch (Chain.getOpcode()) { 14528 case ISD::EntryToken: 14529 // Entry token is ideal chain operand, but handled in FindBetterChain. 14530 break; 14531 14532 case ISD::LOAD: 14533 case ISD::STORE: { 14534 // Get alias information for Chain. 14535 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14536 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14537 14538 // If chain is alias then stop here. 14539 if (!(IsLoad && IsOpLoad) && 14540 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14541 Aliases.push_back(Chain); 14542 } else { 14543 // Look further up the chain. 14544 Chains.push_back(Chain.getOperand(0)); 14545 ++Depth; 14546 } 14547 break; 14548 } 14549 14550 case ISD::TokenFactor: 14551 // We have to check each of the operands of the token factor for "small" 14552 // token factors, so we queue them up. Adding the operands to the queue 14553 // (stack) in reverse order maintains the original order and increases the 14554 // likelihood that getNode will find a matching token factor (CSE.) 14555 if (Chain.getNumOperands() > 16) { 14556 Aliases.push_back(Chain); 14557 break; 14558 } 14559 for (unsigned n = Chain.getNumOperands(); n;) 14560 Chains.push_back(Chain.getOperand(--n)); 14561 ++Depth; 14562 break; 14563 14564 default: 14565 // For all other instructions we will just have to take what we can get. 14566 Aliases.push_back(Chain); 14567 break; 14568 } 14569 } 14570 14571 // We need to be careful here to also search for aliases through the 14572 // value operand of a store, etc. Consider the following situation: 14573 // Token1 = ... 14574 // L1 = load Token1, %52 14575 // S1 = store Token1, L1, %51 14576 // L2 = load Token1, %52+8 14577 // S2 = store Token1, L2, %51+8 14578 // Token2 = Token(S1, S2) 14579 // L3 = load Token2, %53 14580 // S3 = store Token2, L3, %52 14581 // L4 = load Token2, %53+8 14582 // S4 = store Token2, L4, %52+8 14583 // If we search for aliases of S3 (which loads address %52), and we look 14584 // only through the chain, then we'll miss the trivial dependence on L1 14585 // (which also loads from %52). We then might change all loads and 14586 // stores to use Token1 as their chain operand, which could result in 14587 // copying %53 into %52 before copying %52 into %51 (which should 14588 // happen first). 14589 // 14590 // The problem is, however, that searching for such data dependencies 14591 // can become expensive, and the cost is not directly related to the 14592 // chain depth. Instead, we'll rule out such configurations here by 14593 // insisting that we've visited all chain users (except for users 14594 // of the original chain, which is not necessary). When doing this, 14595 // we need to look through nodes we don't care about (otherwise, things 14596 // like register copies will interfere with trivial cases). 14597 14598 SmallVector<const SDNode *, 16> Worklist; 14599 for (const SDNode *N : Visited) 14600 if (N != OriginalChain.getNode()) 14601 Worklist.push_back(N); 14602 14603 while (!Worklist.empty()) { 14604 const SDNode *M = Worklist.pop_back_val(); 14605 14606 // We have already visited M, and want to make sure we've visited any uses 14607 // of M that we care about. For uses that we've not visisted, and don't 14608 // care about, queue them to the worklist. 14609 14610 for (SDNode::use_iterator UI = M->use_begin(), 14611 UIE = M->use_end(); UI != UIE; ++UI) 14612 if (UI.getUse().getValueType() == MVT::Other && 14613 Visited.insert(*UI).second) { 14614 if (isa<MemSDNode>(*UI)) { 14615 // We've not visited this use, and we care about it (it could have an 14616 // ordering dependency with the original node). 14617 Aliases.clear(); 14618 Aliases.push_back(OriginalChain); 14619 return; 14620 } 14621 14622 // We've not visited this use, but we don't care about it. Mark it as 14623 // visited and enqueue it to the worklist. 14624 Worklist.push_back(*UI); 14625 } 14626 } 14627 } 14628 14629 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14630 /// (aliasing node.) 14631 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14632 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14633 14634 // Accumulate all the aliases to this node. 14635 GatherAllAliases(N, OldChain, Aliases); 14636 14637 // If no operands then chain to entry token. 14638 if (Aliases.size() == 0) 14639 return DAG.getEntryNode(); 14640 14641 // If a single operand then chain to it. We don't need to revisit it. 14642 if (Aliases.size() == 1) 14643 return Aliases[0]; 14644 14645 // Construct a custom tailored token factor. 14646 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14647 } 14648 14649 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) { 14650 // This holds the base pointer, index, and the offset in bytes from the base 14651 // pointer. 14652 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 14653 14654 // We must have a base and an offset. 14655 if (!BasePtr.Base.getNode()) 14656 return false; 14657 14658 // Do not handle stores to undef base pointers. 14659 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 14660 return false; 14661 14662 SmallVector<StoreSDNode *, 8> ChainedStores; 14663 ChainedStores.push_back(St); 14664 14665 // Walk up the chain and look for nodes with offsets from the same 14666 // base pointer. Stop when reaching an instruction with a different kind 14667 // or instruction which has a different base pointer. 14668 StoreSDNode *Index = St; 14669 while (Index) { 14670 // If the chain has more than one use, then we can't reorder the mem ops. 14671 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14672 break; 14673 14674 if (Index->isVolatile() || Index->isIndexed()) 14675 break; 14676 14677 // Find the base pointer and offset for this memory node. 14678 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 14679 14680 // Check that the base pointer is the same as the original one. 14681 if (!Ptr.equalBaseIndex(BasePtr)) 14682 break; 14683 14684 // Find the next memory operand in the chain. If the next operand in the 14685 // chain is a store then move up and continue the scan with the next 14686 // memory operand. If the next operand is a load save it and use alias 14687 // information to check if it interferes with anything. 14688 SDNode *NextInChain = Index->getChain().getNode(); 14689 while (true) { 14690 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14691 // We found a store node. Use it for the next iteration. 14692 ChainedStores.push_back(STn); 14693 Index = STn; 14694 break; 14695 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14696 NextInChain = Ldn->getChain().getNode(); 14697 continue; 14698 } else { 14699 Index = nullptr; 14700 break; 14701 } 14702 } 14703 } 14704 14705 bool MadeChange = false; 14706 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 14707 14708 for (StoreSDNode *ChainedStore : ChainedStores) { 14709 SDValue Chain = ChainedStore->getChain(); 14710 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 14711 14712 if (Chain != BetterChain) { 14713 MadeChange = true; 14714 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 14715 } 14716 } 14717 14718 // Do all replacements after finding the replacements to make to avoid making 14719 // the chains more complicated by introducing new TokenFactors. 14720 for (auto Replacement : BetterChains) 14721 replaceStoreChain(Replacement.first, Replacement.second); 14722 14723 return MadeChange; 14724 } 14725 14726 /// This is the entry point for the file. 14727 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 14728 CodeGenOpt::Level OptLevel) { 14729 /// This is the main entry point to this class. 14730 DAGCombiner(*this, AA, OptLevel).Run(Level); 14731 } 14732