1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/SelectionDAG.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/LLVMContext.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Target/TargetLowering.h" 38 #include "llvm/Target/TargetOptions.h" 39 #include "llvm/Target/TargetRegisterInfo.h" 40 #include "llvm/Target/TargetSubtargetInfo.h" 41 #include <algorithm> 42 using namespace llvm; 43 44 #define DEBUG_TYPE "dagcombine" 45 46 STATISTIC(NodesCombined , "Number of dag nodes combined"); 47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 49 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 50 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 51 STATISTIC(SlicedLoads, "Number of load sliced"); 52 53 namespace { 54 static cl::opt<bool> 55 CombinerAA("combiner-alias-analysis", cl::Hidden, 56 cl::desc("Enable DAG combiner alias-analysis heuristics")); 57 58 static cl::opt<bool> 59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 60 cl::desc("Enable DAG combiner's use of IR alias analysis")); 61 62 static cl::opt<bool> 63 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 64 cl::desc("Enable DAG combiner's use of TBAA")); 65 66 #ifndef NDEBUG 67 static cl::opt<std::string> 68 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 69 cl::desc("Only use DAG-combiner alias analysis in this" 70 " function")); 71 #endif 72 73 /// Hidden option to stress test load slicing, i.e., when this option 74 /// is enabled, load slicing bypasses most of its profitability guards. 75 static cl::opt<bool> 76 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 77 cl::desc("Bypass the profitability model of load " 78 "slicing"), 79 cl::init(false)); 80 81 static cl::opt<bool> 82 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 83 cl::desc("DAG combiner may split indexing from loads")); 84 85 //------------------------------ DAGCombiner ---------------------------------// 86 87 class DAGCombiner { 88 SelectionDAG &DAG; 89 const TargetLowering &TLI; 90 CombineLevel Level; 91 CodeGenOpt::Level OptLevel; 92 bool LegalOperations; 93 bool LegalTypes; 94 bool ForCodeSize; 95 96 /// \brief Worklist of all of the nodes that need to be simplified. 97 /// 98 /// This must behave as a stack -- new nodes to process are pushed onto the 99 /// back and when processing we pop off of the back. 100 /// 101 /// The worklist will not contain duplicates but may contain null entries 102 /// due to nodes being deleted from the underlying DAG. 103 SmallVector<SDNode *, 64> Worklist; 104 105 /// \brief Mapping from an SDNode to its position on the worklist. 106 /// 107 /// This is used to find and remove nodes from the worklist (by nulling 108 /// them) when they are deleted from the underlying DAG. It relies on 109 /// stable indices of nodes within the worklist. 110 DenseMap<SDNode *, unsigned> WorklistMap; 111 112 /// \brief Set of nodes which have been combined (at least once). 113 /// 114 /// This is used to allow us to reliably add any operands of a DAG node 115 /// which have not yet been combined to the worklist. 116 SmallPtrSet<SDNode *, 32> CombinedNodes; 117 118 // AA - Used for DAG load/store alias analysis. 119 AliasAnalysis &AA; 120 121 /// When an instruction is simplified, add all users of the instruction to 122 /// the work lists because they might get more simplified now. 123 void AddUsersToWorklist(SDNode *N) { 124 for (SDNode *Node : N->uses()) 125 AddToWorklist(Node); 126 } 127 128 /// Call the node-specific routine that folds each particular type of node. 129 SDValue visit(SDNode *N); 130 131 public: 132 /// Add to the worklist making sure its instance is at the back (next to be 133 /// processed.) 134 void AddToWorklist(SDNode *N) { 135 // Skip handle nodes as they can't usefully be combined and confuse the 136 // zero-use deletion strategy. 137 if (N->getOpcode() == ISD::HANDLENODE) 138 return; 139 140 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 141 Worklist.push_back(N); 142 } 143 144 /// Remove all instances of N from the worklist. 145 void removeFromWorklist(SDNode *N) { 146 CombinedNodes.erase(N); 147 148 auto It = WorklistMap.find(N); 149 if (It == WorklistMap.end()) 150 return; // Not in the worklist. 151 152 // Null out the entry rather than erasing it to avoid a linear operation. 153 Worklist[It->second] = nullptr; 154 WorklistMap.erase(It); 155 } 156 157 void deleteAndRecombine(SDNode *N); 158 bool recursivelyDeleteUnusedNodes(SDNode *N); 159 160 /// Replaces all uses of the results of one DAG node with new values. 161 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 162 bool AddTo = true); 163 164 /// Replaces all uses of the results of one DAG node with new values. 165 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 166 return CombineTo(N, &Res, 1, AddTo); 167 } 168 169 /// Replaces all uses of the results of one DAG node with new values. 170 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 171 bool AddTo = true) { 172 SDValue To[] = { Res0, Res1 }; 173 return CombineTo(N, To, 2, AddTo); 174 } 175 176 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 177 178 private: 179 180 /// Check the specified integer node value to see if it can be simplified or 181 /// if things it uses can be simplified by bit propagation. 182 /// If so, return true. 183 bool SimplifyDemandedBits(SDValue Op) { 184 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 185 APInt Demanded = APInt::getAllOnesValue(BitWidth); 186 return SimplifyDemandedBits(Op, Demanded); 187 } 188 189 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 190 191 bool CombineToPreIndexedLoadStore(SDNode *N); 192 bool CombineToPostIndexedLoadStore(SDNode *N); 193 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 194 bool SliceUpLoad(SDNode *N); 195 196 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 197 /// load. 198 /// 199 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 200 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 201 /// \param EltNo index of the vector element to load. 202 /// \param OriginalLoad load that EVE came from to be replaced. 203 /// \returns EVE on success SDValue() on failure. 204 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 205 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 206 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 207 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 208 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 209 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 210 SDValue PromoteIntBinOp(SDValue Op); 211 SDValue PromoteIntShiftOp(SDValue Op); 212 SDValue PromoteExtend(SDValue Op); 213 bool PromoteLoad(SDValue Op); 214 215 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 216 SDValue ExtLoad, const SDLoc &DL, 217 ISD::NodeType ExtType); 218 219 /// Call the node-specific routine that knows how to fold each 220 /// particular type of node. If that doesn't do anything, try the 221 /// target-specific DAG combines. 222 SDValue combine(SDNode *N); 223 224 // Visitation implementation - Implement dag node combining for different 225 // node types. The semantics are as follows: 226 // Return Value: 227 // SDValue.getNode() == 0 - No change was made 228 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 229 // otherwise - N should be replaced by the returned Operand. 230 // 231 SDValue visitTokenFactor(SDNode *N); 232 SDValue visitMERGE_VALUES(SDNode *N); 233 SDValue visitADD(SDNode *N); 234 SDValue visitSUB(SDNode *N); 235 SDValue visitADDC(SDNode *N); 236 SDValue visitSUBC(SDNode *N); 237 SDValue visitADDE(SDNode *N); 238 SDValue visitSUBE(SDNode *N); 239 SDValue visitMUL(SDNode *N); 240 SDValue useDivRem(SDNode *N); 241 SDValue visitSDIV(SDNode *N); 242 SDValue visitUDIV(SDNode *N); 243 SDValue visitREM(SDNode *N); 244 SDValue visitMULHU(SDNode *N); 245 SDValue visitMULHS(SDNode *N); 246 SDValue visitSMUL_LOHI(SDNode *N); 247 SDValue visitUMUL_LOHI(SDNode *N); 248 SDValue visitSMULO(SDNode *N); 249 SDValue visitUMULO(SDNode *N); 250 SDValue visitIMINMAX(SDNode *N); 251 SDValue visitAND(SDNode *N); 252 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 253 SDValue visitOR(SDNode *N); 254 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 255 SDValue visitXOR(SDNode *N); 256 SDValue SimplifyVBinOp(SDNode *N); 257 SDValue visitSHL(SDNode *N); 258 SDValue visitSRA(SDNode *N); 259 SDValue visitSRL(SDNode *N); 260 SDValue visitRotate(SDNode *N); 261 SDValue visitBSWAP(SDNode *N); 262 SDValue visitBITREVERSE(SDNode *N); 263 SDValue visitCTLZ(SDNode *N); 264 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 265 SDValue visitCTTZ(SDNode *N); 266 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 267 SDValue visitCTPOP(SDNode *N); 268 SDValue visitSELECT(SDNode *N); 269 SDValue visitVSELECT(SDNode *N); 270 SDValue visitSELECT_CC(SDNode *N); 271 SDValue visitSETCC(SDNode *N); 272 SDValue visitSETCCE(SDNode *N); 273 SDValue visitSIGN_EXTEND(SDNode *N); 274 SDValue visitZERO_EXTEND(SDNode *N); 275 SDValue visitANY_EXTEND(SDNode *N); 276 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 277 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 278 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 279 SDValue visitTRUNCATE(SDNode *N); 280 SDValue visitBITCAST(SDNode *N); 281 SDValue visitBUILD_PAIR(SDNode *N); 282 SDValue visitFADD(SDNode *N); 283 SDValue visitFSUB(SDNode *N); 284 SDValue visitFMUL(SDNode *N); 285 SDValue visitFMA(SDNode *N); 286 SDValue visitFDIV(SDNode *N); 287 SDValue visitFREM(SDNode *N); 288 SDValue visitFSQRT(SDNode *N); 289 SDValue visitFCOPYSIGN(SDNode *N); 290 SDValue visitSINT_TO_FP(SDNode *N); 291 SDValue visitUINT_TO_FP(SDNode *N); 292 SDValue visitFP_TO_SINT(SDNode *N); 293 SDValue visitFP_TO_UINT(SDNode *N); 294 SDValue visitFP_ROUND(SDNode *N); 295 SDValue visitFP_ROUND_INREG(SDNode *N); 296 SDValue visitFP_EXTEND(SDNode *N); 297 SDValue visitFNEG(SDNode *N); 298 SDValue visitFABS(SDNode *N); 299 SDValue visitFCEIL(SDNode *N); 300 SDValue visitFTRUNC(SDNode *N); 301 SDValue visitFFLOOR(SDNode *N); 302 SDValue visitFMINNUM(SDNode *N); 303 SDValue visitFMAXNUM(SDNode *N); 304 SDValue visitBRCOND(SDNode *N); 305 SDValue visitBR_CC(SDNode *N); 306 SDValue visitLOAD(SDNode *N); 307 308 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 309 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 310 311 SDValue visitSTORE(SDNode *N); 312 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 313 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 314 SDValue visitBUILD_VECTOR(SDNode *N); 315 SDValue visitCONCAT_VECTORS(SDNode *N); 316 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 317 SDValue visitVECTOR_SHUFFLE(SDNode *N); 318 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 319 SDValue visitINSERT_SUBVECTOR(SDNode *N); 320 SDValue visitMLOAD(SDNode *N); 321 SDValue visitMSTORE(SDNode *N); 322 SDValue visitMGATHER(SDNode *N); 323 SDValue visitMSCATTER(SDNode *N); 324 SDValue visitFP_TO_FP16(SDNode *N); 325 SDValue visitFP16_TO_FP(SDNode *N); 326 327 SDValue visitFADDForFMACombine(SDNode *N); 328 SDValue visitFSUBForFMACombine(SDNode *N); 329 SDValue visitFMULForFMACombine(SDNode *N); 330 331 SDValue XformToShuffleWithZero(SDNode *N); 332 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 333 SDValue RHS); 334 335 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 336 337 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 338 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 339 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 340 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 341 SDValue N2, SDValue N3, ISD::CondCode CC, 342 bool NotExtCompare = false); 343 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 344 const SDLoc &DL, bool foldBooleans = true); 345 346 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 347 SDValue &CC) const; 348 bool isOneUseSetCC(SDValue N) const; 349 350 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 351 unsigned HiOp); 352 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 353 SDValue CombineExtLoad(SDNode *N); 354 SDValue combineRepeatedFPDivisors(SDNode *N); 355 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 356 SDValue BuildSDIV(SDNode *N); 357 SDValue BuildSDIVPow2(SDNode *N); 358 SDValue BuildUDIV(SDNode *N); 359 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 360 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 361 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags); 362 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip); 363 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 364 SDNodeFlags *Flags, bool Reciprocal); 365 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 366 SDNodeFlags *Flags, bool Reciprocal); 367 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 368 bool DemandHighBits = true); 369 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 370 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 371 SDValue InnerPos, SDValue InnerNeg, 372 unsigned PosOpcode, unsigned NegOpcode, 373 const SDLoc &DL); 374 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 375 SDValue ReduceLoadWidth(SDNode *N); 376 SDValue ReduceLoadOpStoreWidth(SDNode *N); 377 SDValue splitMergedValStore(StoreSDNode *ST); 378 SDValue TransformFPLoadStorePair(SDNode *N); 379 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 380 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 381 382 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 383 384 /// Walk up chain skipping non-aliasing memory nodes, 385 /// looking for aliasing nodes and adding them to the Aliases vector. 386 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 387 SmallVectorImpl<SDValue> &Aliases); 388 389 /// Return true if there is any possibility that the two addresses overlap. 390 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 391 392 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 393 /// chain (aliasing node.) 394 SDValue FindBetterChain(SDNode *N, SDValue Chain); 395 396 /// Try to replace a store and any possibly adjacent stores on 397 /// consecutive chains with better chains. Return true only if St is 398 /// replaced. 399 /// 400 /// Notice that other chains may still be replaced even if the function 401 /// returns false. 402 bool findBetterNeighborChains(StoreSDNode *St); 403 404 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 405 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 406 407 /// Holds a pointer to an LSBaseSDNode as well as information on where it 408 /// is located in a sequence of memory operations connected by a chain. 409 struct MemOpLink { 410 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 411 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 412 // Ptr to the mem node. 413 LSBaseSDNode *MemNode; 414 // Offset from the base ptr. 415 int64_t OffsetFromBase; 416 // What is the sequence number of this mem node. 417 // Lowest mem operand in the DAG starts at zero. 418 unsigned SequenceNum; 419 }; 420 421 /// This is a helper function for visitMUL to check the profitability 422 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 423 /// MulNode is the original multiply, AddNode is (add x, c1), 424 /// and ConstNode is c2. 425 bool isMulAddWithConstProfitable(SDNode *MulNode, 426 SDValue &AddNode, 427 SDValue &ConstNode); 428 429 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 430 /// constant build_vector of the stored constant values in Stores. 431 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL, 432 ArrayRef<MemOpLink> Stores, 433 SmallVectorImpl<SDValue> &Chains, 434 EVT Ty) const; 435 436 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 437 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 438 /// the type of the loaded value to be extended. LoadedVT returns the type 439 /// of the original loaded value. NarrowLoad returns whether the load would 440 /// need to be narrowed in order to match. 441 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 442 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 443 bool &NarrowLoad); 444 445 /// This is a helper function for MergeConsecutiveStores. When the source 446 /// elements of the consecutive stores are all constants or all extracted 447 /// vector elements, try to merge them into one larger store. 448 /// \return True if a merged store was created. 449 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 450 EVT MemVT, unsigned NumStores, 451 bool IsConstantSrc, bool UseVector); 452 453 /// This is a helper function for MergeConsecutiveStores. 454 /// Stores that may be merged are placed in StoreNodes. 455 /// Loads that may alias with those stores are placed in AliasLoadNodes. 456 void getStoreMergeAndAliasCandidates( 457 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 458 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 459 460 /// Helper function for MergeConsecutiveStores. Checks if 461 /// Candidate stores have indirect dependency through their 462 /// operands. \return True if safe to merge 463 bool checkMergeStoreCandidatesForDependencies( 464 SmallVectorImpl<MemOpLink> &StoreNodes); 465 466 /// Merge consecutive store operations into a wide store. 467 /// This optimization uses wide integers or vectors when possible. 468 /// \return True if some memory operations were changed. 469 bool MergeConsecutiveStores(StoreSDNode *N); 470 471 /// \brief Try to transform a truncation where C is a constant: 472 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 473 /// 474 /// \p N needs to be a truncation and its first operand an AND. Other 475 /// requirements are checked by the function (e.g. that trunc is 476 /// single-use) and if missed an empty SDValue is returned. 477 SDValue distributeTruncateThroughAnd(SDNode *N); 478 479 public: 480 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 481 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 482 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 483 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 484 } 485 486 /// Runs the dag combiner on all nodes in the work list 487 void Run(CombineLevel AtLevel); 488 489 SelectionDAG &getDAG() const { return DAG; } 490 491 /// Returns a type large enough to hold any valid shift amount - before type 492 /// legalization these can be huge. 493 EVT getShiftAmountTy(EVT LHSTy) { 494 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 495 if (LHSTy.isVector()) 496 return LHSTy; 497 auto &DL = DAG.getDataLayout(); 498 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 499 : TLI.getPointerTy(DL); 500 } 501 502 /// This method returns true if we are running before type legalization or 503 /// if the specified VT is legal. 504 bool isTypeLegal(const EVT &VT) { 505 if (!LegalTypes) return true; 506 return TLI.isTypeLegal(VT); 507 } 508 509 /// Convenience wrapper around TargetLowering::getSetCCResultType 510 EVT getSetCCResultType(EVT VT) const { 511 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 512 } 513 }; 514 } 515 516 517 namespace { 518 /// This class is a DAGUpdateListener that removes any deleted 519 /// nodes from the worklist. 520 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 521 DAGCombiner &DC; 522 public: 523 explicit WorklistRemover(DAGCombiner &dc) 524 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 525 526 void NodeDeleted(SDNode *N, SDNode *E) override { 527 DC.removeFromWorklist(N); 528 } 529 }; 530 } 531 532 //===----------------------------------------------------------------------===// 533 // TargetLowering::DAGCombinerInfo implementation 534 //===----------------------------------------------------------------------===// 535 536 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 537 ((DAGCombiner*)DC)->AddToWorklist(N); 538 } 539 540 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 541 ((DAGCombiner*)DC)->removeFromWorklist(N); 542 } 543 544 SDValue TargetLowering::DAGCombinerInfo:: 545 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 546 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 547 } 548 549 SDValue TargetLowering::DAGCombinerInfo:: 550 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 551 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 552 } 553 554 555 SDValue TargetLowering::DAGCombinerInfo:: 556 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 557 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 558 } 559 560 void TargetLowering::DAGCombinerInfo:: 561 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 562 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 563 } 564 565 //===----------------------------------------------------------------------===// 566 // Helper Functions 567 //===----------------------------------------------------------------------===// 568 569 void DAGCombiner::deleteAndRecombine(SDNode *N) { 570 removeFromWorklist(N); 571 572 // If the operands of this node are only used by the node, they will now be 573 // dead. Make sure to re-visit them and recursively delete dead nodes. 574 for (const SDValue &Op : N->ops()) 575 // For an operand generating multiple values, one of the values may 576 // become dead allowing further simplification (e.g. split index 577 // arithmetic from an indexed load). 578 if (Op->hasOneUse() || Op->getNumValues() > 1) 579 AddToWorklist(Op.getNode()); 580 581 DAG.DeleteNode(N); 582 } 583 584 /// Return 1 if we can compute the negated form of the specified expression for 585 /// the same cost as the expression itself, or 2 if we can compute the negated 586 /// form more cheaply than the expression itself. 587 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 588 const TargetLowering &TLI, 589 const TargetOptions *Options, 590 unsigned Depth = 0) { 591 // fneg is removable even if it has multiple uses. 592 if (Op.getOpcode() == ISD::FNEG) return 2; 593 594 // Don't allow anything with multiple uses. 595 if (!Op.hasOneUse()) return 0; 596 597 // Don't recurse exponentially. 598 if (Depth > 6) return 0; 599 600 switch (Op.getOpcode()) { 601 default: return false; 602 case ISD::ConstantFP: 603 // Don't invert constant FP values after legalize. The negated constant 604 // isn't necessarily legal. 605 return LegalOperations ? 0 : 1; 606 case ISD::FADD: 607 // FIXME: determine better conditions for this xform. 608 if (!Options->UnsafeFPMath) return 0; 609 610 // After operation legalization, it might not be legal to create new FSUBs. 611 if (LegalOperations && 612 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 613 return 0; 614 615 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 616 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 617 Options, Depth + 1)) 618 return V; 619 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 620 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 621 Depth + 1); 622 case ISD::FSUB: 623 // We can't turn -(A-B) into B-A when we honor signed zeros. 624 if (!Options->UnsafeFPMath) return 0; 625 626 // fold (fneg (fsub A, B)) -> (fsub B, A) 627 return 1; 628 629 case ISD::FMUL: 630 case ISD::FDIV: 631 if (Options->HonorSignDependentRoundingFPMath()) return 0; 632 633 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 634 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 635 Options, Depth + 1)) 636 return V; 637 638 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 639 Depth + 1); 640 641 case ISD::FP_EXTEND: 642 case ISD::FP_ROUND: 643 case ISD::FSIN: 644 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 645 Depth + 1); 646 } 647 } 648 649 /// If isNegatibleForFree returns true, return the newly negated expression. 650 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 651 bool LegalOperations, unsigned Depth = 0) { 652 const TargetOptions &Options = DAG.getTarget().Options; 653 // fneg is removable even if it has multiple uses. 654 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 655 656 // Don't allow anything with multiple uses. 657 assert(Op.hasOneUse() && "Unknown reuse!"); 658 659 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 660 661 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 662 663 switch (Op.getOpcode()) { 664 default: llvm_unreachable("Unknown code"); 665 case ISD::ConstantFP: { 666 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 667 V.changeSign(); 668 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 669 } 670 case ISD::FADD: 671 // FIXME: determine better conditions for this xform. 672 assert(Options.UnsafeFPMath); 673 674 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 675 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 676 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 677 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 678 GetNegatedExpression(Op.getOperand(0), DAG, 679 LegalOperations, Depth+1), 680 Op.getOperand(1), Flags); 681 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 682 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 683 GetNegatedExpression(Op.getOperand(1), DAG, 684 LegalOperations, Depth+1), 685 Op.getOperand(0), Flags); 686 case ISD::FSUB: 687 // We can't turn -(A-B) into B-A when we honor signed zeros. 688 assert(Options.UnsafeFPMath); 689 690 // fold (fneg (fsub 0, B)) -> B 691 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 692 if (N0CFP->isZero()) 693 return Op.getOperand(1); 694 695 // fold (fneg (fsub A, B)) -> (fsub B, A) 696 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 697 Op.getOperand(1), Op.getOperand(0), Flags); 698 699 case ISD::FMUL: 700 case ISD::FDIV: 701 assert(!Options.HonorSignDependentRoundingFPMath()); 702 703 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 704 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 705 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 706 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 707 GetNegatedExpression(Op.getOperand(0), DAG, 708 LegalOperations, Depth+1), 709 Op.getOperand(1), Flags); 710 711 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 712 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 713 Op.getOperand(0), 714 GetNegatedExpression(Op.getOperand(1), DAG, 715 LegalOperations, Depth+1), Flags); 716 717 case ISD::FP_EXTEND: 718 case ISD::FSIN: 719 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 720 GetNegatedExpression(Op.getOperand(0), DAG, 721 LegalOperations, Depth+1)); 722 case ISD::FP_ROUND: 723 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 724 GetNegatedExpression(Op.getOperand(0), DAG, 725 LegalOperations, Depth+1), 726 Op.getOperand(1)); 727 } 728 } 729 730 // APInts must be the same size for most operations, this helper 731 // function zero extends the shorter of the pair so that they match. 732 // We provide an Offset so that we can create bitwidths that won't overflow. 733 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 734 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 735 LHS = LHS.zextOrSelf(Bits); 736 RHS = RHS.zextOrSelf(Bits); 737 } 738 739 // Return true if this node is a setcc, or is a select_cc 740 // that selects between the target values used for true and false, making it 741 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 742 // the appropriate nodes based on the type of node we are checking. This 743 // simplifies life a bit for the callers. 744 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 745 SDValue &CC) const { 746 if (N.getOpcode() == ISD::SETCC) { 747 LHS = N.getOperand(0); 748 RHS = N.getOperand(1); 749 CC = N.getOperand(2); 750 return true; 751 } 752 753 if (N.getOpcode() != ISD::SELECT_CC || 754 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 755 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 756 return false; 757 758 if (TLI.getBooleanContents(N.getValueType()) == 759 TargetLowering::UndefinedBooleanContent) 760 return false; 761 762 LHS = N.getOperand(0); 763 RHS = N.getOperand(1); 764 CC = N.getOperand(4); 765 return true; 766 } 767 768 /// Return true if this is a SetCC-equivalent operation with only one use. 769 /// If this is true, it allows the users to invert the operation for free when 770 /// it is profitable to do so. 771 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 772 SDValue N0, N1, N2; 773 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 774 return true; 775 return false; 776 } 777 778 // \brief Returns the SDNode if it is a constant float BuildVector 779 // or constant float. 780 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 781 if (isa<ConstantFPSDNode>(N)) 782 return N.getNode(); 783 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 784 return N.getNode(); 785 return nullptr; 786 } 787 788 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 789 // int. 790 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 791 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 792 return CN; 793 794 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 795 BitVector UndefElements; 796 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 797 798 // BuildVectors can truncate their operands. Ignore that case here. 799 // FIXME: We blindly ignore splats which include undef which is overly 800 // pessimistic. 801 if (CN && UndefElements.none() && 802 CN->getValueType(0) == N.getValueType().getScalarType()) 803 return CN; 804 } 805 806 return nullptr; 807 } 808 809 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 810 // float. 811 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 812 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 813 return CN; 814 815 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 816 BitVector UndefElements; 817 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 818 819 if (CN && UndefElements.none()) 820 return CN; 821 } 822 823 return nullptr; 824 } 825 826 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 827 SDValue N1) { 828 EVT VT = N0.getValueType(); 829 if (N0.getOpcode() == Opc) { 830 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 831 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 832 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 833 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 834 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 835 return SDValue(); 836 } 837 if (N0.hasOneUse()) { 838 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 839 // use 840 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 841 if (!OpNode.getNode()) 842 return SDValue(); 843 AddToWorklist(OpNode.getNode()); 844 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 845 } 846 } 847 } 848 849 if (N1.getOpcode() == Opc) { 850 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 851 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 852 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 853 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 854 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 855 return SDValue(); 856 } 857 if (N1.hasOneUse()) { 858 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 859 // use 860 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 861 if (!OpNode.getNode()) 862 return SDValue(); 863 AddToWorklist(OpNode.getNode()); 864 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 865 } 866 } 867 } 868 869 return SDValue(); 870 } 871 872 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 873 bool AddTo) { 874 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 875 ++NodesCombined; 876 DEBUG(dbgs() << "\nReplacing.1 "; 877 N->dump(&DAG); 878 dbgs() << "\nWith: "; 879 To[0].getNode()->dump(&DAG); 880 dbgs() << " and " << NumTo-1 << " other values\n"); 881 for (unsigned i = 0, e = NumTo; i != e; ++i) 882 assert((!To[i].getNode() || 883 N->getValueType(i) == To[i].getValueType()) && 884 "Cannot combine value to value of different type!"); 885 886 WorklistRemover DeadNodes(*this); 887 DAG.ReplaceAllUsesWith(N, To); 888 if (AddTo) { 889 // Push the new nodes and any users onto the worklist 890 for (unsigned i = 0, e = NumTo; i != e; ++i) { 891 if (To[i].getNode()) { 892 AddToWorklist(To[i].getNode()); 893 AddUsersToWorklist(To[i].getNode()); 894 } 895 } 896 } 897 898 // Finally, if the node is now dead, remove it from the graph. The node 899 // may not be dead if the replacement process recursively simplified to 900 // something else needing this node. 901 if (N->use_empty()) 902 deleteAndRecombine(N); 903 return SDValue(N, 0); 904 } 905 906 void DAGCombiner:: 907 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 908 // Replace all uses. If any nodes become isomorphic to other nodes and 909 // are deleted, make sure to remove them from our worklist. 910 WorklistRemover DeadNodes(*this); 911 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 912 913 // Push the new node and any (possibly new) users onto the worklist. 914 AddToWorklist(TLO.New.getNode()); 915 AddUsersToWorklist(TLO.New.getNode()); 916 917 // Finally, if the node is now dead, remove it from the graph. The node 918 // may not be dead if the replacement process recursively simplified to 919 // something else needing this node. 920 if (TLO.Old.getNode()->use_empty()) 921 deleteAndRecombine(TLO.Old.getNode()); 922 } 923 924 /// Check the specified integer node value to see if it can be simplified or if 925 /// things it uses can be simplified by bit propagation. If so, return true. 926 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 927 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 928 APInt KnownZero, KnownOne; 929 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 930 return false; 931 932 // Revisit the node. 933 AddToWorklist(Op.getNode()); 934 935 // Replace the old value with the new one. 936 ++NodesCombined; 937 DEBUG(dbgs() << "\nReplacing.2 "; 938 TLO.Old.getNode()->dump(&DAG); 939 dbgs() << "\nWith: "; 940 TLO.New.getNode()->dump(&DAG); 941 dbgs() << '\n'); 942 943 CommitTargetLoweringOpt(TLO); 944 return true; 945 } 946 947 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 948 SDLoc dl(Load); 949 EVT VT = Load->getValueType(0); 950 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 951 952 DEBUG(dbgs() << "\nReplacing.9 "; 953 Load->dump(&DAG); 954 dbgs() << "\nWith: "; 955 Trunc.getNode()->dump(&DAG); 956 dbgs() << '\n'); 957 WorklistRemover DeadNodes(*this); 958 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 959 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 960 deleteAndRecombine(Load); 961 AddToWorklist(Trunc.getNode()); 962 } 963 964 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 965 Replace = false; 966 SDLoc dl(Op); 967 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 968 LoadSDNode *LD = cast<LoadSDNode>(Op); 969 EVT MemVT = LD->getMemoryVT(); 970 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 971 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 972 : ISD::EXTLOAD) 973 : LD->getExtensionType(); 974 Replace = true; 975 return DAG.getExtLoad(ExtType, dl, PVT, 976 LD->getChain(), LD->getBasePtr(), 977 MemVT, LD->getMemOperand()); 978 } 979 980 unsigned Opc = Op.getOpcode(); 981 switch (Opc) { 982 default: break; 983 case ISD::AssertSext: 984 return DAG.getNode(ISD::AssertSext, dl, PVT, 985 SExtPromoteOperand(Op.getOperand(0), PVT), 986 Op.getOperand(1)); 987 case ISD::AssertZext: 988 return DAG.getNode(ISD::AssertZext, dl, PVT, 989 ZExtPromoteOperand(Op.getOperand(0), PVT), 990 Op.getOperand(1)); 991 case ISD::Constant: { 992 unsigned ExtOpc = 993 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 994 return DAG.getNode(ExtOpc, dl, PVT, Op); 995 } 996 } 997 998 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 999 return SDValue(); 1000 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 1001 } 1002 1003 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1004 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1005 return SDValue(); 1006 EVT OldVT = Op.getValueType(); 1007 SDLoc dl(Op); 1008 bool Replace = false; 1009 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1010 if (!NewOp.getNode()) 1011 return SDValue(); 1012 AddToWorklist(NewOp.getNode()); 1013 1014 if (Replace) 1015 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1016 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 1017 DAG.getValueType(OldVT)); 1018 } 1019 1020 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1021 EVT OldVT = Op.getValueType(); 1022 SDLoc dl(Op); 1023 bool Replace = false; 1024 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1025 if (!NewOp.getNode()) 1026 return SDValue(); 1027 AddToWorklist(NewOp.getNode()); 1028 1029 if (Replace) 1030 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1031 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1032 } 1033 1034 /// Promote the specified integer binary operation if the target indicates it is 1035 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1036 /// i32 since i16 instructions are longer. 1037 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1038 if (!LegalOperations) 1039 return SDValue(); 1040 1041 EVT VT = Op.getValueType(); 1042 if (VT.isVector() || !VT.isInteger()) 1043 return SDValue(); 1044 1045 // If operation type is 'undesirable', e.g. i16 on x86, consider 1046 // promoting it. 1047 unsigned Opc = Op.getOpcode(); 1048 if (TLI.isTypeDesirableForOp(Opc, VT)) 1049 return SDValue(); 1050 1051 EVT PVT = VT; 1052 // Consult target whether it is a good idea to promote this operation and 1053 // what's the right type to promote it to. 1054 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1055 assert(PVT != VT && "Don't know what type to promote to!"); 1056 1057 bool Replace0 = false; 1058 SDValue N0 = Op.getOperand(0); 1059 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1060 if (!NN0.getNode()) 1061 return SDValue(); 1062 1063 bool Replace1 = false; 1064 SDValue N1 = Op.getOperand(1); 1065 SDValue NN1; 1066 if (N0 == N1) 1067 NN1 = NN0; 1068 else { 1069 NN1 = PromoteOperand(N1, PVT, Replace1); 1070 if (!NN1.getNode()) 1071 return SDValue(); 1072 } 1073 1074 AddToWorklist(NN0.getNode()); 1075 if (NN1.getNode()) 1076 AddToWorklist(NN1.getNode()); 1077 1078 if (Replace0) 1079 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1080 if (Replace1) 1081 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1082 1083 DEBUG(dbgs() << "\nPromoting "; 1084 Op.getNode()->dump(&DAG)); 1085 SDLoc dl(Op); 1086 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1087 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1088 } 1089 return SDValue(); 1090 } 1091 1092 /// Promote the specified integer shift operation if the target indicates it is 1093 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1094 /// i32 since i16 instructions are longer. 1095 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1096 if (!LegalOperations) 1097 return SDValue(); 1098 1099 EVT VT = Op.getValueType(); 1100 if (VT.isVector() || !VT.isInteger()) 1101 return SDValue(); 1102 1103 // If operation type is 'undesirable', e.g. i16 on x86, consider 1104 // promoting it. 1105 unsigned Opc = Op.getOpcode(); 1106 if (TLI.isTypeDesirableForOp(Opc, VT)) 1107 return SDValue(); 1108 1109 EVT PVT = VT; 1110 // Consult target whether it is a good idea to promote this operation and 1111 // what's the right type to promote it to. 1112 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1113 assert(PVT != VT && "Don't know what type to promote to!"); 1114 1115 bool Replace = false; 1116 SDValue N0 = Op.getOperand(0); 1117 if (Opc == ISD::SRA) 1118 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1119 else if (Opc == ISD::SRL) 1120 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1121 else 1122 N0 = PromoteOperand(N0, PVT, Replace); 1123 if (!N0.getNode()) 1124 return SDValue(); 1125 1126 AddToWorklist(N0.getNode()); 1127 if (Replace) 1128 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1129 1130 DEBUG(dbgs() << "\nPromoting "; 1131 Op.getNode()->dump(&DAG)); 1132 SDLoc dl(Op); 1133 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1134 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1135 } 1136 return SDValue(); 1137 } 1138 1139 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1140 if (!LegalOperations) 1141 return SDValue(); 1142 1143 EVT VT = Op.getValueType(); 1144 if (VT.isVector() || !VT.isInteger()) 1145 return SDValue(); 1146 1147 // If operation type is 'undesirable', e.g. i16 on x86, consider 1148 // promoting it. 1149 unsigned Opc = Op.getOpcode(); 1150 if (TLI.isTypeDesirableForOp(Opc, VT)) 1151 return SDValue(); 1152 1153 EVT PVT = VT; 1154 // Consult target whether it is a good idea to promote this operation and 1155 // what's the right type to promote it to. 1156 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1157 assert(PVT != VT && "Don't know what type to promote to!"); 1158 // fold (aext (aext x)) -> (aext x) 1159 // fold (aext (zext x)) -> (zext x) 1160 // fold (aext (sext x)) -> (sext x) 1161 DEBUG(dbgs() << "\nPromoting "; 1162 Op.getNode()->dump(&DAG)); 1163 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1164 } 1165 return SDValue(); 1166 } 1167 1168 bool DAGCombiner::PromoteLoad(SDValue Op) { 1169 if (!LegalOperations) 1170 return false; 1171 1172 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1173 return false; 1174 1175 EVT VT = Op.getValueType(); 1176 if (VT.isVector() || !VT.isInteger()) 1177 return false; 1178 1179 // If operation type is 'undesirable', e.g. i16 on x86, consider 1180 // promoting it. 1181 unsigned Opc = Op.getOpcode(); 1182 if (TLI.isTypeDesirableForOp(Opc, VT)) 1183 return false; 1184 1185 EVT PVT = VT; 1186 // Consult target whether it is a good idea to promote this operation and 1187 // what's the right type to promote it to. 1188 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1189 assert(PVT != VT && "Don't know what type to promote to!"); 1190 1191 SDLoc dl(Op); 1192 SDNode *N = Op.getNode(); 1193 LoadSDNode *LD = cast<LoadSDNode>(N); 1194 EVT MemVT = LD->getMemoryVT(); 1195 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1196 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1197 : ISD::EXTLOAD) 1198 : LD->getExtensionType(); 1199 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1200 LD->getChain(), LD->getBasePtr(), 1201 MemVT, LD->getMemOperand()); 1202 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1203 1204 DEBUG(dbgs() << "\nPromoting "; 1205 N->dump(&DAG); 1206 dbgs() << "\nTo: "; 1207 Result.getNode()->dump(&DAG); 1208 dbgs() << '\n'); 1209 WorklistRemover DeadNodes(*this); 1210 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1211 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1212 deleteAndRecombine(N); 1213 AddToWorklist(Result.getNode()); 1214 return true; 1215 } 1216 return false; 1217 } 1218 1219 /// \brief Recursively delete a node which has no uses and any operands for 1220 /// which it is the only use. 1221 /// 1222 /// Note that this both deletes the nodes and removes them from the worklist. 1223 /// It also adds any nodes who have had a user deleted to the worklist as they 1224 /// may now have only one use and subject to other combines. 1225 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1226 if (!N->use_empty()) 1227 return false; 1228 1229 SmallSetVector<SDNode *, 16> Nodes; 1230 Nodes.insert(N); 1231 do { 1232 N = Nodes.pop_back_val(); 1233 if (!N) 1234 continue; 1235 1236 if (N->use_empty()) { 1237 for (const SDValue &ChildN : N->op_values()) 1238 Nodes.insert(ChildN.getNode()); 1239 1240 removeFromWorklist(N); 1241 DAG.DeleteNode(N); 1242 } else { 1243 AddToWorklist(N); 1244 } 1245 } while (!Nodes.empty()); 1246 return true; 1247 } 1248 1249 //===----------------------------------------------------------------------===// 1250 // Main DAG Combiner implementation 1251 //===----------------------------------------------------------------------===// 1252 1253 void DAGCombiner::Run(CombineLevel AtLevel) { 1254 // set the instance variables, so that the various visit routines may use it. 1255 Level = AtLevel; 1256 LegalOperations = Level >= AfterLegalizeVectorOps; 1257 LegalTypes = Level >= AfterLegalizeTypes; 1258 1259 // Add all the dag nodes to the worklist. 1260 for (SDNode &Node : DAG.allnodes()) 1261 AddToWorklist(&Node); 1262 1263 // Create a dummy node (which is not added to allnodes), that adds a reference 1264 // to the root node, preventing it from being deleted, and tracking any 1265 // changes of the root. 1266 HandleSDNode Dummy(DAG.getRoot()); 1267 1268 // While the worklist isn't empty, find a node and try to combine it. 1269 while (!WorklistMap.empty()) { 1270 SDNode *N; 1271 // The Worklist holds the SDNodes in order, but it may contain null entries. 1272 do { 1273 N = Worklist.pop_back_val(); 1274 } while (!N); 1275 1276 bool GoodWorklistEntry = WorklistMap.erase(N); 1277 (void)GoodWorklistEntry; 1278 assert(GoodWorklistEntry && 1279 "Found a worklist entry without a corresponding map entry!"); 1280 1281 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1282 // N is deleted from the DAG, since they too may now be dead or may have a 1283 // reduced number of uses, allowing other xforms. 1284 if (recursivelyDeleteUnusedNodes(N)) 1285 continue; 1286 1287 WorklistRemover DeadNodes(*this); 1288 1289 // If this combine is running after legalizing the DAG, re-legalize any 1290 // nodes pulled off the worklist. 1291 if (Level == AfterLegalizeDAG) { 1292 SmallSetVector<SDNode *, 16> UpdatedNodes; 1293 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1294 1295 for (SDNode *LN : UpdatedNodes) { 1296 AddToWorklist(LN); 1297 AddUsersToWorklist(LN); 1298 } 1299 if (!NIsValid) 1300 continue; 1301 } 1302 1303 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1304 1305 // Add any operands of the new node which have not yet been combined to the 1306 // worklist as well. Because the worklist uniques things already, this 1307 // won't repeatedly process the same operand. 1308 CombinedNodes.insert(N); 1309 for (const SDValue &ChildN : N->op_values()) 1310 if (!CombinedNodes.count(ChildN.getNode())) 1311 AddToWorklist(ChildN.getNode()); 1312 1313 SDValue RV = combine(N); 1314 1315 if (!RV.getNode()) 1316 continue; 1317 1318 ++NodesCombined; 1319 1320 // If we get back the same node we passed in, rather than a new node or 1321 // zero, we know that the node must have defined multiple values and 1322 // CombineTo was used. Since CombineTo takes care of the worklist 1323 // mechanics for us, we have no work to do in this case. 1324 if (RV.getNode() == N) 1325 continue; 1326 1327 assert(N->getOpcode() != ISD::DELETED_NODE && 1328 RV.getOpcode() != ISD::DELETED_NODE && 1329 "Node was deleted but visit returned new node!"); 1330 1331 DEBUG(dbgs() << " ... into: "; 1332 RV.getNode()->dump(&DAG)); 1333 1334 if (N->getNumValues() == RV.getNode()->getNumValues()) 1335 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1336 else { 1337 assert(N->getValueType(0) == RV.getValueType() && 1338 N->getNumValues() == 1 && "Type mismatch"); 1339 SDValue OpV = RV; 1340 DAG.ReplaceAllUsesWith(N, &OpV); 1341 } 1342 1343 // Push the new node and any users onto the worklist 1344 AddToWorklist(RV.getNode()); 1345 AddUsersToWorklist(RV.getNode()); 1346 1347 // Finally, if the node is now dead, remove it from the graph. The node 1348 // may not be dead if the replacement process recursively simplified to 1349 // something else needing this node. This will also take care of adding any 1350 // operands which have lost a user to the worklist. 1351 recursivelyDeleteUnusedNodes(N); 1352 } 1353 1354 // If the root changed (e.g. it was a dead load, update the root). 1355 DAG.setRoot(Dummy.getValue()); 1356 DAG.RemoveDeadNodes(); 1357 } 1358 1359 SDValue DAGCombiner::visit(SDNode *N) { 1360 switch (N->getOpcode()) { 1361 default: break; 1362 case ISD::TokenFactor: return visitTokenFactor(N); 1363 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1364 case ISD::ADD: return visitADD(N); 1365 case ISD::SUB: return visitSUB(N); 1366 case ISD::ADDC: return visitADDC(N); 1367 case ISD::SUBC: return visitSUBC(N); 1368 case ISD::ADDE: return visitADDE(N); 1369 case ISD::SUBE: return visitSUBE(N); 1370 case ISD::MUL: return visitMUL(N); 1371 case ISD::SDIV: return visitSDIV(N); 1372 case ISD::UDIV: return visitUDIV(N); 1373 case ISD::SREM: 1374 case ISD::UREM: return visitREM(N); 1375 case ISD::MULHU: return visitMULHU(N); 1376 case ISD::MULHS: return visitMULHS(N); 1377 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1378 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1379 case ISD::SMULO: return visitSMULO(N); 1380 case ISD::UMULO: return visitUMULO(N); 1381 case ISD::SMIN: 1382 case ISD::SMAX: 1383 case ISD::UMIN: 1384 case ISD::UMAX: return visitIMINMAX(N); 1385 case ISD::AND: return visitAND(N); 1386 case ISD::OR: return visitOR(N); 1387 case ISD::XOR: return visitXOR(N); 1388 case ISD::SHL: return visitSHL(N); 1389 case ISD::SRA: return visitSRA(N); 1390 case ISD::SRL: return visitSRL(N); 1391 case ISD::ROTR: 1392 case ISD::ROTL: return visitRotate(N); 1393 case ISD::BSWAP: return visitBSWAP(N); 1394 case ISD::BITREVERSE: return visitBITREVERSE(N); 1395 case ISD::CTLZ: return visitCTLZ(N); 1396 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1397 case ISD::CTTZ: return visitCTTZ(N); 1398 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1399 case ISD::CTPOP: return visitCTPOP(N); 1400 case ISD::SELECT: return visitSELECT(N); 1401 case ISD::VSELECT: return visitVSELECT(N); 1402 case ISD::SELECT_CC: return visitSELECT_CC(N); 1403 case ISD::SETCC: return visitSETCC(N); 1404 case ISD::SETCCE: return visitSETCCE(N); 1405 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1406 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1407 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1408 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1409 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1410 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1411 case ISD::TRUNCATE: return visitTRUNCATE(N); 1412 case ISD::BITCAST: return visitBITCAST(N); 1413 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1414 case ISD::FADD: return visitFADD(N); 1415 case ISD::FSUB: return visitFSUB(N); 1416 case ISD::FMUL: return visitFMUL(N); 1417 case ISD::FMA: return visitFMA(N); 1418 case ISD::FDIV: return visitFDIV(N); 1419 case ISD::FREM: return visitFREM(N); 1420 case ISD::FSQRT: return visitFSQRT(N); 1421 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1422 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1423 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1424 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1425 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1426 case ISD::FP_ROUND: return visitFP_ROUND(N); 1427 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1428 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1429 case ISD::FNEG: return visitFNEG(N); 1430 case ISD::FABS: return visitFABS(N); 1431 case ISD::FFLOOR: return visitFFLOOR(N); 1432 case ISD::FMINNUM: return visitFMINNUM(N); 1433 case ISD::FMAXNUM: return visitFMAXNUM(N); 1434 case ISD::FCEIL: return visitFCEIL(N); 1435 case ISD::FTRUNC: return visitFTRUNC(N); 1436 case ISD::BRCOND: return visitBRCOND(N); 1437 case ISD::BR_CC: return visitBR_CC(N); 1438 case ISD::LOAD: return visitLOAD(N); 1439 case ISD::STORE: return visitSTORE(N); 1440 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1441 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1442 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1443 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1444 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1445 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1446 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1447 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1448 case ISD::MGATHER: return visitMGATHER(N); 1449 case ISD::MLOAD: return visitMLOAD(N); 1450 case ISD::MSCATTER: return visitMSCATTER(N); 1451 case ISD::MSTORE: return visitMSTORE(N); 1452 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1453 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1454 } 1455 return SDValue(); 1456 } 1457 1458 SDValue DAGCombiner::combine(SDNode *N) { 1459 SDValue RV = visit(N); 1460 1461 // If nothing happened, try a target-specific DAG combine. 1462 if (!RV.getNode()) { 1463 assert(N->getOpcode() != ISD::DELETED_NODE && 1464 "Node was deleted but visit returned NULL!"); 1465 1466 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1467 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1468 1469 // Expose the DAG combiner to the target combiner impls. 1470 TargetLowering::DAGCombinerInfo 1471 DagCombineInfo(DAG, Level, false, this); 1472 1473 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1474 } 1475 } 1476 1477 // If nothing happened still, try promoting the operation. 1478 if (!RV.getNode()) { 1479 switch (N->getOpcode()) { 1480 default: break; 1481 case ISD::ADD: 1482 case ISD::SUB: 1483 case ISD::MUL: 1484 case ISD::AND: 1485 case ISD::OR: 1486 case ISD::XOR: 1487 RV = PromoteIntBinOp(SDValue(N, 0)); 1488 break; 1489 case ISD::SHL: 1490 case ISD::SRA: 1491 case ISD::SRL: 1492 RV = PromoteIntShiftOp(SDValue(N, 0)); 1493 break; 1494 case ISD::SIGN_EXTEND: 1495 case ISD::ZERO_EXTEND: 1496 case ISD::ANY_EXTEND: 1497 RV = PromoteExtend(SDValue(N, 0)); 1498 break; 1499 case ISD::LOAD: 1500 if (PromoteLoad(SDValue(N, 0))) 1501 RV = SDValue(N, 0); 1502 break; 1503 } 1504 } 1505 1506 // If N is a commutative binary node, try commuting it to enable more 1507 // sdisel CSE. 1508 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1509 N->getNumValues() == 1) { 1510 SDValue N0 = N->getOperand(0); 1511 SDValue N1 = N->getOperand(1); 1512 1513 // Constant operands are canonicalized to RHS. 1514 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1515 SDValue Ops[] = {N1, N0}; 1516 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1517 N->getFlags()); 1518 if (CSENode) 1519 return SDValue(CSENode, 0); 1520 } 1521 } 1522 1523 return RV; 1524 } 1525 1526 /// Given a node, return its input chain if it has one, otherwise return a null 1527 /// sd operand. 1528 static SDValue getInputChainForNode(SDNode *N) { 1529 if (unsigned NumOps = N->getNumOperands()) { 1530 if (N->getOperand(0).getValueType() == MVT::Other) 1531 return N->getOperand(0); 1532 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1533 return N->getOperand(NumOps-1); 1534 for (unsigned i = 1; i < NumOps-1; ++i) 1535 if (N->getOperand(i).getValueType() == MVT::Other) 1536 return N->getOperand(i); 1537 } 1538 return SDValue(); 1539 } 1540 1541 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1542 // If N has two operands, where one has an input chain equal to the other, 1543 // the 'other' chain is redundant. 1544 if (N->getNumOperands() == 2) { 1545 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1546 return N->getOperand(0); 1547 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1548 return N->getOperand(1); 1549 } 1550 1551 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1552 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1553 SmallPtrSet<SDNode*, 16> SeenOps; 1554 bool Changed = false; // If we should replace this token factor. 1555 1556 // Start out with this token factor. 1557 TFs.push_back(N); 1558 1559 // Iterate through token factors. The TFs grows when new token factors are 1560 // encountered. 1561 for (unsigned i = 0; i < TFs.size(); ++i) { 1562 SDNode *TF = TFs[i]; 1563 1564 // Check each of the operands. 1565 for (const SDValue &Op : TF->op_values()) { 1566 1567 switch (Op.getOpcode()) { 1568 case ISD::EntryToken: 1569 // Entry tokens don't need to be added to the list. They are 1570 // redundant. 1571 Changed = true; 1572 break; 1573 1574 case ISD::TokenFactor: 1575 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1576 // Queue up for processing. 1577 TFs.push_back(Op.getNode()); 1578 // Clean up in case the token factor is removed. 1579 AddToWorklist(Op.getNode()); 1580 Changed = true; 1581 break; 1582 } 1583 LLVM_FALLTHROUGH; 1584 1585 default: 1586 // Only add if it isn't already in the list. 1587 if (SeenOps.insert(Op.getNode()).second) 1588 Ops.push_back(Op); 1589 else 1590 Changed = true; 1591 break; 1592 } 1593 } 1594 } 1595 1596 SDValue Result; 1597 1598 // If we've changed things around then replace token factor. 1599 if (Changed) { 1600 if (Ops.empty()) { 1601 // The entry token is the only possible outcome. 1602 Result = DAG.getEntryNode(); 1603 } else { 1604 // New and improved token factor. 1605 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1606 } 1607 1608 // Add users to worklist if AA is enabled, since it may introduce 1609 // a lot of new chained token factors while removing memory deps. 1610 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1611 : DAG.getSubtarget().useAA(); 1612 return CombineTo(N, Result, UseAA /*add to worklist*/); 1613 } 1614 1615 return Result; 1616 } 1617 1618 /// MERGE_VALUES can always be eliminated. 1619 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1620 WorklistRemover DeadNodes(*this); 1621 // Replacing results may cause a different MERGE_VALUES to suddenly 1622 // be CSE'd with N, and carry its uses with it. Iterate until no 1623 // uses remain, to ensure that the node can be safely deleted. 1624 // First add the users of this node to the work list so that they 1625 // can be tried again once they have new operands. 1626 AddUsersToWorklist(N); 1627 do { 1628 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1629 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1630 } while (!N->use_empty()); 1631 deleteAndRecombine(N); 1632 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1633 } 1634 1635 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1636 /// ConstantSDNode pointer else nullptr. 1637 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1638 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1639 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1640 } 1641 1642 SDValue DAGCombiner::visitADD(SDNode *N) { 1643 SDValue N0 = N->getOperand(0); 1644 SDValue N1 = N->getOperand(1); 1645 EVT VT = N0.getValueType(); 1646 1647 // fold vector ops 1648 if (VT.isVector()) { 1649 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1650 return FoldedVOp; 1651 1652 // fold (add x, 0) -> x, vector edition 1653 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1654 return N0; 1655 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1656 return N1; 1657 } 1658 1659 // fold (add x, undef) -> undef 1660 if (N0.isUndef()) 1661 return N0; 1662 if (N1.isUndef()) 1663 return N1; 1664 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1665 // canonicalize constant to RHS 1666 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1667 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1668 // fold (add c1, c2) -> c1+c2 1669 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, 1670 N0.getNode(), N1.getNode()); 1671 } 1672 // fold (add x, 0) -> x 1673 if (isNullConstant(N1)) 1674 return N0; 1675 // fold ((c1-A)+c2) -> (c1+c2)-A 1676 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) { 1677 if (N0.getOpcode() == ISD::SUB) 1678 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1679 SDLoc DL(N); 1680 return DAG.getNode(ISD::SUB, DL, VT, 1681 DAG.getConstant(N1C->getAPIntValue()+ 1682 N0C->getAPIntValue(), DL, VT), 1683 N0.getOperand(1)); 1684 } 1685 } 1686 // reassociate add 1687 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1688 return RADD; 1689 // fold ((0-A) + B) -> B-A 1690 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1691 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1692 // fold (A + (0-B)) -> A-B 1693 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1694 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1695 // fold (A+(B-A)) -> B 1696 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1697 return N1.getOperand(0); 1698 // fold ((B-A)+A) -> B 1699 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1700 return N0.getOperand(0); 1701 // fold (A+(B-(A+C))) to (B-C) 1702 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1703 N0 == N1.getOperand(1).getOperand(0)) 1704 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1705 N1.getOperand(1).getOperand(1)); 1706 // fold (A+(B-(C+A))) to (B-C) 1707 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1708 N0 == N1.getOperand(1).getOperand(1)) 1709 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1710 N1.getOperand(1).getOperand(0)); 1711 // fold (A+((B-A)+or-C)) to (B+or-C) 1712 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1713 N1.getOperand(0).getOpcode() == ISD::SUB && 1714 N0 == N1.getOperand(0).getOperand(1)) 1715 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1716 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1717 1718 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1719 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1720 SDValue N00 = N0.getOperand(0); 1721 SDValue N01 = N0.getOperand(1); 1722 SDValue N10 = N1.getOperand(0); 1723 SDValue N11 = N1.getOperand(1); 1724 1725 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1726 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1727 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1728 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1729 } 1730 1731 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1732 return SDValue(N, 0); 1733 1734 // fold (a+b) -> (a|b) iff a and b share no bits. 1735 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1736 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1)) 1737 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1738 1739 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1740 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1741 isNullConstant(N1.getOperand(0).getOperand(0))) 1742 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1743 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1744 N1.getOperand(0).getOperand(1), 1745 N1.getOperand(1))); 1746 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1747 isNullConstant(N0.getOperand(0).getOperand(0))) 1748 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1749 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1750 N0.getOperand(0).getOperand(1), 1751 N0.getOperand(1))); 1752 1753 if (N1.getOpcode() == ISD::AND) { 1754 SDValue AndOp0 = N1.getOperand(0); 1755 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1756 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1757 1758 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1759 // and similar xforms where the inner op is either ~0 or 0. 1760 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1761 SDLoc DL(N); 1762 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1763 } 1764 } 1765 1766 // add (sext i1), X -> sub X, (zext i1) 1767 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1768 N0.getOperand(0).getValueType() == MVT::i1 && 1769 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1770 SDLoc DL(N); 1771 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1772 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1773 } 1774 1775 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1776 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1777 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1778 if (TN->getVT() == MVT::i1) { 1779 SDLoc DL(N); 1780 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1781 DAG.getConstant(1, DL, VT)); 1782 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1783 } 1784 } 1785 1786 return SDValue(); 1787 } 1788 1789 SDValue DAGCombiner::visitADDC(SDNode *N) { 1790 SDValue N0 = N->getOperand(0); 1791 SDValue N1 = N->getOperand(1); 1792 EVT VT = N0.getValueType(); 1793 1794 // If the flag result is dead, turn this into an ADD. 1795 if (!N->hasAnyUseOfValue(1)) 1796 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1797 DAG.getNode(ISD::CARRY_FALSE, 1798 SDLoc(N), MVT::Glue)); 1799 1800 // canonicalize constant to RHS. 1801 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1802 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1803 if (N0C && !N1C) 1804 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1805 1806 // fold (addc x, 0) -> x + no carry out 1807 if (isNullConstant(N1)) 1808 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1809 SDLoc(N), MVT::Glue)); 1810 1811 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1812 APInt LHSZero, LHSOne; 1813 APInt RHSZero, RHSOne; 1814 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1815 1816 if (LHSZero.getBoolValue()) { 1817 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1818 1819 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1820 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1821 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1822 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1823 DAG.getNode(ISD::CARRY_FALSE, 1824 SDLoc(N), MVT::Glue)); 1825 } 1826 1827 return SDValue(); 1828 } 1829 1830 SDValue DAGCombiner::visitADDE(SDNode *N) { 1831 SDValue N0 = N->getOperand(0); 1832 SDValue N1 = N->getOperand(1); 1833 SDValue CarryIn = N->getOperand(2); 1834 1835 // canonicalize constant to RHS 1836 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1837 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1838 if (N0C && !N1C) 1839 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1840 N1, N0, CarryIn); 1841 1842 // fold (adde x, y, false) -> (addc x, y) 1843 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1844 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1845 1846 return SDValue(); 1847 } 1848 1849 // Since it may not be valid to emit a fold to zero for vector initializers 1850 // check if we can before folding. 1851 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 1852 SelectionDAG &DAG, bool LegalOperations, 1853 bool LegalTypes) { 1854 if (!VT.isVector()) 1855 return DAG.getConstant(0, DL, VT); 1856 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1857 return DAG.getConstant(0, DL, VT); 1858 return SDValue(); 1859 } 1860 1861 SDValue DAGCombiner::visitSUB(SDNode *N) { 1862 SDValue N0 = N->getOperand(0); 1863 SDValue N1 = N->getOperand(1); 1864 EVT VT = N0.getValueType(); 1865 1866 // fold vector ops 1867 if (VT.isVector()) { 1868 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1869 return FoldedVOp; 1870 1871 // fold (sub x, 0) -> x, vector edition 1872 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1873 return N0; 1874 } 1875 1876 // fold (sub x, x) -> 0 1877 // FIXME: Refactor this and xor and other similar operations together. 1878 if (N0 == N1) 1879 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1880 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1881 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1882 // fold (sub c1, c2) -> c1-c2 1883 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, 1884 N0.getNode(), N1.getNode()); 1885 } 1886 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1887 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1888 // fold (sub x, c) -> (add x, -c) 1889 if (N1C) { 1890 SDLoc DL(N); 1891 return DAG.getNode(ISD::ADD, DL, VT, N0, 1892 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1893 } 1894 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1895 if (isAllOnesConstant(N0)) 1896 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1897 // fold A-(A-B) -> B 1898 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1899 return N1.getOperand(1); 1900 // fold (A+B)-A -> B 1901 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1902 return N0.getOperand(1); 1903 // fold (A+B)-B -> A 1904 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1905 return N0.getOperand(0); 1906 // fold C2-(A+C1) -> (C2-C1)-A 1907 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1908 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1909 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1910 SDLoc DL(N); 1911 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1912 DL, VT); 1913 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1914 N1.getOperand(0)); 1915 } 1916 // fold ((A+(B+or-C))-B) -> A+or-C 1917 if (N0.getOpcode() == ISD::ADD && 1918 (N0.getOperand(1).getOpcode() == ISD::SUB || 1919 N0.getOperand(1).getOpcode() == ISD::ADD) && 1920 N0.getOperand(1).getOperand(0) == N1) 1921 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1922 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1923 // fold ((A+(C+B))-B) -> A+C 1924 if (N0.getOpcode() == ISD::ADD && 1925 N0.getOperand(1).getOpcode() == ISD::ADD && 1926 N0.getOperand(1).getOperand(1) == N1) 1927 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1928 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1929 // fold ((A-(B-C))-C) -> A-B 1930 if (N0.getOpcode() == ISD::SUB && 1931 N0.getOperand(1).getOpcode() == ISD::SUB && 1932 N0.getOperand(1).getOperand(1) == N1) 1933 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1934 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1935 1936 // If either operand of a sub is undef, the result is undef 1937 if (N0.isUndef()) 1938 return N0; 1939 if (N1.isUndef()) 1940 return N1; 1941 1942 // If the relocation model supports it, consider symbol offsets. 1943 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1944 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1945 // fold (sub Sym, c) -> Sym-c 1946 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1947 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1948 GA->getOffset() - 1949 (uint64_t)N1C->getSExtValue()); 1950 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1951 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1952 if (GA->getGlobal() == GB->getGlobal()) 1953 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1954 SDLoc(N), VT); 1955 } 1956 1957 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1958 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1959 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1960 if (TN->getVT() == MVT::i1) { 1961 SDLoc DL(N); 1962 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1963 DAG.getConstant(1, DL, VT)); 1964 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1965 } 1966 } 1967 1968 return SDValue(); 1969 } 1970 1971 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1972 SDValue N0 = N->getOperand(0); 1973 SDValue N1 = N->getOperand(1); 1974 EVT VT = N0.getValueType(); 1975 SDLoc DL(N); 1976 1977 // If the flag result is dead, turn this into an SUB. 1978 if (!N->hasAnyUseOfValue(1)) 1979 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 1980 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1981 1982 // fold (subc x, x) -> 0 + no borrow 1983 if (N0 == N1) 1984 return CombineTo(N, DAG.getConstant(0, DL, VT), 1985 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1986 1987 // fold (subc x, 0) -> x + no borrow 1988 if (isNullConstant(N1)) 1989 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1990 1991 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1992 if (isAllOnesConstant(N0)) 1993 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 1994 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1995 1996 return SDValue(); 1997 } 1998 1999 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2000 SDValue N0 = N->getOperand(0); 2001 SDValue N1 = N->getOperand(1); 2002 SDValue CarryIn = N->getOperand(2); 2003 2004 // fold (sube x, y, false) -> (subc x, y) 2005 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2006 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2007 2008 return SDValue(); 2009 } 2010 2011 SDValue DAGCombiner::visitMUL(SDNode *N) { 2012 SDValue N0 = N->getOperand(0); 2013 SDValue N1 = N->getOperand(1); 2014 EVT VT = N0.getValueType(); 2015 2016 // fold (mul x, undef) -> 0 2017 if (N0.isUndef() || N1.isUndef()) 2018 return DAG.getConstant(0, SDLoc(N), VT); 2019 2020 bool N0IsConst = false; 2021 bool N1IsConst = false; 2022 bool N1IsOpaqueConst = false; 2023 bool N0IsOpaqueConst = false; 2024 APInt ConstValue0, ConstValue1; 2025 // fold vector ops 2026 if (VT.isVector()) { 2027 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2028 return FoldedVOp; 2029 2030 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2031 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2032 } else { 2033 N0IsConst = isa<ConstantSDNode>(N0); 2034 if (N0IsConst) { 2035 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2036 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2037 } 2038 N1IsConst = isa<ConstantSDNode>(N1); 2039 if (N1IsConst) { 2040 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2041 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2042 } 2043 } 2044 2045 // fold (mul c1, c2) -> c1*c2 2046 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2047 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2048 N0.getNode(), N1.getNode()); 2049 2050 // canonicalize constant to RHS (vector doesn't have to splat) 2051 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2052 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2053 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2054 // fold (mul x, 0) -> 0 2055 if (N1IsConst && ConstValue1 == 0) 2056 return N1; 2057 // We require a splat of the entire scalar bit width for non-contiguous 2058 // bit patterns. 2059 bool IsFullSplat = 2060 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2061 // fold (mul x, 1) -> x 2062 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2063 return N0; 2064 // fold (mul x, -1) -> 0-x 2065 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2066 SDLoc DL(N); 2067 return DAG.getNode(ISD::SUB, DL, VT, 2068 DAG.getConstant(0, DL, VT), N0); 2069 } 2070 // fold (mul x, (1 << c)) -> x << c 2071 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2072 IsFullSplat) { 2073 SDLoc DL(N); 2074 return DAG.getNode(ISD::SHL, DL, VT, N0, 2075 DAG.getConstant(ConstValue1.logBase2(), DL, 2076 getShiftAmountTy(N0.getValueType()))); 2077 } 2078 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2079 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2080 IsFullSplat) { 2081 unsigned Log2Val = (-ConstValue1).logBase2(); 2082 SDLoc DL(N); 2083 // FIXME: If the input is something that is easily negated (e.g. a 2084 // single-use add), we should put the negate there. 2085 return DAG.getNode(ISD::SUB, DL, VT, 2086 DAG.getConstant(0, DL, VT), 2087 DAG.getNode(ISD::SHL, DL, VT, N0, 2088 DAG.getConstant(Log2Val, DL, 2089 getShiftAmountTy(N0.getValueType())))); 2090 } 2091 2092 APInt Val; 2093 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2094 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2095 (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2096 isa<ConstantSDNode>(N0.getOperand(1)))) { 2097 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2098 AddToWorklist(C3.getNode()); 2099 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2100 } 2101 2102 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2103 // use. 2104 { 2105 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2106 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2107 if (N0.getOpcode() == ISD::SHL && 2108 (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2109 isa<ConstantSDNode>(N0.getOperand(1))) && 2110 N0.getNode()->hasOneUse()) { 2111 Sh = N0; Y = N1; 2112 } else if (N1.getOpcode() == ISD::SHL && 2113 isa<ConstantSDNode>(N1.getOperand(1)) && 2114 N1.getNode()->hasOneUse()) { 2115 Sh = N1; Y = N0; 2116 } 2117 2118 if (Sh.getNode()) { 2119 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2120 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2121 } 2122 } 2123 2124 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2125 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2126 N0.getOpcode() == ISD::ADD && 2127 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2128 isMulAddWithConstProfitable(N, N0, N1)) 2129 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2130 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2131 N0.getOperand(0), N1), 2132 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2133 N0.getOperand(1), N1)); 2134 2135 // reassociate mul 2136 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2137 return RMUL; 2138 2139 return SDValue(); 2140 } 2141 2142 /// Return true if divmod libcall is available. 2143 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2144 const TargetLowering &TLI) { 2145 RTLIB::Libcall LC; 2146 EVT NodeType = Node->getValueType(0); 2147 if (!NodeType.isSimple()) 2148 return false; 2149 switch (NodeType.getSimpleVT().SimpleTy) { 2150 default: return false; // No libcall for vector types. 2151 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2152 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2153 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2154 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2155 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2156 } 2157 2158 return TLI.getLibcallName(LC) != nullptr; 2159 } 2160 2161 /// Issue divrem if both quotient and remainder are needed. 2162 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2163 if (Node->use_empty()) 2164 return SDValue(); // This is a dead node, leave it alone. 2165 2166 unsigned Opcode = Node->getOpcode(); 2167 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2168 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2169 2170 // DivMod lib calls can still work on non-legal types if using lib-calls. 2171 EVT VT = Node->getValueType(0); 2172 if (VT.isVector() || !VT.isInteger()) 2173 return SDValue(); 2174 2175 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2176 return SDValue(); 2177 2178 // If DIVREM is going to get expanded into a libcall, 2179 // but there is no libcall available, then don't combine. 2180 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2181 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2182 return SDValue(); 2183 2184 // If div is legal, it's better to do the normal expansion 2185 unsigned OtherOpcode = 0; 2186 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2187 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2188 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2189 return SDValue(); 2190 } else { 2191 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2192 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2193 return SDValue(); 2194 } 2195 2196 SDValue Op0 = Node->getOperand(0); 2197 SDValue Op1 = Node->getOperand(1); 2198 SDValue combined; 2199 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2200 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2201 SDNode *User = *UI; 2202 if (User == Node || User->use_empty()) 2203 continue; 2204 // Convert the other matching node(s), too; 2205 // otherwise, the DIVREM may get target-legalized into something 2206 // target-specific that we won't be able to recognize. 2207 unsigned UserOpc = User->getOpcode(); 2208 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2209 User->getOperand(0) == Op0 && 2210 User->getOperand(1) == Op1) { 2211 if (!combined) { 2212 if (UserOpc == OtherOpcode) { 2213 SDVTList VTs = DAG.getVTList(VT, VT); 2214 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2215 } else if (UserOpc == DivRemOpc) { 2216 combined = SDValue(User, 0); 2217 } else { 2218 assert(UserOpc == Opcode); 2219 continue; 2220 } 2221 } 2222 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2223 CombineTo(User, combined); 2224 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2225 CombineTo(User, combined.getValue(1)); 2226 } 2227 } 2228 return combined; 2229 } 2230 2231 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2232 SDValue N0 = N->getOperand(0); 2233 SDValue N1 = N->getOperand(1); 2234 EVT VT = N->getValueType(0); 2235 2236 // fold vector ops 2237 if (VT.isVector()) 2238 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2239 return FoldedVOp; 2240 2241 SDLoc DL(N); 2242 2243 // fold (sdiv c1, c2) -> c1/c2 2244 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2245 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2246 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2247 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2248 // fold (sdiv X, 1) -> X 2249 if (N1C && N1C->isOne()) 2250 return N0; 2251 // fold (sdiv X, -1) -> 0-X 2252 if (N1C && N1C->isAllOnesValue()) 2253 return DAG.getNode(ISD::SUB, DL, VT, 2254 DAG.getConstant(0, DL, VT), N0); 2255 2256 // If we know the sign bits of both operands are zero, strength reduce to a 2257 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2258 if (!VT.isVector()) { 2259 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2260 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2261 } 2262 2263 // fold (sdiv X, pow2) -> simple ops after legalize 2264 // FIXME: We check for the exact bit here because the generic lowering gives 2265 // better results in that case. The target-specific lowering should learn how 2266 // to handle exact sdivs efficiently. 2267 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2268 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2269 (N1C->getAPIntValue().isPowerOf2() || 2270 (-N1C->getAPIntValue()).isPowerOf2())) { 2271 // Target-specific implementation of sdiv x, pow2. 2272 if (SDValue Res = BuildSDIVPow2(N)) 2273 return Res; 2274 2275 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2276 2277 // Splat the sign bit into the register 2278 SDValue SGN = 2279 DAG.getNode(ISD::SRA, DL, VT, N0, 2280 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2281 getShiftAmountTy(N0.getValueType()))); 2282 AddToWorklist(SGN.getNode()); 2283 2284 // Add (N0 < 0) ? abs2 - 1 : 0; 2285 SDValue SRL = 2286 DAG.getNode(ISD::SRL, DL, VT, SGN, 2287 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2288 getShiftAmountTy(SGN.getValueType()))); 2289 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2290 AddToWorklist(SRL.getNode()); 2291 AddToWorklist(ADD.getNode()); // Divide by pow2 2292 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2293 DAG.getConstant(lg2, DL, 2294 getShiftAmountTy(ADD.getValueType()))); 2295 2296 // If we're dividing by a positive value, we're done. Otherwise, we must 2297 // negate the result. 2298 if (N1C->getAPIntValue().isNonNegative()) 2299 return SRA; 2300 2301 AddToWorklist(SRA.getNode()); 2302 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2303 } 2304 2305 // If integer divide is expensive and we satisfy the requirements, emit an 2306 // alternate sequence. Targets may check function attributes for size/speed 2307 // trade-offs. 2308 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2309 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2310 if (SDValue Op = BuildSDIV(N)) 2311 return Op; 2312 2313 // sdiv, srem -> sdivrem 2314 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2315 // Otherwise, we break the simplification logic in visitREM(). 2316 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2317 if (SDValue DivRem = useDivRem(N)) 2318 return DivRem; 2319 2320 // undef / X -> 0 2321 if (N0.isUndef()) 2322 return DAG.getConstant(0, DL, VT); 2323 // X / undef -> undef 2324 if (N1.isUndef()) 2325 return N1; 2326 2327 return SDValue(); 2328 } 2329 2330 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2331 SDValue N0 = N->getOperand(0); 2332 SDValue N1 = N->getOperand(1); 2333 EVT VT = N->getValueType(0); 2334 2335 // fold vector ops 2336 if (VT.isVector()) 2337 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2338 return FoldedVOp; 2339 2340 SDLoc DL(N); 2341 2342 // fold (udiv c1, c2) -> c1/c2 2343 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2344 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2345 if (N0C && N1C) 2346 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2347 N0C, N1C)) 2348 return Folded; 2349 // fold (udiv x, (1 << c)) -> x >>u c 2350 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2351 return DAG.getNode(ISD::SRL, DL, VT, N0, 2352 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2353 getShiftAmountTy(N0.getValueType()))); 2354 2355 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2356 if (N1.getOpcode() == ISD::SHL) { 2357 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2358 if (SHC->getAPIntValue().isPowerOf2()) { 2359 EVT ADDVT = N1.getOperand(1).getValueType(); 2360 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2361 N1.getOperand(1), 2362 DAG.getConstant(SHC->getAPIntValue() 2363 .logBase2(), 2364 DL, ADDVT)); 2365 AddToWorklist(Add.getNode()); 2366 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2367 } 2368 } 2369 } 2370 2371 // fold (udiv x, c) -> alternate 2372 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2373 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2374 if (SDValue Op = BuildUDIV(N)) 2375 return Op; 2376 2377 // sdiv, srem -> sdivrem 2378 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2379 // Otherwise, we break the simplification logic in visitREM(). 2380 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2381 if (SDValue DivRem = useDivRem(N)) 2382 return DivRem; 2383 2384 // undef / X -> 0 2385 if (N0.isUndef()) 2386 return DAG.getConstant(0, DL, VT); 2387 // X / undef -> undef 2388 if (N1.isUndef()) 2389 return N1; 2390 2391 return SDValue(); 2392 } 2393 2394 // handles ISD::SREM and ISD::UREM 2395 SDValue DAGCombiner::visitREM(SDNode *N) { 2396 unsigned Opcode = N->getOpcode(); 2397 SDValue N0 = N->getOperand(0); 2398 SDValue N1 = N->getOperand(1); 2399 EVT VT = N->getValueType(0); 2400 bool isSigned = (Opcode == ISD::SREM); 2401 SDLoc DL(N); 2402 2403 // fold (rem c1, c2) -> c1%c2 2404 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2405 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2406 if (N0C && N1C) 2407 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2408 return Folded; 2409 2410 if (isSigned) { 2411 // If we know the sign bits of both operands are zero, strength reduce to a 2412 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2413 if (!VT.isVector()) { 2414 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2415 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2416 } 2417 } else { 2418 // fold (urem x, pow2) -> (and x, pow2-1) 2419 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2420 N1C->getAPIntValue().isPowerOf2()) { 2421 return DAG.getNode(ISD::AND, DL, VT, N0, 2422 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2423 } 2424 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2425 if (N1.getOpcode() == ISD::SHL) { 2426 ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0)); 2427 if (SHC && SHC->getAPIntValue().isPowerOf2()) { 2428 APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits()); 2429 SDValue Add = 2430 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT)); 2431 AddToWorklist(Add.getNode()); 2432 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2433 } 2434 } 2435 } 2436 2437 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2438 2439 // If X/C can be simplified by the division-by-constant logic, lower 2440 // X%C to the equivalent of X-X/C*C. 2441 // To avoid mangling nodes, this simplification requires that the combine() 2442 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2443 // against this by skipping the simplification if isIntDivCheap(). When 2444 // div is not cheap, combine will not return a DIVREM. Regardless, 2445 // checking cheapness here makes sense since the simplification results in 2446 // fatter code. 2447 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2448 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2449 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2450 AddToWorklist(Div.getNode()); 2451 SDValue OptimizedDiv = combine(Div.getNode()); 2452 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2453 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2454 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2455 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2456 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2457 AddToWorklist(Mul.getNode()); 2458 return Sub; 2459 } 2460 } 2461 2462 // sdiv, srem -> sdivrem 2463 if (SDValue DivRem = useDivRem(N)) 2464 return DivRem.getValue(1); 2465 2466 // undef % X -> 0 2467 if (N0.isUndef()) 2468 return DAG.getConstant(0, DL, VT); 2469 // X % undef -> undef 2470 if (N1.isUndef()) 2471 return N1; 2472 2473 return SDValue(); 2474 } 2475 2476 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2477 SDValue N0 = N->getOperand(0); 2478 SDValue N1 = N->getOperand(1); 2479 EVT VT = N->getValueType(0); 2480 SDLoc DL(N); 2481 2482 // fold (mulhs x, 0) -> 0 2483 if (isNullConstant(N1)) 2484 return N1; 2485 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2486 if (isOneConstant(N1)) { 2487 SDLoc DL(N); 2488 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2489 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2490 DL, 2491 getShiftAmountTy(N0.getValueType()))); 2492 } 2493 // fold (mulhs x, undef) -> 0 2494 if (N0.isUndef() || N1.isUndef()) 2495 return DAG.getConstant(0, SDLoc(N), VT); 2496 2497 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2498 // plus a shift. 2499 if (VT.isSimple() && !VT.isVector()) { 2500 MVT Simple = VT.getSimpleVT(); 2501 unsigned SimpleSize = Simple.getSizeInBits(); 2502 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2503 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2504 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2505 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2506 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2507 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2508 DAG.getConstant(SimpleSize, DL, 2509 getShiftAmountTy(N1.getValueType()))); 2510 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2511 } 2512 } 2513 2514 return SDValue(); 2515 } 2516 2517 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2518 SDValue N0 = N->getOperand(0); 2519 SDValue N1 = N->getOperand(1); 2520 EVT VT = N->getValueType(0); 2521 SDLoc DL(N); 2522 2523 // fold (mulhu x, 0) -> 0 2524 if (isNullConstant(N1)) 2525 return N1; 2526 // fold (mulhu x, 1) -> 0 2527 if (isOneConstant(N1)) 2528 return DAG.getConstant(0, DL, N0.getValueType()); 2529 // fold (mulhu x, undef) -> 0 2530 if (N0.isUndef() || N1.isUndef()) 2531 return DAG.getConstant(0, DL, VT); 2532 2533 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2534 // plus a shift. 2535 if (VT.isSimple() && !VT.isVector()) { 2536 MVT Simple = VT.getSimpleVT(); 2537 unsigned SimpleSize = Simple.getSizeInBits(); 2538 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2539 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2540 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2541 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2542 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2543 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2544 DAG.getConstant(SimpleSize, DL, 2545 getShiftAmountTy(N1.getValueType()))); 2546 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2547 } 2548 } 2549 2550 return SDValue(); 2551 } 2552 2553 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2554 /// give the opcodes for the two computations that are being performed. Return 2555 /// true if a simplification was made. 2556 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2557 unsigned HiOp) { 2558 // If the high half is not needed, just compute the low half. 2559 bool HiExists = N->hasAnyUseOfValue(1); 2560 if (!HiExists && 2561 (!LegalOperations || 2562 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2563 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2564 return CombineTo(N, Res, Res); 2565 } 2566 2567 // If the low half is not needed, just compute the high half. 2568 bool LoExists = N->hasAnyUseOfValue(0); 2569 if (!LoExists && 2570 (!LegalOperations || 2571 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2572 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2573 return CombineTo(N, Res, Res); 2574 } 2575 2576 // If both halves are used, return as it is. 2577 if (LoExists && HiExists) 2578 return SDValue(); 2579 2580 // If the two computed results can be simplified separately, separate them. 2581 if (LoExists) { 2582 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2583 AddToWorklist(Lo.getNode()); 2584 SDValue LoOpt = combine(Lo.getNode()); 2585 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2586 (!LegalOperations || 2587 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2588 return CombineTo(N, LoOpt, LoOpt); 2589 } 2590 2591 if (HiExists) { 2592 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2593 AddToWorklist(Hi.getNode()); 2594 SDValue HiOpt = combine(Hi.getNode()); 2595 if (HiOpt.getNode() && HiOpt != Hi && 2596 (!LegalOperations || 2597 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2598 return CombineTo(N, HiOpt, HiOpt); 2599 } 2600 2601 return SDValue(); 2602 } 2603 2604 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2605 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2606 return Res; 2607 2608 EVT VT = N->getValueType(0); 2609 SDLoc DL(N); 2610 2611 // If the type is twice as wide is legal, transform the mulhu to a wider 2612 // multiply plus a shift. 2613 if (VT.isSimple() && !VT.isVector()) { 2614 MVT Simple = VT.getSimpleVT(); 2615 unsigned SimpleSize = Simple.getSizeInBits(); 2616 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2617 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2618 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2619 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2620 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2621 // Compute the high part as N1. 2622 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2623 DAG.getConstant(SimpleSize, DL, 2624 getShiftAmountTy(Lo.getValueType()))); 2625 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2626 // Compute the low part as N0. 2627 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2628 return CombineTo(N, Lo, Hi); 2629 } 2630 } 2631 2632 return SDValue(); 2633 } 2634 2635 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2636 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2637 return Res; 2638 2639 EVT VT = N->getValueType(0); 2640 SDLoc DL(N); 2641 2642 // If the type is twice as wide is legal, transform the mulhu to a wider 2643 // multiply plus a shift. 2644 if (VT.isSimple() && !VT.isVector()) { 2645 MVT Simple = VT.getSimpleVT(); 2646 unsigned SimpleSize = Simple.getSizeInBits(); 2647 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2648 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2649 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2650 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2651 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2652 // Compute the high part as N1. 2653 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2654 DAG.getConstant(SimpleSize, DL, 2655 getShiftAmountTy(Lo.getValueType()))); 2656 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2657 // Compute the low part as N0. 2658 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2659 return CombineTo(N, Lo, Hi); 2660 } 2661 } 2662 2663 return SDValue(); 2664 } 2665 2666 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2667 // (smulo x, 2) -> (saddo x, x) 2668 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2669 if (C2->getAPIntValue() == 2) 2670 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2671 N->getOperand(0), N->getOperand(0)); 2672 2673 return SDValue(); 2674 } 2675 2676 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2677 // (umulo x, 2) -> (uaddo x, x) 2678 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2679 if (C2->getAPIntValue() == 2) 2680 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2681 N->getOperand(0), N->getOperand(0)); 2682 2683 return SDValue(); 2684 } 2685 2686 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2687 SDValue N0 = N->getOperand(0); 2688 SDValue N1 = N->getOperand(1); 2689 EVT VT = N0.getValueType(); 2690 2691 // fold vector ops 2692 if (VT.isVector()) 2693 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2694 return FoldedVOp; 2695 2696 // fold (add c1, c2) -> c1+c2 2697 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2698 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2699 if (N0C && N1C) 2700 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2701 2702 // canonicalize constant to RHS 2703 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2704 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2705 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2706 2707 return SDValue(); 2708 } 2709 2710 /// If this is a binary operator with two operands of the same opcode, try to 2711 /// simplify it. 2712 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2713 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2714 EVT VT = N0.getValueType(); 2715 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2716 2717 // Bail early if none of these transforms apply. 2718 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2719 2720 // For each of OP in AND/OR/XOR: 2721 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2722 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2723 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2724 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2725 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2726 // 2727 // do not sink logical op inside of a vector extend, since it may combine 2728 // into a vsetcc. 2729 EVT Op0VT = N0.getOperand(0).getValueType(); 2730 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2731 N0.getOpcode() == ISD::SIGN_EXTEND || 2732 N0.getOpcode() == ISD::BSWAP || 2733 // Avoid infinite looping with PromoteIntBinOp. 2734 (N0.getOpcode() == ISD::ANY_EXTEND && 2735 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2736 (N0.getOpcode() == ISD::TRUNCATE && 2737 (!TLI.isZExtFree(VT, Op0VT) || 2738 !TLI.isTruncateFree(Op0VT, VT)) && 2739 TLI.isTypeLegal(Op0VT))) && 2740 !VT.isVector() && 2741 Op0VT == N1.getOperand(0).getValueType() && 2742 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2743 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2744 N0.getOperand(0).getValueType(), 2745 N0.getOperand(0), N1.getOperand(0)); 2746 AddToWorklist(ORNode.getNode()); 2747 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2748 } 2749 2750 // For each of OP in SHL/SRL/SRA/AND... 2751 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2752 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2753 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2754 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2755 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2756 N0.getOperand(1) == N1.getOperand(1)) { 2757 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2758 N0.getOperand(0).getValueType(), 2759 N0.getOperand(0), N1.getOperand(0)); 2760 AddToWorklist(ORNode.getNode()); 2761 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2762 ORNode, N0.getOperand(1)); 2763 } 2764 2765 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2766 // Only perform this optimization up until type legalization, before 2767 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2768 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2769 // we don't want to undo this promotion. 2770 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2771 // on scalars. 2772 if ((N0.getOpcode() == ISD::BITCAST || 2773 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2774 Level <= AfterLegalizeTypes) { 2775 SDValue In0 = N0.getOperand(0); 2776 SDValue In1 = N1.getOperand(0); 2777 EVT In0Ty = In0.getValueType(); 2778 EVT In1Ty = In1.getValueType(); 2779 SDLoc DL(N); 2780 // If both incoming values are integers, and the original types are the 2781 // same. 2782 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2783 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2784 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2785 AddToWorklist(Op.getNode()); 2786 return BC; 2787 } 2788 } 2789 2790 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2791 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2792 // If both shuffles use the same mask, and both shuffle within a single 2793 // vector, then it is worthwhile to move the swizzle after the operation. 2794 // The type-legalizer generates this pattern when loading illegal 2795 // vector types from memory. In many cases this allows additional shuffle 2796 // optimizations. 2797 // There are other cases where moving the shuffle after the xor/and/or 2798 // is profitable even if shuffles don't perform a swizzle. 2799 // If both shuffles use the same mask, and both shuffles have the same first 2800 // or second operand, then it might still be profitable to move the shuffle 2801 // after the xor/and/or operation. 2802 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2803 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2804 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2805 2806 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2807 "Inputs to shuffles are not the same type"); 2808 2809 // Check that both shuffles use the same mask. The masks are known to be of 2810 // the same length because the result vector type is the same. 2811 // Check also that shuffles have only one use to avoid introducing extra 2812 // instructions. 2813 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2814 SVN0->getMask().equals(SVN1->getMask())) { 2815 SDValue ShOp = N0->getOperand(1); 2816 2817 // Don't try to fold this node if it requires introducing a 2818 // build vector of all zeros that might be illegal at this stage. 2819 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2820 if (!LegalTypes) 2821 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2822 else 2823 ShOp = SDValue(); 2824 } 2825 2826 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2827 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2828 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2829 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2830 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2831 N0->getOperand(0), N1->getOperand(0)); 2832 AddToWorklist(NewNode.getNode()); 2833 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2834 SVN0->getMask()); 2835 } 2836 2837 // Don't try to fold this node if it requires introducing a 2838 // build vector of all zeros that might be illegal at this stage. 2839 ShOp = N0->getOperand(0); 2840 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2841 if (!LegalTypes) 2842 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2843 else 2844 ShOp = SDValue(); 2845 } 2846 2847 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2848 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2849 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2850 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2851 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2852 N0->getOperand(1), N1->getOperand(1)); 2853 AddToWorklist(NewNode.getNode()); 2854 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2855 SVN0->getMask()); 2856 } 2857 } 2858 } 2859 2860 return SDValue(); 2861 } 2862 2863 /// This contains all DAGCombine rules which reduce two values combined by 2864 /// an And operation to a single value. This makes them reusable in the context 2865 /// of visitSELECT(). Rules involving constants are not included as 2866 /// visitSELECT() already handles those cases. 2867 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2868 SDNode *LocReference) { 2869 EVT VT = N1.getValueType(); 2870 2871 // fold (and x, undef) -> 0 2872 if (N0.isUndef() || N1.isUndef()) 2873 return DAG.getConstant(0, SDLoc(LocReference), VT); 2874 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2875 SDValue LL, LR, RL, RR, CC0, CC1; 2876 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2877 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2878 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2879 2880 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2881 LL.getValueType().isInteger()) { 2882 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2883 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2884 EVT CCVT = getSetCCResultType(LR.getValueType()); 2885 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2886 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2887 LR.getValueType(), LL, RL); 2888 AddToWorklist(ORNode.getNode()); 2889 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2890 } 2891 } 2892 if (isAllOnesConstant(LR)) { 2893 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2894 if (Op1 == ISD::SETEQ) { 2895 EVT CCVT = getSetCCResultType(LR.getValueType()); 2896 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2897 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2898 LR.getValueType(), LL, RL); 2899 AddToWorklist(ANDNode.getNode()); 2900 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2901 } 2902 } 2903 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2904 if (Op1 == ISD::SETGT) { 2905 EVT CCVT = getSetCCResultType(LR.getValueType()); 2906 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2907 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2908 LR.getValueType(), LL, RL); 2909 AddToWorklist(ORNode.getNode()); 2910 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2911 } 2912 } 2913 } 2914 } 2915 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2916 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2917 Op0 == Op1 && LL.getValueType().isInteger() && 2918 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2919 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2920 EVT CCVT = getSetCCResultType(LL.getValueType()); 2921 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 2922 SDLoc DL(N0); 2923 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2924 LL, DAG.getConstant(1, DL, 2925 LL.getValueType())); 2926 AddToWorklist(ADDNode.getNode()); 2927 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2928 DAG.getConstant(2, DL, LL.getValueType()), 2929 ISD::SETUGE); 2930 } 2931 } 2932 // canonicalize equivalent to ll == rl 2933 if (LL == RR && LR == RL) { 2934 Op1 = ISD::getSetCCSwappedOperands(Op1); 2935 std::swap(RL, RR); 2936 } 2937 if (LL == RL && LR == RR) { 2938 bool isInteger = LL.getValueType().isInteger(); 2939 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2940 if (Result != ISD::SETCC_INVALID && 2941 (!LegalOperations || 2942 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2943 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2944 EVT CCVT = getSetCCResultType(LL.getValueType()); 2945 if (N0.getValueType() == CCVT || 2946 (!LegalOperations && N0.getValueType() == MVT::i1)) 2947 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2948 LL, LR, Result); 2949 } 2950 } 2951 } 2952 2953 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2954 VT.getSizeInBits() <= 64) { 2955 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2956 APInt ADDC = ADDI->getAPIntValue(); 2957 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2958 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2959 // immediate for an add, but it is legal if its top c2 bits are set, 2960 // transform the ADD so the immediate doesn't need to be materialized 2961 // in a register. 2962 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2963 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2964 SRLI->getZExtValue()); 2965 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2966 ADDC |= Mask; 2967 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2968 SDLoc DL(N0); 2969 SDValue NewAdd = 2970 DAG.getNode(ISD::ADD, DL, VT, 2971 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2972 CombineTo(N0.getNode(), NewAdd); 2973 // Return N so it doesn't get rechecked! 2974 return SDValue(LocReference, 0); 2975 } 2976 } 2977 } 2978 } 2979 } 2980 } 2981 2982 // Reduce bit extract of low half of an integer to the narrower type. 2983 // (and (srl i64:x, K), KMask) -> 2984 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 2985 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 2986 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 2987 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2988 unsigned Size = VT.getSizeInBits(); 2989 const APInt &AndMask = CAnd->getAPIntValue(); 2990 unsigned ShiftBits = CShift->getZExtValue(); 2991 unsigned MaskBits = AndMask.countTrailingOnes(); 2992 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 2993 2994 if (APIntOps::isMask(AndMask) && 2995 // Required bits must not span the two halves of the integer and 2996 // must fit in the half size type. 2997 (ShiftBits + MaskBits <= Size / 2) && 2998 TLI.isNarrowingProfitable(VT, HalfVT) && 2999 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 3000 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 3001 TLI.isTruncateFree(VT, HalfVT) && 3002 TLI.isZExtFree(HalfVT, VT)) { 3003 // The isNarrowingProfitable is to avoid regressions on PPC and 3004 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3005 // on downstream users of this. Those patterns could probably be 3006 // extended to handle extensions mixed in. 3007 3008 SDValue SL(N0); 3009 assert(ShiftBits != 0 && MaskBits <= Size); 3010 3011 // Extracting the highest bit of the low half. 3012 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3013 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3014 N0.getOperand(0)); 3015 3016 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3017 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3018 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3019 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3020 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3021 } 3022 } 3023 } 3024 } 3025 3026 return SDValue(); 3027 } 3028 3029 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3030 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3031 bool &NarrowLoad) { 3032 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3033 3034 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 3035 return false; 3036 3037 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3038 LoadedVT = LoadN->getMemoryVT(); 3039 3040 if (ExtVT == LoadedVT && 3041 (!LegalOperations || 3042 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3043 // ZEXTLOAD will match without needing to change the size of the value being 3044 // loaded. 3045 NarrowLoad = false; 3046 return true; 3047 } 3048 3049 // Do not change the width of a volatile load. 3050 if (LoadN->isVolatile()) 3051 return false; 3052 3053 // Do not generate loads of non-round integer types since these can 3054 // be expensive (and would be wrong if the type is not byte sized). 3055 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3056 return false; 3057 3058 if (LegalOperations && 3059 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3060 return false; 3061 3062 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3063 return false; 3064 3065 NarrowLoad = true; 3066 return true; 3067 } 3068 3069 SDValue DAGCombiner::visitAND(SDNode *N) { 3070 SDValue N0 = N->getOperand(0); 3071 SDValue N1 = N->getOperand(1); 3072 EVT VT = N1.getValueType(); 3073 3074 // fold vector ops 3075 if (VT.isVector()) { 3076 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3077 return FoldedVOp; 3078 3079 // fold (and x, 0) -> 0, vector edition 3080 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3081 // do not return N0, because undef node may exist in N0 3082 return DAG.getConstant( 3083 APInt::getNullValue( 3084 N0.getValueType().getScalarType().getSizeInBits()), 3085 SDLoc(N), N0.getValueType()); 3086 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3087 // do not return N1, because undef node may exist in N1 3088 return DAG.getConstant( 3089 APInt::getNullValue( 3090 N1.getValueType().getScalarType().getSizeInBits()), 3091 SDLoc(N), N1.getValueType()); 3092 3093 // fold (and x, -1) -> x, vector edition 3094 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3095 return N1; 3096 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3097 return N0; 3098 } 3099 3100 // fold (and c1, c2) -> c1&c2 3101 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3102 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3103 if (N0C && N1C && !N1C->isOpaque()) 3104 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3105 // canonicalize constant to RHS 3106 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3107 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3108 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3109 // fold (and x, -1) -> x 3110 if (isAllOnesConstant(N1)) 3111 return N0; 3112 // if (and x, c) is known to be zero, return 0 3113 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3114 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3115 APInt::getAllOnesValue(BitWidth))) 3116 return DAG.getConstant(0, SDLoc(N), VT); 3117 // reassociate and 3118 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3119 return RAND; 3120 // fold (and (or x, C), D) -> D if (C & D) == D 3121 if (N1C && N0.getOpcode() == ISD::OR) 3122 if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1))) 3123 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3124 return N1; 3125 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3126 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3127 SDValue N0Op0 = N0.getOperand(0); 3128 APInt Mask = ~N1C->getAPIntValue(); 3129 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 3130 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3131 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3132 N0.getValueType(), N0Op0); 3133 3134 // Replace uses of the AND with uses of the Zero extend node. 3135 CombineTo(N, Zext); 3136 3137 // We actually want to replace all uses of the any_extend with the 3138 // zero_extend, to avoid duplicating things. This will later cause this 3139 // AND to be folded. 3140 CombineTo(N0.getNode(), Zext); 3141 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3142 } 3143 } 3144 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3145 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3146 // already be zero by virtue of the width of the base type of the load. 3147 // 3148 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3149 // more cases. 3150 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3151 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3152 N0.getOperand(0).getOpcode() == ISD::LOAD && 3153 N0.getOperand(0).getResNo() == 0) || 3154 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3155 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3156 N0 : N0.getOperand(0) ); 3157 3158 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3159 // This can be a pure constant or a vector splat, in which case we treat the 3160 // vector as a scalar and use the splat value. 3161 APInt Constant = APInt::getNullValue(1); 3162 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3163 Constant = C->getAPIntValue(); 3164 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3165 APInt SplatValue, SplatUndef; 3166 unsigned SplatBitSize; 3167 bool HasAnyUndefs; 3168 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3169 SplatBitSize, HasAnyUndefs); 3170 if (IsSplat) { 3171 // Undef bits can contribute to a possible optimisation if set, so 3172 // set them. 3173 SplatValue |= SplatUndef; 3174 3175 // The splat value may be something like "0x00FFFFFF", which means 0 for 3176 // the first vector value and FF for the rest, repeating. We need a mask 3177 // that will apply equally to all members of the vector, so AND all the 3178 // lanes of the constant together. 3179 EVT VT = Vector->getValueType(0); 3180 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3181 3182 // If the splat value has been compressed to a bitlength lower 3183 // than the size of the vector lane, we need to re-expand it to 3184 // the lane size. 3185 if (BitWidth > SplatBitSize) 3186 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3187 SplatBitSize < BitWidth; 3188 SplatBitSize = SplatBitSize * 2) 3189 SplatValue |= SplatValue.shl(SplatBitSize); 3190 3191 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3192 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3193 if (SplatBitSize % BitWidth == 0) { 3194 Constant = APInt::getAllOnesValue(BitWidth); 3195 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3196 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3197 } 3198 } 3199 } 3200 3201 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3202 // actually legal and isn't going to get expanded, else this is a false 3203 // optimisation. 3204 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3205 Load->getValueType(0), 3206 Load->getMemoryVT()); 3207 3208 // Resize the constant to the same size as the original memory access before 3209 // extension. If it is still the AllOnesValue then this AND is completely 3210 // unneeded. 3211 Constant = 3212 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3213 3214 bool B; 3215 switch (Load->getExtensionType()) { 3216 default: B = false; break; 3217 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3218 case ISD::ZEXTLOAD: 3219 case ISD::NON_EXTLOAD: B = true; break; 3220 } 3221 3222 if (B && Constant.isAllOnesValue()) { 3223 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3224 // preserve semantics once we get rid of the AND. 3225 SDValue NewLoad(Load, 0); 3226 if (Load->getExtensionType() == ISD::EXTLOAD) { 3227 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3228 Load->getValueType(0), SDLoc(Load), 3229 Load->getChain(), Load->getBasePtr(), 3230 Load->getOffset(), Load->getMemoryVT(), 3231 Load->getMemOperand()); 3232 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3233 if (Load->getNumValues() == 3) { 3234 // PRE/POST_INC loads have 3 values. 3235 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3236 NewLoad.getValue(2) }; 3237 CombineTo(Load, To, 3, true); 3238 } else { 3239 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3240 } 3241 } 3242 3243 // Fold the AND away, taking care not to fold to the old load node if we 3244 // replaced it. 3245 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3246 3247 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3248 } 3249 } 3250 3251 // fold (and (load x), 255) -> (zextload x, i8) 3252 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3253 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3254 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 3255 (N0.getOpcode() == ISD::ANY_EXTEND && 3256 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3257 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3258 LoadSDNode *LN0 = HasAnyExt 3259 ? cast<LoadSDNode>(N0.getOperand(0)) 3260 : cast<LoadSDNode>(N0); 3261 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3262 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3263 auto NarrowLoad = false; 3264 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3265 EVT ExtVT, LoadedVT; 3266 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3267 NarrowLoad)) { 3268 if (!NarrowLoad) { 3269 SDValue NewLoad = 3270 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3271 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3272 LN0->getMemOperand()); 3273 AddToWorklist(N); 3274 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3275 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3276 } else { 3277 EVT PtrType = LN0->getOperand(1).getValueType(); 3278 3279 unsigned Alignment = LN0->getAlignment(); 3280 SDValue NewPtr = LN0->getBasePtr(); 3281 3282 // For big endian targets, we need to add an offset to the pointer 3283 // to load the correct bytes. For little endian systems, we merely 3284 // need to read fewer bytes from the same pointer. 3285 if (DAG.getDataLayout().isBigEndian()) { 3286 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3287 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3288 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3289 SDLoc DL(LN0); 3290 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3291 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3292 Alignment = MinAlign(Alignment, PtrOff); 3293 } 3294 3295 AddToWorklist(NewPtr.getNode()); 3296 3297 SDValue Load = DAG.getExtLoad( 3298 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3299 LN0->getPointerInfo(), ExtVT, Alignment, 3300 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3301 AddToWorklist(N); 3302 CombineTo(LN0, Load, Load.getValue(1)); 3303 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3304 } 3305 } 3306 } 3307 } 3308 3309 if (SDValue Combined = visitANDLike(N0, N1, N)) 3310 return Combined; 3311 3312 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3313 if (N0.getOpcode() == N1.getOpcode()) 3314 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3315 return Tmp; 3316 3317 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3318 // fold (and (sra)) -> (and (srl)) when possible. 3319 if (!VT.isVector() && 3320 SimplifyDemandedBits(SDValue(N, 0))) 3321 return SDValue(N, 0); 3322 3323 // fold (zext_inreg (extload x)) -> (zextload x) 3324 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3325 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3326 EVT MemVT = LN0->getMemoryVT(); 3327 // If we zero all the possible extended bits, then we can turn this into 3328 // a zextload if we are running before legalize or the operation is legal. 3329 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3330 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3331 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3332 ((!LegalOperations && !LN0->isVolatile()) || 3333 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3334 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3335 LN0->getChain(), LN0->getBasePtr(), 3336 MemVT, LN0->getMemOperand()); 3337 AddToWorklist(N); 3338 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3339 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3340 } 3341 } 3342 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3343 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3344 N0.hasOneUse()) { 3345 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3346 EVT MemVT = LN0->getMemoryVT(); 3347 // If we zero all the possible extended bits, then we can turn this into 3348 // a zextload if we are running before legalize or the operation is legal. 3349 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3350 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3351 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3352 ((!LegalOperations && !LN0->isVolatile()) || 3353 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3354 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3355 LN0->getChain(), LN0->getBasePtr(), 3356 MemVT, LN0->getMemOperand()); 3357 AddToWorklist(N); 3358 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3359 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3360 } 3361 } 3362 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3363 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3364 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3365 N0.getOperand(1), false)) 3366 return BSwap; 3367 } 3368 3369 return SDValue(); 3370 } 3371 3372 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3373 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3374 bool DemandHighBits) { 3375 if (!LegalOperations) 3376 return SDValue(); 3377 3378 EVT VT = N->getValueType(0); 3379 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3380 return SDValue(); 3381 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3382 return SDValue(); 3383 3384 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3385 bool LookPassAnd0 = false; 3386 bool LookPassAnd1 = false; 3387 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3388 std::swap(N0, N1); 3389 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3390 std::swap(N0, N1); 3391 if (N0.getOpcode() == ISD::AND) { 3392 if (!N0.getNode()->hasOneUse()) 3393 return SDValue(); 3394 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3395 if (!N01C || N01C->getZExtValue() != 0xFF00) 3396 return SDValue(); 3397 N0 = N0.getOperand(0); 3398 LookPassAnd0 = true; 3399 } 3400 3401 if (N1.getOpcode() == ISD::AND) { 3402 if (!N1.getNode()->hasOneUse()) 3403 return SDValue(); 3404 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3405 if (!N11C || N11C->getZExtValue() != 0xFF) 3406 return SDValue(); 3407 N1 = N1.getOperand(0); 3408 LookPassAnd1 = true; 3409 } 3410 3411 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3412 std::swap(N0, N1); 3413 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3414 return SDValue(); 3415 if (!N0.getNode()->hasOneUse() || 3416 !N1.getNode()->hasOneUse()) 3417 return SDValue(); 3418 3419 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3420 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3421 if (!N01C || !N11C) 3422 return SDValue(); 3423 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3424 return SDValue(); 3425 3426 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3427 SDValue N00 = N0->getOperand(0); 3428 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3429 if (!N00.getNode()->hasOneUse()) 3430 return SDValue(); 3431 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3432 if (!N001C || N001C->getZExtValue() != 0xFF) 3433 return SDValue(); 3434 N00 = N00.getOperand(0); 3435 LookPassAnd0 = true; 3436 } 3437 3438 SDValue N10 = N1->getOperand(0); 3439 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3440 if (!N10.getNode()->hasOneUse()) 3441 return SDValue(); 3442 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3443 if (!N101C || N101C->getZExtValue() != 0xFF00) 3444 return SDValue(); 3445 N10 = N10.getOperand(0); 3446 LookPassAnd1 = true; 3447 } 3448 3449 if (N00 != N10) 3450 return SDValue(); 3451 3452 // Make sure everything beyond the low halfword gets set to zero since the SRL 3453 // 16 will clear the top bits. 3454 unsigned OpSizeInBits = VT.getSizeInBits(); 3455 if (DemandHighBits && OpSizeInBits > 16) { 3456 // If the left-shift isn't masked out then the only way this is a bswap is 3457 // if all bits beyond the low 8 are 0. In that case the entire pattern 3458 // reduces to a left shift anyway: leave it for other parts of the combiner. 3459 if (!LookPassAnd0) 3460 return SDValue(); 3461 3462 // However, if the right shift isn't masked out then it might be because 3463 // it's not needed. See if we can spot that too. 3464 if (!LookPassAnd1 && 3465 !DAG.MaskedValueIsZero( 3466 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3467 return SDValue(); 3468 } 3469 3470 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3471 if (OpSizeInBits > 16) { 3472 SDLoc DL(N); 3473 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3474 DAG.getConstant(OpSizeInBits - 16, DL, 3475 getShiftAmountTy(VT))); 3476 } 3477 return Res; 3478 } 3479 3480 /// Return true if the specified node is an element that makes up a 32-bit 3481 /// packed halfword byteswap. 3482 /// ((x & 0x000000ff) << 8) | 3483 /// ((x & 0x0000ff00) >> 8) | 3484 /// ((x & 0x00ff0000) << 8) | 3485 /// ((x & 0xff000000) >> 8) 3486 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3487 if (!N.getNode()->hasOneUse()) 3488 return false; 3489 3490 unsigned Opc = N.getOpcode(); 3491 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3492 return false; 3493 3494 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3495 if (!N1C) 3496 return false; 3497 3498 unsigned Num; 3499 switch (N1C->getZExtValue()) { 3500 default: 3501 return false; 3502 case 0xFF: Num = 0; break; 3503 case 0xFF00: Num = 1; break; 3504 case 0xFF0000: Num = 2; break; 3505 case 0xFF000000: Num = 3; break; 3506 } 3507 3508 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3509 SDValue N0 = N.getOperand(0); 3510 if (Opc == ISD::AND) { 3511 if (Num == 0 || Num == 2) { 3512 // (x >> 8) & 0xff 3513 // (x >> 8) & 0xff0000 3514 if (N0.getOpcode() != ISD::SRL) 3515 return false; 3516 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3517 if (!C || C->getZExtValue() != 8) 3518 return false; 3519 } else { 3520 // (x << 8) & 0xff00 3521 // (x << 8) & 0xff000000 3522 if (N0.getOpcode() != ISD::SHL) 3523 return false; 3524 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3525 if (!C || C->getZExtValue() != 8) 3526 return false; 3527 } 3528 } else if (Opc == ISD::SHL) { 3529 // (x & 0xff) << 8 3530 // (x & 0xff0000) << 8 3531 if (Num != 0 && Num != 2) 3532 return false; 3533 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3534 if (!C || C->getZExtValue() != 8) 3535 return false; 3536 } else { // Opc == ISD::SRL 3537 // (x & 0xff00) >> 8 3538 // (x & 0xff000000) >> 8 3539 if (Num != 1 && Num != 3) 3540 return false; 3541 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3542 if (!C || C->getZExtValue() != 8) 3543 return false; 3544 } 3545 3546 if (Parts[Num]) 3547 return false; 3548 3549 Parts[Num] = N0.getOperand(0).getNode(); 3550 return true; 3551 } 3552 3553 /// Match a 32-bit packed halfword bswap. That is 3554 /// ((x & 0x000000ff) << 8) | 3555 /// ((x & 0x0000ff00) >> 8) | 3556 /// ((x & 0x00ff0000) << 8) | 3557 /// ((x & 0xff000000) >> 8) 3558 /// => (rotl (bswap x), 16) 3559 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3560 if (!LegalOperations) 3561 return SDValue(); 3562 3563 EVT VT = N->getValueType(0); 3564 if (VT != MVT::i32) 3565 return SDValue(); 3566 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3567 return SDValue(); 3568 3569 // Look for either 3570 // (or (or (and), (and)), (or (and), (and))) 3571 // (or (or (or (and), (and)), (and)), (and)) 3572 if (N0.getOpcode() != ISD::OR) 3573 return SDValue(); 3574 SDValue N00 = N0.getOperand(0); 3575 SDValue N01 = N0.getOperand(1); 3576 SDNode *Parts[4] = {}; 3577 3578 if (N1.getOpcode() == ISD::OR && 3579 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3580 // (or (or (and), (and)), (or (and), (and))) 3581 SDValue N000 = N00.getOperand(0); 3582 if (!isBSwapHWordElement(N000, Parts)) 3583 return SDValue(); 3584 3585 SDValue N001 = N00.getOperand(1); 3586 if (!isBSwapHWordElement(N001, Parts)) 3587 return SDValue(); 3588 SDValue N010 = N01.getOperand(0); 3589 if (!isBSwapHWordElement(N010, Parts)) 3590 return SDValue(); 3591 SDValue N011 = N01.getOperand(1); 3592 if (!isBSwapHWordElement(N011, Parts)) 3593 return SDValue(); 3594 } else { 3595 // (or (or (or (and), (and)), (and)), (and)) 3596 if (!isBSwapHWordElement(N1, Parts)) 3597 return SDValue(); 3598 if (!isBSwapHWordElement(N01, Parts)) 3599 return SDValue(); 3600 if (N00.getOpcode() != ISD::OR) 3601 return SDValue(); 3602 SDValue N000 = N00.getOperand(0); 3603 if (!isBSwapHWordElement(N000, Parts)) 3604 return SDValue(); 3605 SDValue N001 = N00.getOperand(1); 3606 if (!isBSwapHWordElement(N001, Parts)) 3607 return SDValue(); 3608 } 3609 3610 // Make sure the parts are all coming from the same node. 3611 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3612 return SDValue(); 3613 3614 SDLoc DL(N); 3615 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3616 SDValue(Parts[0], 0)); 3617 3618 // Result of the bswap should be rotated by 16. If it's not legal, then 3619 // do (x << 16) | (x >> 16). 3620 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3621 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3622 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3623 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3624 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3625 return DAG.getNode(ISD::OR, DL, VT, 3626 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3627 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3628 } 3629 3630 /// This contains all DAGCombine rules which reduce two values combined by 3631 /// an Or operation to a single value \see visitANDLike(). 3632 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3633 EVT VT = N1.getValueType(); 3634 // fold (or x, undef) -> -1 3635 if (!LegalOperations && 3636 (N0.isUndef() || N1.isUndef())) { 3637 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3638 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3639 SDLoc(LocReference), VT); 3640 } 3641 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3642 SDValue LL, LR, RL, RR, CC0, CC1; 3643 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3644 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3645 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3646 3647 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3648 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3649 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3650 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3651 EVT CCVT = getSetCCResultType(LR.getValueType()); 3652 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3653 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3654 LR.getValueType(), LL, RL); 3655 AddToWorklist(ORNode.getNode()); 3656 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3657 } 3658 } 3659 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3660 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3661 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3662 EVT CCVT = getSetCCResultType(LR.getValueType()); 3663 if (VT == CCVT || (!LegalOperations && VT == MVT::i1)) { 3664 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3665 LR.getValueType(), LL, RL); 3666 AddToWorklist(ANDNode.getNode()); 3667 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3668 } 3669 } 3670 } 3671 // canonicalize equivalent to ll == rl 3672 if (LL == RR && LR == RL) { 3673 Op1 = ISD::getSetCCSwappedOperands(Op1); 3674 std::swap(RL, RR); 3675 } 3676 if (LL == RL && LR == RR) { 3677 bool isInteger = LL.getValueType().isInteger(); 3678 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3679 if (Result != ISD::SETCC_INVALID && 3680 (!LegalOperations || 3681 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3682 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3683 EVT CCVT = getSetCCResultType(LL.getValueType()); 3684 if (N0.getValueType() == CCVT || 3685 (!LegalOperations && N0.getValueType() == MVT::i1)) 3686 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3687 LL, LR, Result); 3688 } 3689 } 3690 } 3691 3692 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3693 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3694 // Don't increase # computations. 3695 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3696 // We can only do this xform if we know that bits from X that are set in C2 3697 // but not in C1 are already zero. Likewise for Y. 3698 if (const ConstantSDNode *N0O1C = 3699 getAsNonOpaqueConstant(N0.getOperand(1))) { 3700 if (const ConstantSDNode *N1O1C = 3701 getAsNonOpaqueConstant(N1.getOperand(1))) { 3702 // We can only do this xform if we know that bits from X that are set in 3703 // C2 but not in C1 are already zero. Likewise for Y. 3704 const APInt &LHSMask = N0O1C->getAPIntValue(); 3705 const APInt &RHSMask = N1O1C->getAPIntValue(); 3706 3707 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3708 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3709 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3710 N0.getOperand(0), N1.getOperand(0)); 3711 SDLoc DL(LocReference); 3712 return DAG.getNode(ISD::AND, DL, VT, X, 3713 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3714 } 3715 } 3716 } 3717 } 3718 3719 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3720 if (N0.getOpcode() == ISD::AND && 3721 N1.getOpcode() == ISD::AND && 3722 N0.getOperand(0) == N1.getOperand(0) && 3723 // Don't increase # computations. 3724 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3725 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3726 N0.getOperand(1), N1.getOperand(1)); 3727 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3728 } 3729 3730 return SDValue(); 3731 } 3732 3733 SDValue DAGCombiner::visitOR(SDNode *N) { 3734 SDValue N0 = N->getOperand(0); 3735 SDValue N1 = N->getOperand(1); 3736 EVT VT = N1.getValueType(); 3737 3738 // fold vector ops 3739 if (VT.isVector()) { 3740 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3741 return FoldedVOp; 3742 3743 // fold (or x, 0) -> x, vector edition 3744 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3745 return N1; 3746 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3747 return N0; 3748 3749 // fold (or x, -1) -> -1, vector edition 3750 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3751 // do not return N0, because undef node may exist in N0 3752 return DAG.getConstant( 3753 APInt::getAllOnesValue( 3754 N0.getValueType().getScalarType().getSizeInBits()), 3755 SDLoc(N), N0.getValueType()); 3756 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3757 // do not return N1, because undef node may exist in N1 3758 return DAG.getConstant( 3759 APInt::getAllOnesValue( 3760 N1.getValueType().getScalarType().getSizeInBits()), 3761 SDLoc(N), N1.getValueType()); 3762 3763 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 3764 // Do this only if the resulting shuffle is legal. 3765 if (isa<ShuffleVectorSDNode>(N0) && 3766 isa<ShuffleVectorSDNode>(N1) && 3767 // Avoid folding a node with illegal type. 3768 TLI.isTypeLegal(VT)) { 3769 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 3770 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 3771 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 3772 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 3773 // Ensure both shuffles have a zero input. 3774 if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) { 3775 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 3776 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 3777 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3778 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3779 bool CanFold = true; 3780 int NumElts = VT.getVectorNumElements(); 3781 SmallVector<int, 4> Mask(NumElts); 3782 3783 for (int i = 0; i != NumElts; ++i) { 3784 int M0 = SV0->getMaskElt(i); 3785 int M1 = SV1->getMaskElt(i); 3786 3787 // Determine if either index is pointing to a zero vector. 3788 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 3789 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 3790 3791 // If one element is zero and the otherside is undef, keep undef. 3792 // This also handles the case that both are undef. 3793 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 3794 Mask[i] = -1; 3795 continue; 3796 } 3797 3798 // Make sure only one of the elements is zero. 3799 if (M0Zero == M1Zero) { 3800 CanFold = false; 3801 break; 3802 } 3803 3804 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 3805 3806 // We have a zero and non-zero element. If the non-zero came from 3807 // SV0 make the index a LHS index. If it came from SV1, make it 3808 // a RHS index. We need to mod by NumElts because we don't care 3809 // which operand it came from in the original shuffles. 3810 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 3811 } 3812 3813 if (CanFold) { 3814 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 3815 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 3816 3817 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3818 if (!LegalMask) { 3819 std::swap(NewLHS, NewRHS); 3820 ShuffleVectorSDNode::commuteMask(Mask); 3821 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3822 } 3823 3824 if (LegalMask) 3825 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 3826 } 3827 } 3828 } 3829 } 3830 3831 // fold (or c1, c2) -> c1|c2 3832 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3833 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3834 if (N0C && N1C && !N1C->isOpaque()) 3835 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3836 // canonicalize constant to RHS 3837 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3838 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3839 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3840 // fold (or x, 0) -> x 3841 if (isNullConstant(N1)) 3842 return N0; 3843 // fold (or x, -1) -> -1 3844 if (isAllOnesConstant(N1)) 3845 return N1; 3846 // fold (or x, c) -> c iff (x & ~c) == 0 3847 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3848 return N1; 3849 3850 if (SDValue Combined = visitORLike(N0, N1, N)) 3851 return Combined; 3852 3853 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3854 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3855 return BSwap; 3856 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3857 return BSwap; 3858 3859 // reassociate or 3860 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3861 return ROR; 3862 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3863 // iff (c1 & c2) == 0. 3864 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3865 isa<ConstantSDNode>(N0.getOperand(1))) { 3866 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3867 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3868 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3869 N1C, C1)) 3870 return DAG.getNode( 3871 ISD::AND, SDLoc(N), VT, 3872 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3873 return SDValue(); 3874 } 3875 } 3876 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3877 if (N0.getOpcode() == N1.getOpcode()) 3878 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3879 return Tmp; 3880 3881 // See if this is some rotate idiom. 3882 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3883 return SDValue(Rot, 0); 3884 3885 // Simplify the operands using demanded-bits information. 3886 if (!VT.isVector() && 3887 SimplifyDemandedBits(SDValue(N, 0))) 3888 return SDValue(N, 0); 3889 3890 return SDValue(); 3891 } 3892 3893 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3894 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3895 if (Op.getOpcode() == ISD::AND) { 3896 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3897 Mask = Op.getOperand(1); 3898 Op = Op.getOperand(0); 3899 } else { 3900 return false; 3901 } 3902 } 3903 3904 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3905 Shift = Op; 3906 return true; 3907 } 3908 3909 return false; 3910 } 3911 3912 // Return true if we can prove that, whenever Neg and Pos are both in the 3913 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 3914 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3915 // 3916 // (or (shift1 X, Neg), (shift2 X, Pos)) 3917 // 3918 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3919 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 3920 // to consider shift amounts with defined behavior. 3921 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 3922 // If EltSize is a power of 2 then: 3923 // 3924 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 3925 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 3926 // 3927 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 3928 // for the stronger condition: 3929 // 3930 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 3931 // 3932 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 3933 // we can just replace Neg with Neg' for the rest of the function. 3934 // 3935 // In other cases we check for the even stronger condition: 3936 // 3937 // Neg == EltSize - Pos [B] 3938 // 3939 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3940 // behavior if Pos == 0 (and consequently Neg == EltSize). 3941 // 3942 // We could actually use [A] whenever EltSize is a power of 2, but the 3943 // only extra cases that it would match are those uninteresting ones 3944 // where Neg and Pos are never in range at the same time. E.g. for 3945 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3946 // as well as (sub 32, Pos), but: 3947 // 3948 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3949 // 3950 // always invokes undefined behavior for 32-bit X. 3951 // 3952 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 3953 unsigned MaskLoBits = 0; 3954 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 3955 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 3956 if (NegC->getAPIntValue() == EltSize - 1) { 3957 Neg = Neg.getOperand(0); 3958 MaskLoBits = Log2_64(EltSize); 3959 } 3960 } 3961 } 3962 3963 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3964 if (Neg.getOpcode() != ISD::SUB) 3965 return false; 3966 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 3967 if (!NegC) 3968 return false; 3969 SDValue NegOp1 = Neg.getOperand(1); 3970 3971 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 3972 // Pos'. The truncation is redundant for the purpose of the equality. 3973 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 3974 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3975 if (PosC->getAPIntValue() == EltSize - 1) 3976 Pos = Pos.getOperand(0); 3977 3978 // The condition we need is now: 3979 // 3980 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 3981 // 3982 // If NegOp1 == Pos then we need: 3983 // 3984 // EltSize & Mask == NegC & Mask 3985 // 3986 // (because "x & Mask" is a truncation and distributes through subtraction). 3987 APInt Width; 3988 if (Pos == NegOp1) 3989 Width = NegC->getAPIntValue(); 3990 3991 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3992 // Then the condition we want to prove becomes: 3993 // 3994 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 3995 // 3996 // which, again because "x & Mask" is a truncation, becomes: 3997 // 3998 // NegC & Mask == (EltSize - PosC) & Mask 3999 // EltSize & Mask == (NegC + PosC) & Mask 4000 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 4001 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 4002 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 4003 else 4004 return false; 4005 } else 4006 return false; 4007 4008 // Now we just need to check that EltSize & Mask == Width & Mask. 4009 if (MaskLoBits) 4010 // EltSize & Mask is 0 since Mask is EltSize - 1. 4011 return Width.getLoBits(MaskLoBits) == 0; 4012 return Width == EltSize; 4013 } 4014 4015 // A subroutine of MatchRotate used once we have found an OR of two opposite 4016 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 4017 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 4018 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4019 // Neg with outer conversions stripped away. 4020 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4021 SDValue Neg, SDValue InnerPos, 4022 SDValue InnerNeg, unsigned PosOpcode, 4023 unsigned NegOpcode, const SDLoc &DL) { 4024 // fold (or (shl x, (*ext y)), 4025 // (srl x, (*ext (sub 32, y)))) -> 4026 // (rotl x, y) or (rotr x, (sub 32, y)) 4027 // 4028 // fold (or (shl x, (*ext (sub 32, y))), 4029 // (srl x, (*ext y))) -> 4030 // (rotr x, y) or (rotl x, (sub 32, y)) 4031 EVT VT = Shifted.getValueType(); 4032 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4033 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4034 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4035 HasPos ? Pos : Neg).getNode(); 4036 } 4037 4038 return nullptr; 4039 } 4040 4041 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4042 // idioms for rotate, and if the target supports rotation instructions, generate 4043 // a rot[lr]. 4044 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4045 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4046 EVT VT = LHS.getValueType(); 4047 if (!TLI.isTypeLegal(VT)) return nullptr; 4048 4049 // The target must have at least one rotate flavor. 4050 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4051 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4052 if (!HasROTL && !HasROTR) return nullptr; 4053 4054 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4055 SDValue LHSShift; // The shift. 4056 SDValue LHSMask; // AND value if any. 4057 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4058 return nullptr; // Not part of a rotate. 4059 4060 SDValue RHSShift; // The shift. 4061 SDValue RHSMask; // AND value if any. 4062 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4063 return nullptr; // Not part of a rotate. 4064 4065 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4066 return nullptr; // Not shifting the same value. 4067 4068 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4069 return nullptr; // Shifts must disagree. 4070 4071 // Canonicalize shl to left side in a shl/srl pair. 4072 if (RHSShift.getOpcode() == ISD::SHL) { 4073 std::swap(LHS, RHS); 4074 std::swap(LHSShift, RHSShift); 4075 std::swap(LHSMask, RHSMask); 4076 } 4077 4078 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4079 SDValue LHSShiftArg = LHSShift.getOperand(0); 4080 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4081 SDValue RHSShiftArg = RHSShift.getOperand(0); 4082 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4083 4084 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4085 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4086 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4087 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4088 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4089 if ((LShVal + RShVal) != EltSizeInBits) 4090 return nullptr; 4091 4092 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4093 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4094 4095 // If there is an AND of either shifted operand, apply it to the result. 4096 if (LHSMask.getNode() || RHSMask.getNode()) { 4097 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4098 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4099 4100 if (LHSMask.getNode()) { 4101 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4102 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4103 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4104 DAG.getConstant(RHSBits, DL, VT))); 4105 } 4106 if (RHSMask.getNode()) { 4107 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4108 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4109 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4110 DAG.getConstant(LHSBits, DL, VT))); 4111 } 4112 4113 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4114 } 4115 4116 return Rot.getNode(); 4117 } 4118 4119 // If there is a mask here, and we have a variable shift, we can't be sure 4120 // that we're masking out the right stuff. 4121 if (LHSMask.getNode() || RHSMask.getNode()) 4122 return nullptr; 4123 4124 // If the shift amount is sign/zext/any-extended just peel it off. 4125 SDValue LExtOp0 = LHSShiftAmt; 4126 SDValue RExtOp0 = RHSShiftAmt; 4127 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4128 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4129 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4130 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4131 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4132 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4133 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4134 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4135 LExtOp0 = LHSShiftAmt.getOperand(0); 4136 RExtOp0 = RHSShiftAmt.getOperand(0); 4137 } 4138 4139 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4140 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4141 if (TryL) 4142 return TryL; 4143 4144 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4145 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4146 if (TryR) 4147 return TryR; 4148 4149 return nullptr; 4150 } 4151 4152 SDValue DAGCombiner::visitXOR(SDNode *N) { 4153 SDValue N0 = N->getOperand(0); 4154 SDValue N1 = N->getOperand(1); 4155 EVT VT = N0.getValueType(); 4156 4157 // fold vector ops 4158 if (VT.isVector()) { 4159 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4160 return FoldedVOp; 4161 4162 // fold (xor x, 0) -> x, vector edition 4163 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4164 return N1; 4165 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4166 return N0; 4167 } 4168 4169 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4170 if (N0.isUndef() && N1.isUndef()) 4171 return DAG.getConstant(0, SDLoc(N), VT); 4172 // fold (xor x, undef) -> undef 4173 if (N0.isUndef()) 4174 return N0; 4175 if (N1.isUndef()) 4176 return N1; 4177 // fold (xor c1, c2) -> c1^c2 4178 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4179 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4180 if (N0C && N1C) 4181 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4182 // canonicalize constant to RHS 4183 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4184 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4185 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4186 // fold (xor x, 0) -> x 4187 if (isNullConstant(N1)) 4188 return N0; 4189 // reassociate xor 4190 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4191 return RXOR; 4192 4193 // fold !(x cc y) -> (x !cc y) 4194 SDValue LHS, RHS, CC; 4195 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4196 bool isInt = LHS.getValueType().isInteger(); 4197 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4198 isInt); 4199 4200 if (!LegalOperations || 4201 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4202 switch (N0.getOpcode()) { 4203 default: 4204 llvm_unreachable("Unhandled SetCC Equivalent!"); 4205 case ISD::SETCC: 4206 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4207 case ISD::SELECT_CC: 4208 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4209 N0.getOperand(3), NotCC); 4210 } 4211 } 4212 } 4213 4214 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4215 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4216 N0.getNode()->hasOneUse() && 4217 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4218 SDValue V = N0.getOperand(0); 4219 SDLoc DL(N0); 4220 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4221 DAG.getConstant(1, DL, V.getValueType())); 4222 AddToWorklist(V.getNode()); 4223 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4224 } 4225 4226 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4227 if (isOneConstant(N1) && VT == MVT::i1 && 4228 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4229 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4230 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4231 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4232 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4233 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4234 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4235 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4236 } 4237 } 4238 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4239 if (isAllOnesConstant(N1) && 4240 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4241 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4242 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4243 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4244 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4245 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4246 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4247 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4248 } 4249 } 4250 // fold (xor (and x, y), y) -> (and (not x), y) 4251 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4252 N0->getOperand(1) == N1) { 4253 SDValue X = N0->getOperand(0); 4254 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4255 AddToWorklist(NotX.getNode()); 4256 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4257 } 4258 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4259 if (N1C && N0.getOpcode() == ISD::XOR) { 4260 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4261 SDLoc DL(N); 4262 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4263 DAG.getConstant(N1C->getAPIntValue() ^ 4264 N00C->getAPIntValue(), DL, VT)); 4265 } 4266 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4267 SDLoc DL(N); 4268 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4269 DAG.getConstant(N1C->getAPIntValue() ^ 4270 N01C->getAPIntValue(), DL, VT)); 4271 } 4272 } 4273 // fold (xor x, x) -> 0 4274 if (N0 == N1) 4275 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4276 4277 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4278 // Here is a concrete example of this equivalence: 4279 // i16 x == 14 4280 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4281 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4282 // 4283 // => 4284 // 4285 // i16 ~1 == 0b1111111111111110 4286 // i16 rol(~1, 14) == 0b1011111111111111 4287 // 4288 // Some additional tips to help conceptualize this transform: 4289 // - Try to see the operation as placing a single zero in a value of all ones. 4290 // - There exists no value for x which would allow the result to contain zero. 4291 // - Values of x larger than the bitwidth are undefined and do not require a 4292 // consistent result. 4293 // - Pushing the zero left requires shifting one bits in from the right. 4294 // A rotate left of ~1 is a nice way of achieving the desired result. 4295 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4296 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4297 SDLoc DL(N); 4298 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4299 N0.getOperand(1)); 4300 } 4301 4302 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4303 if (N0.getOpcode() == N1.getOpcode()) 4304 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4305 return Tmp; 4306 4307 // Simplify the expression using non-local knowledge. 4308 if (!VT.isVector() && 4309 SimplifyDemandedBits(SDValue(N, 0))) 4310 return SDValue(N, 0); 4311 4312 return SDValue(); 4313 } 4314 4315 /// Handle transforms common to the three shifts, when the shift amount is a 4316 /// constant. 4317 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4318 SDNode *LHS = N->getOperand(0).getNode(); 4319 if (!LHS->hasOneUse()) return SDValue(); 4320 4321 // We want to pull some binops through shifts, so that we have (and (shift)) 4322 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4323 // thing happens with address calculations, so it's important to canonicalize 4324 // it. 4325 bool HighBitSet = false; // Can we transform this if the high bit is set? 4326 4327 switch (LHS->getOpcode()) { 4328 default: return SDValue(); 4329 case ISD::OR: 4330 case ISD::XOR: 4331 HighBitSet = false; // We can only transform sra if the high bit is clear. 4332 break; 4333 case ISD::AND: 4334 HighBitSet = true; // We can only transform sra if the high bit is set. 4335 break; 4336 case ISD::ADD: 4337 if (N->getOpcode() != ISD::SHL) 4338 return SDValue(); // only shl(add) not sr[al](add). 4339 HighBitSet = false; // We can only transform sra if the high bit is clear. 4340 break; 4341 } 4342 4343 // We require the RHS of the binop to be a constant and not opaque as well. 4344 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4345 if (!BinOpCst) return SDValue(); 4346 4347 // FIXME: disable this unless the input to the binop is a shift by a constant. 4348 // If it is not a shift, it pessimizes some common cases like: 4349 // 4350 // void foo(int *X, int i) { X[i & 1235] = 1; } 4351 // int bar(int *X, int i) { return X[i & 255]; } 4352 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4353 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4354 BinOpLHSVal->getOpcode() != ISD::SRA && 4355 BinOpLHSVal->getOpcode() != ISD::SRL) || 4356 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4357 return SDValue(); 4358 4359 EVT VT = N->getValueType(0); 4360 4361 // If this is a signed shift right, and the high bit is modified by the 4362 // logical operation, do not perform the transformation. The highBitSet 4363 // boolean indicates the value of the high bit of the constant which would 4364 // cause it to be modified for this operation. 4365 if (N->getOpcode() == ISD::SRA) { 4366 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4367 if (BinOpRHSSignSet != HighBitSet) 4368 return SDValue(); 4369 } 4370 4371 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4372 return SDValue(); 4373 4374 // Fold the constants, shifting the binop RHS by the shift amount. 4375 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4376 N->getValueType(0), 4377 LHS->getOperand(1), N->getOperand(1)); 4378 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4379 4380 // Create the new shift. 4381 SDValue NewShift = DAG.getNode(N->getOpcode(), 4382 SDLoc(LHS->getOperand(0)), 4383 VT, LHS->getOperand(0), N->getOperand(1)); 4384 4385 // Create the new binop. 4386 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4387 } 4388 4389 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4390 assert(N->getOpcode() == ISD::TRUNCATE); 4391 assert(N->getOperand(0).getOpcode() == ISD::AND); 4392 4393 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4394 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4395 SDValue N01 = N->getOperand(0).getOperand(1); 4396 4397 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4398 if (!N01C->isOpaque()) { 4399 EVT TruncVT = N->getValueType(0); 4400 SDValue N00 = N->getOperand(0).getOperand(0); 4401 APInt TruncC = N01C->getAPIntValue(); 4402 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4403 SDLoc DL(N); 4404 4405 return DAG.getNode(ISD::AND, DL, TruncVT, 4406 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4407 DAG.getConstant(TruncC, DL, TruncVT)); 4408 } 4409 } 4410 } 4411 4412 return SDValue(); 4413 } 4414 4415 SDValue DAGCombiner::visitRotate(SDNode *N) { 4416 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4417 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4418 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4419 if (SDValue NewOp1 = 4420 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 4421 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4422 N->getOperand(0), NewOp1); 4423 } 4424 return SDValue(); 4425 } 4426 4427 SDValue DAGCombiner::visitSHL(SDNode *N) { 4428 SDValue N0 = N->getOperand(0); 4429 SDValue N1 = N->getOperand(1); 4430 EVT VT = N0.getValueType(); 4431 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4432 4433 // fold vector ops 4434 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4435 if (VT.isVector()) { 4436 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4437 return FoldedVOp; 4438 4439 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4440 // If setcc produces all-one true value then: 4441 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4442 if (N1CV && N1CV->isConstant()) { 4443 if (N0.getOpcode() == ISD::AND) { 4444 SDValue N00 = N0->getOperand(0); 4445 SDValue N01 = N0->getOperand(1); 4446 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4447 4448 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4449 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4450 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4451 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4452 N01CV, N1CV)) 4453 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4454 } 4455 } else { 4456 N1C = isConstOrConstSplat(N1); 4457 } 4458 } 4459 } 4460 4461 // fold (shl c1, c2) -> c1<<c2 4462 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4463 if (N0C && N1C && !N1C->isOpaque()) 4464 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4465 // fold (shl 0, x) -> 0 4466 if (isNullConstant(N0)) 4467 return N0; 4468 // fold (shl x, c >= size(x)) -> undef 4469 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4470 return DAG.getUNDEF(VT); 4471 // fold (shl x, 0) -> x 4472 if (N1C && N1C->isNullValue()) 4473 return N0; 4474 // fold (shl undef, x) -> 0 4475 if (N0.isUndef()) 4476 return DAG.getConstant(0, SDLoc(N), VT); 4477 // if (shl x, c) is known to be zero, return 0 4478 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4479 APInt::getAllOnesValue(OpSizeInBits))) 4480 return DAG.getConstant(0, SDLoc(N), VT); 4481 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4482 if (N1.getOpcode() == ISD::TRUNCATE && 4483 N1.getOperand(0).getOpcode() == ISD::AND) { 4484 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4485 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4486 } 4487 4488 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4489 return SDValue(N, 0); 4490 4491 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4492 if (N1C && N0.getOpcode() == ISD::SHL) { 4493 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4494 SDLoc DL(N); 4495 APInt c1 = N0C1->getAPIntValue(); 4496 APInt c2 = N1C->getAPIntValue(); 4497 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4498 4499 APInt Sum = c1 + c2; 4500 if (Sum.uge(OpSizeInBits)) 4501 return DAG.getConstant(0, DL, VT); 4502 4503 return DAG.getNode( 4504 ISD::SHL, DL, VT, N0.getOperand(0), 4505 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4506 } 4507 } 4508 4509 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4510 // For this to be valid, the second form must not preserve any of the bits 4511 // that are shifted out by the inner shift in the first form. This means 4512 // the outer shift size must be >= the number of bits added by the ext. 4513 // As a corollary, we don't care what kind of ext it is. 4514 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4515 N0.getOpcode() == ISD::ANY_EXTEND || 4516 N0.getOpcode() == ISD::SIGN_EXTEND) && 4517 N0.getOperand(0).getOpcode() == ISD::SHL) { 4518 SDValue N0Op0 = N0.getOperand(0); 4519 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4520 uint64_t c1 = N0Op0C1->getZExtValue(); 4521 uint64_t c2 = N1C->getZExtValue(); 4522 EVT InnerShiftVT = N0Op0.getValueType(); 4523 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4524 if (c2 >= OpSizeInBits - InnerShiftSize) { 4525 SDLoc DL(N0); 4526 if (c1 + c2 >= OpSizeInBits) 4527 return DAG.getConstant(0, DL, VT); 4528 return DAG.getNode(ISD::SHL, DL, VT, 4529 DAG.getNode(N0.getOpcode(), DL, VT, 4530 N0Op0->getOperand(0)), 4531 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4532 } 4533 } 4534 } 4535 4536 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4537 // Only fold this if the inner zext has no other uses to avoid increasing 4538 // the total number of instructions. 4539 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4540 N0.getOperand(0).getOpcode() == ISD::SRL) { 4541 SDValue N0Op0 = N0.getOperand(0); 4542 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4543 uint64_t c1 = N0Op0C1->getZExtValue(); 4544 if (c1 < VT.getScalarSizeInBits()) { 4545 uint64_t c2 = N1C->getZExtValue(); 4546 if (c1 == c2) { 4547 SDValue NewOp0 = N0.getOperand(0); 4548 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4549 SDLoc DL(N); 4550 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4551 NewOp0, 4552 DAG.getConstant(c2, DL, CountVT)); 4553 AddToWorklist(NewSHL.getNode()); 4554 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4555 } 4556 } 4557 } 4558 } 4559 4560 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4561 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4562 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4563 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4564 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4565 uint64_t C1 = N0C1->getZExtValue(); 4566 uint64_t C2 = N1C->getZExtValue(); 4567 SDLoc DL(N); 4568 if (C1 <= C2) 4569 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4570 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4571 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4572 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4573 } 4574 } 4575 4576 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4577 // (and (srl x, (sub c1, c2), MASK) 4578 // Only fold this if the inner shift has no other uses -- if it does, folding 4579 // this will increase the total number of instructions. 4580 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4581 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4582 uint64_t c1 = N0C1->getZExtValue(); 4583 if (c1 < OpSizeInBits) { 4584 uint64_t c2 = N1C->getZExtValue(); 4585 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4586 SDValue Shift; 4587 if (c2 > c1) { 4588 Mask = Mask.shl(c2 - c1); 4589 SDLoc DL(N); 4590 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4591 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4592 } else { 4593 Mask = Mask.lshr(c1 - c2); 4594 SDLoc DL(N); 4595 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4596 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4597 } 4598 SDLoc DL(N0); 4599 return DAG.getNode(ISD::AND, DL, VT, Shift, 4600 DAG.getConstant(Mask, DL, VT)); 4601 } 4602 } 4603 } 4604 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4605 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4606 unsigned BitSize = VT.getScalarSizeInBits(); 4607 SDLoc DL(N); 4608 SDValue HiBitsMask = 4609 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4610 BitSize - N1C->getZExtValue()), 4611 DL, VT); 4612 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4613 HiBitsMask); 4614 } 4615 4616 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4617 // Variant of version done on multiply, except mul by a power of 2 is turned 4618 // into a shift. 4619 APInt Val; 4620 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4621 (isa<ConstantSDNode>(N0.getOperand(1)) || 4622 ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4623 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4624 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4625 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4626 } 4627 4628 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4629 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4630 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4631 if (SDValue Folded = 4632 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4633 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4634 } 4635 } 4636 4637 if (N1C && !N1C->isOpaque()) 4638 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4639 return NewSHL; 4640 4641 return SDValue(); 4642 } 4643 4644 SDValue DAGCombiner::visitSRA(SDNode *N) { 4645 SDValue N0 = N->getOperand(0); 4646 SDValue N1 = N->getOperand(1); 4647 EVT VT = N0.getValueType(); 4648 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4649 4650 // fold vector ops 4651 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4652 if (VT.isVector()) { 4653 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4654 return FoldedVOp; 4655 4656 N1C = isConstOrConstSplat(N1); 4657 } 4658 4659 // fold (sra c1, c2) -> (sra c1, c2) 4660 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4661 if (N0C && N1C && !N1C->isOpaque()) 4662 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4663 // fold (sra 0, x) -> 0 4664 if (isNullConstant(N0)) 4665 return N0; 4666 // fold (sra -1, x) -> -1 4667 if (isAllOnesConstant(N0)) 4668 return N0; 4669 // fold (sra x, c >= size(x)) -> undef 4670 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4671 return DAG.getUNDEF(VT); 4672 // fold (sra x, 0) -> x 4673 if (N1C && N1C->isNullValue()) 4674 return N0; 4675 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4676 // sext_inreg. 4677 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4678 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4679 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4680 if (VT.isVector()) 4681 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4682 ExtVT, VT.getVectorNumElements()); 4683 if ((!LegalOperations || 4684 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4685 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4686 N0.getOperand(0), DAG.getValueType(ExtVT)); 4687 } 4688 4689 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4690 if (N1C && N0.getOpcode() == ISD::SRA) { 4691 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4692 SDLoc DL(N); 4693 APInt c1 = N0C1->getAPIntValue(); 4694 APInt c2 = N1C->getAPIntValue(); 4695 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4696 4697 APInt Sum = c1 + c2; 4698 if (Sum.uge(OpSizeInBits)) 4699 Sum = APInt(OpSizeInBits, OpSizeInBits - 1); 4700 4701 return DAG.getNode( 4702 ISD::SRA, DL, VT, N0.getOperand(0), 4703 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4704 } 4705 } 4706 4707 // fold (sra (shl X, m), (sub result_size, n)) 4708 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4709 // result_size - n != m. 4710 // If truncate is free for the target sext(shl) is likely to result in better 4711 // code. 4712 if (N0.getOpcode() == ISD::SHL && N1C) { 4713 // Get the two constanst of the shifts, CN0 = m, CN = n. 4714 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4715 if (N01C) { 4716 LLVMContext &Ctx = *DAG.getContext(); 4717 // Determine what the truncate's result bitsize and type would be. 4718 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4719 4720 if (VT.isVector()) 4721 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4722 4723 // Determine the residual right-shift amount. 4724 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4725 4726 // If the shift is not a no-op (in which case this should be just a sign 4727 // extend already), the truncated to type is legal, sign_extend is legal 4728 // on that type, and the truncate to that type is both legal and free, 4729 // perform the transform. 4730 if ((ShiftAmt > 0) && 4731 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4732 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4733 TLI.isTruncateFree(VT, TruncVT)) { 4734 4735 SDLoc DL(N); 4736 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4737 getShiftAmountTy(N0.getOperand(0).getValueType())); 4738 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4739 N0.getOperand(0), Amt); 4740 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4741 Shift); 4742 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4743 N->getValueType(0), Trunc); 4744 } 4745 } 4746 } 4747 4748 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4749 if (N1.getOpcode() == ISD::TRUNCATE && 4750 N1.getOperand(0).getOpcode() == ISD::AND) { 4751 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4752 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4753 } 4754 4755 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4756 // if c1 is equal to the number of bits the trunc removes 4757 if (N0.getOpcode() == ISD::TRUNCATE && 4758 (N0.getOperand(0).getOpcode() == ISD::SRL || 4759 N0.getOperand(0).getOpcode() == ISD::SRA) && 4760 N0.getOperand(0).hasOneUse() && 4761 N0.getOperand(0).getOperand(1).hasOneUse() && 4762 N1C) { 4763 SDValue N0Op0 = N0.getOperand(0); 4764 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4765 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4766 EVT LargeVT = N0Op0.getValueType(); 4767 4768 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4769 SDLoc DL(N); 4770 SDValue Amt = 4771 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4772 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4773 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4774 N0Op0.getOperand(0), Amt); 4775 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4776 } 4777 } 4778 } 4779 4780 // Simplify, based on bits shifted out of the LHS. 4781 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4782 return SDValue(N, 0); 4783 4784 4785 // If the sign bit is known to be zero, switch this to a SRL. 4786 if (DAG.SignBitIsZero(N0)) 4787 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4788 4789 if (N1C && !N1C->isOpaque()) 4790 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4791 return NewSRA; 4792 4793 return SDValue(); 4794 } 4795 4796 SDValue DAGCombiner::visitSRL(SDNode *N) { 4797 SDValue N0 = N->getOperand(0); 4798 SDValue N1 = N->getOperand(1); 4799 EVT VT = N0.getValueType(); 4800 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4801 4802 // fold vector ops 4803 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4804 if (VT.isVector()) { 4805 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4806 return FoldedVOp; 4807 4808 N1C = isConstOrConstSplat(N1); 4809 } 4810 4811 // fold (srl c1, c2) -> c1 >>u c2 4812 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4813 if (N0C && N1C && !N1C->isOpaque()) 4814 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4815 // fold (srl 0, x) -> 0 4816 if (isNullConstant(N0)) 4817 return N0; 4818 // fold (srl x, c >= size(x)) -> undef 4819 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4820 return DAG.getUNDEF(VT); 4821 // fold (srl x, 0) -> x 4822 if (N1C && N1C->isNullValue()) 4823 return N0; 4824 // if (srl x, c) is known to be zero, return 0 4825 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4826 APInt::getAllOnesValue(OpSizeInBits))) 4827 return DAG.getConstant(0, SDLoc(N), VT); 4828 4829 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4830 if (N1C && N0.getOpcode() == ISD::SRL) { 4831 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4832 SDLoc DL(N); 4833 APInt c1 = N0C1->getAPIntValue(); 4834 APInt c2 = N1C->getAPIntValue(); 4835 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4836 4837 APInt Sum = c1 + c2; 4838 if (Sum.uge(OpSizeInBits)) 4839 return DAG.getConstant(0, DL, VT); 4840 4841 return DAG.getNode( 4842 ISD::SRL, DL, VT, N0.getOperand(0), 4843 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4844 } 4845 } 4846 4847 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4848 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4849 N0.getOperand(0).getOpcode() == ISD::SRL && 4850 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4851 uint64_t c1 = 4852 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4853 uint64_t c2 = N1C->getZExtValue(); 4854 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4855 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4856 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4857 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4858 if (c1 + OpSizeInBits == InnerShiftSize) { 4859 SDLoc DL(N0); 4860 if (c1 + c2 >= InnerShiftSize) 4861 return DAG.getConstant(0, DL, VT); 4862 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4863 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4864 N0.getOperand(0)->getOperand(0), 4865 DAG.getConstant(c1 + c2, DL, 4866 ShiftCountVT))); 4867 } 4868 } 4869 4870 // fold (srl (shl x, c), c) -> (and x, cst2) 4871 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4872 unsigned BitSize = N0.getScalarValueSizeInBits(); 4873 if (BitSize <= 64) { 4874 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4875 SDLoc DL(N); 4876 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4877 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4878 } 4879 } 4880 4881 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4882 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4883 // Shifting in all undef bits? 4884 EVT SmallVT = N0.getOperand(0).getValueType(); 4885 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4886 if (N1C->getZExtValue() >= BitSize) 4887 return DAG.getUNDEF(VT); 4888 4889 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4890 uint64_t ShiftAmt = N1C->getZExtValue(); 4891 SDLoc DL0(N0); 4892 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4893 N0.getOperand(0), 4894 DAG.getConstant(ShiftAmt, DL0, 4895 getShiftAmountTy(SmallVT))); 4896 AddToWorklist(SmallShift.getNode()); 4897 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4898 SDLoc DL(N); 4899 return DAG.getNode(ISD::AND, DL, VT, 4900 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4901 DAG.getConstant(Mask, DL, VT)); 4902 } 4903 } 4904 4905 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4906 // bit, which is unmodified by sra. 4907 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4908 if (N0.getOpcode() == ISD::SRA) 4909 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4910 } 4911 4912 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4913 if (N1C && N0.getOpcode() == ISD::CTLZ && 4914 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4915 APInt KnownZero, KnownOne; 4916 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4917 4918 // If any of the input bits are KnownOne, then the input couldn't be all 4919 // zeros, thus the result of the srl will always be zero. 4920 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4921 4922 // If all of the bits input the to ctlz node are known to be zero, then 4923 // the result of the ctlz is "32" and the result of the shift is one. 4924 APInt UnknownBits = ~KnownZero; 4925 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4926 4927 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4928 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4929 // Okay, we know that only that the single bit specified by UnknownBits 4930 // could be set on input to the CTLZ node. If this bit is set, the SRL 4931 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4932 // to an SRL/XOR pair, which is likely to simplify more. 4933 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4934 SDValue Op = N0.getOperand(0); 4935 4936 if (ShAmt) { 4937 SDLoc DL(N0); 4938 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4939 DAG.getConstant(ShAmt, DL, 4940 getShiftAmountTy(Op.getValueType()))); 4941 AddToWorklist(Op.getNode()); 4942 } 4943 4944 SDLoc DL(N); 4945 return DAG.getNode(ISD::XOR, DL, VT, 4946 Op, DAG.getConstant(1, DL, VT)); 4947 } 4948 } 4949 4950 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4951 if (N1.getOpcode() == ISD::TRUNCATE && 4952 N1.getOperand(0).getOpcode() == ISD::AND) { 4953 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4954 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4955 } 4956 4957 // fold operands of srl based on knowledge that the low bits are not 4958 // demanded. 4959 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4960 return SDValue(N, 0); 4961 4962 if (N1C && !N1C->isOpaque()) 4963 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4964 return NewSRL; 4965 4966 // Attempt to convert a srl of a load into a narrower zero-extending load. 4967 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4968 return NarrowLoad; 4969 4970 // Here is a common situation. We want to optimize: 4971 // 4972 // %a = ... 4973 // %b = and i32 %a, 2 4974 // %c = srl i32 %b, 1 4975 // brcond i32 %c ... 4976 // 4977 // into 4978 // 4979 // %a = ... 4980 // %b = and %a, 2 4981 // %c = setcc eq %b, 0 4982 // brcond %c ... 4983 // 4984 // However when after the source operand of SRL is optimized into AND, the SRL 4985 // itself may not be optimized further. Look for it and add the BRCOND into 4986 // the worklist. 4987 if (N->hasOneUse()) { 4988 SDNode *Use = *N->use_begin(); 4989 if (Use->getOpcode() == ISD::BRCOND) 4990 AddToWorklist(Use); 4991 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4992 // Also look pass the truncate. 4993 Use = *Use->use_begin(); 4994 if (Use->getOpcode() == ISD::BRCOND) 4995 AddToWorklist(Use); 4996 } 4997 } 4998 4999 return SDValue(); 5000 } 5001 5002 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 5003 SDValue N0 = N->getOperand(0); 5004 EVT VT = N->getValueType(0); 5005 5006 // fold (bswap c1) -> c2 5007 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5008 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 5009 // fold (bswap (bswap x)) -> x 5010 if (N0.getOpcode() == ISD::BSWAP) 5011 return N0->getOperand(0); 5012 return SDValue(); 5013 } 5014 5015 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 5016 SDValue N0 = N->getOperand(0); 5017 5018 // fold (bitreverse (bitreverse x)) -> x 5019 if (N0.getOpcode() == ISD::BITREVERSE) 5020 return N0.getOperand(0); 5021 return SDValue(); 5022 } 5023 5024 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 5025 SDValue N0 = N->getOperand(0); 5026 EVT VT = N->getValueType(0); 5027 5028 // fold (ctlz c1) -> c2 5029 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5030 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 5031 return SDValue(); 5032 } 5033 5034 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 5035 SDValue N0 = N->getOperand(0); 5036 EVT VT = N->getValueType(0); 5037 5038 // fold (ctlz_zero_undef c1) -> c2 5039 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5040 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5041 return SDValue(); 5042 } 5043 5044 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5045 SDValue N0 = N->getOperand(0); 5046 EVT VT = N->getValueType(0); 5047 5048 // fold (cttz c1) -> c2 5049 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5050 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5051 return SDValue(); 5052 } 5053 5054 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5055 SDValue N0 = N->getOperand(0); 5056 EVT VT = N->getValueType(0); 5057 5058 // fold (cttz_zero_undef c1) -> c2 5059 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5060 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5061 return SDValue(); 5062 } 5063 5064 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5065 SDValue N0 = N->getOperand(0); 5066 EVT VT = N->getValueType(0); 5067 5068 // fold (ctpop c1) -> c2 5069 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5070 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5071 return SDValue(); 5072 } 5073 5074 5075 /// \brief Generate Min/Max node 5076 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 5077 SDValue RHS, SDValue True, SDValue False, 5078 ISD::CondCode CC, const TargetLowering &TLI, 5079 SelectionDAG &DAG) { 5080 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5081 return SDValue(); 5082 5083 switch (CC) { 5084 case ISD::SETOLT: 5085 case ISD::SETOLE: 5086 case ISD::SETLT: 5087 case ISD::SETLE: 5088 case ISD::SETULT: 5089 case ISD::SETULE: { 5090 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5091 if (TLI.isOperationLegal(Opcode, VT)) 5092 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5093 return SDValue(); 5094 } 5095 case ISD::SETOGT: 5096 case ISD::SETOGE: 5097 case ISD::SETGT: 5098 case ISD::SETGE: 5099 case ISD::SETUGT: 5100 case ISD::SETUGE: { 5101 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5102 if (TLI.isOperationLegal(Opcode, VT)) 5103 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5104 return SDValue(); 5105 } 5106 default: 5107 return SDValue(); 5108 } 5109 } 5110 5111 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5112 SDValue N0 = N->getOperand(0); 5113 SDValue N1 = N->getOperand(1); 5114 SDValue N2 = N->getOperand(2); 5115 EVT VT = N->getValueType(0); 5116 EVT VT0 = N0.getValueType(); 5117 5118 // fold (select C, X, X) -> X 5119 if (N1 == N2) 5120 return N1; 5121 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5122 // fold (select true, X, Y) -> X 5123 // fold (select false, X, Y) -> Y 5124 return !N0C->isNullValue() ? N1 : N2; 5125 } 5126 // fold (select C, 1, X) -> (or C, X) 5127 if (VT == MVT::i1 && isOneConstant(N1)) 5128 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5129 // fold (select C, 0, 1) -> (xor C, 1) 5130 // We can't do this reliably if integer based booleans have different contents 5131 // to floating point based booleans. This is because we can't tell whether we 5132 // have an integer-based boolean or a floating-point-based boolean unless we 5133 // can find the SETCC that produced it and inspect its operands. This is 5134 // fairly easy if C is the SETCC node, but it can potentially be 5135 // undiscoverable (or not reasonably discoverable). For example, it could be 5136 // in another basic block or it could require searching a complicated 5137 // expression. 5138 if (VT.isInteger() && 5139 (VT0 == MVT::i1 || (VT0.isInteger() && 5140 TLI.getBooleanContents(false, false) == 5141 TLI.getBooleanContents(false, true) && 5142 TLI.getBooleanContents(false, false) == 5143 TargetLowering::ZeroOrOneBooleanContent)) && 5144 isNullConstant(N1) && isOneConstant(N2)) { 5145 SDValue XORNode; 5146 if (VT == VT0) { 5147 SDLoc DL(N); 5148 return DAG.getNode(ISD::XOR, DL, VT0, 5149 N0, DAG.getConstant(1, DL, VT0)); 5150 } 5151 SDLoc DL0(N0); 5152 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5153 N0, DAG.getConstant(1, DL0, VT0)); 5154 AddToWorklist(XORNode.getNode()); 5155 if (VT.bitsGT(VT0)) 5156 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5157 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5158 } 5159 // fold (select C, 0, X) -> (and (not C), X) 5160 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5161 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5162 AddToWorklist(NOTNode.getNode()); 5163 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5164 } 5165 // fold (select C, X, 1) -> (or (not C), X) 5166 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5167 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5168 AddToWorklist(NOTNode.getNode()); 5169 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5170 } 5171 // fold (select C, X, 0) -> (and C, X) 5172 if (VT == MVT::i1 && isNullConstant(N2)) 5173 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5174 // fold (select X, X, Y) -> (or X, Y) 5175 // fold (select X, 1, Y) -> (or X, Y) 5176 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5177 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5178 // fold (select X, Y, X) -> (and X, Y) 5179 // fold (select X, Y, 0) -> (and X, Y) 5180 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5181 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5182 5183 // If we can fold this based on the true/false value, do so. 5184 if (SimplifySelectOps(N, N1, N2)) 5185 return SDValue(N, 0); // Don't revisit N. 5186 5187 if (VT0 == MVT::i1) { 5188 // The code in this block deals with the following 2 equivalences: 5189 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5190 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5191 // The target can specify its prefered form with the 5192 // shouldNormalizeToSelectSequence() callback. However we always transform 5193 // to the right anyway if we find the inner select exists in the DAG anyway 5194 // and we always transform to the left side if we know that we can further 5195 // optimize the combination of the conditions. 5196 bool normalizeToSequence 5197 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5198 // select (and Cond0, Cond1), X, Y 5199 // -> select Cond0, (select Cond1, X, Y), Y 5200 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5201 SDValue Cond0 = N0->getOperand(0); 5202 SDValue Cond1 = N0->getOperand(1); 5203 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5204 N1.getValueType(), Cond1, N1, N2); 5205 if (normalizeToSequence || !InnerSelect.use_empty()) 5206 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5207 InnerSelect, N2); 5208 } 5209 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5210 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5211 SDValue Cond0 = N0->getOperand(0); 5212 SDValue Cond1 = N0->getOperand(1); 5213 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5214 N1.getValueType(), Cond1, N1, N2); 5215 if (normalizeToSequence || !InnerSelect.use_empty()) 5216 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5217 InnerSelect); 5218 } 5219 5220 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5221 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5222 SDValue N1_0 = N1->getOperand(0); 5223 SDValue N1_1 = N1->getOperand(1); 5224 SDValue N1_2 = N1->getOperand(2); 5225 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5226 // Create the actual and node if we can generate good code for it. 5227 if (!normalizeToSequence) { 5228 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5229 N0, N1_0); 5230 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5231 N1_1, N2); 5232 } 5233 // Otherwise see if we can optimize the "and" to a better pattern. 5234 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5235 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5236 N1_1, N2); 5237 } 5238 } 5239 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5240 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5241 SDValue N2_0 = N2->getOperand(0); 5242 SDValue N2_1 = N2->getOperand(1); 5243 SDValue N2_2 = N2->getOperand(2); 5244 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5245 // Create the actual or node if we can generate good code for it. 5246 if (!normalizeToSequence) { 5247 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5248 N0, N2_0); 5249 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5250 N1, N2_2); 5251 } 5252 // Otherwise see if we can optimize to a better pattern. 5253 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5254 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5255 N1, N2_2); 5256 } 5257 } 5258 } 5259 5260 // fold selects based on a setcc into other things, such as min/max/abs 5261 if (N0.getOpcode() == ISD::SETCC) { 5262 // select x, y (fcmp lt x, y) -> fminnum x, y 5263 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5264 // 5265 // This is OK if we don't care about what happens if either operand is a 5266 // NaN. 5267 // 5268 5269 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5270 // no signed zeros as well as no nans. 5271 const TargetOptions &Options = DAG.getTarget().Options; 5272 if (Options.UnsafeFPMath && 5273 VT.isFloatingPoint() && N0.hasOneUse() && 5274 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5275 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5276 5277 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5278 N0.getOperand(1), N1, N2, CC, 5279 TLI, DAG)) 5280 return FMinMax; 5281 } 5282 5283 if ((!LegalOperations && 5284 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5285 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5286 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5287 N0.getOperand(0), N0.getOperand(1), 5288 N1, N2, N0.getOperand(2)); 5289 return SimplifySelect(SDLoc(N), N0, N1, N2); 5290 } 5291 5292 return SDValue(); 5293 } 5294 5295 static 5296 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5297 SDLoc DL(N); 5298 EVT LoVT, HiVT; 5299 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5300 5301 // Split the inputs. 5302 SDValue Lo, Hi, LL, LH, RL, RH; 5303 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5304 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5305 5306 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5307 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5308 5309 return std::make_pair(Lo, Hi); 5310 } 5311 5312 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5313 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5314 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5315 SDLoc dl(N); 5316 SDValue Cond = N->getOperand(0); 5317 SDValue LHS = N->getOperand(1); 5318 SDValue RHS = N->getOperand(2); 5319 EVT VT = N->getValueType(0); 5320 int NumElems = VT.getVectorNumElements(); 5321 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5322 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5323 Cond.getOpcode() == ISD::BUILD_VECTOR); 5324 5325 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5326 // binary ones here. 5327 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5328 return SDValue(); 5329 5330 // We're sure we have an even number of elements due to the 5331 // concat_vectors we have as arguments to vselect. 5332 // Skip BV elements until we find one that's not an UNDEF 5333 // After we find an UNDEF element, keep looping until we get to half the 5334 // length of the BV and see if all the non-undef nodes are the same. 5335 ConstantSDNode *BottomHalf = nullptr; 5336 for (int i = 0; i < NumElems / 2; ++i) { 5337 if (Cond->getOperand(i)->isUndef()) 5338 continue; 5339 5340 if (BottomHalf == nullptr) 5341 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5342 else if (Cond->getOperand(i).getNode() != BottomHalf) 5343 return SDValue(); 5344 } 5345 5346 // Do the same for the second half of the BuildVector 5347 ConstantSDNode *TopHalf = nullptr; 5348 for (int i = NumElems / 2; i < NumElems; ++i) { 5349 if (Cond->getOperand(i)->isUndef()) 5350 continue; 5351 5352 if (TopHalf == nullptr) 5353 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5354 else if (Cond->getOperand(i).getNode() != TopHalf) 5355 return SDValue(); 5356 } 5357 5358 assert(TopHalf && BottomHalf && 5359 "One half of the selector was all UNDEFs and the other was all the " 5360 "same value. This should have been addressed before this function."); 5361 return DAG.getNode( 5362 ISD::CONCAT_VECTORS, dl, VT, 5363 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5364 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5365 } 5366 5367 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5368 5369 if (Level >= AfterLegalizeTypes) 5370 return SDValue(); 5371 5372 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5373 SDValue Mask = MSC->getMask(); 5374 SDValue Data = MSC->getValue(); 5375 SDLoc DL(N); 5376 5377 // If the MSCATTER data type requires splitting and the mask is provided by a 5378 // SETCC, then split both nodes and its operands before legalization. This 5379 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5380 // and enables future optimizations (e.g. min/max pattern matching on X86). 5381 if (Mask.getOpcode() != ISD::SETCC) 5382 return SDValue(); 5383 5384 // Check if any splitting is required. 5385 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5386 TargetLowering::TypeSplitVector) 5387 return SDValue(); 5388 SDValue MaskLo, MaskHi, Lo, Hi; 5389 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5390 5391 EVT LoVT, HiVT; 5392 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5393 5394 SDValue Chain = MSC->getChain(); 5395 5396 EVT MemoryVT = MSC->getMemoryVT(); 5397 unsigned Alignment = MSC->getOriginalAlignment(); 5398 5399 EVT LoMemVT, HiMemVT; 5400 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5401 5402 SDValue DataLo, DataHi; 5403 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5404 5405 SDValue BasePtr = MSC->getBasePtr(); 5406 SDValue IndexLo, IndexHi; 5407 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5408 5409 MachineMemOperand *MMO = DAG.getMachineFunction(). 5410 getMachineMemOperand(MSC->getPointerInfo(), 5411 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5412 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5413 5414 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5415 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5416 DL, OpsLo, MMO); 5417 5418 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5419 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5420 DL, OpsHi, MMO); 5421 5422 AddToWorklist(Lo.getNode()); 5423 AddToWorklist(Hi.getNode()); 5424 5425 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5426 } 5427 5428 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5429 5430 if (Level >= AfterLegalizeTypes) 5431 return SDValue(); 5432 5433 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5434 SDValue Mask = MST->getMask(); 5435 SDValue Data = MST->getValue(); 5436 SDLoc DL(N); 5437 5438 // If the MSTORE data type requires splitting and the mask is provided by a 5439 // SETCC, then split both nodes and its operands before legalization. This 5440 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5441 // and enables future optimizations (e.g. min/max pattern matching on X86). 5442 if (Mask.getOpcode() == ISD::SETCC) { 5443 5444 // Check if any splitting is required. 5445 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5446 TargetLowering::TypeSplitVector) 5447 return SDValue(); 5448 5449 SDValue MaskLo, MaskHi, Lo, Hi; 5450 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5451 5452 EVT LoVT, HiVT; 5453 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5454 5455 SDValue Chain = MST->getChain(); 5456 SDValue Ptr = MST->getBasePtr(); 5457 5458 EVT MemoryVT = MST->getMemoryVT(); 5459 unsigned Alignment = MST->getOriginalAlignment(); 5460 5461 // if Alignment is equal to the vector size, 5462 // take the half of it for the second part 5463 unsigned SecondHalfAlignment = 5464 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5465 Alignment/2 : Alignment; 5466 5467 EVT LoMemVT, HiMemVT; 5468 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5469 5470 SDValue DataLo, DataHi; 5471 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5472 5473 MachineMemOperand *MMO = DAG.getMachineFunction(). 5474 getMachineMemOperand(MST->getPointerInfo(), 5475 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5476 Alignment, MST->getAAInfo(), MST->getRanges()); 5477 5478 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5479 MST->isTruncatingStore()); 5480 5481 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5482 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5483 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5484 5485 MMO = DAG.getMachineFunction(). 5486 getMachineMemOperand(MST->getPointerInfo(), 5487 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5488 SecondHalfAlignment, MST->getAAInfo(), 5489 MST->getRanges()); 5490 5491 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5492 MST->isTruncatingStore()); 5493 5494 AddToWorklist(Lo.getNode()); 5495 AddToWorklist(Hi.getNode()); 5496 5497 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5498 } 5499 return SDValue(); 5500 } 5501 5502 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5503 5504 if (Level >= AfterLegalizeTypes) 5505 return SDValue(); 5506 5507 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5508 SDValue Mask = MGT->getMask(); 5509 SDLoc DL(N); 5510 5511 // If the MGATHER 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 return SDValue(); 5518 5519 EVT VT = N->getValueType(0); 5520 5521 // Check if any splitting is required. 5522 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5523 TargetLowering::TypeSplitVector) 5524 return SDValue(); 5525 5526 SDValue MaskLo, MaskHi, Lo, Hi; 5527 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5528 5529 SDValue Src0 = MGT->getValue(); 5530 SDValue Src0Lo, Src0Hi; 5531 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5532 5533 EVT LoVT, HiVT; 5534 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5535 5536 SDValue Chain = MGT->getChain(); 5537 EVT MemoryVT = MGT->getMemoryVT(); 5538 unsigned Alignment = MGT->getOriginalAlignment(); 5539 5540 EVT LoMemVT, HiMemVT; 5541 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5542 5543 SDValue BasePtr = MGT->getBasePtr(); 5544 SDValue Index = MGT->getIndex(); 5545 SDValue IndexLo, IndexHi; 5546 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5547 5548 MachineMemOperand *MMO = DAG.getMachineFunction(). 5549 getMachineMemOperand(MGT->getPointerInfo(), 5550 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5551 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5552 5553 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5554 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5555 MMO); 5556 5557 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5558 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5559 MMO); 5560 5561 AddToWorklist(Lo.getNode()); 5562 AddToWorklist(Hi.getNode()); 5563 5564 // Build a factor node to remember that this load is independent of the 5565 // other one. 5566 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5567 Hi.getValue(1)); 5568 5569 // Legalized the chain result - switch anything that used the old chain to 5570 // use the new one. 5571 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5572 5573 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5574 5575 SDValue RetOps[] = { GatherRes, Chain }; 5576 return DAG.getMergeValues(RetOps, DL); 5577 } 5578 5579 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5580 5581 if (Level >= AfterLegalizeTypes) 5582 return SDValue(); 5583 5584 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5585 SDValue Mask = MLD->getMask(); 5586 SDLoc DL(N); 5587 5588 // If the MLOAD result requires splitting and the mask is provided by a 5589 // SETCC, then split both nodes and its operands before legalization. This 5590 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5591 // and enables future optimizations (e.g. min/max pattern matching on X86). 5592 5593 if (Mask.getOpcode() == ISD::SETCC) { 5594 EVT VT = N->getValueType(0); 5595 5596 // Check if any splitting is required. 5597 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5598 TargetLowering::TypeSplitVector) 5599 return SDValue(); 5600 5601 SDValue MaskLo, MaskHi, Lo, Hi; 5602 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5603 5604 SDValue Src0 = MLD->getSrc0(); 5605 SDValue Src0Lo, Src0Hi; 5606 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5607 5608 EVT LoVT, HiVT; 5609 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5610 5611 SDValue Chain = MLD->getChain(); 5612 SDValue Ptr = MLD->getBasePtr(); 5613 EVT MemoryVT = MLD->getMemoryVT(); 5614 unsigned Alignment = MLD->getOriginalAlignment(); 5615 5616 // if Alignment is equal to the vector size, 5617 // take the half of it for the second part 5618 unsigned SecondHalfAlignment = 5619 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5620 Alignment/2 : Alignment; 5621 5622 EVT LoMemVT, HiMemVT; 5623 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5624 5625 MachineMemOperand *MMO = DAG.getMachineFunction(). 5626 getMachineMemOperand(MLD->getPointerInfo(), 5627 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5628 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5629 5630 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5631 ISD::NON_EXTLOAD); 5632 5633 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5634 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5635 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5636 5637 MMO = DAG.getMachineFunction(). 5638 getMachineMemOperand(MLD->getPointerInfo(), 5639 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5640 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5641 5642 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5643 ISD::NON_EXTLOAD); 5644 5645 AddToWorklist(Lo.getNode()); 5646 AddToWorklist(Hi.getNode()); 5647 5648 // Build a factor node to remember that this load is independent of the 5649 // other one. 5650 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5651 Hi.getValue(1)); 5652 5653 // Legalized the chain result - switch anything that used the old chain to 5654 // use the new one. 5655 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5656 5657 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5658 5659 SDValue RetOps[] = { LoadRes, Chain }; 5660 return DAG.getMergeValues(RetOps, DL); 5661 } 5662 return SDValue(); 5663 } 5664 5665 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5666 SDValue N0 = N->getOperand(0); 5667 SDValue N1 = N->getOperand(1); 5668 SDValue N2 = N->getOperand(2); 5669 SDLoc DL(N); 5670 5671 // Canonicalize integer abs. 5672 // vselect (setg[te] X, 0), X, -X -> 5673 // vselect (setgt X, -1), X, -X -> 5674 // vselect (setl[te] X, 0), -X, X -> 5675 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5676 if (N0.getOpcode() == ISD::SETCC) { 5677 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5678 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5679 bool isAbs = false; 5680 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5681 5682 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5683 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5684 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5685 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5686 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5687 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5688 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5689 5690 if (isAbs) { 5691 EVT VT = LHS.getValueType(); 5692 SDValue Shift = DAG.getNode( 5693 ISD::SRA, DL, VT, LHS, 5694 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5695 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5696 AddToWorklist(Shift.getNode()); 5697 AddToWorklist(Add.getNode()); 5698 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5699 } 5700 } 5701 5702 if (SimplifySelectOps(N, N1, N2)) 5703 return SDValue(N, 0); // Don't revisit N. 5704 5705 // If the VSELECT result requires splitting and the mask is provided by a 5706 // SETCC, then split both nodes and its operands before legalization. This 5707 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5708 // and enables future optimizations (e.g. min/max pattern matching on X86). 5709 if (N0.getOpcode() == ISD::SETCC) { 5710 EVT VT = N->getValueType(0); 5711 5712 // Check if any splitting is required. 5713 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5714 TargetLowering::TypeSplitVector) 5715 return SDValue(); 5716 5717 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5718 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5719 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5720 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5721 5722 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5723 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5724 5725 // Add the new VSELECT nodes to the work list in case they need to be split 5726 // again. 5727 AddToWorklist(Lo.getNode()); 5728 AddToWorklist(Hi.getNode()); 5729 5730 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5731 } 5732 5733 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5734 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5735 return N1; 5736 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5737 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5738 return N2; 5739 5740 // The ConvertSelectToConcatVector function is assuming both the above 5741 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5742 // and addressed. 5743 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5744 N2.getOpcode() == ISD::CONCAT_VECTORS && 5745 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5746 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5747 return CV; 5748 } 5749 5750 return SDValue(); 5751 } 5752 5753 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5754 SDValue N0 = N->getOperand(0); 5755 SDValue N1 = N->getOperand(1); 5756 SDValue N2 = N->getOperand(2); 5757 SDValue N3 = N->getOperand(3); 5758 SDValue N4 = N->getOperand(4); 5759 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5760 5761 // fold select_cc lhs, rhs, x, x, cc -> x 5762 if (N2 == N3) 5763 return N2; 5764 5765 // Determine if the condition we're dealing with is constant 5766 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 5767 CC, SDLoc(N), false)) { 5768 AddToWorklist(SCC.getNode()); 5769 5770 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5771 if (!SCCC->isNullValue()) 5772 return N2; // cond always true -> true val 5773 else 5774 return N3; // cond always false -> false val 5775 } else if (SCC->isUndef()) { 5776 // When the condition is UNDEF, just return the first operand. This is 5777 // coherent the DAG creation, no setcc node is created in this case 5778 return N2; 5779 } else if (SCC.getOpcode() == ISD::SETCC) { 5780 // Fold to a simpler select_cc 5781 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5782 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5783 SCC.getOperand(2)); 5784 } 5785 } 5786 5787 // If we can fold this based on the true/false value, do so. 5788 if (SimplifySelectOps(N, N2, N3)) 5789 return SDValue(N, 0); // Don't revisit N. 5790 5791 // fold select_cc into other things, such as min/max/abs 5792 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5793 } 5794 5795 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5796 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5797 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5798 SDLoc(N)); 5799 } 5800 5801 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5802 SDValue LHS = N->getOperand(0); 5803 SDValue RHS = N->getOperand(1); 5804 SDValue Carry = N->getOperand(2); 5805 SDValue Cond = N->getOperand(3); 5806 5807 // If Carry is false, fold to a regular SETCC. 5808 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5809 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5810 5811 return SDValue(); 5812 } 5813 5814 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5815 /// a build_vector of constants. 5816 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5817 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5818 /// Vector extends are not folded if operations are legal; this is to 5819 /// avoid introducing illegal build_vector dag nodes. 5820 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5821 SelectionDAG &DAG, bool LegalTypes, 5822 bool LegalOperations) { 5823 unsigned Opcode = N->getOpcode(); 5824 SDValue N0 = N->getOperand(0); 5825 EVT VT = N->getValueType(0); 5826 5827 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5828 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 5829 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 5830 && "Expected EXTEND dag node in input!"); 5831 5832 // fold (sext c1) -> c1 5833 // fold (zext c1) -> c1 5834 // fold (aext c1) -> c1 5835 if (isa<ConstantSDNode>(N0)) 5836 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5837 5838 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5839 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5840 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5841 EVT SVT = VT.getScalarType(); 5842 if (!(VT.isVector() && 5843 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5844 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5845 return nullptr; 5846 5847 // We can fold this node into a build_vector. 5848 unsigned VTBits = SVT.getSizeInBits(); 5849 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5850 SmallVector<SDValue, 8> Elts; 5851 unsigned NumElts = VT.getVectorNumElements(); 5852 SDLoc DL(N); 5853 5854 for (unsigned i=0; i != NumElts; ++i) { 5855 SDValue Op = N0->getOperand(i); 5856 if (Op->isUndef()) { 5857 Elts.push_back(DAG.getUNDEF(SVT)); 5858 continue; 5859 } 5860 5861 SDLoc DL(Op); 5862 // Get the constant value and if needed trunc it to the size of the type. 5863 // Nodes like build_vector might have constants wider than the scalar type. 5864 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5865 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5866 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5867 else 5868 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5869 } 5870 5871 return DAG.getBuildVector(VT, DL, Elts).getNode(); 5872 } 5873 5874 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5875 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5876 // transformation. Returns true if extension are possible and the above 5877 // mentioned transformation is profitable. 5878 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5879 unsigned ExtOpc, 5880 SmallVectorImpl<SDNode *> &ExtendNodes, 5881 const TargetLowering &TLI) { 5882 bool HasCopyToRegUses = false; 5883 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5884 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5885 UE = N0.getNode()->use_end(); 5886 UI != UE; ++UI) { 5887 SDNode *User = *UI; 5888 if (User == N) 5889 continue; 5890 if (UI.getUse().getResNo() != N0.getResNo()) 5891 continue; 5892 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5893 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5894 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5895 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5896 // Sign bits will be lost after a zext. 5897 return false; 5898 bool Add = false; 5899 for (unsigned i = 0; i != 2; ++i) { 5900 SDValue UseOp = User->getOperand(i); 5901 if (UseOp == N0) 5902 continue; 5903 if (!isa<ConstantSDNode>(UseOp)) 5904 return false; 5905 Add = true; 5906 } 5907 if (Add) 5908 ExtendNodes.push_back(User); 5909 continue; 5910 } 5911 // If truncates aren't free and there are users we can't 5912 // extend, it isn't worthwhile. 5913 if (!isTruncFree) 5914 return false; 5915 // Remember if this value is live-out. 5916 if (User->getOpcode() == ISD::CopyToReg) 5917 HasCopyToRegUses = true; 5918 } 5919 5920 if (HasCopyToRegUses) { 5921 bool BothLiveOut = false; 5922 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5923 UI != UE; ++UI) { 5924 SDUse &Use = UI.getUse(); 5925 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5926 BothLiveOut = true; 5927 break; 5928 } 5929 } 5930 if (BothLiveOut) 5931 // Both unextended and extended values are live out. There had better be 5932 // a good reason for the transformation. 5933 return ExtendNodes.size(); 5934 } 5935 return true; 5936 } 5937 5938 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5939 SDValue Trunc, SDValue ExtLoad, 5940 const SDLoc &DL, ISD::NodeType ExtType) { 5941 // Extend SetCC uses if necessary. 5942 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5943 SDNode *SetCC = SetCCs[i]; 5944 SmallVector<SDValue, 4> Ops; 5945 5946 for (unsigned j = 0; j != 2; ++j) { 5947 SDValue SOp = SetCC->getOperand(j); 5948 if (SOp == Trunc) 5949 Ops.push_back(ExtLoad); 5950 else 5951 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5952 } 5953 5954 Ops.push_back(SetCC->getOperand(2)); 5955 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5956 } 5957 } 5958 5959 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5960 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5961 SDValue N0 = N->getOperand(0); 5962 EVT DstVT = N->getValueType(0); 5963 EVT SrcVT = N0.getValueType(); 5964 5965 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5966 N->getOpcode() == ISD::ZERO_EXTEND) && 5967 "Unexpected node type (not an extend)!"); 5968 5969 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5970 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5971 // (v8i32 (sext (v8i16 (load x)))) 5972 // into: 5973 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5974 // (v4i32 (sextload (x + 16))))) 5975 // Where uses of the original load, i.e.: 5976 // (v8i16 (load x)) 5977 // are replaced with: 5978 // (v8i16 (truncate 5979 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5980 // (v4i32 (sextload (x + 16))))))) 5981 // 5982 // This combine is only applicable to illegal, but splittable, vectors. 5983 // All legal types, and illegal non-vector types, are handled elsewhere. 5984 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5985 // 5986 if (N0->getOpcode() != ISD::LOAD) 5987 return SDValue(); 5988 5989 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5990 5991 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5992 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5993 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5994 return SDValue(); 5995 5996 SmallVector<SDNode *, 4> SetCCs; 5997 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5998 return SDValue(); 5999 6000 ISD::LoadExtType ExtType = 6001 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 6002 6003 // Try to split the vector types to get down to legal types. 6004 EVT SplitSrcVT = SrcVT; 6005 EVT SplitDstVT = DstVT; 6006 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 6007 SplitSrcVT.getVectorNumElements() > 1) { 6008 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 6009 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 6010 } 6011 6012 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 6013 return SDValue(); 6014 6015 SDLoc DL(N); 6016 const unsigned NumSplits = 6017 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 6018 const unsigned Stride = SplitSrcVT.getStoreSize(); 6019 SmallVector<SDValue, 4> Loads; 6020 SmallVector<SDValue, 4> Chains; 6021 6022 SDValue BasePtr = LN0->getBasePtr(); 6023 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 6024 const unsigned Offset = Idx * Stride; 6025 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 6026 6027 SDValue SplitLoad = DAG.getExtLoad( 6028 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 6029 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 6030 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6031 6032 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 6033 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 6034 6035 Loads.push_back(SplitLoad.getValue(0)); 6036 Chains.push_back(SplitLoad.getValue(1)); 6037 } 6038 6039 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 6040 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 6041 6042 CombineTo(N, NewValue); 6043 6044 // Replace uses of the original load (before extension) 6045 // with a truncate of the concatenated sextloaded vectors. 6046 SDValue Trunc = 6047 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6048 CombineTo(N0.getNode(), Trunc, NewChain); 6049 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6050 (ISD::NodeType)N->getOpcode()); 6051 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6052 } 6053 6054 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 6055 SDValue N0 = N->getOperand(0); 6056 EVT VT = N->getValueType(0); 6057 6058 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6059 LegalOperations)) 6060 return SDValue(Res, 0); 6061 6062 // fold (sext (sext x)) -> (sext x) 6063 // fold (sext (aext x)) -> (sext x) 6064 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6065 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 6066 N0.getOperand(0)); 6067 6068 if (N0.getOpcode() == ISD::TRUNCATE) { 6069 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 6070 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 6071 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6072 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6073 if (NarrowLoad.getNode() != N0.getNode()) { 6074 CombineTo(N0.getNode(), NarrowLoad); 6075 // CombineTo deleted the truncate, if needed, but not what's under it. 6076 AddToWorklist(oye); 6077 } 6078 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6079 } 6080 6081 // See if the value being truncated is already sign extended. If so, just 6082 // eliminate the trunc/sext pair. 6083 SDValue Op = N0.getOperand(0); 6084 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 6085 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 6086 unsigned DestBits = VT.getScalarType().getSizeInBits(); 6087 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6088 6089 if (OpBits == DestBits) { 6090 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6091 // bits, it is already ready. 6092 if (NumSignBits > DestBits-MidBits) 6093 return Op; 6094 } else if (OpBits < DestBits) { 6095 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6096 // bits, just sext from i32. 6097 if (NumSignBits > OpBits-MidBits) 6098 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 6099 } else { 6100 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6101 // bits, just truncate to i32. 6102 if (NumSignBits > OpBits-MidBits) 6103 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6104 } 6105 6106 // fold (sext (truncate x)) -> (sextinreg x). 6107 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6108 N0.getValueType())) { 6109 if (OpBits < DestBits) 6110 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6111 else if (OpBits > DestBits) 6112 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6113 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6114 DAG.getValueType(N0.getValueType())); 6115 } 6116 } 6117 6118 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6119 // Only generate vector extloads when 1) they're legal, and 2) they are 6120 // deemed desirable by the target. 6121 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6122 ((!LegalOperations && !VT.isVector() && 6123 !cast<LoadSDNode>(N0)->isVolatile()) || 6124 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6125 bool DoXform = true; 6126 SmallVector<SDNode*, 4> SetCCs; 6127 if (!N0.hasOneUse()) 6128 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6129 if (VT.isVector()) 6130 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6131 if (DoXform) { 6132 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6133 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6134 LN0->getChain(), 6135 LN0->getBasePtr(), N0.getValueType(), 6136 LN0->getMemOperand()); 6137 CombineTo(N, ExtLoad); 6138 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6139 N0.getValueType(), ExtLoad); 6140 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6141 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6142 ISD::SIGN_EXTEND); 6143 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6144 } 6145 } 6146 6147 // fold (sext (load x)) to multiple smaller sextloads. 6148 // Only on illegal but splittable vectors. 6149 if (SDValue ExtLoad = CombineExtLoad(N)) 6150 return ExtLoad; 6151 6152 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6153 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6154 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6155 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6156 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6157 EVT MemVT = LN0->getMemoryVT(); 6158 if ((!LegalOperations && !LN0->isVolatile()) || 6159 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6160 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6161 LN0->getChain(), 6162 LN0->getBasePtr(), MemVT, 6163 LN0->getMemOperand()); 6164 CombineTo(N, ExtLoad); 6165 CombineTo(N0.getNode(), 6166 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6167 N0.getValueType(), ExtLoad), 6168 ExtLoad.getValue(1)); 6169 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6170 } 6171 } 6172 6173 // fold (sext (and/or/xor (load x), cst)) -> 6174 // (and/or/xor (sextload x), (sext cst)) 6175 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6176 N0.getOpcode() == ISD::XOR) && 6177 isa<LoadSDNode>(N0.getOperand(0)) && 6178 N0.getOperand(1).getOpcode() == ISD::Constant && 6179 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6180 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6181 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6182 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6183 bool DoXform = true; 6184 SmallVector<SDNode*, 4> SetCCs; 6185 if (!N0.hasOneUse()) 6186 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6187 SetCCs, TLI); 6188 if (DoXform) { 6189 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6190 LN0->getChain(), LN0->getBasePtr(), 6191 LN0->getMemoryVT(), 6192 LN0->getMemOperand()); 6193 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6194 Mask = Mask.sext(VT.getSizeInBits()); 6195 SDLoc DL(N); 6196 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6197 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6198 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6199 SDLoc(N0.getOperand(0)), 6200 N0.getOperand(0).getValueType(), ExtLoad); 6201 CombineTo(N, And); 6202 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6203 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6204 ISD::SIGN_EXTEND); 6205 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6206 } 6207 } 6208 } 6209 6210 if (N0.getOpcode() == ISD::SETCC) { 6211 EVT N0VT = N0.getOperand(0).getValueType(); 6212 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6213 // Only do this before legalize for now. 6214 if (VT.isVector() && !LegalOperations && 6215 TLI.getBooleanContents(N0VT) == 6216 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6217 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6218 // of the same size as the compared operands. Only optimize sext(setcc()) 6219 // if this is the case. 6220 EVT SVT = getSetCCResultType(N0VT); 6221 6222 // We know that the # elements of the results is the same as the 6223 // # elements of the compare (and the # elements of the compare result 6224 // for that matter). Check to see that they are the same size. If so, 6225 // we know that the element size of the sext'd result matches the 6226 // element size of the compare operands. 6227 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6228 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6229 N0.getOperand(1), 6230 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6231 6232 // If the desired elements are smaller or larger than the source 6233 // elements we can use a matching integer vector type and then 6234 // truncate/sign extend 6235 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6236 if (SVT == MatchingVectorType) { 6237 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6238 N0.getOperand(0), N0.getOperand(1), 6239 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6240 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6241 } 6242 } 6243 6244 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 6245 // Here, T can be 1 or -1, depending on the type of the setcc and 6246 // getBooleanContents(). 6247 unsigned SetCCWidth = N0.getValueType().getScalarSizeInBits(); 6248 6249 SDLoc DL(N); 6250 // To determine the "true" side of the select, we need to know the high bit 6251 // of the value returned by the setcc if it evaluates to true. 6252 // If the type of the setcc is i1, then the true case of the select is just 6253 // sext(i1 1), that is, -1. 6254 // If the type of the setcc is larger (say, i8) then the value of the high 6255 // bit depends on getBooleanContents(). So, ask TLI for a real "true" value 6256 // of the appropriate width. 6257 SDValue ExtTrueVal = 6258 (SetCCWidth == 1) 6259 ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()), 6260 DL, VT) 6261 : TLI.getConstTrueVal(DAG, VT, DL); 6262 6263 if (SDValue SCC = SimplifySelectCC( 6264 DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal, 6265 DAG.getConstant(0, DL, VT), 6266 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6267 return SCC; 6268 6269 if (!VT.isVector()) { 6270 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6271 if (!LegalOperations || 6272 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6273 SDLoc DL(N); 6274 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6275 SDValue SetCC = 6276 DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC); 6277 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, 6278 DAG.getConstant(0, DL, VT)); 6279 } 6280 } 6281 } 6282 6283 // fold (sext x) -> (zext x) if the sign bit is known zero. 6284 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6285 DAG.SignBitIsZero(N0)) 6286 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6287 6288 return SDValue(); 6289 } 6290 6291 // isTruncateOf - If N is a truncate of some other value, return true, record 6292 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6293 // This function computes KnownZero to avoid a duplicated call to 6294 // computeKnownBits in the caller. 6295 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6296 APInt &KnownZero) { 6297 APInt KnownOne; 6298 if (N->getOpcode() == ISD::TRUNCATE) { 6299 Op = N->getOperand(0); 6300 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6301 return true; 6302 } 6303 6304 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6305 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6306 return false; 6307 6308 SDValue Op0 = N->getOperand(0); 6309 SDValue Op1 = N->getOperand(1); 6310 assert(Op0.getValueType() == Op1.getValueType()); 6311 6312 if (isNullConstant(Op0)) 6313 Op = Op1; 6314 else if (isNullConstant(Op1)) 6315 Op = Op0; 6316 else 6317 return false; 6318 6319 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6320 6321 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6322 return false; 6323 6324 return true; 6325 } 6326 6327 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6328 SDValue N0 = N->getOperand(0); 6329 EVT VT = N->getValueType(0); 6330 6331 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6332 LegalOperations)) 6333 return SDValue(Res, 0); 6334 6335 // fold (zext (zext x)) -> (zext x) 6336 // fold (zext (aext x)) -> (zext x) 6337 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6338 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6339 N0.getOperand(0)); 6340 6341 // fold (zext (truncate x)) -> (zext x) or 6342 // (zext (truncate x)) -> (truncate x) 6343 // This is valid when the truncated bits of x are already zero. 6344 // FIXME: We should extend this to work for vectors too. 6345 SDValue Op; 6346 APInt KnownZero; 6347 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6348 APInt TruncatedBits = 6349 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6350 APInt(Op.getValueSizeInBits(), 0) : 6351 APInt::getBitsSet(Op.getValueSizeInBits(), 6352 N0.getValueSizeInBits(), 6353 std::min(Op.getValueSizeInBits(), 6354 VT.getSizeInBits())); 6355 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6356 if (VT.bitsGT(Op.getValueType())) 6357 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6358 if (VT.bitsLT(Op.getValueType())) 6359 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6360 6361 return Op; 6362 } 6363 } 6364 6365 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6366 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6367 if (N0.getOpcode() == ISD::TRUNCATE) { 6368 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6369 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6370 if (NarrowLoad.getNode() != N0.getNode()) { 6371 CombineTo(N0.getNode(), NarrowLoad); 6372 // CombineTo deleted the truncate, if needed, but not what's under it. 6373 AddToWorklist(oye); 6374 } 6375 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6376 } 6377 } 6378 6379 // fold (zext (truncate x)) -> (and x, mask) 6380 if (N0.getOpcode() == ISD::TRUNCATE) { 6381 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6382 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6383 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6384 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6385 if (NarrowLoad.getNode() != N0.getNode()) { 6386 CombineTo(N0.getNode(), NarrowLoad); 6387 // CombineTo deleted the truncate, if needed, but not what's under it. 6388 AddToWorklist(oye); 6389 } 6390 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6391 } 6392 6393 EVT SrcVT = N0.getOperand(0).getValueType(); 6394 EVT MinVT = N0.getValueType(); 6395 6396 // Try to mask before the extension to avoid having to generate a larger mask, 6397 // possibly over several sub-vectors. 6398 if (SrcVT.bitsLT(VT)) { 6399 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6400 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6401 SDValue Op = N0.getOperand(0); 6402 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6403 AddToWorklist(Op.getNode()); 6404 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6405 } 6406 } 6407 6408 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6409 SDValue Op = N0.getOperand(0); 6410 if (SrcVT.bitsLT(VT)) { 6411 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6412 AddToWorklist(Op.getNode()); 6413 } else if (SrcVT.bitsGT(VT)) { 6414 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6415 AddToWorklist(Op.getNode()); 6416 } 6417 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6418 } 6419 } 6420 6421 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6422 // if either of the casts is not free. 6423 if (N0.getOpcode() == ISD::AND && 6424 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6425 N0.getOperand(1).getOpcode() == ISD::Constant && 6426 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6427 N0.getValueType()) || 6428 !TLI.isZExtFree(N0.getValueType(), VT))) { 6429 SDValue X = N0.getOperand(0).getOperand(0); 6430 if (X.getValueType().bitsLT(VT)) { 6431 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6432 } else if (X.getValueType().bitsGT(VT)) { 6433 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6434 } 6435 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6436 Mask = Mask.zext(VT.getSizeInBits()); 6437 SDLoc DL(N); 6438 return DAG.getNode(ISD::AND, DL, VT, 6439 X, DAG.getConstant(Mask, DL, VT)); 6440 } 6441 6442 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6443 // Only generate vector extloads when 1) they're legal, and 2) they are 6444 // deemed desirable by the target. 6445 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6446 ((!LegalOperations && !VT.isVector() && 6447 !cast<LoadSDNode>(N0)->isVolatile()) || 6448 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6449 bool DoXform = true; 6450 SmallVector<SDNode*, 4> SetCCs; 6451 if (!N0.hasOneUse()) 6452 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6453 if (VT.isVector()) 6454 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6455 if (DoXform) { 6456 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6457 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6458 LN0->getChain(), 6459 LN0->getBasePtr(), N0.getValueType(), 6460 LN0->getMemOperand()); 6461 CombineTo(N, ExtLoad); 6462 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6463 N0.getValueType(), ExtLoad); 6464 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6465 6466 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6467 ISD::ZERO_EXTEND); 6468 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6469 } 6470 } 6471 6472 // fold (zext (load x)) to multiple smaller zextloads. 6473 // Only on illegal but splittable vectors. 6474 if (SDValue ExtLoad = CombineExtLoad(N)) 6475 return ExtLoad; 6476 6477 // fold (zext (and/or/xor (load x), cst)) -> 6478 // (and/or/xor (zextload x), (zext cst)) 6479 // Unless (and (load x) cst) will match as a zextload already and has 6480 // additional users. 6481 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6482 N0.getOpcode() == ISD::XOR) && 6483 isa<LoadSDNode>(N0.getOperand(0)) && 6484 N0.getOperand(1).getOpcode() == ISD::Constant && 6485 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6486 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6487 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6488 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6489 bool DoXform = true; 6490 SmallVector<SDNode*, 4> SetCCs; 6491 if (!N0.hasOneUse()) { 6492 if (N0.getOpcode() == ISD::AND) { 6493 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6494 auto NarrowLoad = false; 6495 EVT LoadResultTy = AndC->getValueType(0); 6496 EVT ExtVT, LoadedVT; 6497 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6498 NarrowLoad)) 6499 DoXform = false; 6500 } 6501 if (DoXform) 6502 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6503 ISD::ZERO_EXTEND, SetCCs, TLI); 6504 } 6505 if (DoXform) { 6506 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6507 LN0->getChain(), LN0->getBasePtr(), 6508 LN0->getMemoryVT(), 6509 LN0->getMemOperand()); 6510 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6511 Mask = Mask.zext(VT.getSizeInBits()); 6512 SDLoc DL(N); 6513 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6514 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6515 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6516 SDLoc(N0.getOperand(0)), 6517 N0.getOperand(0).getValueType(), ExtLoad); 6518 CombineTo(N, And); 6519 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6520 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6521 ISD::ZERO_EXTEND); 6522 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6523 } 6524 } 6525 } 6526 6527 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6528 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6529 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6530 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6531 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6532 EVT MemVT = LN0->getMemoryVT(); 6533 if ((!LegalOperations && !LN0->isVolatile()) || 6534 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6535 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6536 LN0->getChain(), 6537 LN0->getBasePtr(), MemVT, 6538 LN0->getMemOperand()); 6539 CombineTo(N, ExtLoad); 6540 CombineTo(N0.getNode(), 6541 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6542 ExtLoad), 6543 ExtLoad.getValue(1)); 6544 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6545 } 6546 } 6547 6548 if (N0.getOpcode() == ISD::SETCC) { 6549 // Only do this before legalize for now. 6550 if (!LegalOperations && VT.isVector() && 6551 N0.getValueType().getVectorElementType() == MVT::i1) { 6552 EVT N00VT = N0.getOperand(0).getValueType(); 6553 if (getSetCCResultType(N00VT) == N0.getValueType()) 6554 return SDValue(); 6555 6556 // We know that the # elements of the results is the same as the # 6557 // elements of the compare (and the # elements of the compare result for 6558 // that matter). Check to see that they are the same size. If so, we know 6559 // that the element size of the sext'd result matches the element size of 6560 // the compare operands. 6561 SDLoc DL(N); 6562 SDValue VecOnes = DAG.getConstant(1, DL, VT); 6563 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 6564 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6565 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 6566 N0.getOperand(1), N0.getOperand(2)); 6567 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 6568 } 6569 6570 // If the desired elements are smaller or larger than the source 6571 // elements we can use a matching integer vector type and then 6572 // truncate/sign extend. 6573 EVT MatchingElementType = EVT::getIntegerVT( 6574 *DAG.getContext(), N00VT.getScalarType().getSizeInBits()); 6575 EVT MatchingVectorType = EVT::getVectorVT( 6576 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 6577 SDValue VsetCC = 6578 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 6579 N0.getOperand(1), N0.getOperand(2)); 6580 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 6581 VecOnes); 6582 } 6583 6584 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6585 SDLoc DL(N); 6586 if (SDValue SCC = SimplifySelectCC( 6587 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6588 DAG.getConstant(0, DL, VT), 6589 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6590 return SCC; 6591 } 6592 6593 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6594 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6595 isa<ConstantSDNode>(N0.getOperand(1)) && 6596 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6597 N0.hasOneUse()) { 6598 SDValue ShAmt = N0.getOperand(1); 6599 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6600 if (N0.getOpcode() == ISD::SHL) { 6601 SDValue InnerZExt = N0.getOperand(0); 6602 // If the original shl may be shifting out bits, do not perform this 6603 // transformation. 6604 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6605 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6606 if (ShAmtVal > KnownZeroBits) 6607 return SDValue(); 6608 } 6609 6610 SDLoc DL(N); 6611 6612 // Ensure that the shift amount is wide enough for the shifted value. 6613 if (VT.getSizeInBits() >= 256) 6614 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6615 6616 return DAG.getNode(N0.getOpcode(), DL, VT, 6617 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6618 ShAmt); 6619 } 6620 6621 return SDValue(); 6622 } 6623 6624 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6625 SDValue N0 = N->getOperand(0); 6626 EVT VT = N->getValueType(0); 6627 6628 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6629 LegalOperations)) 6630 return SDValue(Res, 0); 6631 6632 // fold (aext (aext x)) -> (aext x) 6633 // fold (aext (zext x)) -> (zext x) 6634 // fold (aext (sext x)) -> (sext x) 6635 if (N0.getOpcode() == ISD::ANY_EXTEND || 6636 N0.getOpcode() == ISD::ZERO_EXTEND || 6637 N0.getOpcode() == ISD::SIGN_EXTEND) 6638 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6639 6640 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6641 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6642 if (N0.getOpcode() == ISD::TRUNCATE) { 6643 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6644 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6645 if (NarrowLoad.getNode() != N0.getNode()) { 6646 CombineTo(N0.getNode(), NarrowLoad); 6647 // CombineTo deleted the truncate, if needed, but not what's under it. 6648 AddToWorklist(oye); 6649 } 6650 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6651 } 6652 } 6653 6654 // fold (aext (truncate x)) 6655 if (N0.getOpcode() == ISD::TRUNCATE) { 6656 SDValue TruncOp = N0.getOperand(0); 6657 if (TruncOp.getValueType() == VT) 6658 return TruncOp; // x iff x size == zext size. 6659 if (TruncOp.getValueType().bitsGT(VT)) 6660 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6661 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6662 } 6663 6664 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6665 // if the trunc is not free. 6666 if (N0.getOpcode() == ISD::AND && 6667 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6668 N0.getOperand(1).getOpcode() == ISD::Constant && 6669 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6670 N0.getValueType())) { 6671 SDValue X = N0.getOperand(0).getOperand(0); 6672 if (X.getValueType().bitsLT(VT)) { 6673 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6674 } else if (X.getValueType().bitsGT(VT)) { 6675 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6676 } 6677 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6678 Mask = Mask.zext(VT.getSizeInBits()); 6679 SDLoc DL(N); 6680 return DAG.getNode(ISD::AND, DL, VT, 6681 X, DAG.getConstant(Mask, DL, VT)); 6682 } 6683 6684 // fold (aext (load x)) -> (aext (truncate (extload x))) 6685 // None of the supported targets knows how to perform load and any_ext 6686 // on vectors in one instruction. We only perform this transformation on 6687 // scalars. 6688 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6689 ISD::isUNINDEXEDLoad(N0.getNode()) && 6690 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6691 bool DoXform = true; 6692 SmallVector<SDNode*, 4> SetCCs; 6693 if (!N0.hasOneUse()) 6694 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6695 if (DoXform) { 6696 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6697 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6698 LN0->getChain(), 6699 LN0->getBasePtr(), N0.getValueType(), 6700 LN0->getMemOperand()); 6701 CombineTo(N, ExtLoad); 6702 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6703 N0.getValueType(), ExtLoad); 6704 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6705 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6706 ISD::ANY_EXTEND); 6707 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6708 } 6709 } 6710 6711 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6712 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6713 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6714 if (N0.getOpcode() == ISD::LOAD && 6715 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6716 N0.hasOneUse()) { 6717 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6718 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6719 EVT MemVT = LN0->getMemoryVT(); 6720 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6721 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6722 VT, LN0->getChain(), LN0->getBasePtr(), 6723 MemVT, LN0->getMemOperand()); 6724 CombineTo(N, ExtLoad); 6725 CombineTo(N0.getNode(), 6726 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6727 N0.getValueType(), ExtLoad), 6728 ExtLoad.getValue(1)); 6729 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6730 } 6731 } 6732 6733 if (N0.getOpcode() == ISD::SETCC) { 6734 // For vectors: 6735 // aext(setcc) -> vsetcc 6736 // aext(setcc) -> truncate(vsetcc) 6737 // aext(setcc) -> aext(vsetcc) 6738 // Only do this before legalize for now. 6739 if (VT.isVector() && !LegalOperations) { 6740 EVT N0VT = N0.getOperand(0).getValueType(); 6741 // We know that the # elements of the results is the same as the 6742 // # elements of the compare (and the # elements of the compare result 6743 // for that matter). Check to see that they are the same size. If so, 6744 // we know that the element size of the sext'd result matches the 6745 // element size of the compare operands. 6746 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6747 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6748 N0.getOperand(1), 6749 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6750 // If the desired elements are smaller or larger than the source 6751 // elements we can use a matching integer vector type and then 6752 // truncate/any extend 6753 else { 6754 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6755 SDValue VsetCC = 6756 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6757 N0.getOperand(1), 6758 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6759 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6760 } 6761 } 6762 6763 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6764 SDLoc DL(N); 6765 if (SDValue SCC = SimplifySelectCC( 6766 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6767 DAG.getConstant(0, DL, VT), 6768 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6769 return SCC; 6770 } 6771 6772 return SDValue(); 6773 } 6774 6775 /// See if the specified operand can be simplified with the knowledge that only 6776 /// the bits specified by Mask are used. If so, return the simpler operand, 6777 /// otherwise return a null SDValue. 6778 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6779 switch (V.getOpcode()) { 6780 default: break; 6781 case ISD::Constant: { 6782 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6783 assert(CV && "Const value should be ConstSDNode."); 6784 const APInt &CVal = CV->getAPIntValue(); 6785 APInt NewVal = CVal & Mask; 6786 if (NewVal != CVal) 6787 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6788 break; 6789 } 6790 case ISD::OR: 6791 case ISD::XOR: 6792 // If the LHS or RHS don't contribute bits to the or, drop them. 6793 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6794 return V.getOperand(1); 6795 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6796 return V.getOperand(0); 6797 break; 6798 case ISD::SRL: 6799 // Only look at single-use SRLs. 6800 if (!V.getNode()->hasOneUse()) 6801 break; 6802 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6803 // See if we can recursively simplify the LHS. 6804 unsigned Amt = RHSC->getZExtValue(); 6805 6806 // Watch out for shift count overflow though. 6807 if (Amt >= Mask.getBitWidth()) break; 6808 APInt NewMask = Mask << Amt; 6809 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6810 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6811 SimplifyLHS, V.getOperand(1)); 6812 } 6813 } 6814 return SDValue(); 6815 } 6816 6817 /// If the result of a wider load is shifted to right of N bits and then 6818 /// truncated to a narrower type and where N is a multiple of number of bits of 6819 /// the narrower type, transform it to a narrower load from address + N / num of 6820 /// bits of new type. If the result is to be extended, also fold the extension 6821 /// to form a extending load. 6822 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6823 unsigned Opc = N->getOpcode(); 6824 6825 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6826 SDValue N0 = N->getOperand(0); 6827 EVT VT = N->getValueType(0); 6828 EVT ExtVT = VT; 6829 6830 // This transformation isn't valid for vector loads. 6831 if (VT.isVector()) 6832 return SDValue(); 6833 6834 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6835 // extended to VT. 6836 if (Opc == ISD::SIGN_EXTEND_INREG) { 6837 ExtType = ISD::SEXTLOAD; 6838 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6839 } else if (Opc == ISD::SRL) { 6840 // Another special-case: SRL is basically zero-extending a narrower value. 6841 ExtType = ISD::ZEXTLOAD; 6842 N0 = SDValue(N, 0); 6843 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6844 if (!N01) return SDValue(); 6845 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6846 VT.getSizeInBits() - N01->getZExtValue()); 6847 } 6848 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6849 return SDValue(); 6850 6851 unsigned EVTBits = ExtVT.getSizeInBits(); 6852 6853 // Do not generate loads of non-round integer types since these can 6854 // be expensive (and would be wrong if the type is not byte sized). 6855 if (!ExtVT.isRound()) 6856 return SDValue(); 6857 6858 unsigned ShAmt = 0; 6859 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6860 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6861 ShAmt = N01->getZExtValue(); 6862 // Is the shift amount a multiple of size of VT? 6863 if ((ShAmt & (EVTBits-1)) == 0) { 6864 N0 = N0.getOperand(0); 6865 // Is the load width a multiple of size of VT? 6866 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6867 return SDValue(); 6868 } 6869 6870 // At this point, we must have a load or else we can't do the transform. 6871 if (!isa<LoadSDNode>(N0)) return SDValue(); 6872 6873 // Because a SRL must be assumed to *need* to zero-extend the high bits 6874 // (as opposed to anyext the high bits), we can't combine the zextload 6875 // lowering of SRL and an sextload. 6876 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6877 return SDValue(); 6878 6879 // If the shift amount is larger than the input type then we're not 6880 // accessing any of the loaded bytes. If the load was a zextload/extload 6881 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6882 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6883 return SDValue(); 6884 } 6885 } 6886 6887 // If the load is shifted left (and the result isn't shifted back right), 6888 // we can fold the truncate through the shift. 6889 unsigned ShLeftAmt = 0; 6890 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6891 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6892 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6893 ShLeftAmt = N01->getZExtValue(); 6894 N0 = N0.getOperand(0); 6895 } 6896 } 6897 6898 // If we haven't found a load, we can't narrow it. Don't transform one with 6899 // multiple uses, this would require adding a new load. 6900 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6901 return SDValue(); 6902 6903 // Don't change the width of a volatile load. 6904 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6905 if (LN0->isVolatile()) 6906 return SDValue(); 6907 6908 // Verify that we are actually reducing a load width here. 6909 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6910 return SDValue(); 6911 6912 // For the transform to be legal, the load must produce only two values 6913 // (the value loaded and the chain). Don't transform a pre-increment 6914 // load, for example, which produces an extra value. Otherwise the 6915 // transformation is not equivalent, and the downstream logic to replace 6916 // uses gets things wrong. 6917 if (LN0->getNumValues() > 2) 6918 return SDValue(); 6919 6920 // If the load that we're shrinking is an extload and we're not just 6921 // discarding the extension we can't simply shrink the load. Bail. 6922 // TODO: It would be possible to merge the extensions in some cases. 6923 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6924 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6925 return SDValue(); 6926 6927 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6928 return SDValue(); 6929 6930 EVT PtrType = N0.getOperand(1).getValueType(); 6931 6932 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6933 // It's not possible to generate a constant of extended or untyped type. 6934 return SDValue(); 6935 6936 // For big endian targets, we need to adjust the offset to the pointer to 6937 // load the correct bytes. 6938 if (DAG.getDataLayout().isBigEndian()) { 6939 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6940 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6941 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6942 } 6943 6944 uint64_t PtrOff = ShAmt / 8; 6945 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6946 SDLoc DL(LN0); 6947 // The original load itself didn't wrap, so an offset within it doesn't. 6948 SDNodeFlags Flags; 6949 Flags.setNoUnsignedWrap(true); 6950 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6951 PtrType, LN0->getBasePtr(), 6952 DAG.getConstant(PtrOff, DL, PtrType), 6953 &Flags); 6954 AddToWorklist(NewPtr.getNode()); 6955 6956 SDValue Load; 6957 if (ExtType == ISD::NON_EXTLOAD) 6958 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6959 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 6960 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6961 else 6962 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 6963 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 6964 NewAlign, LN0->getMemOperand()->getFlags(), 6965 LN0->getAAInfo()); 6966 6967 // Replace the old load's chain with the new load's chain. 6968 WorklistRemover DeadNodes(*this); 6969 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6970 6971 // Shift the result left, if we've swallowed a left shift. 6972 SDValue Result = Load; 6973 if (ShLeftAmt != 0) { 6974 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6975 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6976 ShImmTy = VT; 6977 // If the shift amount is as large as the result size (but, presumably, 6978 // no larger than the source) then the useful bits of the result are 6979 // zero; we can't simply return the shortened shift, because the result 6980 // of that operation is undefined. 6981 SDLoc DL(N0); 6982 if (ShLeftAmt >= VT.getSizeInBits()) 6983 Result = DAG.getConstant(0, DL, VT); 6984 else 6985 Result = DAG.getNode(ISD::SHL, DL, VT, 6986 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6987 } 6988 6989 // Return the new loaded value. 6990 return Result; 6991 } 6992 6993 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6994 SDValue N0 = N->getOperand(0); 6995 SDValue N1 = N->getOperand(1); 6996 EVT VT = N->getValueType(0); 6997 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6998 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6999 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 7000 7001 if (N0.isUndef()) 7002 return DAG.getUNDEF(VT); 7003 7004 // fold (sext_in_reg c1) -> c1 7005 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7006 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 7007 7008 // If the input is already sign extended, just drop the extension. 7009 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 7010 return N0; 7011 7012 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 7013 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 7014 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 7015 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7016 N0.getOperand(0), N1); 7017 7018 // fold (sext_in_reg (sext x)) -> (sext x) 7019 // fold (sext_in_reg (aext x)) -> (sext x) 7020 // if x is small enough. 7021 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 7022 SDValue N00 = N0.getOperand(0); 7023 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 7024 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 7025 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 7026 } 7027 7028 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 7029 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 7030 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 7031 7032 // fold operands of sext_in_reg based on knowledge that the top bits are not 7033 // demanded. 7034 if (SimplifyDemandedBits(SDValue(N, 0))) 7035 return SDValue(N, 0); 7036 7037 // fold (sext_in_reg (load x)) -> (smaller sextload x) 7038 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 7039 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 7040 return NarrowLoad; 7041 7042 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 7043 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 7044 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 7045 if (N0.getOpcode() == ISD::SRL) { 7046 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 7047 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 7048 // We can turn this into an SRA iff the input to the SRL is already sign 7049 // extended enough. 7050 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 7051 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 7052 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 7053 N0.getOperand(0), N0.getOperand(1)); 7054 } 7055 } 7056 7057 // fold (sext_inreg (extload x)) -> (sextload x) 7058 if (ISD::isEXTLoad(N0.getNode()) && 7059 ISD::isUNINDEXEDLoad(N0.getNode()) && 7060 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7061 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7062 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7063 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7064 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7065 LN0->getChain(), 7066 LN0->getBasePtr(), EVT, 7067 LN0->getMemOperand()); 7068 CombineTo(N, ExtLoad); 7069 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7070 AddToWorklist(ExtLoad.getNode()); 7071 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7072 } 7073 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 7074 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7075 N0.hasOneUse() && 7076 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7077 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7078 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7079 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7080 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7081 LN0->getChain(), 7082 LN0->getBasePtr(), EVT, 7083 LN0->getMemOperand()); 7084 CombineTo(N, ExtLoad); 7085 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7086 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7087 } 7088 7089 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7090 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7091 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7092 N0.getOperand(1), false)) 7093 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7094 BSwap, N1); 7095 } 7096 7097 return SDValue(); 7098 } 7099 7100 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7101 SDValue N0 = N->getOperand(0); 7102 EVT VT = N->getValueType(0); 7103 7104 if (N0.isUndef()) 7105 return DAG.getUNDEF(VT); 7106 7107 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7108 LegalOperations)) 7109 return SDValue(Res, 0); 7110 7111 return SDValue(); 7112 } 7113 7114 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7115 SDValue N0 = N->getOperand(0); 7116 EVT VT = N->getValueType(0); 7117 7118 if (N0.isUndef()) 7119 return DAG.getUNDEF(VT); 7120 7121 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7122 LegalOperations)) 7123 return SDValue(Res, 0); 7124 7125 return SDValue(); 7126 } 7127 7128 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7129 SDValue N0 = N->getOperand(0); 7130 EVT VT = N->getValueType(0); 7131 bool isLE = DAG.getDataLayout().isLittleEndian(); 7132 7133 // noop truncate 7134 if (N0.getValueType() == N->getValueType(0)) 7135 return N0; 7136 // fold (truncate c1) -> c1 7137 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7138 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7139 // fold (truncate (truncate x)) -> (truncate x) 7140 if (N0.getOpcode() == ISD::TRUNCATE) 7141 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7142 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7143 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7144 N0.getOpcode() == ISD::SIGN_EXTEND || 7145 N0.getOpcode() == ISD::ANY_EXTEND) { 7146 // if the source is smaller than the dest, we still need an extend. 7147 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7148 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7149 // if the source is larger than the dest, than we just need the truncate. 7150 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7151 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7152 // if the source and dest are the same type, we can drop both the extend 7153 // and the truncate. 7154 return N0.getOperand(0); 7155 } 7156 7157 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 7158 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 7159 return SDValue(); 7160 7161 // Fold extract-and-trunc into a narrow extract. For example: 7162 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7163 // i32 y = TRUNCATE(i64 x) 7164 // -- becomes -- 7165 // v16i8 b = BITCAST (v2i64 val) 7166 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7167 // 7168 // Note: We only run this optimization after type legalization (which often 7169 // creates this pattern) and before operation legalization after which 7170 // we need to be more careful about the vector instructions that we generate. 7171 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7172 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7173 7174 EVT VecTy = N0.getOperand(0).getValueType(); 7175 EVT ExTy = N0.getValueType(); 7176 EVT TrTy = N->getValueType(0); 7177 7178 unsigned NumElem = VecTy.getVectorNumElements(); 7179 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7180 7181 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7182 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7183 7184 SDValue EltNo = N0->getOperand(1); 7185 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7186 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7187 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7188 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7189 7190 SDLoc DL(N); 7191 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7192 DAG.getBitcast(NVT, N0.getOperand(0)), 7193 DAG.getConstant(Index, DL, IndexTy)); 7194 } 7195 } 7196 7197 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7198 if (N0.getOpcode() == ISD::SELECT) { 7199 EVT SrcVT = N0.getValueType(); 7200 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7201 TLI.isTruncateFree(SrcVT, VT)) { 7202 SDLoc SL(N0); 7203 SDValue Cond = N0.getOperand(0); 7204 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7205 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7206 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7207 } 7208 } 7209 7210 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 7211 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7212 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 7213 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 7214 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 7215 uint64_t Amt = CAmt->getZExtValue(); 7216 unsigned Size = VT.getScalarSizeInBits(); 7217 7218 if (Amt < Size) { 7219 SDLoc SL(N); 7220 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 7221 7222 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 7223 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 7224 DAG.getConstant(Amt, SL, AmtVT)); 7225 } 7226 } 7227 } 7228 7229 // Fold a series of buildvector, bitcast, and truncate if possible. 7230 // For example fold 7231 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7232 // (2xi32 (buildvector x, y)). 7233 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7234 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7235 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7236 N0.getOperand(0).hasOneUse()) { 7237 7238 SDValue BuildVect = N0.getOperand(0); 7239 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7240 EVT TruncVecEltTy = VT.getVectorElementType(); 7241 7242 // Check that the element types match. 7243 if (BuildVectEltTy == TruncVecEltTy) { 7244 // Now we only need to compute the offset of the truncated elements. 7245 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7246 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7247 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7248 7249 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7250 "Invalid number of elements"); 7251 7252 SmallVector<SDValue, 8> Opnds; 7253 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7254 Opnds.push_back(BuildVect.getOperand(i)); 7255 7256 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 7257 } 7258 } 7259 7260 // See if we can simplify the input to this truncate through knowledge that 7261 // only the low bits are being used. 7262 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7263 // Currently we only perform this optimization on scalars because vectors 7264 // may have different active low bits. 7265 if (!VT.isVector()) { 7266 if (SDValue Shorter = 7267 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7268 VT.getSizeInBits()))) 7269 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7270 } 7271 // fold (truncate (load x)) -> (smaller load x) 7272 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7273 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7274 if (SDValue Reduced = ReduceLoadWidth(N)) 7275 return Reduced; 7276 7277 // Handle the case where the load remains an extending load even 7278 // after truncation. 7279 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7280 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7281 if (!LN0->isVolatile() && 7282 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7283 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7284 VT, LN0->getChain(), LN0->getBasePtr(), 7285 LN0->getMemoryVT(), 7286 LN0->getMemOperand()); 7287 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7288 return NewLoad; 7289 } 7290 } 7291 } 7292 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7293 // where ... are all 'undef'. 7294 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7295 SmallVector<EVT, 8> VTs; 7296 SDValue V; 7297 unsigned Idx = 0; 7298 unsigned NumDefs = 0; 7299 7300 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7301 SDValue X = N0.getOperand(i); 7302 if (!X.isUndef()) { 7303 V = X; 7304 Idx = i; 7305 NumDefs++; 7306 } 7307 // Stop if more than one members are non-undef. 7308 if (NumDefs > 1) 7309 break; 7310 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7311 VT.getVectorElementType(), 7312 X.getValueType().getVectorNumElements())); 7313 } 7314 7315 if (NumDefs == 0) 7316 return DAG.getUNDEF(VT); 7317 7318 if (NumDefs == 1) { 7319 assert(V.getNode() && "The single defined operand is empty!"); 7320 SmallVector<SDValue, 8> Opnds; 7321 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7322 if (i != Idx) { 7323 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7324 continue; 7325 } 7326 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7327 AddToWorklist(NV.getNode()); 7328 Opnds.push_back(NV); 7329 } 7330 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7331 } 7332 } 7333 7334 // Fold truncate of a bitcast of a vector to an extract of the low vector 7335 // element. 7336 // 7337 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 7338 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 7339 SDValue VecSrc = N0.getOperand(0); 7340 EVT SrcVT = VecSrc.getValueType(); 7341 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 7342 (!LegalOperations || 7343 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 7344 SDLoc SL(N); 7345 7346 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 7347 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 7348 VecSrc, DAG.getConstant(0, SL, IdxVT)); 7349 } 7350 } 7351 7352 // Simplify the operands using demanded-bits information. 7353 if (!VT.isVector() && 7354 SimplifyDemandedBits(SDValue(N, 0))) 7355 return SDValue(N, 0); 7356 7357 return SDValue(); 7358 } 7359 7360 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7361 SDValue Elt = N->getOperand(i); 7362 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7363 return Elt.getNode(); 7364 return Elt.getOperand(Elt.getResNo()).getNode(); 7365 } 7366 7367 /// build_pair (load, load) -> load 7368 /// if load locations are consecutive. 7369 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7370 assert(N->getOpcode() == ISD::BUILD_PAIR); 7371 7372 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7373 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7374 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7375 LD1->getAddressSpace() != LD2->getAddressSpace()) 7376 return SDValue(); 7377 EVT LD1VT = LD1->getValueType(0); 7378 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 7379 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 7380 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 7381 unsigned Align = LD1->getAlignment(); 7382 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7383 VT.getTypeForEVT(*DAG.getContext())); 7384 7385 if (NewAlign <= Align && 7386 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7387 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 7388 LD1->getPointerInfo(), Align); 7389 } 7390 7391 return SDValue(); 7392 } 7393 7394 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7395 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7396 // and Lo parts; on big-endian machines it doesn't. 7397 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7398 } 7399 7400 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 7401 const TargetLowering &TLI) { 7402 // If this is not a bitcast to an FP type or if the target doesn't have 7403 // IEEE754-compliant FP logic, we're done. 7404 EVT VT = N->getValueType(0); 7405 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 7406 return SDValue(); 7407 7408 // TODO: Use splat values for the constant-checking below and remove this 7409 // restriction. 7410 SDValue N0 = N->getOperand(0); 7411 EVT SourceVT = N0.getValueType(); 7412 if (SourceVT.isVector()) 7413 return SDValue(); 7414 7415 unsigned FPOpcode; 7416 APInt SignMask; 7417 switch (N0.getOpcode()) { 7418 case ISD::AND: 7419 FPOpcode = ISD::FABS; 7420 SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits()); 7421 break; 7422 case ISD::XOR: 7423 FPOpcode = ISD::FNEG; 7424 SignMask = APInt::getSignBit(SourceVT.getSizeInBits()); 7425 break; 7426 // TODO: ISD::OR --> ISD::FNABS? 7427 default: 7428 return SDValue(); 7429 } 7430 7431 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 7432 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 7433 SDValue LogicOp0 = N0.getOperand(0); 7434 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7435 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 7436 LogicOp0.getOpcode() == ISD::BITCAST && 7437 LogicOp0->getOperand(0).getValueType() == VT) 7438 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 7439 7440 return SDValue(); 7441 } 7442 7443 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7444 SDValue N0 = N->getOperand(0); 7445 EVT VT = N->getValueType(0); 7446 7447 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7448 // Only do this before legalize, since afterward the target may be depending 7449 // on the bitconvert. 7450 // First check to see if this is all constant. 7451 if (!LegalTypes && 7452 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7453 VT.isVector()) { 7454 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7455 7456 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7457 assert(!DestEltVT.isVector() && 7458 "Element type of vector ValueType must not be vector!"); 7459 if (isSimple) 7460 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7461 } 7462 7463 // If the input is a constant, let getNode fold it. 7464 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7465 // If we can't allow illegal operations, we need to check that this is just 7466 // a fp -> int or int -> conversion and that the resulting operation will 7467 // be legal. 7468 if (!LegalOperations || 7469 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7470 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7471 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7472 TLI.isOperationLegal(ISD::Constant, VT))) 7473 return DAG.getBitcast(VT, N0); 7474 } 7475 7476 // (conv (conv x, t1), t2) -> (conv x, t2) 7477 if (N0.getOpcode() == ISD::BITCAST) 7478 return DAG.getBitcast(VT, N0.getOperand(0)); 7479 7480 // fold (conv (load x)) -> (load (conv*)x) 7481 // If the resultant load doesn't need a higher alignment than the original! 7482 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7483 // Do not change the width of a volatile load. 7484 !cast<LoadSDNode>(N0)->isVolatile() && 7485 // Do not remove the cast if the types differ in endian layout. 7486 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7487 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7488 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7489 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7490 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7491 unsigned OrigAlign = LN0->getAlignment(); 7492 7493 bool Fast = false; 7494 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7495 LN0->getAddressSpace(), OrigAlign, &Fast) && 7496 Fast) { 7497 SDValue Load = 7498 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 7499 LN0->getPointerInfo(), OrigAlign, 7500 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7501 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7502 return Load; 7503 } 7504 } 7505 7506 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 7507 return V; 7508 7509 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7510 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7511 // 7512 // For ppc_fp128: 7513 // fold (bitcast (fneg x)) -> 7514 // flipbit = signbit 7515 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7516 // 7517 // fold (bitcast (fabs x)) -> 7518 // flipbit = (and (extract_element (bitcast x), 0), signbit) 7519 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7520 // This often reduces constant pool loads. 7521 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7522 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7523 N0.getNode()->hasOneUse() && VT.isInteger() && 7524 !VT.isVector() && !N0.getValueType().isVector()) { 7525 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 7526 AddToWorklist(NewConv.getNode()); 7527 7528 SDLoc DL(N); 7529 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7530 assert(VT.getSizeInBits() == 128); 7531 SDValue SignBit = DAG.getConstant( 7532 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 7533 SDValue FlipBit; 7534 if (N0.getOpcode() == ISD::FNEG) { 7535 FlipBit = SignBit; 7536 AddToWorklist(FlipBit.getNode()); 7537 } else { 7538 assert(N0.getOpcode() == ISD::FABS); 7539 SDValue Hi = 7540 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 7541 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7542 SDLoc(NewConv))); 7543 AddToWorklist(Hi.getNode()); 7544 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 7545 AddToWorklist(FlipBit.getNode()); 7546 } 7547 SDValue FlipBits = 7548 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7549 AddToWorklist(FlipBits.getNode()); 7550 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 7551 } 7552 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7553 if (N0.getOpcode() == ISD::FNEG) 7554 return DAG.getNode(ISD::XOR, DL, VT, 7555 NewConv, DAG.getConstant(SignBit, DL, VT)); 7556 assert(N0.getOpcode() == ISD::FABS); 7557 return DAG.getNode(ISD::AND, DL, VT, 7558 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7559 } 7560 7561 // fold (bitconvert (fcopysign cst, x)) -> 7562 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7563 // Note that we don't handle (copysign x, cst) because this can always be 7564 // folded to an fneg or fabs. 7565 // 7566 // For ppc_fp128: 7567 // fold (bitcast (fcopysign cst, x)) -> 7568 // flipbit = (and (extract_element 7569 // (xor (bitcast cst), (bitcast x)), 0), 7570 // signbit) 7571 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 7572 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7573 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7574 VT.isInteger() && !VT.isVector()) { 7575 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7576 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7577 if (isTypeLegal(IntXVT)) { 7578 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 7579 AddToWorklist(X.getNode()); 7580 7581 // If X has a different width than the result/lhs, sext it or truncate it. 7582 unsigned VTWidth = VT.getSizeInBits(); 7583 if (OrigXWidth < VTWidth) { 7584 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7585 AddToWorklist(X.getNode()); 7586 } else if (OrigXWidth > VTWidth) { 7587 // To get the sign bit in the right place, we have to shift it right 7588 // before truncating. 7589 SDLoc DL(X); 7590 X = DAG.getNode(ISD::SRL, DL, 7591 X.getValueType(), X, 7592 DAG.getConstant(OrigXWidth-VTWidth, DL, 7593 X.getValueType())); 7594 AddToWorklist(X.getNode()); 7595 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7596 AddToWorklist(X.getNode()); 7597 } 7598 7599 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7600 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 7601 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7602 AddToWorklist(Cst.getNode()); 7603 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 7604 AddToWorklist(X.getNode()); 7605 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 7606 AddToWorklist(XorResult.getNode()); 7607 SDValue XorResult64 = DAG.getNode( 7608 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 7609 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7610 SDLoc(XorResult))); 7611 AddToWorklist(XorResult64.getNode()); 7612 SDValue FlipBit = 7613 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 7614 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 7615 AddToWorklist(FlipBit.getNode()); 7616 SDValue FlipBits = 7617 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7618 AddToWorklist(FlipBits.getNode()); 7619 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 7620 } 7621 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7622 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7623 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7624 AddToWorklist(X.getNode()); 7625 7626 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7627 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7628 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7629 AddToWorklist(Cst.getNode()); 7630 7631 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7632 } 7633 } 7634 7635 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7636 if (N0.getOpcode() == ISD::BUILD_PAIR) 7637 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7638 return CombineLD; 7639 7640 // Remove double bitcasts from shuffles - this is often a legacy of 7641 // XformToShuffleWithZero being used to combine bitmaskings (of 7642 // float vectors bitcast to integer vectors) into shuffles. 7643 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7644 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7645 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7646 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7647 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7648 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7649 7650 // If operands are a bitcast, peek through if it casts the original VT. 7651 // If operands are a constant, just bitcast back to original VT. 7652 auto PeekThroughBitcast = [&](SDValue Op) { 7653 if (Op.getOpcode() == ISD::BITCAST && 7654 Op.getOperand(0).getValueType() == VT) 7655 return SDValue(Op.getOperand(0)); 7656 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7657 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7658 return DAG.getBitcast(VT, Op); 7659 return SDValue(); 7660 }; 7661 7662 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7663 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7664 if (!(SV0 && SV1)) 7665 return SDValue(); 7666 7667 int MaskScale = 7668 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7669 SmallVector<int, 8> NewMask; 7670 for (int M : SVN->getMask()) 7671 for (int i = 0; i != MaskScale; ++i) 7672 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7673 7674 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7675 if (!LegalMask) { 7676 std::swap(SV0, SV1); 7677 ShuffleVectorSDNode::commuteMask(NewMask); 7678 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7679 } 7680 7681 if (LegalMask) 7682 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7683 } 7684 7685 return SDValue(); 7686 } 7687 7688 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7689 EVT VT = N->getValueType(0); 7690 return CombineConsecutiveLoads(N, VT); 7691 } 7692 7693 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7694 /// operands. DstEltVT indicates the destination element value type. 7695 SDValue DAGCombiner:: 7696 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7697 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7698 7699 // If this is already the right type, we're done. 7700 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7701 7702 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7703 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7704 7705 // If this is a conversion of N elements of one type to N elements of another 7706 // type, convert each element. This handles FP<->INT cases. 7707 if (SrcBitSize == DstBitSize) { 7708 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7709 BV->getValueType(0).getVectorNumElements()); 7710 7711 // Due to the FP element handling below calling this routine recursively, 7712 // we can end up with a scalar-to-vector node here. 7713 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7714 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7715 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 7716 7717 SmallVector<SDValue, 8> Ops; 7718 for (SDValue Op : BV->op_values()) { 7719 // If the vector element type is not legal, the BUILD_VECTOR operands 7720 // are promoted and implicitly truncated. Make that explicit here. 7721 if (Op.getValueType() != SrcEltVT) 7722 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7723 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 7724 AddToWorklist(Ops.back().getNode()); 7725 } 7726 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 7727 } 7728 7729 // Otherwise, we're growing or shrinking the elements. To avoid having to 7730 // handle annoying details of growing/shrinking FP values, we convert them to 7731 // int first. 7732 if (SrcEltVT.isFloatingPoint()) { 7733 // Convert the input float vector to a int vector where the elements are the 7734 // same sizes. 7735 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7736 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7737 SrcEltVT = IntVT; 7738 } 7739 7740 // Now we know the input is an integer vector. If the output is a FP type, 7741 // convert to integer first, then to FP of the right size. 7742 if (DstEltVT.isFloatingPoint()) { 7743 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7744 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7745 7746 // Next, convert to FP elements of the same size. 7747 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7748 } 7749 7750 SDLoc DL(BV); 7751 7752 // Okay, we know the src/dst types are both integers of differing types. 7753 // Handling growing first. 7754 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7755 if (SrcBitSize < DstBitSize) { 7756 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7757 7758 SmallVector<SDValue, 8> Ops; 7759 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7760 i += NumInputsPerOutput) { 7761 bool isLE = DAG.getDataLayout().isLittleEndian(); 7762 APInt NewBits = APInt(DstBitSize, 0); 7763 bool EltIsUndef = true; 7764 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7765 // Shift the previously computed bits over. 7766 NewBits <<= SrcBitSize; 7767 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7768 if (Op.isUndef()) continue; 7769 EltIsUndef = false; 7770 7771 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7772 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7773 } 7774 7775 if (EltIsUndef) 7776 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7777 else 7778 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7779 } 7780 7781 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7782 return DAG.getBuildVector(VT, DL, Ops); 7783 } 7784 7785 // Finally, this must be the case where we are shrinking elements: each input 7786 // turns into multiple outputs. 7787 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7788 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7789 NumOutputsPerInput*BV->getNumOperands()); 7790 SmallVector<SDValue, 8> Ops; 7791 7792 for (const SDValue &Op : BV->op_values()) { 7793 if (Op.isUndef()) { 7794 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7795 continue; 7796 } 7797 7798 APInt OpVal = cast<ConstantSDNode>(Op)-> 7799 getAPIntValue().zextOrTrunc(SrcBitSize); 7800 7801 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7802 APInt ThisVal = OpVal.trunc(DstBitSize); 7803 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7804 OpVal = OpVal.lshr(DstBitSize); 7805 } 7806 7807 // For big endian targets, swap the order of the pieces of each element. 7808 if (DAG.getDataLayout().isBigEndian()) 7809 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7810 } 7811 7812 return DAG.getBuildVector(VT, DL, Ops); 7813 } 7814 7815 /// Try to perform FMA combining on a given FADD node. 7816 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7817 SDValue N0 = N->getOperand(0); 7818 SDValue N1 = N->getOperand(1); 7819 EVT VT = N->getValueType(0); 7820 SDLoc SL(N); 7821 7822 const TargetOptions &Options = DAG.getTarget().Options; 7823 bool AllowFusion = 7824 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7825 7826 // Floating-point multiply-add with intermediate rounding. 7827 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7828 7829 // Floating-point multiply-add without intermediate rounding. 7830 bool HasFMA = 7831 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7832 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7833 7834 // No valid opcode, do not combine. 7835 if (!HasFMAD && !HasFMA) 7836 return SDValue(); 7837 7838 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7839 ; 7840 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7841 return SDValue(); 7842 7843 // Always prefer FMAD to FMA for precision. 7844 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7845 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7846 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7847 7848 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7849 // prefer to fold the multiply with fewer uses. 7850 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7851 N1.getOpcode() == ISD::FMUL) { 7852 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7853 std::swap(N0, N1); 7854 } 7855 7856 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7857 if (N0.getOpcode() == ISD::FMUL && 7858 (Aggressive || N0->hasOneUse())) { 7859 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7860 N0.getOperand(0), N0.getOperand(1), N1); 7861 } 7862 7863 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7864 // Note: Commutes FADD operands. 7865 if (N1.getOpcode() == ISD::FMUL && 7866 (Aggressive || N1->hasOneUse())) { 7867 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7868 N1.getOperand(0), N1.getOperand(1), N0); 7869 } 7870 7871 // Look through FP_EXTEND nodes to do more combining. 7872 if (AllowFusion && LookThroughFPExt) { 7873 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7874 if (N0.getOpcode() == ISD::FP_EXTEND) { 7875 SDValue N00 = N0.getOperand(0); 7876 if (N00.getOpcode() == ISD::FMUL) 7877 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7878 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7879 N00.getOperand(0)), 7880 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7881 N00.getOperand(1)), N1); 7882 } 7883 7884 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7885 // Note: Commutes FADD operands. 7886 if (N1.getOpcode() == ISD::FP_EXTEND) { 7887 SDValue N10 = N1.getOperand(0); 7888 if (N10.getOpcode() == ISD::FMUL) 7889 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7890 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7891 N10.getOperand(0)), 7892 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7893 N10.getOperand(1)), N0); 7894 } 7895 } 7896 7897 // More folding opportunities when target permits. 7898 if ((AllowFusion || HasFMAD) && Aggressive) { 7899 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, 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 N1)); 7908 } 7909 7910 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7911 if (N1->getOpcode() == PreferredFusedOpcode && 7912 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7913 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7914 N1.getOperand(0), N1.getOperand(1), 7915 DAG.getNode(PreferredFusedOpcode, SL, VT, 7916 N1.getOperand(2).getOperand(0), 7917 N1.getOperand(2).getOperand(1), 7918 N0)); 7919 } 7920 7921 if (AllowFusion && LookThroughFPExt) { 7922 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7923 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7924 auto FoldFAddFMAFPExtFMul = [&] ( 7925 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7926 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7927 DAG.getNode(PreferredFusedOpcode, SL, VT, 7928 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7929 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7930 Z)); 7931 }; 7932 if (N0.getOpcode() == PreferredFusedOpcode) { 7933 SDValue N02 = N0.getOperand(2); 7934 if (N02.getOpcode() == ISD::FP_EXTEND) { 7935 SDValue N020 = N02.getOperand(0); 7936 if (N020.getOpcode() == ISD::FMUL) 7937 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7938 N020.getOperand(0), N020.getOperand(1), 7939 N1); 7940 } 7941 } 7942 7943 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7944 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7945 // FIXME: This turns two single-precision and one double-precision 7946 // operation into two double-precision operations, which might not be 7947 // interesting for all targets, especially GPUs. 7948 auto FoldFAddFPExtFMAFMul = [&] ( 7949 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7950 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7951 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7952 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7953 DAG.getNode(PreferredFusedOpcode, SL, VT, 7954 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7955 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7956 Z)); 7957 }; 7958 if (N0.getOpcode() == ISD::FP_EXTEND) { 7959 SDValue N00 = N0.getOperand(0); 7960 if (N00.getOpcode() == PreferredFusedOpcode) { 7961 SDValue N002 = N00.getOperand(2); 7962 if (N002.getOpcode() == ISD::FMUL) 7963 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7964 N002.getOperand(0), N002.getOperand(1), 7965 N1); 7966 } 7967 } 7968 7969 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7970 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7971 if (N1.getOpcode() == PreferredFusedOpcode) { 7972 SDValue N12 = N1.getOperand(2); 7973 if (N12.getOpcode() == ISD::FP_EXTEND) { 7974 SDValue N120 = N12.getOperand(0); 7975 if (N120.getOpcode() == ISD::FMUL) 7976 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7977 N120.getOperand(0), N120.getOperand(1), 7978 N0); 7979 } 7980 } 7981 7982 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7983 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7984 // FIXME: This turns two single-precision and one double-precision 7985 // operation into two double-precision operations, which might not be 7986 // interesting for all targets, especially GPUs. 7987 if (N1.getOpcode() == ISD::FP_EXTEND) { 7988 SDValue N10 = N1.getOperand(0); 7989 if (N10.getOpcode() == PreferredFusedOpcode) { 7990 SDValue N102 = N10.getOperand(2); 7991 if (N102.getOpcode() == ISD::FMUL) 7992 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7993 N102.getOperand(0), N102.getOperand(1), 7994 N0); 7995 } 7996 } 7997 } 7998 } 7999 8000 return SDValue(); 8001 } 8002 8003 /// Try to perform FMA combining on a given FSUB node. 8004 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 8005 SDValue N0 = N->getOperand(0); 8006 SDValue N1 = N->getOperand(1); 8007 EVT VT = N->getValueType(0); 8008 SDLoc SL(N); 8009 8010 const TargetOptions &Options = DAG.getTarget().Options; 8011 bool AllowFusion = 8012 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8013 8014 // Floating-point multiply-add with intermediate rounding. 8015 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8016 8017 // Floating-point multiply-add without intermediate rounding. 8018 bool HasFMA = 8019 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8020 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8021 8022 // No valid opcode, do not combine. 8023 if (!HasFMAD && !HasFMA) 8024 return SDValue(); 8025 8026 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8027 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8028 return SDValue(); 8029 8030 // Always prefer FMAD to FMA for precision. 8031 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8032 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8033 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8034 8035 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 8036 if (N0.getOpcode() == ISD::FMUL && 8037 (Aggressive || N0->hasOneUse())) { 8038 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8039 N0.getOperand(0), N0.getOperand(1), 8040 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8041 } 8042 8043 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 8044 // Note: Commutes FSUB operands. 8045 if (N1.getOpcode() == ISD::FMUL && 8046 (Aggressive || N1->hasOneUse())) 8047 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8048 DAG.getNode(ISD::FNEG, SL, VT, 8049 N1.getOperand(0)), 8050 N1.getOperand(1), N0); 8051 8052 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 8053 if (N0.getOpcode() == ISD::FNEG && 8054 N0.getOperand(0).getOpcode() == ISD::FMUL && 8055 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 8056 SDValue N00 = N0.getOperand(0).getOperand(0); 8057 SDValue N01 = N0.getOperand(0).getOperand(1); 8058 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8059 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 8060 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8061 } 8062 8063 // Look through FP_EXTEND nodes to do more combining. 8064 if (AllowFusion && LookThroughFPExt) { 8065 // fold (fsub (fpext (fmul x, y)), z) 8066 // -> (fma (fpext x), (fpext y), (fneg z)) 8067 if (N0.getOpcode() == ISD::FP_EXTEND) { 8068 SDValue N00 = N0.getOperand(0); 8069 if (N00.getOpcode() == ISD::FMUL) 8070 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8071 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8072 N00.getOperand(0)), 8073 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8074 N00.getOperand(1)), 8075 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8076 } 8077 8078 // fold (fsub x, (fpext (fmul y, z))) 8079 // -> (fma (fneg (fpext y)), (fpext z), x) 8080 // Note: Commutes FSUB operands. 8081 if (N1.getOpcode() == ISD::FP_EXTEND) { 8082 SDValue N10 = N1.getOperand(0); 8083 if (N10.getOpcode() == ISD::FMUL) 8084 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8085 DAG.getNode(ISD::FNEG, SL, VT, 8086 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8087 N10.getOperand(0))), 8088 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8089 N10.getOperand(1)), 8090 N0); 8091 } 8092 8093 // fold (fsub (fpext (fneg (fmul, x, y))), z) 8094 // -> (fneg (fma (fpext x), (fpext y), z)) 8095 // Note: This could be removed with appropriate canonicalization of the 8096 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8097 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8098 // from implementing the canonicalization in visitFSUB. 8099 if (N0.getOpcode() == ISD::FP_EXTEND) { 8100 SDValue N00 = N0.getOperand(0); 8101 if (N00.getOpcode() == ISD::FNEG) { 8102 SDValue N000 = N00.getOperand(0); 8103 if (N000.getOpcode() == ISD::FMUL) { 8104 return DAG.getNode(ISD::FNEG, SL, VT, 8105 DAG.getNode(PreferredFusedOpcode, SL, VT, 8106 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8107 N000.getOperand(0)), 8108 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8109 N000.getOperand(1)), 8110 N1)); 8111 } 8112 } 8113 } 8114 8115 // fold (fsub (fneg (fpext (fmul, x, y))), z) 8116 // -> (fneg (fma (fpext x)), (fpext y), z) 8117 // Note: This could be removed with appropriate canonicalization of the 8118 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8119 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8120 // from implementing the canonicalization in visitFSUB. 8121 if (N0.getOpcode() == ISD::FNEG) { 8122 SDValue N00 = N0.getOperand(0); 8123 if (N00.getOpcode() == ISD::FP_EXTEND) { 8124 SDValue N000 = N00.getOperand(0); 8125 if (N000.getOpcode() == ISD::FMUL) { 8126 return DAG.getNode(ISD::FNEG, SL, VT, 8127 DAG.getNode(PreferredFusedOpcode, SL, VT, 8128 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8129 N000.getOperand(0)), 8130 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8131 N000.getOperand(1)), 8132 N1)); 8133 } 8134 } 8135 } 8136 8137 } 8138 8139 // More folding opportunities when target permits. 8140 if ((AllowFusion || HasFMAD) && Aggressive) { 8141 // fold (fsub (fma x, y, (fmul u, v)), z) 8142 // -> (fma x, y (fma u, v, (fneg z))) 8143 if (N0.getOpcode() == PreferredFusedOpcode && 8144 N0.getOperand(2).getOpcode() == ISD::FMUL) { 8145 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8146 N0.getOperand(0), N0.getOperand(1), 8147 DAG.getNode(PreferredFusedOpcode, SL, VT, 8148 N0.getOperand(2).getOperand(0), 8149 N0.getOperand(2).getOperand(1), 8150 DAG.getNode(ISD::FNEG, SL, VT, 8151 N1))); 8152 } 8153 8154 // fold (fsub x, (fma y, z, (fmul u, v))) 8155 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 8156 if (N1.getOpcode() == PreferredFusedOpcode && 8157 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8158 SDValue N20 = N1.getOperand(2).getOperand(0); 8159 SDValue N21 = N1.getOperand(2).getOperand(1); 8160 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8161 DAG.getNode(ISD::FNEG, SL, VT, 8162 N1.getOperand(0)), 8163 N1.getOperand(1), 8164 DAG.getNode(PreferredFusedOpcode, SL, VT, 8165 DAG.getNode(ISD::FNEG, SL, VT, N20), 8166 8167 N21, N0)); 8168 } 8169 8170 if (AllowFusion && LookThroughFPExt) { 8171 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 8172 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8173 if (N0.getOpcode() == PreferredFusedOpcode) { 8174 SDValue N02 = N0.getOperand(2); 8175 if (N02.getOpcode() == ISD::FP_EXTEND) { 8176 SDValue N020 = N02.getOperand(0); 8177 if (N020.getOpcode() == ISD::FMUL) 8178 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8179 N0.getOperand(0), N0.getOperand(1), 8180 DAG.getNode(PreferredFusedOpcode, SL, VT, 8181 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8182 N020.getOperand(0)), 8183 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8184 N020.getOperand(1)), 8185 DAG.getNode(ISD::FNEG, SL, VT, 8186 N1))); 8187 } 8188 } 8189 8190 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8191 // -> (fma (fpext x), (fpext y), 8192 // (fma (fpext u), (fpext v), (fneg z))) 8193 // FIXME: This turns two single-precision and one double-precision 8194 // operation into two double-precision operations, which might not be 8195 // interesting for all targets, especially GPUs. 8196 if (N0.getOpcode() == ISD::FP_EXTEND) { 8197 SDValue N00 = N0.getOperand(0); 8198 if (N00.getOpcode() == PreferredFusedOpcode) { 8199 SDValue N002 = N00.getOperand(2); 8200 if (N002.getOpcode() == ISD::FMUL) 8201 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8202 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8203 N00.getOperand(0)), 8204 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8205 N00.getOperand(1)), 8206 DAG.getNode(PreferredFusedOpcode, SL, VT, 8207 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8208 N002.getOperand(0)), 8209 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8210 N002.getOperand(1)), 8211 DAG.getNode(ISD::FNEG, SL, VT, 8212 N1))); 8213 } 8214 } 8215 8216 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8217 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8218 if (N1.getOpcode() == PreferredFusedOpcode && 8219 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8220 SDValue N120 = N1.getOperand(2).getOperand(0); 8221 if (N120.getOpcode() == ISD::FMUL) { 8222 SDValue N1200 = N120.getOperand(0); 8223 SDValue N1201 = N120.getOperand(1); 8224 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8225 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8226 N1.getOperand(1), 8227 DAG.getNode(PreferredFusedOpcode, SL, VT, 8228 DAG.getNode(ISD::FNEG, SL, VT, 8229 DAG.getNode(ISD::FP_EXTEND, SL, 8230 VT, N1200)), 8231 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8232 N1201), 8233 N0)); 8234 } 8235 } 8236 8237 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8238 // -> (fma (fneg (fpext y)), (fpext z), 8239 // (fma (fneg (fpext u)), (fpext v), x)) 8240 // FIXME: This turns two single-precision and one double-precision 8241 // operation into two double-precision operations, which might not be 8242 // interesting for all targets, especially GPUs. 8243 if (N1.getOpcode() == ISD::FP_EXTEND && 8244 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8245 SDValue N100 = N1.getOperand(0).getOperand(0); 8246 SDValue N101 = N1.getOperand(0).getOperand(1); 8247 SDValue N102 = N1.getOperand(0).getOperand(2); 8248 if (N102.getOpcode() == ISD::FMUL) { 8249 SDValue N1020 = N102.getOperand(0); 8250 SDValue N1021 = N102.getOperand(1); 8251 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8252 DAG.getNode(ISD::FNEG, SL, VT, 8253 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8254 N100)), 8255 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8256 DAG.getNode(PreferredFusedOpcode, SL, VT, 8257 DAG.getNode(ISD::FNEG, SL, VT, 8258 DAG.getNode(ISD::FP_EXTEND, SL, 8259 VT, N1020)), 8260 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8261 N1021), 8262 N0)); 8263 } 8264 } 8265 } 8266 } 8267 8268 return SDValue(); 8269 } 8270 8271 /// Try to perform FMA combining on a given FMUL node. 8272 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 8273 SDValue N0 = N->getOperand(0); 8274 SDValue N1 = N->getOperand(1); 8275 EVT VT = N->getValueType(0); 8276 SDLoc SL(N); 8277 8278 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8279 8280 const TargetOptions &Options = DAG.getTarget().Options; 8281 bool AllowFusion = 8282 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8283 8284 // Floating-point multiply-add with intermediate rounding. 8285 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8286 8287 // Floating-point multiply-add without intermediate rounding. 8288 bool HasFMA = 8289 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8290 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8291 8292 // No valid opcode, do not combine. 8293 if (!HasFMAD && !HasFMA) 8294 return SDValue(); 8295 8296 // Always prefer FMAD to FMA for precision. 8297 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8298 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8299 8300 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8301 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8302 auto FuseFADD = [&](SDValue X, SDValue Y) { 8303 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8304 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8305 if (XC1 && XC1->isExactlyValue(+1.0)) 8306 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8307 if (XC1 && XC1->isExactlyValue(-1.0)) 8308 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8309 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8310 } 8311 return SDValue(); 8312 }; 8313 8314 if (SDValue FMA = FuseFADD(N0, N1)) 8315 return FMA; 8316 if (SDValue FMA = FuseFADD(N1, N0)) 8317 return FMA; 8318 8319 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8320 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8321 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8322 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8323 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8324 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8325 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8326 if (XC0 && XC0->isExactlyValue(+1.0)) 8327 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8328 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8329 Y); 8330 if (XC0 && XC0->isExactlyValue(-1.0)) 8331 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8332 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8333 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8334 8335 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8336 if (XC1 && XC1->isExactlyValue(+1.0)) 8337 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8338 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8339 if (XC1 && XC1->isExactlyValue(-1.0)) 8340 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8341 } 8342 return SDValue(); 8343 }; 8344 8345 if (SDValue FMA = FuseFSUB(N0, N1)) 8346 return FMA; 8347 if (SDValue FMA = FuseFSUB(N1, N0)) 8348 return FMA; 8349 8350 return SDValue(); 8351 } 8352 8353 SDValue DAGCombiner::visitFADD(SDNode *N) { 8354 SDValue N0 = N->getOperand(0); 8355 SDValue N1 = N->getOperand(1); 8356 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8357 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8358 EVT VT = N->getValueType(0); 8359 SDLoc DL(N); 8360 const TargetOptions &Options = DAG.getTarget().Options; 8361 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8362 8363 // fold vector ops 8364 if (VT.isVector()) 8365 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8366 return FoldedVOp; 8367 8368 // fold (fadd c1, c2) -> c1 + c2 8369 if (N0CFP && N1CFP) 8370 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8371 8372 // canonicalize constant to RHS 8373 if (N0CFP && !N1CFP) 8374 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8375 8376 // fold (fadd A, (fneg B)) -> (fsub A, B) 8377 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8378 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8379 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8380 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8381 8382 // fold (fadd (fneg A), B) -> (fsub B, A) 8383 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8384 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8385 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8386 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8387 8388 // If 'unsafe math' is enabled, fold lots of things. 8389 if (Options.UnsafeFPMath) { 8390 // No FP constant should be created after legalization as Instruction 8391 // Selection pass has a hard time dealing with FP constants. 8392 bool AllowNewConst = (Level < AfterLegalizeDAG); 8393 8394 // fold (fadd A, 0) -> A 8395 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8396 if (N1C->isZero()) 8397 return N0; 8398 8399 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8400 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8401 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8402 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8403 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8404 Flags), 8405 Flags); 8406 8407 // If allowed, fold (fadd (fneg x), x) -> 0.0 8408 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8409 return DAG.getConstantFP(0.0, DL, VT); 8410 8411 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8412 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8413 return DAG.getConstantFP(0.0, DL, VT); 8414 8415 // We can fold chains of FADD's of the same value into multiplications. 8416 // This transform is not safe in general because we are reducing the number 8417 // of rounding steps. 8418 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8419 if (N0.getOpcode() == ISD::FMUL) { 8420 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8421 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8422 8423 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8424 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8425 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8426 DAG.getConstantFP(1.0, DL, VT), Flags); 8427 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8428 } 8429 8430 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8431 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8432 N1.getOperand(0) == N1.getOperand(1) && 8433 N0.getOperand(0) == N1.getOperand(0)) { 8434 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8435 DAG.getConstantFP(2.0, DL, VT), Flags); 8436 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8437 } 8438 } 8439 8440 if (N1.getOpcode() == ISD::FMUL) { 8441 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8442 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8443 8444 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8445 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8446 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8447 DAG.getConstantFP(1.0, DL, VT), Flags); 8448 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8449 } 8450 8451 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8452 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8453 N0.getOperand(0) == N0.getOperand(1) && 8454 N1.getOperand(0) == N0.getOperand(0)) { 8455 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8456 DAG.getConstantFP(2.0, DL, VT), Flags); 8457 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8458 } 8459 } 8460 8461 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8462 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8463 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8464 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8465 (N0.getOperand(0) == N1)) { 8466 return DAG.getNode(ISD::FMUL, DL, VT, 8467 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8468 } 8469 } 8470 8471 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8472 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8473 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8474 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8475 N1.getOperand(0) == N0) { 8476 return DAG.getNode(ISD::FMUL, DL, VT, 8477 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8478 } 8479 } 8480 8481 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8482 if (AllowNewConst && 8483 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8484 N0.getOperand(0) == N0.getOperand(1) && 8485 N1.getOperand(0) == N1.getOperand(1) && 8486 N0.getOperand(0) == N1.getOperand(0)) { 8487 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8488 DAG.getConstantFP(4.0, DL, VT), Flags); 8489 } 8490 } 8491 } // enable-unsafe-fp-math 8492 8493 // FADD -> FMA combines: 8494 if (SDValue Fused = visitFADDForFMACombine(N)) { 8495 AddToWorklist(Fused.getNode()); 8496 return Fused; 8497 } 8498 return SDValue(); 8499 } 8500 8501 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8502 SDValue N0 = N->getOperand(0); 8503 SDValue N1 = N->getOperand(1); 8504 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8505 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8506 EVT VT = N->getValueType(0); 8507 SDLoc dl(N); 8508 const TargetOptions &Options = DAG.getTarget().Options; 8509 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8510 8511 // fold vector ops 8512 if (VT.isVector()) 8513 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8514 return FoldedVOp; 8515 8516 // fold (fsub c1, c2) -> c1-c2 8517 if (N0CFP && N1CFP) 8518 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8519 8520 // fold (fsub A, (fneg B)) -> (fadd A, B) 8521 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8522 return DAG.getNode(ISD::FADD, dl, VT, N0, 8523 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8524 8525 // If 'unsafe math' is enabled, fold lots of things. 8526 if (Options.UnsafeFPMath) { 8527 // (fsub A, 0) -> A 8528 if (N1CFP && N1CFP->isZero()) 8529 return N0; 8530 8531 // (fsub 0, B) -> -B 8532 if (N0CFP && N0CFP->isZero()) { 8533 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8534 return GetNegatedExpression(N1, DAG, LegalOperations); 8535 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8536 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8537 } 8538 8539 // (fsub x, x) -> 0.0 8540 if (N0 == N1) 8541 return DAG.getConstantFP(0.0f, dl, VT); 8542 8543 // (fsub x, (fadd x, y)) -> (fneg y) 8544 // (fsub x, (fadd y, x)) -> (fneg y) 8545 if (N1.getOpcode() == ISD::FADD) { 8546 SDValue N10 = N1->getOperand(0); 8547 SDValue N11 = N1->getOperand(1); 8548 8549 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8550 return GetNegatedExpression(N11, DAG, LegalOperations); 8551 8552 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8553 return GetNegatedExpression(N10, DAG, LegalOperations); 8554 } 8555 } 8556 8557 // FSUB -> FMA combines: 8558 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8559 AddToWorklist(Fused.getNode()); 8560 return Fused; 8561 } 8562 8563 return SDValue(); 8564 } 8565 8566 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8567 SDValue N0 = N->getOperand(0); 8568 SDValue N1 = N->getOperand(1); 8569 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8570 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8571 EVT VT = N->getValueType(0); 8572 SDLoc DL(N); 8573 const TargetOptions &Options = DAG.getTarget().Options; 8574 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8575 8576 // fold vector ops 8577 if (VT.isVector()) { 8578 // This just handles C1 * C2 for vectors. Other vector folds are below. 8579 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8580 return FoldedVOp; 8581 } 8582 8583 // fold (fmul c1, c2) -> c1*c2 8584 if (N0CFP && N1CFP) 8585 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8586 8587 // canonicalize constant to RHS 8588 if (isConstantFPBuildVectorOrConstantFP(N0) && 8589 !isConstantFPBuildVectorOrConstantFP(N1)) 8590 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8591 8592 // fold (fmul A, 1.0) -> A 8593 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8594 return N0; 8595 8596 if (Options.UnsafeFPMath) { 8597 // fold (fmul A, 0) -> 0 8598 if (N1CFP && N1CFP->isZero()) 8599 return N1; 8600 8601 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8602 if (N0.getOpcode() == ISD::FMUL) { 8603 // Fold scalars or any vector constants (not just splats). 8604 // This fold is done in general by InstCombine, but extra fmul insts 8605 // may have been generated during lowering. 8606 SDValue N00 = N0.getOperand(0); 8607 SDValue N01 = N0.getOperand(1); 8608 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8609 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8610 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8611 8612 // Check 1: Make sure that the first operand of the inner multiply is NOT 8613 // a constant. Otherwise, we may induce infinite looping. 8614 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8615 // Check 2: Make sure that the second operand of the inner multiply and 8616 // the second operand of the outer multiply are constants. 8617 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8618 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8619 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8620 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8621 } 8622 } 8623 } 8624 8625 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8626 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8627 // during an early run of DAGCombiner can prevent folding with fmuls 8628 // inserted during lowering. 8629 if (N0.getOpcode() == ISD::FADD && 8630 (N0.getOperand(0) == N0.getOperand(1)) && 8631 N0.hasOneUse()) { 8632 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8633 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8634 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8635 } 8636 } 8637 8638 // fold (fmul X, 2.0) -> (fadd X, X) 8639 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8640 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8641 8642 // fold (fmul X, -1.0) -> (fneg X) 8643 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8644 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8645 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8646 8647 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8648 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8649 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8650 // Both can be negated for free, check to see if at least one is cheaper 8651 // negated. 8652 if (LHSNeg == 2 || RHSNeg == 2) 8653 return DAG.getNode(ISD::FMUL, DL, VT, 8654 GetNegatedExpression(N0, DAG, LegalOperations), 8655 GetNegatedExpression(N1, DAG, LegalOperations), 8656 Flags); 8657 } 8658 } 8659 8660 // FMUL -> FMA combines: 8661 if (SDValue Fused = visitFMULForFMACombine(N)) { 8662 AddToWorklist(Fused.getNode()); 8663 return Fused; 8664 } 8665 8666 return SDValue(); 8667 } 8668 8669 SDValue DAGCombiner::visitFMA(SDNode *N) { 8670 SDValue N0 = N->getOperand(0); 8671 SDValue N1 = N->getOperand(1); 8672 SDValue N2 = N->getOperand(2); 8673 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8674 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8675 EVT VT = N->getValueType(0); 8676 SDLoc dl(N); 8677 const TargetOptions &Options = DAG.getTarget().Options; 8678 8679 // Constant fold FMA. 8680 if (isa<ConstantFPSDNode>(N0) && 8681 isa<ConstantFPSDNode>(N1) && 8682 isa<ConstantFPSDNode>(N2)) { 8683 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8684 } 8685 8686 if (Options.UnsafeFPMath) { 8687 if (N0CFP && N0CFP->isZero()) 8688 return N2; 8689 if (N1CFP && N1CFP->isZero()) 8690 return N2; 8691 } 8692 // TODO: The FMA node should have flags that propagate to these nodes. 8693 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8694 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8695 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8696 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8697 8698 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8699 if (isConstantFPBuildVectorOrConstantFP(N0) && 8700 !isConstantFPBuildVectorOrConstantFP(N1)) 8701 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8702 8703 // TODO: FMA nodes should have flags that propagate to the created nodes. 8704 // For now, create a Flags object for use with all unsafe math transforms. 8705 SDNodeFlags Flags; 8706 Flags.setUnsafeAlgebra(true); 8707 8708 if (Options.UnsafeFPMath) { 8709 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8710 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8711 isConstantFPBuildVectorOrConstantFP(N1) && 8712 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8713 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8714 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8715 &Flags), &Flags); 8716 } 8717 8718 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8719 if (N0.getOpcode() == ISD::FMUL && 8720 isConstantFPBuildVectorOrConstantFP(N1) && 8721 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8722 return DAG.getNode(ISD::FMA, dl, VT, 8723 N0.getOperand(0), 8724 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8725 &Flags), 8726 N2); 8727 } 8728 } 8729 8730 // (fma x, 1, y) -> (fadd x, y) 8731 // (fma x, -1, y) -> (fadd (fneg x), y) 8732 if (N1CFP) { 8733 if (N1CFP->isExactlyValue(1.0)) 8734 // TODO: The FMA node should have flags that propagate to this node. 8735 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8736 8737 if (N1CFP->isExactlyValue(-1.0) && 8738 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8739 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8740 AddToWorklist(RHSNeg.getNode()); 8741 // TODO: The FMA node should have flags that propagate to this node. 8742 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8743 } 8744 } 8745 8746 if (Options.UnsafeFPMath) { 8747 // (fma x, c, x) -> (fmul x, (c+1)) 8748 if (N1CFP && N0 == N2) { 8749 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8750 DAG.getNode(ISD::FADD, dl, VT, 8751 N1, DAG.getConstantFP(1.0, dl, VT), 8752 &Flags), &Flags); 8753 } 8754 8755 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8756 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8757 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8758 DAG.getNode(ISD::FADD, dl, VT, 8759 N1, DAG.getConstantFP(-1.0, dl, VT), 8760 &Flags), &Flags); 8761 } 8762 } 8763 8764 return SDValue(); 8765 } 8766 8767 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8768 // reciprocal. 8769 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8770 // Notice that this is not always beneficial. One reason is different target 8771 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8772 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8773 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8774 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8775 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8776 const SDNodeFlags *Flags = N->getFlags(); 8777 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8778 return SDValue(); 8779 8780 // Skip if current node is a reciprocal. 8781 SDValue N0 = N->getOperand(0); 8782 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8783 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8784 return SDValue(); 8785 8786 // Exit early if the target does not want this transform or if there can't 8787 // possibly be enough uses of the divisor to make the transform worthwhile. 8788 SDValue N1 = N->getOperand(1); 8789 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8790 if (!MinUses || N1->use_size() < MinUses) 8791 return SDValue(); 8792 8793 // Find all FDIV users of the same divisor. 8794 // Use a set because duplicates may be present in the user list. 8795 SetVector<SDNode *> Users; 8796 for (auto *U : N1->uses()) { 8797 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8798 // This division is eligible for optimization only if global unsafe math 8799 // is enabled or if this division allows reciprocal formation. 8800 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8801 Users.insert(U); 8802 } 8803 } 8804 8805 // Now that we have the actual number of divisor uses, make sure it meets 8806 // the minimum threshold specified by the target. 8807 if (Users.size() < MinUses) 8808 return SDValue(); 8809 8810 EVT VT = N->getValueType(0); 8811 SDLoc DL(N); 8812 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8813 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8814 8815 // Dividend / Divisor -> Dividend * Reciprocal 8816 for (auto *U : Users) { 8817 SDValue Dividend = U->getOperand(0); 8818 if (Dividend != FPOne) { 8819 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8820 Reciprocal, Flags); 8821 CombineTo(U, NewNode); 8822 } else if (U != Reciprocal.getNode()) { 8823 // In the absence of fast-math-flags, this user node is always the 8824 // same node as Reciprocal, but with FMF they may be different nodes. 8825 CombineTo(U, Reciprocal); 8826 } 8827 } 8828 return SDValue(N, 0); // N was replaced. 8829 } 8830 8831 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8832 SDValue N0 = N->getOperand(0); 8833 SDValue N1 = N->getOperand(1); 8834 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8835 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8836 EVT VT = N->getValueType(0); 8837 SDLoc DL(N); 8838 const TargetOptions &Options = DAG.getTarget().Options; 8839 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8840 8841 // fold vector ops 8842 if (VT.isVector()) 8843 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8844 return FoldedVOp; 8845 8846 // fold (fdiv c1, c2) -> c1/c2 8847 if (N0CFP && N1CFP) 8848 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8849 8850 if (Options.UnsafeFPMath) { 8851 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8852 if (N1CFP) { 8853 // Compute the reciprocal 1.0 / c2. 8854 const APFloat &N1APF = N1CFP->getValueAPF(); 8855 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8856 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8857 // Only do the transform if the reciprocal is a legal fp immediate that 8858 // isn't too nasty (eg NaN, denormal, ...). 8859 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8860 (!LegalOperations || 8861 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8862 // backend)... we should handle this gracefully after Legalize. 8863 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8864 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8865 TLI.isFPImmLegal(Recip, VT))) 8866 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8867 DAG.getConstantFP(Recip, DL, VT), Flags); 8868 } 8869 8870 // If this FDIV is part of a reciprocal square root, it may be folded 8871 // into a target-specific square root estimate instruction. 8872 if (N1.getOpcode() == ISD::FSQRT) { 8873 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 8874 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8875 } 8876 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8877 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8878 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8879 Flags)) { 8880 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8881 AddToWorklist(RV.getNode()); 8882 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8883 } 8884 } else if (N1.getOpcode() == ISD::FP_ROUND && 8885 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8886 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8887 Flags)) { 8888 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8889 AddToWorklist(RV.getNode()); 8890 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8891 } 8892 } else if (N1.getOpcode() == ISD::FMUL) { 8893 // Look through an FMUL. Even though this won't remove the FDIV directly, 8894 // it's still worthwhile to get rid of the FSQRT if possible. 8895 SDValue SqrtOp; 8896 SDValue OtherOp; 8897 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8898 SqrtOp = N1.getOperand(0); 8899 OtherOp = N1.getOperand(1); 8900 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8901 SqrtOp = N1.getOperand(1); 8902 OtherOp = N1.getOperand(0); 8903 } 8904 if (SqrtOp.getNode()) { 8905 // We found a FSQRT, so try to make this fold: 8906 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8907 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8908 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8909 AddToWorklist(RV.getNode()); 8910 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8911 } 8912 } 8913 } 8914 8915 // Fold into a reciprocal estimate and multiply instead of a real divide. 8916 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8917 AddToWorklist(RV.getNode()); 8918 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8919 } 8920 } 8921 8922 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8923 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8924 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8925 // Both can be negated for free, check to see if at least one is cheaper 8926 // negated. 8927 if (LHSNeg == 2 || RHSNeg == 2) 8928 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8929 GetNegatedExpression(N0, DAG, LegalOperations), 8930 GetNegatedExpression(N1, DAG, LegalOperations), 8931 Flags); 8932 } 8933 } 8934 8935 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8936 return CombineRepeatedDivisors; 8937 8938 return SDValue(); 8939 } 8940 8941 SDValue DAGCombiner::visitFREM(SDNode *N) { 8942 SDValue N0 = N->getOperand(0); 8943 SDValue N1 = N->getOperand(1); 8944 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8945 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8946 EVT VT = N->getValueType(0); 8947 8948 // fold (frem c1, c2) -> fmod(c1,c2) 8949 if (N0CFP && N1CFP) 8950 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8951 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8952 8953 return SDValue(); 8954 } 8955 8956 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8957 if (!DAG.getTarget().Options.UnsafeFPMath) 8958 return SDValue(); 8959 8960 SDValue N0 = N->getOperand(0); 8961 if (TLI.isFsqrtCheap(N0, DAG)) 8962 return SDValue(); 8963 8964 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8965 // For now, create a Flags object for use with all unsafe math transforms. 8966 SDNodeFlags Flags; 8967 Flags.setUnsafeAlgebra(true); 8968 return buildSqrtEstimate(N0, &Flags); 8969 } 8970 8971 /// copysign(x, fp_extend(y)) -> copysign(x, y) 8972 /// copysign(x, fp_round(y)) -> copysign(x, y) 8973 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 8974 SDValue N1 = N->getOperand(1); 8975 if ((N1.getOpcode() == ISD::FP_EXTEND || 8976 N1.getOpcode() == ISD::FP_ROUND)) { 8977 // Do not optimize out type conversion of f128 type yet. 8978 // For some targets like x86_64, configuration is changed to keep one f128 8979 // value in one SSE register, but instruction selection cannot handle 8980 // FCOPYSIGN on SSE registers yet. 8981 EVT N1VT = N1->getValueType(0); 8982 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 8983 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 8984 } 8985 return false; 8986 } 8987 8988 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8989 SDValue N0 = N->getOperand(0); 8990 SDValue N1 = N->getOperand(1); 8991 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8992 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8993 EVT VT = N->getValueType(0); 8994 8995 if (N0CFP && N1CFP) // Constant fold 8996 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8997 8998 if (N1CFP) { 8999 const APFloat& V = N1CFP->getValueAPF(); 9000 // copysign(x, c1) -> fabs(x) iff ispos(c1) 9001 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 9002 if (!V.isNegative()) { 9003 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 9004 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9005 } else { 9006 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 9007 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9008 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 9009 } 9010 } 9011 9012 // copysign(fabs(x), y) -> copysign(x, y) 9013 // copysign(fneg(x), y) -> copysign(x, y) 9014 // copysign(copysign(x,z), y) -> copysign(x, y) 9015 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 9016 N0.getOpcode() == ISD::FCOPYSIGN) 9017 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9018 N0.getOperand(0), N1); 9019 9020 // copysign(x, abs(y)) -> abs(x) 9021 if (N1.getOpcode() == ISD::FABS) 9022 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9023 9024 // copysign(x, copysign(y,z)) -> copysign(x, z) 9025 if (N1.getOpcode() == ISD::FCOPYSIGN) 9026 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9027 N0, N1.getOperand(1)); 9028 9029 // copysign(x, fp_extend(y)) -> copysign(x, y) 9030 // copysign(x, fp_round(y)) -> copysign(x, y) 9031 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 9032 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9033 N0, N1.getOperand(0)); 9034 9035 return SDValue(); 9036 } 9037 9038 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 9039 SDValue N0 = N->getOperand(0); 9040 EVT VT = N->getValueType(0); 9041 EVT OpVT = N0.getValueType(); 9042 9043 // fold (sint_to_fp c1) -> c1fp 9044 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9045 // ...but only if the target supports immediate floating-point values 9046 (!LegalOperations || 9047 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9048 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9049 9050 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 9051 // but UINT_TO_FP is legal on this target, try to convert. 9052 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 9053 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 9054 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 9055 if (DAG.SignBitIsZero(N0)) 9056 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9057 } 9058 9059 // The next optimizations are desirable only if SELECT_CC can be lowered. 9060 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9061 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9062 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 9063 !VT.isVector() && 9064 (!LegalOperations || 9065 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9066 SDLoc DL(N); 9067 SDValue Ops[] = 9068 { N0.getOperand(0), N0.getOperand(1), 9069 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9070 N0.getOperand(2) }; 9071 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9072 } 9073 9074 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 9075 // (select_cc x, y, 1.0, 0.0,, cc) 9076 if (N0.getOpcode() == ISD::ZERO_EXTEND && 9077 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 9078 (!LegalOperations || 9079 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9080 SDLoc DL(N); 9081 SDValue Ops[] = 9082 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 9083 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9084 N0.getOperand(0).getOperand(2) }; 9085 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9086 } 9087 } 9088 9089 return SDValue(); 9090 } 9091 9092 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 9093 SDValue N0 = N->getOperand(0); 9094 EVT VT = N->getValueType(0); 9095 EVT OpVT = N0.getValueType(); 9096 9097 // fold (uint_to_fp c1) -> c1fp 9098 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9099 // ...but only if the target supports immediate floating-point values 9100 (!LegalOperations || 9101 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9102 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9103 9104 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 9105 // but SINT_TO_FP is legal on this target, try to convert. 9106 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 9107 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 9108 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 9109 if (DAG.SignBitIsZero(N0)) 9110 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9111 } 9112 9113 // The next optimizations are desirable only if SELECT_CC can be lowered. 9114 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9115 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9116 9117 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 9118 (!LegalOperations || 9119 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9120 SDLoc DL(N); 9121 SDValue Ops[] = 9122 { N0.getOperand(0), N0.getOperand(1), 9123 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9124 N0.getOperand(2) }; 9125 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9126 } 9127 } 9128 9129 return SDValue(); 9130 } 9131 9132 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 9133 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 9134 SDValue N0 = N->getOperand(0); 9135 EVT VT = N->getValueType(0); 9136 9137 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 9138 return SDValue(); 9139 9140 SDValue Src = N0.getOperand(0); 9141 EVT SrcVT = Src.getValueType(); 9142 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 9143 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 9144 9145 // We can safely assume the conversion won't overflow the output range, 9146 // because (for example) (uint8_t)18293.f is undefined behavior. 9147 9148 // Since we can assume the conversion won't overflow, our decision as to 9149 // whether the input will fit in the float should depend on the minimum 9150 // of the input range and output range. 9151 9152 // This means this is also safe for a signed input and unsigned output, since 9153 // a negative input would lead to undefined behavior. 9154 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 9155 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9156 unsigned ActualSize = std::min(InputSize, OutputSize); 9157 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9158 9159 // We can only fold away the float conversion if the input range can be 9160 // represented exactly in the float range. 9161 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9162 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9163 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9164 : ISD::ZERO_EXTEND; 9165 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9166 } 9167 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9168 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9169 return DAG.getBitcast(VT, Src); 9170 } 9171 return SDValue(); 9172 } 9173 9174 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9175 SDValue N0 = N->getOperand(0); 9176 EVT VT = N->getValueType(0); 9177 9178 // fold (fp_to_sint c1fp) -> c1 9179 if (isConstantFPBuildVectorOrConstantFP(N0)) 9180 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9181 9182 return FoldIntToFPToInt(N, DAG); 9183 } 9184 9185 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9186 SDValue N0 = N->getOperand(0); 9187 EVT VT = N->getValueType(0); 9188 9189 // fold (fp_to_uint c1fp) -> c1 9190 if (isConstantFPBuildVectorOrConstantFP(N0)) 9191 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9192 9193 return FoldIntToFPToInt(N, DAG); 9194 } 9195 9196 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9197 SDValue N0 = N->getOperand(0); 9198 SDValue N1 = N->getOperand(1); 9199 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9200 EVT VT = N->getValueType(0); 9201 9202 // fold (fp_round c1fp) -> c1fp 9203 if (N0CFP) 9204 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9205 9206 // fold (fp_round (fp_extend x)) -> x 9207 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9208 return N0.getOperand(0); 9209 9210 // fold (fp_round (fp_round x)) -> (fp_round x) 9211 if (N0.getOpcode() == ISD::FP_ROUND) { 9212 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9213 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 9214 9215 // Skip this folding if it results in an fp_round from f80 to f16. 9216 // 9217 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9218 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9219 // instructions from f32 or f64. Moreover, the first (value-preserving) 9220 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9221 // x86. 9222 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9223 return SDValue(); 9224 9225 // If the first fp_round isn't a value preserving truncation, it might 9226 // introduce a tie in the second fp_round, that wouldn't occur in the 9227 // single-step fp_round we want to fold to. 9228 // In other words, double rounding isn't the same as rounding. 9229 // Also, this is a value preserving truncation iff both fp_round's are. 9230 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9231 SDLoc DL(N); 9232 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9233 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9234 } 9235 } 9236 9237 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9238 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9239 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9240 N0.getOperand(0), N1); 9241 AddToWorklist(Tmp.getNode()); 9242 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9243 Tmp, N0.getOperand(1)); 9244 } 9245 9246 return SDValue(); 9247 } 9248 9249 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9250 SDValue N0 = N->getOperand(0); 9251 EVT VT = N->getValueType(0); 9252 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9253 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9254 9255 // fold (fp_round_inreg c1fp) -> c1fp 9256 if (N0CFP && isTypeLegal(EVT)) { 9257 SDLoc DL(N); 9258 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9259 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9260 } 9261 9262 return SDValue(); 9263 } 9264 9265 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9266 SDValue N0 = N->getOperand(0); 9267 EVT VT = N->getValueType(0); 9268 9269 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9270 if (N->hasOneUse() && 9271 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9272 return SDValue(); 9273 9274 // fold (fp_extend c1fp) -> c1fp 9275 if (isConstantFPBuildVectorOrConstantFP(N0)) 9276 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9277 9278 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9279 if (N0.getOpcode() == ISD::FP16_TO_FP && 9280 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9281 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9282 9283 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9284 // value of X. 9285 if (N0.getOpcode() == ISD::FP_ROUND 9286 && N0.getNode()->getConstantOperandVal(1) == 1) { 9287 SDValue In = N0.getOperand(0); 9288 if (In.getValueType() == VT) return In; 9289 if (VT.bitsLT(In.getValueType())) 9290 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9291 In, N0.getOperand(1)); 9292 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9293 } 9294 9295 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9296 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9297 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9298 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9299 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9300 LN0->getChain(), 9301 LN0->getBasePtr(), N0.getValueType(), 9302 LN0->getMemOperand()); 9303 CombineTo(N, ExtLoad); 9304 CombineTo(N0.getNode(), 9305 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9306 N0.getValueType(), ExtLoad, 9307 DAG.getIntPtrConstant(1, SDLoc(N0))), 9308 ExtLoad.getValue(1)); 9309 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9310 } 9311 9312 return SDValue(); 9313 } 9314 9315 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9316 SDValue N0 = N->getOperand(0); 9317 EVT VT = N->getValueType(0); 9318 9319 // fold (fceil c1) -> fceil(c1) 9320 if (isConstantFPBuildVectorOrConstantFP(N0)) 9321 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9322 9323 return SDValue(); 9324 } 9325 9326 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9327 SDValue N0 = N->getOperand(0); 9328 EVT VT = N->getValueType(0); 9329 9330 // fold (ftrunc c1) -> ftrunc(c1) 9331 if (isConstantFPBuildVectorOrConstantFP(N0)) 9332 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9333 9334 return SDValue(); 9335 } 9336 9337 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9338 SDValue N0 = N->getOperand(0); 9339 EVT VT = N->getValueType(0); 9340 9341 // fold (ffloor c1) -> ffloor(c1) 9342 if (isConstantFPBuildVectorOrConstantFP(N0)) 9343 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9344 9345 return SDValue(); 9346 } 9347 9348 // FIXME: FNEG and FABS have a lot in common; refactor. 9349 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9350 SDValue N0 = N->getOperand(0); 9351 EVT VT = N->getValueType(0); 9352 9353 // Constant fold FNEG. 9354 if (isConstantFPBuildVectorOrConstantFP(N0)) 9355 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9356 9357 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9358 &DAG.getTarget().Options)) 9359 return GetNegatedExpression(N0, DAG, LegalOperations); 9360 9361 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9362 // constant pool values. 9363 if (!TLI.isFNegFree(VT) && 9364 N0.getOpcode() == ISD::BITCAST && 9365 N0.getNode()->hasOneUse()) { 9366 SDValue Int = N0.getOperand(0); 9367 EVT IntVT = Int.getValueType(); 9368 if (IntVT.isInteger() && !IntVT.isVector()) { 9369 APInt SignMask; 9370 if (N0.getValueType().isVector()) { 9371 // For a vector, get a mask such as 0x80... per scalar element 9372 // and splat it. 9373 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9374 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9375 } else { 9376 // For a scalar, just generate 0x80... 9377 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9378 } 9379 SDLoc DL0(N0); 9380 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9381 DAG.getConstant(SignMask, DL0, IntVT)); 9382 AddToWorklist(Int.getNode()); 9383 return DAG.getBitcast(VT, Int); 9384 } 9385 } 9386 9387 // (fneg (fmul c, x)) -> (fmul -c, x) 9388 if (N0.getOpcode() == ISD::FMUL && 9389 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9390 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9391 if (CFP1) { 9392 APFloat CVal = CFP1->getValueAPF(); 9393 CVal.changeSign(); 9394 if (Level >= AfterLegalizeDAG && 9395 (TLI.isFPImmLegal(CVal, VT) || 9396 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9397 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9398 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9399 N0.getOperand(1)), 9400 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9401 } 9402 } 9403 9404 return SDValue(); 9405 } 9406 9407 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9408 SDValue N0 = N->getOperand(0); 9409 SDValue N1 = N->getOperand(1); 9410 EVT VT = N->getValueType(0); 9411 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9412 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9413 9414 if (N0CFP && N1CFP) { 9415 const APFloat &C0 = N0CFP->getValueAPF(); 9416 const APFloat &C1 = N1CFP->getValueAPF(); 9417 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9418 } 9419 9420 // Canonicalize to constant on RHS. 9421 if (isConstantFPBuildVectorOrConstantFP(N0) && 9422 !isConstantFPBuildVectorOrConstantFP(N1)) 9423 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9424 9425 return SDValue(); 9426 } 9427 9428 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9429 SDValue N0 = N->getOperand(0); 9430 SDValue N1 = N->getOperand(1); 9431 EVT VT = N->getValueType(0); 9432 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9433 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9434 9435 if (N0CFP && N1CFP) { 9436 const APFloat &C0 = N0CFP->getValueAPF(); 9437 const APFloat &C1 = N1CFP->getValueAPF(); 9438 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9439 } 9440 9441 // Canonicalize to constant on RHS. 9442 if (isConstantFPBuildVectorOrConstantFP(N0) && 9443 !isConstantFPBuildVectorOrConstantFP(N1)) 9444 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9445 9446 return SDValue(); 9447 } 9448 9449 SDValue DAGCombiner::visitFABS(SDNode *N) { 9450 SDValue N0 = N->getOperand(0); 9451 EVT VT = N->getValueType(0); 9452 9453 // fold (fabs c1) -> fabs(c1) 9454 if (isConstantFPBuildVectorOrConstantFP(N0)) 9455 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9456 9457 // fold (fabs (fabs x)) -> (fabs x) 9458 if (N0.getOpcode() == ISD::FABS) 9459 return N->getOperand(0); 9460 9461 // fold (fabs (fneg x)) -> (fabs x) 9462 // fold (fabs (fcopysign x, y)) -> (fabs x) 9463 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9464 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9465 9466 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9467 // constant pool values. 9468 if (!TLI.isFAbsFree(VT) && 9469 N0.getOpcode() == ISD::BITCAST && 9470 N0.getNode()->hasOneUse()) { 9471 SDValue Int = N0.getOperand(0); 9472 EVT IntVT = Int.getValueType(); 9473 if (IntVT.isInteger() && !IntVT.isVector()) { 9474 APInt SignMask; 9475 if (N0.getValueType().isVector()) { 9476 // For a vector, get a mask such as 0x7f... per scalar element 9477 // and splat it. 9478 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9479 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9480 } else { 9481 // For a scalar, just generate 0x7f... 9482 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9483 } 9484 SDLoc DL(N0); 9485 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9486 DAG.getConstant(SignMask, DL, IntVT)); 9487 AddToWorklist(Int.getNode()); 9488 return DAG.getBitcast(N->getValueType(0), Int); 9489 } 9490 } 9491 9492 return SDValue(); 9493 } 9494 9495 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9496 SDValue Chain = N->getOperand(0); 9497 SDValue N1 = N->getOperand(1); 9498 SDValue N2 = N->getOperand(2); 9499 9500 // If N is a constant we could fold this into a fallthrough or unconditional 9501 // branch. However that doesn't happen very often in normal code, because 9502 // Instcombine/SimplifyCFG should have handled the available opportunities. 9503 // If we did this folding here, it would be necessary to update the 9504 // MachineBasicBlock CFG, which is awkward. 9505 9506 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9507 // on the target. 9508 if (N1.getOpcode() == ISD::SETCC && 9509 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9510 N1.getOperand(0).getValueType())) { 9511 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9512 Chain, N1.getOperand(2), 9513 N1.getOperand(0), N1.getOperand(1), N2); 9514 } 9515 9516 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9517 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9518 (N1.getOperand(0).hasOneUse() && 9519 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9520 SDNode *Trunc = nullptr; 9521 if (N1.getOpcode() == ISD::TRUNCATE) { 9522 // Look pass the truncate. 9523 Trunc = N1.getNode(); 9524 N1 = N1.getOperand(0); 9525 } 9526 9527 // Match this pattern so that we can generate simpler code: 9528 // 9529 // %a = ... 9530 // %b = and i32 %a, 2 9531 // %c = srl i32 %b, 1 9532 // brcond i32 %c ... 9533 // 9534 // into 9535 // 9536 // %a = ... 9537 // %b = and i32 %a, 2 9538 // %c = setcc eq %b, 0 9539 // brcond %c ... 9540 // 9541 // This applies only when the AND constant value has one bit set and the 9542 // SRL constant is equal to the log2 of the AND constant. The back-end is 9543 // smart enough to convert the result into a TEST/JMP sequence. 9544 SDValue Op0 = N1.getOperand(0); 9545 SDValue Op1 = N1.getOperand(1); 9546 9547 if (Op0.getOpcode() == ISD::AND && 9548 Op1.getOpcode() == ISD::Constant) { 9549 SDValue AndOp1 = Op0.getOperand(1); 9550 9551 if (AndOp1.getOpcode() == ISD::Constant) { 9552 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9553 9554 if (AndConst.isPowerOf2() && 9555 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9556 SDLoc DL(N); 9557 SDValue SetCC = 9558 DAG.getSetCC(DL, 9559 getSetCCResultType(Op0.getValueType()), 9560 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9561 ISD::SETNE); 9562 9563 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9564 MVT::Other, Chain, SetCC, N2); 9565 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9566 // will convert it back to (X & C1) >> C2. 9567 CombineTo(N, NewBRCond, false); 9568 // Truncate is dead. 9569 if (Trunc) 9570 deleteAndRecombine(Trunc); 9571 // Replace the uses of SRL with SETCC 9572 WorklistRemover DeadNodes(*this); 9573 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9574 deleteAndRecombine(N1.getNode()); 9575 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9576 } 9577 } 9578 } 9579 9580 if (Trunc) 9581 // Restore N1 if the above transformation doesn't match. 9582 N1 = N->getOperand(1); 9583 } 9584 9585 // Transform br(xor(x, y)) -> br(x != y) 9586 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9587 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9588 SDNode *TheXor = N1.getNode(); 9589 SDValue Op0 = TheXor->getOperand(0); 9590 SDValue Op1 = TheXor->getOperand(1); 9591 if (Op0.getOpcode() == Op1.getOpcode()) { 9592 // Avoid missing important xor optimizations. 9593 if (SDValue Tmp = visitXOR(TheXor)) { 9594 if (Tmp.getNode() != TheXor) { 9595 DEBUG(dbgs() << "\nReplacing.8 "; 9596 TheXor->dump(&DAG); 9597 dbgs() << "\nWith: "; 9598 Tmp.getNode()->dump(&DAG); 9599 dbgs() << '\n'); 9600 WorklistRemover DeadNodes(*this); 9601 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9602 deleteAndRecombine(TheXor); 9603 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9604 MVT::Other, Chain, Tmp, N2); 9605 } 9606 9607 // visitXOR has changed XOR's operands or replaced the XOR completely, 9608 // bail out. 9609 return SDValue(N, 0); 9610 } 9611 } 9612 9613 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9614 bool Equal = false; 9615 if (isOneConstant(Op0) && Op0.hasOneUse() && 9616 Op0.getOpcode() == ISD::XOR) { 9617 TheXor = Op0.getNode(); 9618 Equal = true; 9619 } 9620 9621 EVT SetCCVT = N1.getValueType(); 9622 if (LegalTypes) 9623 SetCCVT = getSetCCResultType(SetCCVT); 9624 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9625 SetCCVT, 9626 Op0, Op1, 9627 Equal ? ISD::SETEQ : ISD::SETNE); 9628 // Replace the uses of XOR with SETCC 9629 WorklistRemover DeadNodes(*this); 9630 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9631 deleteAndRecombine(N1.getNode()); 9632 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9633 MVT::Other, Chain, SetCC, N2); 9634 } 9635 } 9636 9637 return SDValue(); 9638 } 9639 9640 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9641 // 9642 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9643 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9644 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9645 9646 // If N is a constant we could fold this into a fallthrough or unconditional 9647 // branch. However that doesn't happen very often in normal code, because 9648 // Instcombine/SimplifyCFG should have handled the available opportunities. 9649 // If we did this folding here, it would be necessary to update the 9650 // MachineBasicBlock CFG, which is awkward. 9651 9652 // Use SimplifySetCC to simplify SETCC's. 9653 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9654 CondLHS, CondRHS, CC->get(), SDLoc(N), 9655 false); 9656 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9657 9658 // fold to a simpler setcc 9659 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9660 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9661 N->getOperand(0), Simp.getOperand(2), 9662 Simp.getOperand(0), Simp.getOperand(1), 9663 N->getOperand(4)); 9664 9665 return SDValue(); 9666 } 9667 9668 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9669 /// and that N may be folded in the load / store addressing mode. 9670 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9671 SelectionDAG &DAG, 9672 const TargetLowering &TLI) { 9673 EVT VT; 9674 unsigned AS; 9675 9676 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9677 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9678 return false; 9679 VT = LD->getMemoryVT(); 9680 AS = LD->getAddressSpace(); 9681 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9682 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9683 return false; 9684 VT = ST->getMemoryVT(); 9685 AS = ST->getAddressSpace(); 9686 } else 9687 return false; 9688 9689 TargetLowering::AddrMode AM; 9690 if (N->getOpcode() == ISD::ADD) { 9691 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9692 if (Offset) 9693 // [reg +/- imm] 9694 AM.BaseOffs = Offset->getSExtValue(); 9695 else 9696 // [reg +/- reg] 9697 AM.Scale = 1; 9698 } else if (N->getOpcode() == ISD::SUB) { 9699 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9700 if (Offset) 9701 // [reg +/- imm] 9702 AM.BaseOffs = -Offset->getSExtValue(); 9703 else 9704 // [reg +/- reg] 9705 AM.Scale = 1; 9706 } else 9707 return false; 9708 9709 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9710 VT.getTypeForEVT(*DAG.getContext()), AS); 9711 } 9712 9713 /// Try turning a load/store into a pre-indexed load/store when the base 9714 /// pointer is an add or subtract and it has other uses besides the load/store. 9715 /// After the transformation, the new indexed load/store has effectively folded 9716 /// the add/subtract in and all of its other uses are redirected to the 9717 /// new load/store. 9718 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9719 if (Level < AfterLegalizeDAG) 9720 return false; 9721 9722 bool isLoad = true; 9723 SDValue Ptr; 9724 EVT VT; 9725 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9726 if (LD->isIndexed()) 9727 return false; 9728 VT = LD->getMemoryVT(); 9729 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9730 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9731 return false; 9732 Ptr = LD->getBasePtr(); 9733 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9734 if (ST->isIndexed()) 9735 return false; 9736 VT = ST->getMemoryVT(); 9737 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9738 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9739 return false; 9740 Ptr = ST->getBasePtr(); 9741 isLoad = false; 9742 } else { 9743 return false; 9744 } 9745 9746 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9747 // out. There is no reason to make this a preinc/predec. 9748 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9749 Ptr.getNode()->hasOneUse()) 9750 return false; 9751 9752 // Ask the target to do addressing mode selection. 9753 SDValue BasePtr; 9754 SDValue Offset; 9755 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9756 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9757 return false; 9758 9759 // Backends without true r+i pre-indexed forms may need to pass a 9760 // constant base with a variable offset so that constant coercion 9761 // will work with the patterns in canonical form. 9762 bool Swapped = false; 9763 if (isa<ConstantSDNode>(BasePtr)) { 9764 std::swap(BasePtr, Offset); 9765 Swapped = true; 9766 } 9767 9768 // Don't create a indexed load / store with zero offset. 9769 if (isNullConstant(Offset)) 9770 return false; 9771 9772 // Try turning it into a pre-indexed load / store except when: 9773 // 1) The new base ptr is a frame index. 9774 // 2) If N is a store and the new base ptr is either the same as or is a 9775 // predecessor of the value being stored. 9776 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9777 // that would create a cycle. 9778 // 4) All uses are load / store ops that use it as old base ptr. 9779 9780 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9781 // (plus the implicit offset) to a register to preinc anyway. 9782 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9783 return false; 9784 9785 // Check #2. 9786 if (!isLoad) { 9787 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9788 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9789 return false; 9790 } 9791 9792 // Caches for hasPredecessorHelper. 9793 SmallPtrSet<const SDNode *, 32> Visited; 9794 SmallVector<const SDNode *, 16> Worklist; 9795 Worklist.push_back(N); 9796 9797 // If the offset is a constant, there may be other adds of constants that 9798 // can be folded with this one. We should do this to avoid having to keep 9799 // a copy of the original base pointer. 9800 SmallVector<SDNode *, 16> OtherUses; 9801 if (isa<ConstantSDNode>(Offset)) 9802 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9803 UE = BasePtr.getNode()->use_end(); 9804 UI != UE; ++UI) { 9805 SDUse &Use = UI.getUse(); 9806 // Skip the use that is Ptr and uses of other results from BasePtr's 9807 // node (important for nodes that return multiple results). 9808 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9809 continue; 9810 9811 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 9812 continue; 9813 9814 if (Use.getUser()->getOpcode() != ISD::ADD && 9815 Use.getUser()->getOpcode() != ISD::SUB) { 9816 OtherUses.clear(); 9817 break; 9818 } 9819 9820 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9821 if (!isa<ConstantSDNode>(Op1)) { 9822 OtherUses.clear(); 9823 break; 9824 } 9825 9826 // FIXME: In some cases, we can be smarter about this. 9827 if (Op1.getValueType() != Offset.getValueType()) { 9828 OtherUses.clear(); 9829 break; 9830 } 9831 9832 OtherUses.push_back(Use.getUser()); 9833 } 9834 9835 if (Swapped) 9836 std::swap(BasePtr, Offset); 9837 9838 // Now check for #3 and #4. 9839 bool RealUse = false; 9840 9841 for (SDNode *Use : Ptr.getNode()->uses()) { 9842 if (Use == N) 9843 continue; 9844 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 9845 return false; 9846 9847 // If Ptr may be folded in addressing mode of other use, then it's 9848 // not profitable to do this transformation. 9849 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9850 RealUse = true; 9851 } 9852 9853 if (!RealUse) 9854 return false; 9855 9856 SDValue Result; 9857 if (isLoad) 9858 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9859 BasePtr, Offset, AM); 9860 else 9861 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9862 BasePtr, Offset, AM); 9863 ++PreIndexedNodes; 9864 ++NodesCombined; 9865 DEBUG(dbgs() << "\nReplacing.4 "; 9866 N->dump(&DAG); 9867 dbgs() << "\nWith: "; 9868 Result.getNode()->dump(&DAG); 9869 dbgs() << '\n'); 9870 WorklistRemover DeadNodes(*this); 9871 if (isLoad) { 9872 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9873 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9874 } else { 9875 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9876 } 9877 9878 // Finally, since the node is now dead, remove it from the graph. 9879 deleteAndRecombine(N); 9880 9881 if (Swapped) 9882 std::swap(BasePtr, Offset); 9883 9884 // Replace other uses of BasePtr that can be updated to use Ptr 9885 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9886 unsigned OffsetIdx = 1; 9887 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9888 OffsetIdx = 0; 9889 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9890 BasePtr.getNode() && "Expected BasePtr operand"); 9891 9892 // We need to replace ptr0 in the following expression: 9893 // x0 * offset0 + y0 * ptr0 = t0 9894 // knowing that 9895 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9896 // 9897 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9898 // indexed load/store and the expresion that needs to be re-written. 9899 // 9900 // Therefore, we have: 9901 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9902 9903 ConstantSDNode *CN = 9904 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9905 int X0, X1, Y0, Y1; 9906 const APInt &Offset0 = CN->getAPIntValue(); 9907 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9908 9909 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9910 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9911 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9912 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9913 9914 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9915 9916 APInt CNV = Offset0; 9917 if (X0 < 0) CNV = -CNV; 9918 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9919 else CNV = CNV - Offset1; 9920 9921 SDLoc DL(OtherUses[i]); 9922 9923 // We can now generate the new expression. 9924 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9925 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9926 9927 SDValue NewUse = DAG.getNode(Opcode, 9928 DL, 9929 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9930 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9931 deleteAndRecombine(OtherUses[i]); 9932 } 9933 9934 // Replace the uses of Ptr with uses of the updated base value. 9935 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9936 deleteAndRecombine(Ptr.getNode()); 9937 9938 return true; 9939 } 9940 9941 /// Try to combine a load/store with a add/sub of the base pointer node into a 9942 /// post-indexed load/store. The transformation folded the add/subtract into the 9943 /// new indexed load/store effectively and all of its uses are redirected to the 9944 /// new load/store. 9945 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9946 if (Level < AfterLegalizeDAG) 9947 return false; 9948 9949 bool isLoad = true; 9950 SDValue Ptr; 9951 EVT VT; 9952 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9953 if (LD->isIndexed()) 9954 return false; 9955 VT = LD->getMemoryVT(); 9956 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9957 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9958 return false; 9959 Ptr = LD->getBasePtr(); 9960 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9961 if (ST->isIndexed()) 9962 return false; 9963 VT = ST->getMemoryVT(); 9964 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9965 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9966 return false; 9967 Ptr = ST->getBasePtr(); 9968 isLoad = false; 9969 } else { 9970 return false; 9971 } 9972 9973 if (Ptr.getNode()->hasOneUse()) 9974 return false; 9975 9976 for (SDNode *Op : Ptr.getNode()->uses()) { 9977 if (Op == N || 9978 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9979 continue; 9980 9981 SDValue BasePtr; 9982 SDValue Offset; 9983 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9984 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9985 // Don't create a indexed load / store with zero offset. 9986 if (isNullConstant(Offset)) 9987 continue; 9988 9989 // Try turning it into a post-indexed load / store except when 9990 // 1) All uses are load / store ops that use it as base ptr (and 9991 // it may be folded as addressing mmode). 9992 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9993 // nor a successor of N. Otherwise, if Op is folded that would 9994 // create a cycle. 9995 9996 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9997 continue; 9998 9999 // Check for #1. 10000 bool TryNext = false; 10001 for (SDNode *Use : BasePtr.getNode()->uses()) { 10002 if (Use == Ptr.getNode()) 10003 continue; 10004 10005 // If all the uses are load / store addresses, then don't do the 10006 // transformation. 10007 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 10008 bool RealUse = false; 10009 for (SDNode *UseUse : Use->uses()) { 10010 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 10011 RealUse = true; 10012 } 10013 10014 if (!RealUse) { 10015 TryNext = true; 10016 break; 10017 } 10018 } 10019 } 10020 10021 if (TryNext) 10022 continue; 10023 10024 // Check for #2 10025 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 10026 SDValue Result = isLoad 10027 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 10028 BasePtr, Offset, AM) 10029 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 10030 BasePtr, Offset, AM); 10031 ++PostIndexedNodes; 10032 ++NodesCombined; 10033 DEBUG(dbgs() << "\nReplacing.5 "; 10034 N->dump(&DAG); 10035 dbgs() << "\nWith: "; 10036 Result.getNode()->dump(&DAG); 10037 dbgs() << '\n'); 10038 WorklistRemover DeadNodes(*this); 10039 if (isLoad) { 10040 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10041 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10042 } else { 10043 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10044 } 10045 10046 // Finally, since the node is now dead, remove it from the graph. 10047 deleteAndRecombine(N); 10048 10049 // Replace the uses of Use with uses of the updated base value. 10050 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 10051 Result.getValue(isLoad ? 1 : 0)); 10052 deleteAndRecombine(Op); 10053 return true; 10054 } 10055 } 10056 } 10057 10058 return false; 10059 } 10060 10061 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 10062 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 10063 ISD::MemIndexedMode AM = LD->getAddressingMode(); 10064 assert(AM != ISD::UNINDEXED); 10065 SDValue BP = LD->getOperand(1); 10066 SDValue Inc = LD->getOperand(2); 10067 10068 // Some backends use TargetConstants for load offsets, but don't expect 10069 // TargetConstants in general ADD nodes. We can convert these constants into 10070 // regular Constants (if the constant is not opaque). 10071 assert((Inc.getOpcode() != ISD::TargetConstant || 10072 !cast<ConstantSDNode>(Inc)->isOpaque()) && 10073 "Cannot split out indexing using opaque target constants"); 10074 if (Inc.getOpcode() == ISD::TargetConstant) { 10075 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 10076 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 10077 ConstInc->getValueType(0)); 10078 } 10079 10080 unsigned Opc = 10081 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 10082 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 10083 } 10084 10085 SDValue DAGCombiner::visitLOAD(SDNode *N) { 10086 LoadSDNode *LD = cast<LoadSDNode>(N); 10087 SDValue Chain = LD->getChain(); 10088 SDValue Ptr = LD->getBasePtr(); 10089 10090 // If load is not volatile and there are no uses of the loaded value (and 10091 // the updated indexed value in case of indexed loads), change uses of the 10092 // chain value into uses of the chain input (i.e. delete the dead load). 10093 if (!LD->isVolatile()) { 10094 if (N->getValueType(1) == MVT::Other) { 10095 // Unindexed loads. 10096 if (!N->hasAnyUseOfValue(0)) { 10097 // It's not safe to use the two value CombineTo variant here. e.g. 10098 // v1, chain2 = load chain1, loc 10099 // v2, chain3 = load chain2, loc 10100 // v3 = add v2, c 10101 // Now we replace use of chain2 with chain1. This makes the second load 10102 // isomorphic to the one we are deleting, and thus makes this load live. 10103 DEBUG(dbgs() << "\nReplacing.6 "; 10104 N->dump(&DAG); 10105 dbgs() << "\nWith chain: "; 10106 Chain.getNode()->dump(&DAG); 10107 dbgs() << "\n"); 10108 WorklistRemover DeadNodes(*this); 10109 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10110 10111 if (N->use_empty()) 10112 deleteAndRecombine(N); 10113 10114 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10115 } 10116 } else { 10117 // Indexed loads. 10118 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 10119 10120 // If this load has an opaque TargetConstant offset, then we cannot split 10121 // the indexing into an add/sub directly (that TargetConstant may not be 10122 // valid for a different type of node, and we cannot convert an opaque 10123 // target constant into a regular constant). 10124 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 10125 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 10126 10127 if (!N->hasAnyUseOfValue(0) && 10128 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 10129 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 10130 SDValue Index; 10131 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 10132 Index = SplitIndexingFromLoad(LD); 10133 // Try to fold the base pointer arithmetic into subsequent loads and 10134 // stores. 10135 AddUsersToWorklist(N); 10136 } else 10137 Index = DAG.getUNDEF(N->getValueType(1)); 10138 DEBUG(dbgs() << "\nReplacing.7 "; 10139 N->dump(&DAG); 10140 dbgs() << "\nWith: "; 10141 Undef.getNode()->dump(&DAG); 10142 dbgs() << " and 2 other values\n"); 10143 WorklistRemover DeadNodes(*this); 10144 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 10145 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 10146 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 10147 deleteAndRecombine(N); 10148 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10149 } 10150 } 10151 } 10152 10153 // If this load is directly stored, replace the load value with the stored 10154 // value. 10155 // TODO: Handle store large -> read small portion. 10156 // TODO: Handle TRUNCSTORE/LOADEXT 10157 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 10158 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10159 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10160 if (PrevST->getBasePtr() == Ptr && 10161 PrevST->getValue().getValueType() == N->getValueType(0)) 10162 return CombineTo(N, Chain.getOperand(1), Chain); 10163 } 10164 } 10165 10166 // Try to infer better alignment information than the load already has. 10167 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10168 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10169 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10170 SDValue NewLoad = DAG.getExtLoad( 10171 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 10172 LD->getPointerInfo(), LD->getMemoryVT(), Align, 10173 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10174 if (NewLoad.getNode() != N) 10175 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10176 } 10177 } 10178 } 10179 10180 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10181 : DAG.getSubtarget().useAA(); 10182 #ifndef NDEBUG 10183 if (CombinerAAOnlyFunc.getNumOccurrences() && 10184 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10185 UseAA = false; 10186 #endif 10187 if (UseAA && LD->isUnindexed()) { 10188 // Walk up chain skipping non-aliasing memory nodes. 10189 SDValue BetterChain = FindBetterChain(N, Chain); 10190 10191 // If there is a better chain. 10192 if (Chain != BetterChain) { 10193 SDValue ReplLoad; 10194 10195 // Replace the chain to void dependency. 10196 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10197 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10198 BetterChain, Ptr, LD->getMemOperand()); 10199 } else { 10200 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10201 LD->getValueType(0), 10202 BetterChain, Ptr, LD->getMemoryVT(), 10203 LD->getMemOperand()); 10204 } 10205 10206 // Create token factor to keep old chain connected. 10207 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10208 MVT::Other, Chain, ReplLoad.getValue(1)); 10209 10210 // Make sure the new and old chains are cleaned up. 10211 AddToWorklist(Token.getNode()); 10212 10213 // Replace uses with load result and token factor. Don't add users 10214 // to work list. 10215 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10216 } 10217 } 10218 10219 // Try transforming N to an indexed load. 10220 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10221 return SDValue(N, 0); 10222 10223 // Try to slice up N to more direct loads if the slices are mapped to 10224 // different register banks or pairing can take place. 10225 if (SliceUpLoad(N)) 10226 return SDValue(N, 0); 10227 10228 return SDValue(); 10229 } 10230 10231 namespace { 10232 /// \brief Helper structure used to slice a load in smaller loads. 10233 /// Basically a slice is obtained from the following sequence: 10234 /// Origin = load Ty1, Base 10235 /// Shift = srl Ty1 Origin, CstTy Amount 10236 /// Inst = trunc Shift to Ty2 10237 /// 10238 /// Then, it will be rewriten into: 10239 /// Slice = load SliceTy, Base + SliceOffset 10240 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10241 /// 10242 /// SliceTy is deduced from the number of bits that are actually used to 10243 /// build Inst. 10244 struct LoadedSlice { 10245 /// \brief Helper structure used to compute the cost of a slice. 10246 struct Cost { 10247 /// Are we optimizing for code size. 10248 bool ForCodeSize; 10249 /// Various cost. 10250 unsigned Loads; 10251 unsigned Truncates; 10252 unsigned CrossRegisterBanksCopies; 10253 unsigned ZExts; 10254 unsigned Shift; 10255 10256 Cost(bool ForCodeSize = false) 10257 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10258 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10259 10260 /// \brief Get the cost of one isolated slice. 10261 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10262 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10263 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10264 EVT TruncType = LS.Inst->getValueType(0); 10265 EVT LoadedType = LS.getLoadedType(); 10266 if (TruncType != LoadedType && 10267 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10268 ZExts = 1; 10269 } 10270 10271 /// \brief Account for slicing gain in the current cost. 10272 /// Slicing provide a few gains like removing a shift or a 10273 /// truncate. This method allows to grow the cost of the original 10274 /// load with the gain from this slice. 10275 void addSliceGain(const LoadedSlice &LS) { 10276 // Each slice saves a truncate. 10277 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10278 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10279 LS.Inst->getValueType(0))) 10280 ++Truncates; 10281 // If there is a shift amount, this slice gets rid of it. 10282 if (LS.Shift) 10283 ++Shift; 10284 // If this slice can merge a cross register bank copy, account for it. 10285 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10286 ++CrossRegisterBanksCopies; 10287 } 10288 10289 Cost &operator+=(const Cost &RHS) { 10290 Loads += RHS.Loads; 10291 Truncates += RHS.Truncates; 10292 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10293 ZExts += RHS.ZExts; 10294 Shift += RHS.Shift; 10295 return *this; 10296 } 10297 10298 bool operator==(const Cost &RHS) const { 10299 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10300 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10301 ZExts == RHS.ZExts && Shift == RHS.Shift; 10302 } 10303 10304 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10305 10306 bool operator<(const Cost &RHS) const { 10307 // Assume cross register banks copies are as expensive as loads. 10308 // FIXME: Do we want some more target hooks? 10309 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10310 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10311 // Unless we are optimizing for code size, consider the 10312 // expensive operation first. 10313 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10314 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10315 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10316 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10317 } 10318 10319 bool operator>(const Cost &RHS) const { return RHS < *this; } 10320 10321 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10322 10323 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10324 }; 10325 // The last instruction that represent the slice. This should be a 10326 // truncate instruction. 10327 SDNode *Inst; 10328 // The original load instruction. 10329 LoadSDNode *Origin; 10330 // The right shift amount in bits from the original load. 10331 unsigned Shift; 10332 // The DAG from which Origin came from. 10333 // This is used to get some contextual information about legal types, etc. 10334 SelectionDAG *DAG; 10335 10336 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10337 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10338 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10339 10340 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10341 /// \return Result is \p BitWidth and has used bits set to 1 and 10342 /// not used bits set to 0. 10343 APInt getUsedBits() const { 10344 // Reproduce the trunc(lshr) sequence: 10345 // - Start from the truncated value. 10346 // - Zero extend to the desired bit width. 10347 // - Shift left. 10348 assert(Origin && "No original load to compare against."); 10349 unsigned BitWidth = Origin->getValueSizeInBits(0); 10350 assert(Inst && "This slice is not bound to an instruction"); 10351 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10352 "Extracted slice is bigger than the whole type!"); 10353 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10354 UsedBits.setAllBits(); 10355 UsedBits = UsedBits.zext(BitWidth); 10356 UsedBits <<= Shift; 10357 return UsedBits; 10358 } 10359 10360 /// \brief Get the size of the slice to be loaded in bytes. 10361 unsigned getLoadedSize() const { 10362 unsigned SliceSize = getUsedBits().countPopulation(); 10363 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10364 return SliceSize / 8; 10365 } 10366 10367 /// \brief Get the type that will be loaded for this slice. 10368 /// Note: This may not be the final type for the slice. 10369 EVT getLoadedType() const { 10370 assert(DAG && "Missing context"); 10371 LLVMContext &Ctxt = *DAG->getContext(); 10372 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10373 } 10374 10375 /// \brief Get the alignment of the load used for this slice. 10376 unsigned getAlignment() const { 10377 unsigned Alignment = Origin->getAlignment(); 10378 unsigned Offset = getOffsetFromBase(); 10379 if (Offset != 0) 10380 Alignment = MinAlign(Alignment, Alignment + Offset); 10381 return Alignment; 10382 } 10383 10384 /// \brief Check if this slice can be rewritten with legal operations. 10385 bool isLegal() const { 10386 // An invalid slice is not legal. 10387 if (!Origin || !Inst || !DAG) 10388 return false; 10389 10390 // Offsets are for indexed load only, we do not handle that. 10391 if (!Origin->getOffset().isUndef()) 10392 return false; 10393 10394 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10395 10396 // Check that the type is legal. 10397 EVT SliceType = getLoadedType(); 10398 if (!TLI.isTypeLegal(SliceType)) 10399 return false; 10400 10401 // Check that the load is legal for this type. 10402 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10403 return false; 10404 10405 // Check that the offset can be computed. 10406 // 1. Check its type. 10407 EVT PtrType = Origin->getBasePtr().getValueType(); 10408 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10409 return false; 10410 10411 // 2. Check that it fits in the immediate. 10412 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10413 return false; 10414 10415 // 3. Check that the computation is legal. 10416 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10417 return false; 10418 10419 // Check that the zext is legal if it needs one. 10420 EVT TruncateType = Inst->getValueType(0); 10421 if (TruncateType != SliceType && 10422 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10423 return false; 10424 10425 return true; 10426 } 10427 10428 /// \brief Get the offset in bytes of this slice in the original chunk of 10429 /// bits. 10430 /// \pre DAG != nullptr. 10431 uint64_t getOffsetFromBase() const { 10432 assert(DAG && "Missing context."); 10433 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10434 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10435 uint64_t Offset = Shift / 8; 10436 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10437 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10438 "The size of the original loaded type is not a multiple of a" 10439 " byte."); 10440 // If Offset is bigger than TySizeInBytes, it means we are loading all 10441 // zeros. This should have been optimized before in the process. 10442 assert(TySizeInBytes > Offset && 10443 "Invalid shift amount for given loaded size"); 10444 if (IsBigEndian) 10445 Offset = TySizeInBytes - Offset - getLoadedSize(); 10446 return Offset; 10447 } 10448 10449 /// \brief Generate the sequence of instructions to load the slice 10450 /// represented by this object and redirect the uses of this slice to 10451 /// this new sequence of instructions. 10452 /// \pre this->Inst && this->Origin are valid Instructions and this 10453 /// object passed the legal check: LoadedSlice::isLegal returned true. 10454 /// \return The last instruction of the sequence used to load the slice. 10455 SDValue loadSlice() const { 10456 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10457 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10458 SDValue BaseAddr = OldBaseAddr; 10459 // Get the offset in that chunk of bytes w.r.t. the endianess. 10460 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10461 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10462 if (Offset) { 10463 // BaseAddr = BaseAddr + Offset. 10464 EVT ArithType = BaseAddr.getValueType(); 10465 SDLoc DL(Origin); 10466 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10467 DAG->getConstant(Offset, DL, ArithType)); 10468 } 10469 10470 // Create the type of the loaded slice according to its size. 10471 EVT SliceType = getLoadedType(); 10472 10473 // Create the load for the slice. 10474 SDValue LastInst = 10475 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10476 Origin->getPointerInfo().getWithOffset(Offset), 10477 getAlignment(), Origin->getMemOperand()->getFlags()); 10478 // If the final type is not the same as the loaded type, this means that 10479 // we have to pad with zero. Create a zero extend for that. 10480 EVT FinalType = Inst->getValueType(0); 10481 if (SliceType != FinalType) 10482 LastInst = 10483 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10484 return LastInst; 10485 } 10486 10487 /// \brief Check if this slice can be merged with an expensive cross register 10488 /// bank copy. E.g., 10489 /// i = load i32 10490 /// f = bitcast i32 i to float 10491 bool canMergeExpensiveCrossRegisterBankCopy() const { 10492 if (!Inst || !Inst->hasOneUse()) 10493 return false; 10494 SDNode *Use = *Inst->use_begin(); 10495 if (Use->getOpcode() != ISD::BITCAST) 10496 return false; 10497 assert(DAG && "Missing context"); 10498 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10499 EVT ResVT = Use->getValueType(0); 10500 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10501 const TargetRegisterClass *ArgRC = 10502 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10503 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10504 return false; 10505 10506 // At this point, we know that we perform a cross-register-bank copy. 10507 // Check if it is expensive. 10508 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10509 // Assume bitcasts are cheap, unless both register classes do not 10510 // explicitly share a common sub class. 10511 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10512 return false; 10513 10514 // Check if it will be merged with the load. 10515 // 1. Check the alignment constraint. 10516 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10517 ResVT.getTypeForEVT(*DAG->getContext())); 10518 10519 if (RequiredAlignment > getAlignment()) 10520 return false; 10521 10522 // 2. Check that the load is a legal operation for that type. 10523 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10524 return false; 10525 10526 // 3. Check that we do not have a zext in the way. 10527 if (Inst->getValueType(0) != getLoadedType()) 10528 return false; 10529 10530 return true; 10531 } 10532 }; 10533 } 10534 10535 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10536 /// \p UsedBits looks like 0..0 1..1 0..0. 10537 static bool areUsedBitsDense(const APInt &UsedBits) { 10538 // If all the bits are one, this is dense! 10539 if (UsedBits.isAllOnesValue()) 10540 return true; 10541 10542 // Get rid of the unused bits on the right. 10543 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10544 // Get rid of the unused bits on the left. 10545 if (NarrowedUsedBits.countLeadingZeros()) 10546 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10547 // Check that the chunk of bits is completely used. 10548 return NarrowedUsedBits.isAllOnesValue(); 10549 } 10550 10551 /// \brief Check whether or not \p First and \p Second are next to each other 10552 /// in memory. This means that there is no hole between the bits loaded 10553 /// by \p First and the bits loaded by \p Second. 10554 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10555 const LoadedSlice &Second) { 10556 assert(First.Origin == Second.Origin && First.Origin && 10557 "Unable to match different memory origins."); 10558 APInt UsedBits = First.getUsedBits(); 10559 assert((UsedBits & Second.getUsedBits()) == 0 && 10560 "Slices are not supposed to overlap."); 10561 UsedBits |= Second.getUsedBits(); 10562 return areUsedBitsDense(UsedBits); 10563 } 10564 10565 /// \brief Adjust the \p GlobalLSCost according to the target 10566 /// paring capabilities and the layout of the slices. 10567 /// \pre \p GlobalLSCost should account for at least as many loads as 10568 /// there is in the slices in \p LoadedSlices. 10569 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10570 LoadedSlice::Cost &GlobalLSCost) { 10571 unsigned NumberOfSlices = LoadedSlices.size(); 10572 // If there is less than 2 elements, no pairing is possible. 10573 if (NumberOfSlices < 2) 10574 return; 10575 10576 // Sort the slices so that elements that are likely to be next to each 10577 // other in memory are next to each other in the list. 10578 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10579 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10580 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10581 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10582 }); 10583 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10584 // First (resp. Second) is the first (resp. Second) potentially candidate 10585 // to be placed in a paired load. 10586 const LoadedSlice *First = nullptr; 10587 const LoadedSlice *Second = nullptr; 10588 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10589 // Set the beginning of the pair. 10590 First = Second) { 10591 10592 Second = &LoadedSlices[CurrSlice]; 10593 10594 // If First is NULL, it means we start a new pair. 10595 // Get to the next slice. 10596 if (!First) 10597 continue; 10598 10599 EVT LoadedType = First->getLoadedType(); 10600 10601 // If the types of the slices are different, we cannot pair them. 10602 if (LoadedType != Second->getLoadedType()) 10603 continue; 10604 10605 // Check if the target supplies paired loads for this type. 10606 unsigned RequiredAlignment = 0; 10607 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10608 // move to the next pair, this type is hopeless. 10609 Second = nullptr; 10610 continue; 10611 } 10612 // Check if we meet the alignment requirement. 10613 if (RequiredAlignment > First->getAlignment()) 10614 continue; 10615 10616 // Check that both loads are next to each other in memory. 10617 if (!areSlicesNextToEachOther(*First, *Second)) 10618 continue; 10619 10620 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10621 --GlobalLSCost.Loads; 10622 // Move to the next pair. 10623 Second = nullptr; 10624 } 10625 } 10626 10627 /// \brief Check the profitability of all involved LoadedSlice. 10628 /// Currently, it is considered profitable if there is exactly two 10629 /// involved slices (1) which are (2) next to each other in memory, and 10630 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10631 /// 10632 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10633 /// the elements themselves. 10634 /// 10635 /// FIXME: When the cost model will be mature enough, we can relax 10636 /// constraints (1) and (2). 10637 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10638 const APInt &UsedBits, bool ForCodeSize) { 10639 unsigned NumberOfSlices = LoadedSlices.size(); 10640 if (StressLoadSlicing) 10641 return NumberOfSlices > 1; 10642 10643 // Check (1). 10644 if (NumberOfSlices != 2) 10645 return false; 10646 10647 // Check (2). 10648 if (!areUsedBitsDense(UsedBits)) 10649 return false; 10650 10651 // Check (3). 10652 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10653 // The original code has one big load. 10654 OrigCost.Loads = 1; 10655 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10656 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10657 // Accumulate the cost of all the slices. 10658 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10659 GlobalSlicingCost += SliceCost; 10660 10661 // Account as cost in the original configuration the gain obtained 10662 // with the current slices. 10663 OrigCost.addSliceGain(LS); 10664 } 10665 10666 // If the target supports paired load, adjust the cost accordingly. 10667 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10668 return OrigCost > GlobalSlicingCost; 10669 } 10670 10671 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10672 /// operations, split it in the various pieces being extracted. 10673 /// 10674 /// This sort of thing is introduced by SROA. 10675 /// This slicing takes care not to insert overlapping loads. 10676 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10677 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10678 if (Level < AfterLegalizeDAG) 10679 return false; 10680 10681 LoadSDNode *LD = cast<LoadSDNode>(N); 10682 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10683 !LD->getValueType(0).isInteger()) 10684 return false; 10685 10686 // Keep track of already used bits to detect overlapping values. 10687 // In that case, we will just abort the transformation. 10688 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10689 10690 SmallVector<LoadedSlice, 4> LoadedSlices; 10691 10692 // Check if this load is used as several smaller chunks of bits. 10693 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10694 // of computation for each trunc. 10695 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10696 UI != UIEnd; ++UI) { 10697 // Skip the uses of the chain. 10698 if (UI.getUse().getResNo() != 0) 10699 continue; 10700 10701 SDNode *User = *UI; 10702 unsigned Shift = 0; 10703 10704 // Check if this is a trunc(lshr). 10705 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10706 isa<ConstantSDNode>(User->getOperand(1))) { 10707 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10708 User = *User->use_begin(); 10709 } 10710 10711 // At this point, User is a Truncate, iff we encountered, trunc or 10712 // trunc(lshr). 10713 if (User->getOpcode() != ISD::TRUNCATE) 10714 return false; 10715 10716 // The width of the type must be a power of 2 and greater than 8-bits. 10717 // Otherwise the load cannot be represented in LLVM IR. 10718 // Moreover, if we shifted with a non-8-bits multiple, the slice 10719 // will be across several bytes. We do not support that. 10720 unsigned Width = User->getValueSizeInBits(0); 10721 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10722 return 0; 10723 10724 // Build the slice for this chain of computations. 10725 LoadedSlice LS(User, LD, Shift, &DAG); 10726 APInt CurrentUsedBits = LS.getUsedBits(); 10727 10728 // Check if this slice overlaps with another. 10729 if ((CurrentUsedBits & UsedBits) != 0) 10730 return false; 10731 // Update the bits used globally. 10732 UsedBits |= CurrentUsedBits; 10733 10734 // Check if the new slice would be legal. 10735 if (!LS.isLegal()) 10736 return false; 10737 10738 // Record the slice. 10739 LoadedSlices.push_back(LS); 10740 } 10741 10742 // Abort slicing if it does not seem to be profitable. 10743 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10744 return false; 10745 10746 ++SlicedLoads; 10747 10748 // Rewrite each chain to use an independent load. 10749 // By construction, each chain can be represented by a unique load. 10750 10751 // Prepare the argument for the new token factor for all the slices. 10752 SmallVector<SDValue, 8> ArgChains; 10753 for (SmallVectorImpl<LoadedSlice>::const_iterator 10754 LSIt = LoadedSlices.begin(), 10755 LSItEnd = LoadedSlices.end(); 10756 LSIt != LSItEnd; ++LSIt) { 10757 SDValue SliceInst = LSIt->loadSlice(); 10758 CombineTo(LSIt->Inst, SliceInst, true); 10759 if (SliceInst.getOpcode() != ISD::LOAD) 10760 SliceInst = SliceInst.getOperand(0); 10761 assert(SliceInst->getOpcode() == ISD::LOAD && 10762 "It takes more than a zext to get to the loaded slice!!"); 10763 ArgChains.push_back(SliceInst.getValue(1)); 10764 } 10765 10766 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10767 ArgChains); 10768 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10769 return true; 10770 } 10771 10772 /// Check to see if V is (and load (ptr), imm), where the load is having 10773 /// specific bytes cleared out. If so, return the byte size being masked out 10774 /// and the shift amount. 10775 static std::pair<unsigned, unsigned> 10776 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10777 std::pair<unsigned, unsigned> Result(0, 0); 10778 10779 // Check for the structure we're looking for. 10780 if (V->getOpcode() != ISD::AND || 10781 !isa<ConstantSDNode>(V->getOperand(1)) || 10782 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10783 return Result; 10784 10785 // Check the chain and pointer. 10786 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10787 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10788 10789 // The store should be chained directly to the load or be an operand of a 10790 // tokenfactor. 10791 if (LD == Chain.getNode()) 10792 ; // ok. 10793 else if (Chain->getOpcode() != ISD::TokenFactor) 10794 return Result; // Fail. 10795 else { 10796 bool isOk = false; 10797 for (const SDValue &ChainOp : Chain->op_values()) 10798 if (ChainOp.getNode() == LD) { 10799 isOk = true; 10800 break; 10801 } 10802 if (!isOk) return Result; 10803 } 10804 10805 // This only handles simple types. 10806 if (V.getValueType() != MVT::i16 && 10807 V.getValueType() != MVT::i32 && 10808 V.getValueType() != MVT::i64) 10809 return Result; 10810 10811 // Check the constant mask. Invert it so that the bits being masked out are 10812 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10813 // follow the sign bit for uniformity. 10814 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10815 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10816 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10817 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10818 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10819 if (NotMaskLZ == 64) return Result; // All zero mask. 10820 10821 // See if we have a continuous run of bits. If so, we have 0*1+0* 10822 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10823 return Result; 10824 10825 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10826 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10827 NotMaskLZ -= 64-V.getValueSizeInBits(); 10828 10829 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10830 switch (MaskedBytes) { 10831 case 1: 10832 case 2: 10833 case 4: break; 10834 default: return Result; // All one mask, or 5-byte mask. 10835 } 10836 10837 // Verify that the first bit starts at a multiple of mask so that the access 10838 // is aligned the same as the access width. 10839 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10840 10841 Result.first = MaskedBytes; 10842 Result.second = NotMaskTZ/8; 10843 return Result; 10844 } 10845 10846 10847 /// Check to see if IVal is something that provides a value as specified by 10848 /// MaskInfo. If so, replace the specified store with a narrower store of 10849 /// truncated IVal. 10850 static SDNode * 10851 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10852 SDValue IVal, StoreSDNode *St, 10853 DAGCombiner *DC) { 10854 unsigned NumBytes = MaskInfo.first; 10855 unsigned ByteShift = MaskInfo.second; 10856 SelectionDAG &DAG = DC->getDAG(); 10857 10858 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10859 // that uses this. If not, this is not a replacement. 10860 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10861 ByteShift*8, (ByteShift+NumBytes)*8); 10862 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10863 10864 // Check that it is legal on the target to do this. It is legal if the new 10865 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10866 // legalization. 10867 MVT VT = MVT::getIntegerVT(NumBytes*8); 10868 if (!DC->isTypeLegal(VT)) 10869 return nullptr; 10870 10871 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10872 // shifted by ByteShift and truncated down to NumBytes. 10873 if (ByteShift) { 10874 SDLoc DL(IVal); 10875 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10876 DAG.getConstant(ByteShift*8, DL, 10877 DC->getShiftAmountTy(IVal.getValueType()))); 10878 } 10879 10880 // Figure out the offset for the store and the alignment of the access. 10881 unsigned StOffset; 10882 unsigned NewAlign = St->getAlignment(); 10883 10884 if (DAG.getDataLayout().isLittleEndian()) 10885 StOffset = ByteShift; 10886 else 10887 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10888 10889 SDValue Ptr = St->getBasePtr(); 10890 if (StOffset) { 10891 SDLoc DL(IVal); 10892 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10893 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10894 NewAlign = MinAlign(NewAlign, StOffset); 10895 } 10896 10897 // Truncate down to the new size. 10898 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10899 10900 ++OpsNarrowed; 10901 return DAG 10902 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10903 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 10904 .getNode(); 10905 } 10906 10907 10908 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10909 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10910 /// narrowing the load and store if it would end up being a win for performance 10911 /// or code size. 10912 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10913 StoreSDNode *ST = cast<StoreSDNode>(N); 10914 if (ST->isVolatile()) 10915 return SDValue(); 10916 10917 SDValue Chain = ST->getChain(); 10918 SDValue Value = ST->getValue(); 10919 SDValue Ptr = ST->getBasePtr(); 10920 EVT VT = Value.getValueType(); 10921 10922 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10923 return SDValue(); 10924 10925 unsigned Opc = Value.getOpcode(); 10926 10927 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10928 // is a byte mask indicating a consecutive number of bytes, check to see if 10929 // Y is known to provide just those bytes. If so, we try to replace the 10930 // load + replace + store sequence with a single (narrower) store, which makes 10931 // the load dead. 10932 if (Opc == ISD::OR) { 10933 std::pair<unsigned, unsigned> MaskedLoad; 10934 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10935 if (MaskedLoad.first) 10936 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10937 Value.getOperand(1), ST,this)) 10938 return SDValue(NewST, 0); 10939 10940 // Or is commutative, so try swapping X and Y. 10941 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10942 if (MaskedLoad.first) 10943 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10944 Value.getOperand(0), ST,this)) 10945 return SDValue(NewST, 0); 10946 } 10947 10948 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10949 Value.getOperand(1).getOpcode() != ISD::Constant) 10950 return SDValue(); 10951 10952 SDValue N0 = Value.getOperand(0); 10953 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10954 Chain == SDValue(N0.getNode(), 1)) { 10955 LoadSDNode *LD = cast<LoadSDNode>(N0); 10956 if (LD->getBasePtr() != Ptr || 10957 LD->getPointerInfo().getAddrSpace() != 10958 ST->getPointerInfo().getAddrSpace()) 10959 return SDValue(); 10960 10961 // Find the type to narrow it the load / op / store to. 10962 SDValue N1 = Value.getOperand(1); 10963 unsigned BitWidth = N1.getValueSizeInBits(); 10964 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10965 if (Opc == ISD::AND) 10966 Imm ^= APInt::getAllOnesValue(BitWidth); 10967 if (Imm == 0 || Imm.isAllOnesValue()) 10968 return SDValue(); 10969 unsigned ShAmt = Imm.countTrailingZeros(); 10970 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10971 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10972 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10973 // The narrowing should be profitable, the load/store operation should be 10974 // legal (or custom) and the store size should be equal to the NewVT width. 10975 while (NewBW < BitWidth && 10976 (NewVT.getStoreSizeInBits() != NewBW || 10977 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10978 !TLI.isNarrowingProfitable(VT, NewVT))) { 10979 NewBW = NextPowerOf2(NewBW); 10980 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10981 } 10982 if (NewBW >= BitWidth) 10983 return SDValue(); 10984 10985 // If the lsb changed does not start at the type bitwidth boundary, 10986 // start at the previous one. 10987 if (ShAmt % NewBW) 10988 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10989 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10990 std::min(BitWidth, ShAmt + NewBW)); 10991 if ((Imm & Mask) == Imm) { 10992 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10993 if (Opc == ISD::AND) 10994 NewImm ^= APInt::getAllOnesValue(NewBW); 10995 uint64_t PtrOff = ShAmt / 8; 10996 // For big endian targets, we need to adjust the offset to the pointer to 10997 // load the correct bytes. 10998 if (DAG.getDataLayout().isBigEndian()) 10999 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 11000 11001 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 11002 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 11003 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 11004 return SDValue(); 11005 11006 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 11007 Ptr.getValueType(), Ptr, 11008 DAG.getConstant(PtrOff, SDLoc(LD), 11009 Ptr.getValueType())); 11010 SDValue NewLD = 11011 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 11012 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 11013 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 11014 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 11015 DAG.getConstant(NewImm, SDLoc(Value), 11016 NewVT)); 11017 SDValue NewST = 11018 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 11019 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 11020 11021 AddToWorklist(NewPtr.getNode()); 11022 AddToWorklist(NewLD.getNode()); 11023 AddToWorklist(NewVal.getNode()); 11024 WorklistRemover DeadNodes(*this); 11025 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 11026 ++OpsNarrowed; 11027 return NewST; 11028 } 11029 } 11030 11031 return SDValue(); 11032 } 11033 11034 /// For a given floating point load / store pair, if the load value isn't used 11035 /// by any other operations, then consider transforming the pair to integer 11036 /// load / store operations if the target deems the transformation profitable. 11037 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 11038 StoreSDNode *ST = cast<StoreSDNode>(N); 11039 SDValue Chain = ST->getChain(); 11040 SDValue Value = ST->getValue(); 11041 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 11042 Value.hasOneUse() && 11043 Chain == SDValue(Value.getNode(), 1)) { 11044 LoadSDNode *LD = cast<LoadSDNode>(Value); 11045 EVT VT = LD->getMemoryVT(); 11046 if (!VT.isFloatingPoint() || 11047 VT != ST->getMemoryVT() || 11048 LD->isNonTemporal() || 11049 ST->isNonTemporal() || 11050 LD->getPointerInfo().getAddrSpace() != 0 || 11051 ST->getPointerInfo().getAddrSpace() != 0) 11052 return SDValue(); 11053 11054 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 11055 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 11056 !TLI.isOperationLegal(ISD::STORE, IntVT) || 11057 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 11058 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 11059 return SDValue(); 11060 11061 unsigned LDAlign = LD->getAlignment(); 11062 unsigned STAlign = ST->getAlignment(); 11063 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 11064 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 11065 if (LDAlign < ABIAlign || STAlign < ABIAlign) 11066 return SDValue(); 11067 11068 SDValue NewLD = 11069 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 11070 LD->getPointerInfo(), LDAlign); 11071 11072 SDValue NewST = 11073 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 11074 ST->getPointerInfo(), STAlign); 11075 11076 AddToWorklist(NewLD.getNode()); 11077 AddToWorklist(NewST.getNode()); 11078 WorklistRemover DeadNodes(*this); 11079 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 11080 ++LdStFP2Int; 11081 return NewST; 11082 } 11083 11084 return SDValue(); 11085 } 11086 11087 namespace { 11088 /// Helper struct to parse and store a memory address as base + index + offset. 11089 /// We ignore sign extensions when it is safe to do so. 11090 /// The following two expressions are not equivalent. To differentiate we need 11091 /// to store whether there was a sign extension involved in the index 11092 /// computation. 11093 /// (load (i64 add (i64 copyfromreg %c) 11094 /// (i64 signextend (add (i8 load %index) 11095 /// (i8 1)))) 11096 /// vs 11097 /// 11098 /// (load (i64 add (i64 copyfromreg %c) 11099 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 11100 /// (i32 1))))) 11101 struct BaseIndexOffset { 11102 SDValue Base; 11103 SDValue Index; 11104 int64_t Offset; 11105 bool IsIndexSignExt; 11106 11107 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 11108 11109 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 11110 bool IsIndexSignExt) : 11111 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 11112 11113 bool equalBaseIndex(const BaseIndexOffset &Other) { 11114 return Other.Base == Base && Other.Index == Index && 11115 Other.IsIndexSignExt == IsIndexSignExt; 11116 } 11117 11118 /// Parses tree in Ptr for base, index, offset addresses. 11119 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 11120 bool IsIndexSignExt = false; 11121 11122 // Split up a folded GlobalAddress+Offset into its component parts. 11123 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 11124 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 11125 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 11126 SDLoc(GA), 11127 GA->getValueType(0), 11128 /*Offset=*/0, 11129 /*isTargetGA=*/false, 11130 GA->getTargetFlags()), 11131 SDValue(), 11132 GA->getOffset(), 11133 IsIndexSignExt); 11134 } 11135 11136 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 11137 // instruction, then it could be just the BASE or everything else we don't 11138 // know how to handle. Just use Ptr as BASE and give up. 11139 if (Ptr->getOpcode() != ISD::ADD) 11140 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11141 11142 // We know that we have at least an ADD instruction. Try to pattern match 11143 // the simple case of BASE + OFFSET. 11144 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 11145 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 11146 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 11147 IsIndexSignExt); 11148 } 11149 11150 // Inside a loop the current BASE pointer is calculated using an ADD and a 11151 // MUL instruction. In this case Ptr is the actual BASE pointer. 11152 // (i64 add (i64 %array_ptr) 11153 // (i64 mul (i64 %induction_var) 11154 // (i64 %element_size))) 11155 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 11156 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11157 11158 // Look at Base + Index + Offset cases. 11159 SDValue Base = Ptr->getOperand(0); 11160 SDValue IndexOffset = Ptr->getOperand(1); 11161 11162 // Skip signextends. 11163 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 11164 IndexOffset = IndexOffset->getOperand(0); 11165 IsIndexSignExt = true; 11166 } 11167 11168 // Either the case of Base + Index (no offset) or something else. 11169 if (IndexOffset->getOpcode() != ISD::ADD) 11170 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 11171 11172 // Now we have the case of Base + Index + offset. 11173 SDValue Index = IndexOffset->getOperand(0); 11174 SDValue Offset = IndexOffset->getOperand(1); 11175 11176 if (!isa<ConstantSDNode>(Offset)) 11177 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11178 11179 // Ignore signextends. 11180 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 11181 Index = Index->getOperand(0); 11182 IsIndexSignExt = true; 11183 } else IsIndexSignExt = false; 11184 11185 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 11186 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 11187 } 11188 }; 11189 } // namespace 11190 11191 // This is a helper function for visitMUL to check the profitability 11192 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11193 // MulNode is the original multiply, AddNode is (add x, c1), 11194 // and ConstNode is c2. 11195 // 11196 // If the (add x, c1) has multiple uses, we could increase 11197 // the number of adds if we make this transformation. 11198 // It would only be worth doing this if we can remove a 11199 // multiply in the process. Check for that here. 11200 // To illustrate: 11201 // (A + c1) * c3 11202 // (A + c2) * c3 11203 // We're checking for cases where we have common "c3 * A" expressions. 11204 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11205 SDValue &AddNode, 11206 SDValue &ConstNode) { 11207 APInt Val; 11208 11209 // If the add only has one use, this would be OK to do. 11210 if (AddNode.getNode()->hasOneUse()) 11211 return true; 11212 11213 // Walk all the users of the constant with which we're multiplying. 11214 for (SDNode *Use : ConstNode->uses()) { 11215 11216 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11217 continue; 11218 11219 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11220 SDNode *OtherOp; 11221 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11222 11223 // OtherOp is what we're multiplying against the constant. 11224 if (Use->getOperand(0) == ConstNode) 11225 OtherOp = Use->getOperand(1).getNode(); 11226 else 11227 OtherOp = Use->getOperand(0).getNode(); 11228 11229 // Check to see if multiply is with the same operand of our "add". 11230 // 11231 // ConstNode = CONST 11232 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11233 // ... 11234 // AddNode = (A + c1) <-- MulVar is A. 11235 // = AddNode * ConstNode <-- current visiting instruction. 11236 // 11237 // If we make this transformation, we will have a common 11238 // multiply (ConstNode * A) that we can save. 11239 if (OtherOp == MulVar) 11240 return true; 11241 11242 // Now check to see if a future expansion will give us a common 11243 // multiply. 11244 // 11245 // ConstNode = CONST 11246 // AddNode = (A + c1) 11247 // ... = AddNode * ConstNode <-- current visiting instruction. 11248 // ... 11249 // OtherOp = (A + c2) 11250 // Use = OtherOp * ConstNode <-- visiting Use. 11251 // 11252 // If we make this transformation, we will have a common 11253 // multiply (CONST * A) after we also do the same transformation 11254 // to the "t2" instruction. 11255 if (OtherOp->getOpcode() == ISD::ADD && 11256 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11257 OtherOp->getOperand(0).getNode() == MulVar) 11258 return true; 11259 } 11260 } 11261 11262 // Didn't find a case where this would be profitable. 11263 return false; 11264 } 11265 11266 SDValue DAGCombiner::getMergedConstantVectorStore( 11267 SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores, 11268 SmallVectorImpl<SDValue> &Chains, EVT Ty) const { 11269 SmallVector<SDValue, 8> BuildVector; 11270 11271 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11272 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11273 Chains.push_back(St->getChain()); 11274 BuildVector.push_back(St->getValue()); 11275 } 11276 11277 return DAG.getBuildVector(Ty, SL, BuildVector); 11278 } 11279 11280 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11281 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11282 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11283 // Make sure we have something to merge. 11284 if (NumStores < 2) 11285 return false; 11286 11287 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11288 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11289 unsigned LatestNodeUsed = 0; 11290 11291 for (unsigned i=0; i < NumStores; ++i) { 11292 // Find a chain for the new wide-store operand. Notice that some 11293 // of the store nodes that we found may not be selected for inclusion 11294 // in the wide store. The chain we use needs to be the chain of the 11295 // latest store node which is *used* and replaced by the wide store. 11296 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11297 LatestNodeUsed = i; 11298 } 11299 11300 SmallVector<SDValue, 8> Chains; 11301 11302 // The latest Node in the DAG. 11303 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11304 SDLoc DL(StoreNodes[0].MemNode); 11305 11306 SDValue StoredVal; 11307 if (UseVector) { 11308 bool IsVec = MemVT.isVector(); 11309 unsigned Elts = NumStores; 11310 if (IsVec) { 11311 // When merging vector stores, get the total number of elements. 11312 Elts *= MemVT.getVectorNumElements(); 11313 } 11314 // Get the type for the merged vector store. 11315 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11316 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11317 11318 if (IsConstantSrc) { 11319 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11320 } else { 11321 SmallVector<SDValue, 8> Ops; 11322 for (unsigned i = 0; i < NumStores; ++i) { 11323 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11324 SDValue Val = St->getValue(); 11325 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11326 if (Val.getValueType() != MemVT) 11327 return false; 11328 Ops.push_back(Val); 11329 Chains.push_back(St->getChain()); 11330 } 11331 11332 // Build the extracted vector elements back into a vector. 11333 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11334 DL, Ty, Ops); } 11335 } else { 11336 // We should always use a vector store when merging extracted vector 11337 // elements, so this path implies a store of constants. 11338 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11339 11340 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11341 APInt StoreInt(SizeInBits, 0); 11342 11343 // Construct a single integer constant which is made of the smaller 11344 // constant inputs. 11345 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11346 for (unsigned i = 0; i < NumStores; ++i) { 11347 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11348 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11349 Chains.push_back(St->getChain()); 11350 11351 SDValue Val = St->getValue(); 11352 StoreInt <<= ElementSizeBytes * 8; 11353 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11354 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11355 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11356 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11357 } else { 11358 llvm_unreachable("Invalid constant element type"); 11359 } 11360 } 11361 11362 // Create the new Load and Store operations. 11363 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11364 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11365 } 11366 11367 assert(!Chains.empty()); 11368 11369 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11370 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11371 FirstInChain->getBasePtr(), 11372 FirstInChain->getPointerInfo(), 11373 FirstInChain->getAlignment()); 11374 11375 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11376 : DAG.getSubtarget().useAA(); 11377 if (UseAA) { 11378 // Replace all merged stores with the new store. 11379 for (unsigned i = 0; i < NumStores; ++i) 11380 CombineTo(StoreNodes[i].MemNode, NewStore); 11381 } else { 11382 // Replace the last store with the new store. 11383 CombineTo(LatestOp, NewStore); 11384 // Erase all other stores. 11385 for (unsigned i = 0; i < NumStores; ++i) { 11386 if (StoreNodes[i].MemNode == LatestOp) 11387 continue; 11388 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11389 // ReplaceAllUsesWith will replace all uses that existed when it was 11390 // called, but graph optimizations may cause new ones to appear. For 11391 // example, the case in pr14333 looks like 11392 // 11393 // St's chain -> St -> another store -> X 11394 // 11395 // And the only difference from St to the other store is the chain. 11396 // When we change it's chain to be St's chain they become identical, 11397 // get CSEed and the net result is that X is now a use of St. 11398 // Since we know that St is redundant, just iterate. 11399 while (!St->use_empty()) 11400 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11401 deleteAndRecombine(St); 11402 } 11403 } 11404 11405 return true; 11406 } 11407 11408 void DAGCombiner::getStoreMergeAndAliasCandidates( 11409 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11410 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11411 // This holds the base pointer, index, and the offset in bytes from the base 11412 // pointer. 11413 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11414 11415 // We must have a base and an offset. 11416 if (!BasePtr.Base.getNode()) 11417 return; 11418 11419 // Do not handle stores to undef base pointers. 11420 if (BasePtr.Base.isUndef()) 11421 return; 11422 11423 // Walk up the chain and look for nodes with offsets from the same 11424 // base pointer. Stop when reaching an instruction with a different kind 11425 // or instruction which has a different base pointer. 11426 EVT MemVT = St->getMemoryVT(); 11427 unsigned Seq = 0; 11428 StoreSDNode *Index = St; 11429 11430 11431 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11432 : DAG.getSubtarget().useAA(); 11433 11434 if (UseAA) { 11435 // Look at other users of the same chain. Stores on the same chain do not 11436 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11437 // to be on the same chain, so don't bother looking at adjacent chains. 11438 11439 SDValue Chain = St->getChain(); 11440 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11441 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11442 if (I.getOperandNo() != 0) 11443 continue; 11444 11445 if (OtherST->isVolatile() || OtherST->isIndexed()) 11446 continue; 11447 11448 if (OtherST->getMemoryVT() != MemVT) 11449 continue; 11450 11451 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11452 11453 if (Ptr.equalBaseIndex(BasePtr)) 11454 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11455 } 11456 } 11457 11458 return; 11459 } 11460 11461 while (Index) { 11462 // If the chain has more than one use, then we can't reorder the mem ops. 11463 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11464 break; 11465 11466 // Find the base pointer and offset for this memory node. 11467 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11468 11469 // Check that the base pointer is the same as the original one. 11470 if (!Ptr.equalBaseIndex(BasePtr)) 11471 break; 11472 11473 // The memory operands must not be volatile. 11474 if (Index->isVolatile() || Index->isIndexed()) 11475 break; 11476 11477 // No truncation. 11478 if (Index->isTruncatingStore()) 11479 break; 11480 11481 // The stored memory type must be the same. 11482 if (Index->getMemoryVT() != MemVT) 11483 break; 11484 11485 // We do not allow under-aligned stores in order to prevent 11486 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11487 // be irrelevant here; what MATTERS is that we not move memory 11488 // operations that potentially overlap past each-other. 11489 if (Index->getAlignment() < MemVT.getStoreSize()) 11490 break; 11491 11492 // We found a potential memory operand to merge. 11493 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11494 11495 // Find the next memory operand in the chain. If the next operand in the 11496 // chain is a store then move up and continue the scan with the next 11497 // memory operand. If the next operand is a load save it and use alias 11498 // information to check if it interferes with anything. 11499 SDNode *NextInChain = Index->getChain().getNode(); 11500 while (1) { 11501 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11502 // We found a store node. Use it for the next iteration. 11503 Index = STn; 11504 break; 11505 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11506 if (Ldn->isVolatile()) { 11507 Index = nullptr; 11508 break; 11509 } 11510 11511 // Save the load node for later. Continue the scan. 11512 AliasLoadNodes.push_back(Ldn); 11513 NextInChain = Ldn->getChain().getNode(); 11514 continue; 11515 } else { 11516 Index = nullptr; 11517 break; 11518 } 11519 } 11520 } 11521 } 11522 11523 // We need to check that merging these stores does not cause a loop 11524 // in the DAG. Any store candidate may depend on another candidate 11525 // indirectly through its operand (we already consider dependencies 11526 // through the chain). Check in parallel by searching up from 11527 // non-chain operands of candidates. 11528 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 11529 SmallVectorImpl<MemOpLink> &StoreNodes) { 11530 SmallPtrSet<const SDNode *, 16> Visited; 11531 SmallVector<const SDNode *, 8> Worklist; 11532 // search ops of store candidates 11533 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11534 SDNode *n = StoreNodes[i].MemNode; 11535 // Potential loops may happen only through non-chain operands 11536 for (unsigned j = 1; j < n->getNumOperands(); ++j) 11537 Worklist.push_back(n->getOperand(j).getNode()); 11538 } 11539 // search through DAG. We can stop early if we find a storenode 11540 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11541 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 11542 return false; 11543 } 11544 return true; 11545 } 11546 11547 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11548 if (OptLevel == CodeGenOpt::None) 11549 return false; 11550 11551 EVT MemVT = St->getMemoryVT(); 11552 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11553 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11554 Attribute::NoImplicitFloat); 11555 11556 // This function cannot currently deal with non-byte-sized memory sizes. 11557 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11558 return false; 11559 11560 if (!MemVT.isSimple()) 11561 return false; 11562 11563 // Perform an early exit check. Do not bother looking at stored values that 11564 // are not constants, loads, or extracted vector elements. 11565 SDValue StoredVal = St->getValue(); 11566 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11567 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11568 isa<ConstantFPSDNode>(StoredVal); 11569 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11570 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11571 11572 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11573 return false; 11574 11575 // Don't merge vectors into wider vectors if the source data comes from loads. 11576 // TODO: This restriction can be lifted by using logic similar to the 11577 // ExtractVecSrc case. 11578 if (MemVT.isVector() && IsLoadSrc) 11579 return false; 11580 11581 // Only look at ends of store sequences. 11582 SDValue Chain = SDValue(St, 0); 11583 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11584 return false; 11585 11586 // Save the LoadSDNodes that we find in the chain. 11587 // We need to make sure that these nodes do not interfere with 11588 // any of the store nodes. 11589 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11590 11591 // Save the StoreSDNodes that we find in the chain. 11592 SmallVector<MemOpLink, 8> StoreNodes; 11593 11594 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11595 11596 // Check if there is anything to merge. 11597 if (StoreNodes.size() < 2) 11598 return false; 11599 11600 // only do dependence check in AA case 11601 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11602 : DAG.getSubtarget().useAA(); 11603 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes)) 11604 return false; 11605 11606 // Sort the memory operands according to their distance from the 11607 // base pointer. As a secondary criteria: make sure stores coming 11608 // later in the code come first in the list. This is important for 11609 // the non-UseAA case, because we're merging stores into the FINAL 11610 // store along a chain which potentially contains aliasing stores. 11611 // Thus, if there are multiple stores to the same address, the last 11612 // one can be considered for merging but not the others. 11613 std::sort(StoreNodes.begin(), StoreNodes.end(), 11614 [](MemOpLink LHS, MemOpLink RHS) { 11615 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11616 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11617 LHS.SequenceNum < RHS.SequenceNum); 11618 }); 11619 11620 // Scan the memory operations on the chain and find the first non-consecutive 11621 // store memory address. 11622 unsigned LastConsecutiveStore = 0; 11623 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11624 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11625 11626 // Check that the addresses are consecutive starting from the second 11627 // element in the list of stores. 11628 if (i > 0) { 11629 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11630 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11631 break; 11632 } 11633 11634 // Check if this store interferes with any of the loads that we found. 11635 // If we find a load that alias with this store. Stop the sequence. 11636 if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) { 11637 return isAlias(Ldn, StoreNodes[i].MemNode); 11638 })) 11639 break; 11640 11641 // Mark this node as useful. 11642 LastConsecutiveStore = i; 11643 } 11644 11645 // The node with the lowest store address. 11646 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11647 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11648 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11649 LLVMContext &Context = *DAG.getContext(); 11650 const DataLayout &DL = DAG.getDataLayout(); 11651 11652 // Store the constants into memory as one consecutive store. 11653 if (IsConstantSrc) { 11654 unsigned LastLegalType = 0; 11655 unsigned LastLegalVectorType = 0; 11656 bool NonZero = false; 11657 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11658 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11659 SDValue StoredVal = St->getValue(); 11660 11661 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11662 NonZero |= !C->isNullValue(); 11663 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11664 NonZero |= !C->getConstantFPValue()->isNullValue(); 11665 } else { 11666 // Non-constant. 11667 break; 11668 } 11669 11670 // Find a legal type for the constant store. 11671 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11672 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11673 bool IsFast; 11674 if (TLI.isTypeLegal(StoreTy) && 11675 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11676 FirstStoreAlign, &IsFast) && IsFast) { 11677 LastLegalType = i+1; 11678 // Or check whether a truncstore is legal. 11679 } else if (TLI.getTypeAction(Context, StoreTy) == 11680 TargetLowering::TypePromoteInteger) { 11681 EVT LegalizedStoredValueTy = 11682 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11683 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11684 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11685 FirstStoreAS, FirstStoreAlign, &IsFast) && 11686 IsFast) { 11687 LastLegalType = i + 1; 11688 } 11689 } 11690 11691 // We only use vectors if the constant is known to be zero or the target 11692 // allows it and the function is not marked with the noimplicitfloat 11693 // attribute. 11694 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11695 FirstStoreAS)) && 11696 !NoVectors) { 11697 // Find a legal type for the vector store. 11698 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11699 if (TLI.isTypeLegal(Ty) && 11700 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11701 FirstStoreAlign, &IsFast) && IsFast) 11702 LastLegalVectorType = i + 1; 11703 } 11704 } 11705 11706 // Check if we found a legal integer type to store. 11707 if (LastLegalType == 0 && LastLegalVectorType == 0) 11708 return false; 11709 11710 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11711 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11712 11713 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11714 true, UseVector); 11715 } 11716 11717 // When extracting multiple vector elements, try to store them 11718 // in one vector store rather than a sequence of scalar stores. 11719 if (IsExtractVecSrc) { 11720 unsigned NumStoresToMerge = 0; 11721 bool IsVec = MemVT.isVector(); 11722 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11723 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11724 unsigned StoreValOpcode = St->getValue().getOpcode(); 11725 // This restriction could be loosened. 11726 // Bail out if any stored values are not elements extracted from a vector. 11727 // It should be possible to handle mixed sources, but load sources need 11728 // more careful handling (see the block of code below that handles 11729 // consecutive loads). 11730 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11731 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11732 return false; 11733 11734 // Find a legal type for the vector store. 11735 unsigned Elts = i + 1; 11736 if (IsVec) { 11737 // When merging vector stores, get the total number of elements. 11738 Elts *= MemVT.getVectorNumElements(); 11739 } 11740 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11741 bool IsFast; 11742 if (TLI.isTypeLegal(Ty) && 11743 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11744 FirstStoreAlign, &IsFast) && IsFast) 11745 NumStoresToMerge = i + 1; 11746 } 11747 11748 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11749 false, true); 11750 } 11751 11752 // Below we handle the case of multiple consecutive stores that 11753 // come from multiple consecutive loads. We merge them into a single 11754 // wide load and a single wide store. 11755 11756 // Look for load nodes which are used by the stored values. 11757 SmallVector<MemOpLink, 8> LoadNodes; 11758 11759 // Find acceptable loads. Loads need to have the same chain (token factor), 11760 // must not be zext, volatile, indexed, and they must be consecutive. 11761 BaseIndexOffset LdBasePtr; 11762 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11763 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11764 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11765 if (!Ld) break; 11766 11767 // Loads must only have one use. 11768 if (!Ld->hasNUsesOfValue(1, 0)) 11769 break; 11770 11771 // The memory operands must not be volatile. 11772 if (Ld->isVolatile() || Ld->isIndexed()) 11773 break; 11774 11775 // We do not accept ext loads. 11776 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11777 break; 11778 11779 // The stored memory type must be the same. 11780 if (Ld->getMemoryVT() != MemVT) 11781 break; 11782 11783 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 11784 // If this is not the first ptr that we check. 11785 if (LdBasePtr.Base.getNode()) { 11786 // The base ptr must be the same. 11787 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11788 break; 11789 } else { 11790 // Check that all other base pointers are the same as this one. 11791 LdBasePtr = LdPtr; 11792 } 11793 11794 // We found a potential memory operand to merge. 11795 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11796 } 11797 11798 if (LoadNodes.size() < 2) 11799 return false; 11800 11801 // If we have load/store pair instructions and we only have two values, 11802 // don't bother. 11803 unsigned RequiredAlignment; 11804 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11805 St->getAlignment() >= RequiredAlignment) 11806 return false; 11807 11808 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11809 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11810 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11811 11812 // Scan the memory operations on the chain and find the first non-consecutive 11813 // load memory address. These variables hold the index in the store node 11814 // array. 11815 unsigned LastConsecutiveLoad = 0; 11816 // This variable refers to the size and not index in the array. 11817 unsigned LastLegalVectorType = 0; 11818 unsigned LastLegalIntegerType = 0; 11819 StartAddress = LoadNodes[0].OffsetFromBase; 11820 SDValue FirstChain = FirstLoad->getChain(); 11821 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11822 // All loads must share the same chain. 11823 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11824 break; 11825 11826 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11827 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11828 break; 11829 LastConsecutiveLoad = i; 11830 // Find a legal type for the vector store. 11831 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11832 bool IsFastSt, IsFastLd; 11833 if (TLI.isTypeLegal(StoreTy) && 11834 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11835 FirstStoreAlign, &IsFastSt) && IsFastSt && 11836 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11837 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11838 LastLegalVectorType = i + 1; 11839 } 11840 11841 // Find a legal type for the integer store. 11842 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11843 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11844 if (TLI.isTypeLegal(StoreTy) && 11845 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11846 FirstStoreAlign, &IsFastSt) && IsFastSt && 11847 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11848 FirstLoadAlign, &IsFastLd) && IsFastLd) 11849 LastLegalIntegerType = i + 1; 11850 // Or check whether a truncstore and extload is legal. 11851 else if (TLI.getTypeAction(Context, StoreTy) == 11852 TargetLowering::TypePromoteInteger) { 11853 EVT LegalizedStoredValueTy = 11854 TLI.getTypeToTransformTo(Context, StoreTy); 11855 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11856 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11857 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11858 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11859 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11860 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11861 IsFastSt && 11862 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11863 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11864 IsFastLd) 11865 LastLegalIntegerType = i+1; 11866 } 11867 } 11868 11869 // Only use vector types if the vector type is larger than the integer type. 11870 // If they are the same, use integers. 11871 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11872 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11873 11874 // We add +1 here because the LastXXX variables refer to location while 11875 // the NumElem refers to array/index size. 11876 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11877 NumElem = std::min(LastLegalType, NumElem); 11878 11879 if (NumElem < 2) 11880 return false; 11881 11882 // Collect the chains from all merged stores. 11883 SmallVector<SDValue, 8> MergeStoreChains; 11884 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11885 11886 // The latest Node in the DAG. 11887 unsigned LatestNodeUsed = 0; 11888 for (unsigned i=1; i<NumElem; ++i) { 11889 // Find a chain for the new wide-store operand. Notice that some 11890 // of the store nodes that we found may not be selected for inclusion 11891 // in the wide store. The chain we use needs to be the chain of the 11892 // latest store node which is *used* and replaced by the wide store. 11893 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11894 LatestNodeUsed = i; 11895 11896 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11897 } 11898 11899 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11900 11901 // Find if it is better to use vectors or integers to load and store 11902 // to memory. 11903 EVT JointMemOpVT; 11904 if (UseVectorTy) { 11905 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11906 } else { 11907 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11908 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11909 } 11910 11911 SDLoc LoadDL(LoadNodes[0].MemNode); 11912 SDLoc StoreDL(StoreNodes[0].MemNode); 11913 11914 // The merged loads are required to have the same incoming chain, so 11915 // using the first's chain is acceptable. 11916 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 11917 FirstLoad->getBasePtr(), 11918 FirstLoad->getPointerInfo(), FirstLoadAlign); 11919 11920 SDValue NewStoreChain = 11921 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11922 11923 SDValue NewStore = 11924 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11925 FirstInChain->getPointerInfo(), FirstStoreAlign); 11926 11927 // Transfer chain users from old loads to the new load. 11928 for (unsigned i = 0; i < NumElem; ++i) { 11929 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11930 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11931 SDValue(NewLoad.getNode(), 1)); 11932 } 11933 11934 if (UseAA) { 11935 // Replace the all stores with the new store. 11936 for (unsigned i = 0; i < NumElem; ++i) 11937 CombineTo(StoreNodes[i].MemNode, NewStore); 11938 } else { 11939 // Replace the last store with the new store. 11940 CombineTo(LatestOp, NewStore); 11941 // Erase all other stores. 11942 for (unsigned i = 0; i < NumElem; ++i) { 11943 // Remove all Store nodes. 11944 if (StoreNodes[i].MemNode == LatestOp) 11945 continue; 11946 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11947 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11948 deleteAndRecombine(St); 11949 } 11950 } 11951 11952 return true; 11953 } 11954 11955 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11956 SDLoc SL(ST); 11957 SDValue ReplStore; 11958 11959 // Replace the chain to avoid dependency. 11960 if (ST->isTruncatingStore()) { 11961 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11962 ST->getBasePtr(), ST->getMemoryVT(), 11963 ST->getMemOperand()); 11964 } else { 11965 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11966 ST->getMemOperand()); 11967 } 11968 11969 // Create token to keep both nodes around. 11970 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11971 MVT::Other, ST->getChain(), ReplStore); 11972 11973 // Make sure the new and old chains are cleaned up. 11974 AddToWorklist(Token.getNode()); 11975 11976 // Don't add users to work list. 11977 return CombineTo(ST, Token, false); 11978 } 11979 11980 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11981 SDValue Value = ST->getValue(); 11982 if (Value.getOpcode() == ISD::TargetConstantFP) 11983 return SDValue(); 11984 11985 SDLoc DL(ST); 11986 11987 SDValue Chain = ST->getChain(); 11988 SDValue Ptr = ST->getBasePtr(); 11989 11990 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11991 11992 // NOTE: If the original store is volatile, this transform must not increase 11993 // the number of stores. For example, on x86-32 an f64 can be stored in one 11994 // processor operation but an i64 (which is not legal) requires two. So the 11995 // transform should not be done in this case. 11996 11997 SDValue Tmp; 11998 switch (CFP->getSimpleValueType(0).SimpleTy) { 11999 default: 12000 llvm_unreachable("Unknown FP type"); 12001 case MVT::f16: // We don't do this for these yet. 12002 case MVT::f80: 12003 case MVT::f128: 12004 case MVT::ppcf128: 12005 return SDValue(); 12006 case MVT::f32: 12007 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 12008 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12009 ; 12010 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 12011 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 12012 MVT::i32); 12013 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 12014 } 12015 12016 return SDValue(); 12017 case MVT::f64: 12018 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 12019 !ST->isVolatile()) || 12020 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 12021 ; 12022 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 12023 getZExtValue(), SDLoc(CFP), MVT::i64); 12024 return DAG.getStore(Chain, DL, Tmp, 12025 Ptr, ST->getMemOperand()); 12026 } 12027 12028 if (!ST->isVolatile() && 12029 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12030 // Many FP stores are not made apparent until after legalize, e.g. for 12031 // argument passing. Since this is so common, custom legalize the 12032 // 64-bit integer store into two 32-bit stores. 12033 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 12034 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 12035 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 12036 if (DAG.getDataLayout().isBigEndian()) 12037 std::swap(Lo, Hi); 12038 12039 unsigned Alignment = ST->getAlignment(); 12040 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12041 AAMDNodes AAInfo = ST->getAAInfo(); 12042 12043 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12044 ST->getAlignment(), MMOFlags, AAInfo); 12045 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12046 DAG.getConstant(4, DL, Ptr.getValueType())); 12047 Alignment = MinAlign(Alignment, 4U); 12048 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 12049 ST->getPointerInfo().getWithOffset(4), 12050 Alignment, MMOFlags, AAInfo); 12051 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 12052 St0, St1); 12053 } 12054 12055 return SDValue(); 12056 } 12057 } 12058 12059 SDValue DAGCombiner::visitSTORE(SDNode *N) { 12060 StoreSDNode *ST = cast<StoreSDNode>(N); 12061 SDValue Chain = ST->getChain(); 12062 SDValue Value = ST->getValue(); 12063 SDValue Ptr = ST->getBasePtr(); 12064 12065 // If this is a store of a bit convert, store the input value if the 12066 // resultant store does not need a higher alignment than the original. 12067 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 12068 ST->isUnindexed()) { 12069 EVT SVT = Value.getOperand(0).getValueType(); 12070 if (((!LegalOperations && !ST->isVolatile()) || 12071 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 12072 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 12073 unsigned OrigAlign = ST->getAlignment(); 12074 bool Fast = false; 12075 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 12076 ST->getAddressSpace(), OrigAlign, &Fast) && 12077 Fast) { 12078 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 12079 ST->getPointerInfo(), OrigAlign, 12080 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12081 } 12082 } 12083 } 12084 12085 // Turn 'store undef, Ptr' -> nothing. 12086 if (Value.isUndef() && ST->isUnindexed()) 12087 return Chain; 12088 12089 // Try to infer better alignment information than the store already has. 12090 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 12091 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12092 if (Align > ST->getAlignment()) { 12093 SDValue NewStore = 12094 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 12095 ST->getMemoryVT(), Align, 12096 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12097 if (NewStore.getNode() != N) 12098 return CombineTo(ST, NewStore, true); 12099 } 12100 } 12101 } 12102 12103 // Try transforming a pair floating point load / store ops to integer 12104 // load / store ops. 12105 if (SDValue NewST = TransformFPLoadStorePair(N)) 12106 return NewST; 12107 12108 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12109 : DAG.getSubtarget().useAA(); 12110 #ifndef NDEBUG 12111 if (CombinerAAOnlyFunc.getNumOccurrences() && 12112 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12113 UseAA = false; 12114 #endif 12115 if (UseAA && ST->isUnindexed()) { 12116 // FIXME: We should do this even without AA enabled. AA will just allow 12117 // FindBetterChain to work in more situations. The problem with this is that 12118 // any combine that expects memory operations to be on consecutive chains 12119 // first needs to be updated to look for users of the same chain. 12120 12121 // Walk up chain skipping non-aliasing memory nodes, on this store and any 12122 // adjacent stores. 12123 if (findBetterNeighborChains(ST)) { 12124 // replaceStoreChain uses CombineTo, which handled all of the worklist 12125 // manipulation. Return the original node to not do anything else. 12126 return SDValue(ST, 0); 12127 } 12128 Chain = ST->getChain(); 12129 } 12130 12131 // Try transforming N to an indexed store. 12132 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12133 return SDValue(N, 0); 12134 12135 // FIXME: is there such a thing as a truncating indexed store? 12136 if (ST->isTruncatingStore() && ST->isUnindexed() && 12137 Value.getValueType().isInteger()) { 12138 // See if we can simplify the input to this truncstore with knowledge that 12139 // only the low bits are being used. For example: 12140 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 12141 SDValue Shorter = 12142 GetDemandedBits(Value, 12143 APInt::getLowBitsSet( 12144 Value.getValueType().getScalarType().getSizeInBits(), 12145 ST->getMemoryVT().getScalarType().getSizeInBits())); 12146 AddToWorklist(Value.getNode()); 12147 if (Shorter.getNode()) 12148 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12149 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12150 12151 // Otherwise, see if we can simplify the operation with 12152 // SimplifyDemandedBits, which only works if the value has a single use. 12153 if (SimplifyDemandedBits(Value, 12154 APInt::getLowBitsSet( 12155 Value.getValueType().getScalarType().getSizeInBits(), 12156 ST->getMemoryVT().getScalarType().getSizeInBits()))) 12157 return SDValue(N, 0); 12158 } 12159 12160 // If this is a load followed by a store to the same location, then the store 12161 // is dead/noop. 12162 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12163 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12164 ST->isUnindexed() && !ST->isVolatile() && 12165 // There can't be any side effects between the load and store, such as 12166 // a call or store. 12167 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12168 // The store is dead, remove it. 12169 return Chain; 12170 } 12171 } 12172 12173 // If this is a store followed by a store with the same value to the same 12174 // location, then the store is dead/noop. 12175 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12176 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12177 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12178 ST1->isUnindexed() && !ST1->isVolatile()) { 12179 // The store is dead, remove it. 12180 return Chain; 12181 } 12182 } 12183 12184 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12185 // truncating store. We can do this even if this is already a truncstore. 12186 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12187 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12188 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12189 ST->getMemoryVT())) { 12190 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12191 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12192 } 12193 12194 // Only perform this optimization before the types are legal, because we 12195 // don't want to perform this optimization on every DAGCombine invocation. 12196 if (!LegalTypes) { 12197 bool EverChanged = false; 12198 12199 do { 12200 // There can be multiple store sequences on the same chain. 12201 // Keep trying to merge store sequences until we are unable to do so 12202 // or until we merge the last store on the chain. 12203 bool Changed = MergeConsecutiveStores(ST); 12204 EverChanged |= Changed; 12205 if (!Changed) break; 12206 } while (ST->getOpcode() != ISD::DELETED_NODE); 12207 12208 if (EverChanged) 12209 return SDValue(N, 0); 12210 } 12211 12212 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12213 // 12214 // Make sure to do this only after attempting to merge stores in order to 12215 // avoid changing the types of some subset of stores due to visit order, 12216 // preventing their merging. 12217 if (isa<ConstantFPSDNode>(Value)) { 12218 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12219 return NewSt; 12220 } 12221 12222 if (SDValue NewSt = splitMergedValStore(ST)) 12223 return NewSt; 12224 12225 return ReduceLoadOpStoreWidth(N); 12226 } 12227 12228 /// For the instruction sequence of store below, F and I values 12229 /// are bundled together as an i64 value before being stored into memory. 12230 /// Sometimes it is more efficent to generate separate stores for F and I, 12231 /// which can remove the bitwise instructions or sink them to colder places. 12232 /// 12233 /// (store (or (zext (bitcast F to i32) to i64), 12234 /// (shl (zext I to i64), 32)), addr) --> 12235 /// (store F, addr) and (store I, addr+4) 12236 /// 12237 /// Similarly, splitting for other merged store can also be beneficial, like: 12238 /// For pair of {i32, i32}, i64 store --> two i32 stores. 12239 /// For pair of {i32, i16}, i64 store --> two i32 stores. 12240 /// For pair of {i16, i16}, i32 store --> two i16 stores. 12241 /// For pair of {i16, i8}, i32 store --> two i16 stores. 12242 /// For pair of {i8, i8}, i16 store --> two i8 stores. 12243 /// 12244 /// We allow each target to determine specifically which kind of splitting is 12245 /// supported. 12246 /// 12247 /// The store patterns are commonly seen from the simple code snippet below 12248 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 12249 /// void goo(const std::pair<int, float> &); 12250 /// hoo() { 12251 /// ... 12252 /// goo(std::make_pair(tmp, ftmp)); 12253 /// ... 12254 /// } 12255 /// 12256 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 12257 if (OptLevel == CodeGenOpt::None) 12258 return SDValue(); 12259 12260 SDValue Val = ST->getValue(); 12261 SDLoc DL(ST); 12262 12263 // Match OR operand. 12264 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 12265 return SDValue(); 12266 12267 // Match SHL operand and get Lower and Higher parts of Val. 12268 SDValue Op1 = Val.getOperand(0); 12269 SDValue Op2 = Val.getOperand(1); 12270 SDValue Lo, Hi; 12271 if (Op1.getOpcode() != ISD::SHL) { 12272 std::swap(Op1, Op2); 12273 if (Op1.getOpcode() != ISD::SHL) 12274 return SDValue(); 12275 } 12276 Lo = Op2; 12277 Hi = Op1.getOperand(0); 12278 if (!Op1.hasOneUse()) 12279 return SDValue(); 12280 12281 // Match shift amount to HalfValBitSize. 12282 unsigned HalfValBitSize = Val.getValueType().getSizeInBits() / 2; 12283 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 12284 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 12285 return SDValue(); 12286 12287 // Lo and Hi are zero-extended from int with size less equal than 32 12288 // to i64. 12289 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 12290 !Lo.getOperand(0).getValueType().isScalarInteger() || 12291 Lo.getOperand(0).getValueType().getSizeInBits() > HalfValBitSize || 12292 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 12293 !Hi.getOperand(0).getValueType().isScalarInteger() || 12294 Hi.getOperand(0).getValueType().getSizeInBits() > HalfValBitSize) 12295 return SDValue(); 12296 12297 if (!TLI.isMultiStoresCheaperThanBitsMerge(Lo.getOperand(0), 12298 Hi.getOperand(0))) 12299 return SDValue(); 12300 12301 // Start to split store. 12302 unsigned Alignment = ST->getAlignment(); 12303 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12304 AAMDNodes AAInfo = ST->getAAInfo(); 12305 12306 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 12307 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 12308 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 12309 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 12310 12311 SDValue Chain = ST->getChain(); 12312 SDValue Ptr = ST->getBasePtr(); 12313 // Lower value store. 12314 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12315 ST->getAlignment(), MMOFlags, AAInfo); 12316 Ptr = 12317 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12318 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 12319 // Higher value store. 12320 SDValue St1 = 12321 DAG.getStore(Chain, DL, Hi, Ptr, 12322 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 12323 Alignment / 2, MMOFlags, AAInfo); 12324 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, St0, St1); 12325 } 12326 12327 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12328 SDValue InVec = N->getOperand(0); 12329 SDValue InVal = N->getOperand(1); 12330 SDValue EltNo = N->getOperand(2); 12331 SDLoc dl(N); 12332 12333 // If the inserted element is an UNDEF, just use the input vector. 12334 if (InVal.isUndef()) 12335 return InVec; 12336 12337 EVT VT = InVec.getValueType(); 12338 12339 // If we can't generate a legal BUILD_VECTOR, exit 12340 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12341 return SDValue(); 12342 12343 // Check that we know which element is being inserted 12344 if (!isa<ConstantSDNode>(EltNo)) 12345 return SDValue(); 12346 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12347 12348 // Canonicalize insert_vector_elt dag nodes. 12349 // Example: 12350 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12351 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12352 // 12353 // Do this only if the child insert_vector node has one use; also 12354 // do this only if indices are both constants and Idx1 < Idx0. 12355 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12356 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12357 unsigned OtherElt = 12358 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12359 if (Elt < OtherElt) { 12360 // Swap nodes. 12361 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 12362 InVec.getOperand(0), InVal, EltNo); 12363 AddToWorklist(NewOp.getNode()); 12364 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12365 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12366 } 12367 } 12368 12369 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12370 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12371 // vector elements. 12372 SmallVector<SDValue, 8> Ops; 12373 // Do not combine these two vectors if the output vector will not replace 12374 // the input vector. 12375 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12376 Ops.append(InVec.getNode()->op_begin(), 12377 InVec.getNode()->op_end()); 12378 } else if (InVec.isUndef()) { 12379 unsigned NElts = VT.getVectorNumElements(); 12380 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12381 } else { 12382 return SDValue(); 12383 } 12384 12385 // Insert the element 12386 if (Elt < Ops.size()) { 12387 // All the operands of BUILD_VECTOR must have the same type; 12388 // we enforce that here. 12389 EVT OpVT = Ops[0].getValueType(); 12390 if (InVal.getValueType() != OpVT) 12391 InVal = OpVT.bitsGT(InVal.getValueType()) ? 12392 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 12393 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 12394 Ops[Elt] = InVal; 12395 } 12396 12397 // Return the new vector 12398 return DAG.getBuildVector(VT, dl, Ops); 12399 } 12400 12401 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12402 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12403 assert(!OriginalLoad->isVolatile()); 12404 12405 EVT ResultVT = EVE->getValueType(0); 12406 EVT VecEltVT = InVecVT.getVectorElementType(); 12407 unsigned Align = OriginalLoad->getAlignment(); 12408 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12409 VecEltVT.getTypeForEVT(*DAG.getContext())); 12410 12411 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12412 return SDValue(); 12413 12414 Align = NewAlign; 12415 12416 SDValue NewPtr = OriginalLoad->getBasePtr(); 12417 SDValue Offset; 12418 EVT PtrType = NewPtr.getValueType(); 12419 MachinePointerInfo MPI; 12420 SDLoc DL(EVE); 12421 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12422 int Elt = ConstEltNo->getZExtValue(); 12423 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12424 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12425 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12426 } else { 12427 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12428 Offset = DAG.getNode( 12429 ISD::MUL, DL, PtrType, Offset, 12430 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12431 MPI = OriginalLoad->getPointerInfo(); 12432 } 12433 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12434 12435 // The replacement we need to do here is a little tricky: we need to 12436 // replace an extractelement of a load with a load. 12437 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12438 // Note that this replacement assumes that the extractvalue is the only 12439 // use of the load; that's okay because we don't want to perform this 12440 // transformation in other cases anyway. 12441 SDValue Load; 12442 SDValue Chain; 12443 if (ResultVT.bitsGT(VecEltVT)) { 12444 // If the result type of vextract is wider than the load, then issue an 12445 // extending load instead. 12446 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12447 VecEltVT) 12448 ? ISD::ZEXTLOAD 12449 : ISD::EXTLOAD; 12450 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 12451 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 12452 Align, OriginalLoad->getMemOperand()->getFlags(), 12453 OriginalLoad->getAAInfo()); 12454 Chain = Load.getValue(1); 12455 } else { 12456 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 12457 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 12458 OriginalLoad->getAAInfo()); 12459 Chain = Load.getValue(1); 12460 if (ResultVT.bitsLT(VecEltVT)) 12461 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12462 else 12463 Load = DAG.getBitcast(ResultVT, Load); 12464 } 12465 WorklistRemover DeadNodes(*this); 12466 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12467 SDValue To[] = { Load, Chain }; 12468 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12469 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12470 // worklist explicitly as well. 12471 AddToWorklist(Load.getNode()); 12472 AddUsersToWorklist(Load.getNode()); // Add users too 12473 // Make sure to revisit this node to clean it up; it will usually be dead. 12474 AddToWorklist(EVE); 12475 ++OpsNarrowed; 12476 return SDValue(EVE, 0); 12477 } 12478 12479 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12480 // (vextract (scalar_to_vector val, 0) -> val 12481 SDValue InVec = N->getOperand(0); 12482 EVT VT = InVec.getValueType(); 12483 EVT NVT = N->getValueType(0); 12484 12485 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12486 // Check if the result type doesn't match the inserted element type. A 12487 // SCALAR_TO_VECTOR may truncate the inserted element and the 12488 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12489 SDValue InOp = InVec.getOperand(0); 12490 if (InOp.getValueType() != NVT) { 12491 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12492 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12493 } 12494 return InOp; 12495 } 12496 12497 SDValue EltNo = N->getOperand(1); 12498 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12499 12500 // extract_vector_elt (build_vector x, y), 1 -> y 12501 if (ConstEltNo && 12502 InVec.getOpcode() == ISD::BUILD_VECTOR && 12503 TLI.isTypeLegal(VT) && 12504 (InVec.hasOneUse() || 12505 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12506 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12507 EVT InEltVT = Elt.getValueType(); 12508 12509 // Sometimes build_vector's scalar input types do not match result type. 12510 if (NVT == InEltVT) 12511 return Elt; 12512 12513 // TODO: It may be useful to truncate if free if the build_vector implicitly 12514 // converts. 12515 } 12516 12517 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 12518 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 12519 ConstEltNo->isNullValue() && VT.isInteger()) { 12520 SDValue BCSrc = InVec.getOperand(0); 12521 if (BCSrc.getValueType().isScalarInteger()) 12522 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 12523 } 12524 12525 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 12526 // 12527 // This only really matters if the index is non-constant since other combines 12528 // on the constant elements already work. 12529 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 12530 EltNo == InVec.getOperand(2)) { 12531 SDValue Elt = InVec.getOperand(1); 12532 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 12533 } 12534 12535 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12536 // We only perform this optimization before the op legalization phase because 12537 // we may introduce new vector instructions which are not backed by TD 12538 // patterns. For example on AVX, extracting elements from a wide vector 12539 // without using extract_subvector. However, if we can find an underlying 12540 // scalar value, then we can always use that. 12541 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12542 int NumElem = VT.getVectorNumElements(); 12543 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12544 // Find the new index to extract from. 12545 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12546 12547 // Extracting an undef index is undef. 12548 if (OrigElt == -1) 12549 return DAG.getUNDEF(NVT); 12550 12551 // Select the right vector half to extract from. 12552 SDValue SVInVec; 12553 if (OrigElt < NumElem) { 12554 SVInVec = InVec->getOperand(0); 12555 } else { 12556 SVInVec = InVec->getOperand(1); 12557 OrigElt -= NumElem; 12558 } 12559 12560 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12561 SDValue InOp = SVInVec.getOperand(OrigElt); 12562 if (InOp.getValueType() != NVT) { 12563 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12564 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12565 } 12566 12567 return InOp; 12568 } 12569 12570 // FIXME: We should handle recursing on other vector shuffles and 12571 // scalar_to_vector here as well. 12572 12573 if (!LegalOperations) { 12574 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12575 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12576 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12577 } 12578 } 12579 12580 bool BCNumEltsChanged = false; 12581 EVT ExtVT = VT.getVectorElementType(); 12582 EVT LVT = ExtVT; 12583 12584 // If the result of load has to be truncated, then it's not necessarily 12585 // profitable. 12586 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12587 return SDValue(); 12588 12589 if (InVec.getOpcode() == ISD::BITCAST) { 12590 // Don't duplicate a load with other uses. 12591 if (!InVec.hasOneUse()) 12592 return SDValue(); 12593 12594 EVT BCVT = InVec.getOperand(0).getValueType(); 12595 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12596 return SDValue(); 12597 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12598 BCNumEltsChanged = true; 12599 InVec = InVec.getOperand(0); 12600 ExtVT = BCVT.getVectorElementType(); 12601 } 12602 12603 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12604 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12605 ISD::isNormalLoad(InVec.getNode()) && 12606 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12607 SDValue Index = N->getOperand(1); 12608 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 12609 if (!OrigLoad->isVolatile()) { 12610 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12611 OrigLoad); 12612 } 12613 } 12614 } 12615 12616 // Perform only after legalization to ensure build_vector / vector_shuffle 12617 // optimizations have already been done. 12618 if (!LegalOperations) return SDValue(); 12619 12620 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12621 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12622 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12623 12624 if (ConstEltNo) { 12625 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12626 12627 LoadSDNode *LN0 = nullptr; 12628 const ShuffleVectorSDNode *SVN = nullptr; 12629 if (ISD::isNormalLoad(InVec.getNode())) { 12630 LN0 = cast<LoadSDNode>(InVec); 12631 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12632 InVec.getOperand(0).getValueType() == ExtVT && 12633 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12634 // Don't duplicate a load with other uses. 12635 if (!InVec.hasOneUse()) 12636 return SDValue(); 12637 12638 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12639 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12640 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12641 // => 12642 // (load $addr+1*size) 12643 12644 // Don't duplicate a load with other uses. 12645 if (!InVec.hasOneUse()) 12646 return SDValue(); 12647 12648 // If the bit convert changed the number of elements, it is unsafe 12649 // to examine the mask. 12650 if (BCNumEltsChanged) 12651 return SDValue(); 12652 12653 // Select the input vector, guarding against out of range extract vector. 12654 unsigned NumElems = VT.getVectorNumElements(); 12655 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12656 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12657 12658 if (InVec.getOpcode() == ISD::BITCAST) { 12659 // Don't duplicate a load with other uses. 12660 if (!InVec.hasOneUse()) 12661 return SDValue(); 12662 12663 InVec = InVec.getOperand(0); 12664 } 12665 if (ISD::isNormalLoad(InVec.getNode())) { 12666 LN0 = cast<LoadSDNode>(InVec); 12667 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12668 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12669 } 12670 } 12671 12672 // Make sure we found a non-volatile load and the extractelement is 12673 // the only use. 12674 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12675 return SDValue(); 12676 12677 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12678 if (Elt == -1) 12679 return DAG.getUNDEF(LVT); 12680 12681 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12682 } 12683 12684 return SDValue(); 12685 } 12686 12687 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12688 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12689 // We perform this optimization post type-legalization because 12690 // the type-legalizer often scalarizes integer-promoted vectors. 12691 // Performing this optimization before may create bit-casts which 12692 // will be type-legalized to complex code sequences. 12693 // We perform this optimization only before the operation legalizer because we 12694 // may introduce illegal operations. 12695 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12696 return SDValue(); 12697 12698 unsigned NumInScalars = N->getNumOperands(); 12699 SDLoc dl(N); 12700 EVT VT = N->getValueType(0); 12701 12702 // Check to see if this is a BUILD_VECTOR of a bunch of values 12703 // which come from any_extend or zero_extend nodes. If so, we can create 12704 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12705 // optimizations. We do not handle sign-extend because we can't fill the sign 12706 // using shuffles. 12707 EVT SourceType = MVT::Other; 12708 bool AllAnyExt = true; 12709 12710 for (unsigned i = 0; i != NumInScalars; ++i) { 12711 SDValue In = N->getOperand(i); 12712 // Ignore undef inputs. 12713 if (In.isUndef()) continue; 12714 12715 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12716 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12717 12718 // Abort if the element is not an extension. 12719 if (!ZeroExt && !AnyExt) { 12720 SourceType = MVT::Other; 12721 break; 12722 } 12723 12724 // The input is a ZeroExt or AnyExt. Check the original type. 12725 EVT InTy = In.getOperand(0).getValueType(); 12726 12727 // Check that all of the widened source types are the same. 12728 if (SourceType == MVT::Other) 12729 // First time. 12730 SourceType = InTy; 12731 else if (InTy != SourceType) { 12732 // Multiple income types. Abort. 12733 SourceType = MVT::Other; 12734 break; 12735 } 12736 12737 // Check if all of the extends are ANY_EXTENDs. 12738 AllAnyExt &= AnyExt; 12739 } 12740 12741 // In order to have valid types, all of the inputs must be extended from the 12742 // same source type and all of the inputs must be any or zero extend. 12743 // Scalar sizes must be a power of two. 12744 EVT OutScalarTy = VT.getScalarType(); 12745 bool ValidTypes = SourceType != MVT::Other && 12746 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12747 isPowerOf2_32(SourceType.getSizeInBits()); 12748 12749 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12750 // turn into a single shuffle instruction. 12751 if (!ValidTypes) 12752 return SDValue(); 12753 12754 bool isLE = DAG.getDataLayout().isLittleEndian(); 12755 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12756 assert(ElemRatio > 1 && "Invalid element size ratio"); 12757 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12758 DAG.getConstant(0, SDLoc(N), SourceType); 12759 12760 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12761 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12762 12763 // Populate the new build_vector 12764 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12765 SDValue Cast = N->getOperand(i); 12766 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12767 Cast.getOpcode() == ISD::ZERO_EXTEND || 12768 Cast.isUndef()) && "Invalid cast opcode"); 12769 SDValue In; 12770 if (Cast.isUndef()) 12771 In = DAG.getUNDEF(SourceType); 12772 else 12773 In = Cast->getOperand(0); 12774 unsigned Index = isLE ? (i * ElemRatio) : 12775 (i * ElemRatio + (ElemRatio - 1)); 12776 12777 assert(Index < Ops.size() && "Invalid index"); 12778 Ops[Index] = In; 12779 } 12780 12781 // The type of the new BUILD_VECTOR node. 12782 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12783 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12784 "Invalid vector size"); 12785 // Check if the new vector type is legal. 12786 if (!isTypeLegal(VecVT)) return SDValue(); 12787 12788 // Make the new BUILD_VECTOR. 12789 SDValue BV = DAG.getBuildVector(VecVT, dl, Ops); 12790 12791 // The new BUILD_VECTOR node has the potential to be further optimized. 12792 AddToWorklist(BV.getNode()); 12793 // Bitcast to the desired type. 12794 return DAG.getBitcast(VT, BV); 12795 } 12796 12797 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12798 EVT VT = N->getValueType(0); 12799 12800 unsigned NumInScalars = N->getNumOperands(); 12801 SDLoc dl(N); 12802 12803 EVT SrcVT = MVT::Other; 12804 unsigned Opcode = ISD::DELETED_NODE; 12805 unsigned NumDefs = 0; 12806 12807 for (unsigned i = 0; i != NumInScalars; ++i) { 12808 SDValue In = N->getOperand(i); 12809 unsigned Opc = In.getOpcode(); 12810 12811 if (Opc == ISD::UNDEF) 12812 continue; 12813 12814 // If all scalar values are floats and converted from integers. 12815 if (Opcode == ISD::DELETED_NODE && 12816 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12817 Opcode = Opc; 12818 } 12819 12820 if (Opc != Opcode) 12821 return SDValue(); 12822 12823 EVT InVT = In.getOperand(0).getValueType(); 12824 12825 // If all scalar values are typed differently, bail out. It's chosen to 12826 // simplify BUILD_VECTOR of integer types. 12827 if (SrcVT == MVT::Other) 12828 SrcVT = InVT; 12829 if (SrcVT != InVT) 12830 return SDValue(); 12831 NumDefs++; 12832 } 12833 12834 // If the vector has just one element defined, it's not worth to fold it into 12835 // a vectorized one. 12836 if (NumDefs < 2) 12837 return SDValue(); 12838 12839 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12840 && "Should only handle conversion from integer to float."); 12841 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12842 12843 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12844 12845 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12846 return SDValue(); 12847 12848 // Just because the floating-point vector type is legal does not necessarily 12849 // mean that the corresponding integer vector type is. 12850 if (!isTypeLegal(NVT)) 12851 return SDValue(); 12852 12853 SmallVector<SDValue, 8> Opnds; 12854 for (unsigned i = 0; i != NumInScalars; ++i) { 12855 SDValue In = N->getOperand(i); 12856 12857 if (In.isUndef()) 12858 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12859 else 12860 Opnds.push_back(In.getOperand(0)); 12861 } 12862 SDValue BV = DAG.getBuildVector(NVT, dl, Opnds); 12863 AddToWorklist(BV.getNode()); 12864 12865 return DAG.getNode(Opcode, dl, VT, BV); 12866 } 12867 12868 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12869 unsigned NumInScalars = N->getNumOperands(); 12870 SDLoc dl(N); 12871 EVT VT = N->getValueType(0); 12872 12873 // A vector built entirely of undefs is undef. 12874 if (ISD::allOperandsUndef(N)) 12875 return DAG.getUNDEF(VT); 12876 12877 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12878 return V; 12879 12880 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12881 return V; 12882 12883 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12884 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12885 // at most two distinct vectors, turn this into a shuffle node. 12886 12887 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12888 if (!isTypeLegal(VT)) 12889 return SDValue(); 12890 12891 // May only combine to shuffle after legalize if shuffle is legal. 12892 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12893 return SDValue(); 12894 12895 SDValue VecIn1, VecIn2; 12896 bool UsesZeroVector = false; 12897 for (unsigned i = 0; i != NumInScalars; ++i) { 12898 SDValue Op = N->getOperand(i); 12899 // Ignore undef inputs. 12900 if (Op.isUndef()) continue; 12901 12902 // See if we can combine this build_vector into a blend with a zero vector. 12903 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12904 UsesZeroVector = true; 12905 continue; 12906 } 12907 12908 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12909 // constant index, bail out. 12910 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12911 !isa<ConstantSDNode>(Op.getOperand(1))) { 12912 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12913 break; 12914 } 12915 12916 // We allow up to two distinct input vectors. 12917 SDValue ExtractedFromVec = Op.getOperand(0); 12918 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12919 continue; 12920 12921 if (!VecIn1.getNode()) { 12922 VecIn1 = ExtractedFromVec; 12923 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12924 VecIn2 = ExtractedFromVec; 12925 } else { 12926 // Too many inputs. 12927 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12928 break; 12929 } 12930 } 12931 12932 // If everything is good, we can make a shuffle operation. 12933 if (VecIn1.getNode()) { 12934 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12935 SmallVector<int, 8> Mask; 12936 for (unsigned i = 0; i != NumInScalars; ++i) { 12937 unsigned Opcode = N->getOperand(i).getOpcode(); 12938 if (Opcode == ISD::UNDEF) { 12939 Mask.push_back(-1); 12940 continue; 12941 } 12942 12943 // Operands can also be zero. 12944 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12945 assert(UsesZeroVector && 12946 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12947 "Unexpected node found!"); 12948 Mask.push_back(NumInScalars+i); 12949 continue; 12950 } 12951 12952 // If extracting from the first vector, just use the index directly. 12953 SDValue Extract = N->getOperand(i); 12954 SDValue ExtVal = Extract.getOperand(1); 12955 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12956 if (Extract.getOperand(0) == VecIn1) { 12957 Mask.push_back(ExtIndex); 12958 continue; 12959 } 12960 12961 // Otherwise, use InIdx + InputVecSize 12962 Mask.push_back(InNumElements + ExtIndex); 12963 } 12964 12965 // Avoid introducing illegal shuffles with zero. 12966 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12967 return SDValue(); 12968 12969 // We can't generate a shuffle node with mismatched input and output types. 12970 // Attempt to transform a single input vector to the correct type. 12971 if ((VT != VecIn1.getValueType())) { 12972 // If the input vector type has a different base type to the output 12973 // vector type, bail out. 12974 EVT VTElemType = VT.getVectorElementType(); 12975 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12976 (VecIn2.getNode() && 12977 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12978 return SDValue(); 12979 12980 // If the input vector is too small, widen it. 12981 // We only support widening of vectors which are half the size of the 12982 // output registers. For example XMM->YMM widening on X86 with AVX. 12983 EVT VecInT = VecIn1.getValueType(); 12984 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12985 // If we only have one small input, widen it by adding undef values. 12986 if (!VecIn2.getNode()) 12987 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12988 DAG.getUNDEF(VecIn1.getValueType())); 12989 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12990 // If we have two small inputs of the same type, try to concat them. 12991 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12992 VecIn2 = SDValue(nullptr, 0); 12993 } else 12994 return SDValue(); 12995 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12996 // If the input vector is too large, try to split it. 12997 // We don't support having two input vectors that are too large. 12998 // If the zero vector was used, we can not split the vector, 12999 // since we'd need 3 inputs. 13000 if (UsesZeroVector || VecIn2.getNode()) 13001 return SDValue(); 13002 13003 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 13004 return SDValue(); 13005 13006 // Try to replace VecIn1 with two extract_subvectors 13007 // No need to update the masks, they should still be correct. 13008 VecIn2 = DAG.getNode( 13009 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 13010 DAG.getConstant(VT.getVectorNumElements(), dl, 13011 TLI.getVectorIdxTy(DAG.getDataLayout()))); 13012 VecIn1 = DAG.getNode( 13013 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 13014 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 13015 } else 13016 return SDValue(); 13017 } 13018 13019 if (UsesZeroVector) 13020 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 13021 DAG.getConstantFP(0.0, dl, VT); 13022 else 13023 // If VecIn2 is unused then change it to undef. 13024 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 13025 13026 // Check that we were able to transform all incoming values to the same 13027 // type. 13028 if (VecIn2.getValueType() != VecIn1.getValueType() || 13029 VecIn1.getValueType() != VT) 13030 return SDValue(); 13031 13032 // Return the new VECTOR_SHUFFLE node. 13033 SDValue Ops[2]; 13034 Ops[0] = VecIn1; 13035 Ops[1] = VecIn2; 13036 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], Mask); 13037 } 13038 13039 return SDValue(); 13040 } 13041 13042 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 13043 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 13044 EVT OpVT = N->getOperand(0).getValueType(); 13045 13046 // If the operands are legal vectors, leave them alone. 13047 if (TLI.isTypeLegal(OpVT)) 13048 return SDValue(); 13049 13050 SDLoc DL(N); 13051 EVT VT = N->getValueType(0); 13052 SmallVector<SDValue, 8> Ops; 13053 13054 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 13055 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 13056 13057 // Keep track of what we encounter. 13058 bool AnyInteger = false; 13059 bool AnyFP = false; 13060 for (const SDValue &Op : N->ops()) { 13061 if (ISD::BITCAST == Op.getOpcode() && 13062 !Op.getOperand(0).getValueType().isVector()) 13063 Ops.push_back(Op.getOperand(0)); 13064 else if (ISD::UNDEF == Op.getOpcode()) 13065 Ops.push_back(ScalarUndef); 13066 else 13067 return SDValue(); 13068 13069 // Note whether we encounter an integer or floating point scalar. 13070 // If it's neither, bail out, it could be something weird like x86mmx. 13071 EVT LastOpVT = Ops.back().getValueType(); 13072 if (LastOpVT.isFloatingPoint()) 13073 AnyFP = true; 13074 else if (LastOpVT.isInteger()) 13075 AnyInteger = true; 13076 else 13077 return SDValue(); 13078 } 13079 13080 // If any of the operands is a floating point scalar bitcast to a vector, 13081 // use floating point types throughout, and bitcast everything. 13082 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 13083 if (AnyFP) { 13084 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 13085 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 13086 if (AnyInteger) { 13087 for (SDValue &Op : Ops) { 13088 if (Op.getValueType() == SVT) 13089 continue; 13090 if (Op.isUndef()) 13091 Op = ScalarUndef; 13092 else 13093 Op = DAG.getBitcast(SVT, Op); 13094 } 13095 } 13096 } 13097 13098 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 13099 VT.getSizeInBits() / SVT.getSizeInBits()); 13100 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 13101 } 13102 13103 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 13104 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 13105 // most two distinct vectors the same size as the result, attempt to turn this 13106 // into a legal shuffle. 13107 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 13108 EVT VT = N->getValueType(0); 13109 EVT OpVT = N->getOperand(0).getValueType(); 13110 int NumElts = VT.getVectorNumElements(); 13111 int NumOpElts = OpVT.getVectorNumElements(); 13112 13113 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 13114 SmallVector<int, 8> Mask; 13115 13116 for (SDValue Op : N->ops()) { 13117 // Peek through any bitcast. 13118 while (Op.getOpcode() == ISD::BITCAST) 13119 Op = Op.getOperand(0); 13120 13121 // UNDEF nodes convert to UNDEF shuffle mask values. 13122 if (Op.isUndef()) { 13123 Mask.append((unsigned)NumOpElts, -1); 13124 continue; 13125 } 13126 13127 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13128 return SDValue(); 13129 13130 // What vector are we extracting the subvector from and at what index? 13131 SDValue ExtVec = Op.getOperand(0); 13132 13133 // We want the EVT of the original extraction to correctly scale the 13134 // extraction index. 13135 EVT ExtVT = ExtVec.getValueType(); 13136 13137 // Peek through any bitcast. 13138 while (ExtVec.getOpcode() == ISD::BITCAST) 13139 ExtVec = ExtVec.getOperand(0); 13140 13141 // UNDEF nodes convert to UNDEF shuffle mask values. 13142 if (ExtVec.isUndef()) { 13143 Mask.append((unsigned)NumOpElts, -1); 13144 continue; 13145 } 13146 13147 if (!isa<ConstantSDNode>(Op.getOperand(1))) 13148 return SDValue(); 13149 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 13150 13151 // Ensure that we are extracting a subvector from a vector the same 13152 // size as the result. 13153 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 13154 return SDValue(); 13155 13156 // Scale the subvector index to account for any bitcast. 13157 int NumExtElts = ExtVT.getVectorNumElements(); 13158 if (0 == (NumExtElts % NumElts)) 13159 ExtIdx /= (NumExtElts / NumElts); 13160 else if (0 == (NumElts % NumExtElts)) 13161 ExtIdx *= (NumElts / NumExtElts); 13162 else 13163 return SDValue(); 13164 13165 // At most we can reference 2 inputs in the final shuffle. 13166 if (SV0.isUndef() || SV0 == ExtVec) { 13167 SV0 = ExtVec; 13168 for (int i = 0; i != NumOpElts; ++i) 13169 Mask.push_back(i + ExtIdx); 13170 } else if (SV1.isUndef() || SV1 == ExtVec) { 13171 SV1 = ExtVec; 13172 for (int i = 0; i != NumOpElts; ++i) 13173 Mask.push_back(i + ExtIdx + NumElts); 13174 } else { 13175 return SDValue(); 13176 } 13177 } 13178 13179 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 13180 return SDValue(); 13181 13182 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 13183 DAG.getBitcast(VT, SV1), Mask); 13184 } 13185 13186 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 13187 // If we only have one input vector, we don't need to do any concatenation. 13188 if (N->getNumOperands() == 1) 13189 return N->getOperand(0); 13190 13191 // Check if all of the operands are undefs. 13192 EVT VT = N->getValueType(0); 13193 if (ISD::allOperandsUndef(N)) 13194 return DAG.getUNDEF(VT); 13195 13196 // Optimize concat_vectors where all but the first of the vectors are undef. 13197 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 13198 return Op.isUndef(); 13199 })) { 13200 SDValue In = N->getOperand(0); 13201 assert(In.getValueType().isVector() && "Must concat vectors"); 13202 13203 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 13204 if (In->getOpcode() == ISD::BITCAST && 13205 !In->getOperand(0)->getValueType(0).isVector()) { 13206 SDValue Scalar = In->getOperand(0); 13207 13208 // If the bitcast type isn't legal, it might be a trunc of a legal type; 13209 // look through the trunc so we can still do the transform: 13210 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 13211 if (Scalar->getOpcode() == ISD::TRUNCATE && 13212 !TLI.isTypeLegal(Scalar.getValueType()) && 13213 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 13214 Scalar = Scalar->getOperand(0); 13215 13216 EVT SclTy = Scalar->getValueType(0); 13217 13218 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 13219 return SDValue(); 13220 13221 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 13222 VT.getSizeInBits() / SclTy.getSizeInBits()); 13223 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 13224 return SDValue(); 13225 13226 SDLoc dl = SDLoc(N); 13227 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 13228 return DAG.getBitcast(VT, Res); 13229 } 13230 } 13231 13232 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 13233 // We have already tested above for an UNDEF only concatenation. 13234 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 13235 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 13236 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 13237 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 13238 }; 13239 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 13240 SmallVector<SDValue, 8> Opnds; 13241 EVT SVT = VT.getScalarType(); 13242 13243 EVT MinVT = SVT; 13244 if (!SVT.isFloatingPoint()) { 13245 // If BUILD_VECTOR are from built from integer, they may have different 13246 // operand types. Get the smallest type and truncate all operands to it. 13247 bool FoundMinVT = false; 13248 for (const SDValue &Op : N->ops()) 13249 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13250 EVT OpSVT = Op.getOperand(0)->getValueType(0); 13251 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 13252 FoundMinVT = true; 13253 } 13254 assert(FoundMinVT && "Concat vector type mismatch"); 13255 } 13256 13257 for (const SDValue &Op : N->ops()) { 13258 EVT OpVT = Op.getValueType(); 13259 unsigned NumElts = OpVT.getVectorNumElements(); 13260 13261 if (ISD::UNDEF == Op.getOpcode()) 13262 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 13263 13264 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13265 if (SVT.isFloatingPoint()) { 13266 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 13267 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 13268 } else { 13269 for (unsigned i = 0; i != NumElts; ++i) 13270 Opnds.push_back( 13271 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 13272 } 13273 } 13274 } 13275 13276 assert(VT.getVectorNumElements() == Opnds.size() && 13277 "Concat vector type mismatch"); 13278 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 13279 } 13280 13281 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 13282 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 13283 return V; 13284 13285 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 13286 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 13287 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 13288 return V; 13289 13290 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 13291 // nodes often generate nop CONCAT_VECTOR nodes. 13292 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 13293 // place the incoming vectors at the exact same location. 13294 SDValue SingleSource = SDValue(); 13295 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 13296 13297 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13298 SDValue Op = N->getOperand(i); 13299 13300 if (Op.isUndef()) 13301 continue; 13302 13303 // Check if this is the identity extract: 13304 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13305 return SDValue(); 13306 13307 // Find the single incoming vector for the extract_subvector. 13308 if (SingleSource.getNode()) { 13309 if (Op.getOperand(0) != SingleSource) 13310 return SDValue(); 13311 } else { 13312 SingleSource = Op.getOperand(0); 13313 13314 // Check the source type is the same as the type of the result. 13315 // If not, this concat may extend the vector, so we can not 13316 // optimize it away. 13317 if (SingleSource.getValueType() != N->getValueType(0)) 13318 return SDValue(); 13319 } 13320 13321 unsigned IdentityIndex = i * PartNumElem; 13322 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13323 // The extract index must be constant. 13324 if (!CS) 13325 return SDValue(); 13326 13327 // Check that we are reading from the identity index. 13328 if (CS->getZExtValue() != IdentityIndex) 13329 return SDValue(); 13330 } 13331 13332 if (SingleSource.getNode()) 13333 return SingleSource; 13334 13335 return SDValue(); 13336 } 13337 13338 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 13339 EVT NVT = N->getValueType(0); 13340 SDValue V = N->getOperand(0); 13341 13342 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 13343 // Combine: 13344 // (extract_subvec (concat V1, V2, ...), i) 13345 // Into: 13346 // Vi if possible 13347 // Only operand 0 is checked as 'concat' assumes all inputs of the same 13348 // type. 13349 if (V->getOperand(0).getValueType() != NVT) 13350 return SDValue(); 13351 unsigned Idx = N->getConstantOperandVal(1); 13352 unsigned NumElems = NVT.getVectorNumElements(); 13353 assert((Idx % NumElems) == 0 && 13354 "IDX in concat is not a multiple of the result vector length."); 13355 return V->getOperand(Idx / NumElems); 13356 } 13357 13358 // Skip bitcasting 13359 if (V->getOpcode() == ISD::BITCAST) 13360 V = V.getOperand(0); 13361 13362 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13363 SDLoc dl(N); 13364 // Handle only simple case where vector being inserted and vector 13365 // being extracted are of same type, and are half size of larger vectors. 13366 EVT BigVT = V->getOperand(0).getValueType(); 13367 EVT SmallVT = V->getOperand(1).getValueType(); 13368 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 13369 return SDValue(); 13370 13371 // Only handle cases where both indexes are constants with the same type. 13372 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13373 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13374 13375 if (InsIdx && ExtIdx && 13376 InsIdx->getValueType(0).getSizeInBits() <= 64 && 13377 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 13378 // Combine: 13379 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 13380 // Into: 13381 // indices are equal or bit offsets are equal => V1 13382 // otherwise => (extract_subvec V1, ExtIdx) 13383 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 13384 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 13385 return DAG.getBitcast(NVT, V->getOperand(1)); 13386 return DAG.getNode( 13387 ISD::EXTRACT_SUBVECTOR, dl, NVT, 13388 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 13389 N->getOperand(1)); 13390 } 13391 } 13392 13393 return SDValue(); 13394 } 13395 13396 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 13397 SDValue V, SelectionDAG &DAG) { 13398 SDLoc DL(V); 13399 EVT VT = V.getValueType(); 13400 13401 switch (V.getOpcode()) { 13402 default: 13403 return V; 13404 13405 case ISD::CONCAT_VECTORS: { 13406 EVT OpVT = V->getOperand(0).getValueType(); 13407 int OpSize = OpVT.getVectorNumElements(); 13408 SmallBitVector OpUsedElements(OpSize, false); 13409 bool FoundSimplification = false; 13410 SmallVector<SDValue, 4> NewOps; 13411 NewOps.reserve(V->getNumOperands()); 13412 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 13413 SDValue Op = V->getOperand(i); 13414 bool OpUsed = false; 13415 for (int j = 0; j < OpSize; ++j) 13416 if (UsedElements[i * OpSize + j]) { 13417 OpUsedElements[j] = true; 13418 OpUsed = true; 13419 } 13420 NewOps.push_back( 13421 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13422 : DAG.getUNDEF(OpVT)); 13423 FoundSimplification |= Op == NewOps.back(); 13424 OpUsedElements.reset(); 13425 } 13426 if (FoundSimplification) 13427 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13428 return V; 13429 } 13430 13431 case ISD::INSERT_SUBVECTOR: { 13432 SDValue BaseV = V->getOperand(0); 13433 SDValue SubV = V->getOperand(1); 13434 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13435 if (!IdxN) 13436 return V; 13437 13438 int SubSize = SubV.getValueType().getVectorNumElements(); 13439 int Idx = IdxN->getZExtValue(); 13440 bool SubVectorUsed = false; 13441 SmallBitVector SubUsedElements(SubSize, false); 13442 for (int i = 0; i < SubSize; ++i) 13443 if (UsedElements[i + Idx]) { 13444 SubVectorUsed = true; 13445 SubUsedElements[i] = true; 13446 UsedElements[i + Idx] = false; 13447 } 13448 13449 // Now recurse on both the base and sub vectors. 13450 SDValue SimplifiedSubV = 13451 SubVectorUsed 13452 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13453 : DAG.getUNDEF(SubV.getValueType()); 13454 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13455 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13456 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13457 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13458 return V; 13459 } 13460 } 13461 } 13462 13463 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13464 SDValue N1, SelectionDAG &DAG) { 13465 EVT VT = SVN->getValueType(0); 13466 int NumElts = VT.getVectorNumElements(); 13467 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13468 for (int M : SVN->getMask()) 13469 if (M >= 0 && M < NumElts) 13470 N0UsedElements[M] = true; 13471 else if (M >= NumElts) 13472 N1UsedElements[M - NumElts] = true; 13473 13474 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13475 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13476 if (S0 == N0 && S1 == N1) 13477 return SDValue(); 13478 13479 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13480 } 13481 13482 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13483 // or turn a shuffle of a single concat into simpler shuffle then concat. 13484 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13485 EVT VT = N->getValueType(0); 13486 unsigned NumElts = VT.getVectorNumElements(); 13487 13488 SDValue N0 = N->getOperand(0); 13489 SDValue N1 = N->getOperand(1); 13490 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13491 13492 SmallVector<SDValue, 4> Ops; 13493 EVT ConcatVT = N0.getOperand(0).getValueType(); 13494 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13495 unsigned NumConcats = NumElts / NumElemsPerConcat; 13496 13497 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13498 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13499 // half vector elements. 13500 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 13501 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13502 SVN->getMask().end(), [](int i) { return i == -1; })) { 13503 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13504 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13505 N1 = DAG.getUNDEF(ConcatVT); 13506 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13507 } 13508 13509 // Look at every vector that's inserted. We're looking for exact 13510 // subvector-sized copies from a concatenated vector 13511 for (unsigned I = 0; I != NumConcats; ++I) { 13512 // Make sure we're dealing with a copy. 13513 unsigned Begin = I * NumElemsPerConcat; 13514 bool AllUndef = true, NoUndef = true; 13515 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13516 if (SVN->getMaskElt(J) >= 0) 13517 AllUndef = false; 13518 else 13519 NoUndef = false; 13520 } 13521 13522 if (NoUndef) { 13523 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13524 return SDValue(); 13525 13526 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13527 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13528 return SDValue(); 13529 13530 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13531 if (FirstElt < N0.getNumOperands()) 13532 Ops.push_back(N0.getOperand(FirstElt)); 13533 else 13534 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13535 13536 } else if (AllUndef) { 13537 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13538 } else { // Mixed with general masks and undefs, can't do optimization. 13539 return SDValue(); 13540 } 13541 } 13542 13543 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13544 } 13545 13546 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13547 EVT VT = N->getValueType(0); 13548 unsigned NumElts = VT.getVectorNumElements(); 13549 13550 SDValue N0 = N->getOperand(0); 13551 SDValue N1 = N->getOperand(1); 13552 13553 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13554 13555 // Canonicalize shuffle undef, undef -> undef 13556 if (N0.isUndef() && N1.isUndef()) 13557 return DAG.getUNDEF(VT); 13558 13559 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13560 13561 // Canonicalize shuffle v, v -> v, undef 13562 if (N0 == N1) { 13563 SmallVector<int, 8> NewMask; 13564 for (unsigned i = 0; i != NumElts; ++i) { 13565 int Idx = SVN->getMaskElt(i); 13566 if (Idx >= (int)NumElts) Idx -= NumElts; 13567 NewMask.push_back(Idx); 13568 } 13569 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 13570 } 13571 13572 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13573 if (N0.isUndef()) 13574 return DAG.getCommutedVectorShuffle(*SVN); 13575 13576 // Remove references to rhs if it is undef 13577 if (N1.isUndef()) { 13578 bool Changed = false; 13579 SmallVector<int, 8> NewMask; 13580 for (unsigned i = 0; i != NumElts; ++i) { 13581 int Idx = SVN->getMaskElt(i); 13582 if (Idx >= (int)NumElts) { 13583 Idx = -1; 13584 Changed = true; 13585 } 13586 NewMask.push_back(Idx); 13587 } 13588 if (Changed) 13589 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 13590 } 13591 13592 // If it is a splat, check if the argument vector is another splat or a 13593 // build_vector. 13594 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13595 SDNode *V = N0.getNode(); 13596 13597 // If this is a bit convert that changes the element type of the vector but 13598 // not the number of vector elements, look through it. Be careful not to 13599 // look though conversions that change things like v4f32 to v2f64. 13600 if (V->getOpcode() == ISD::BITCAST) { 13601 SDValue ConvInput = V->getOperand(0); 13602 if (ConvInput.getValueType().isVector() && 13603 ConvInput.getValueType().getVectorNumElements() == NumElts) 13604 V = ConvInput.getNode(); 13605 } 13606 13607 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13608 assert(V->getNumOperands() == NumElts && 13609 "BUILD_VECTOR has wrong number of operands"); 13610 SDValue Base; 13611 bool AllSame = true; 13612 for (unsigned i = 0; i != NumElts; ++i) { 13613 if (!V->getOperand(i).isUndef()) { 13614 Base = V->getOperand(i); 13615 break; 13616 } 13617 } 13618 // Splat of <u, u, u, u>, return <u, u, u, u> 13619 if (!Base.getNode()) 13620 return N0; 13621 for (unsigned i = 0; i != NumElts; ++i) { 13622 if (V->getOperand(i) != Base) { 13623 AllSame = false; 13624 break; 13625 } 13626 } 13627 // Splat of <x, x, x, x>, return <x, x, x, x> 13628 if (AllSame) 13629 return N0; 13630 13631 // Canonicalize any other splat as a build_vector. 13632 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13633 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13634 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 13635 13636 // We may have jumped through bitcasts, so the type of the 13637 // BUILD_VECTOR may not match the type of the shuffle. 13638 if (V->getValueType(0) != VT) 13639 NewBV = DAG.getBitcast(VT, NewBV); 13640 return NewBV; 13641 } 13642 } 13643 13644 // There are various patterns used to build up a vector from smaller vectors, 13645 // subvectors, or elements. Scan chains of these and replace unused insertions 13646 // or components with undef. 13647 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13648 return S; 13649 13650 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13651 Level < AfterLegalizeVectorOps && 13652 (N1.isUndef() || 13653 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13654 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13655 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 13656 return V; 13657 } 13658 13659 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13660 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13661 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13662 SmallVector<SDValue, 8> Ops; 13663 for (int M : SVN->getMask()) { 13664 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13665 if (M >= 0) { 13666 int Idx = M % NumElts; 13667 SDValue &S = (M < (int)NumElts ? N0 : N1); 13668 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13669 Op = S.getOperand(Idx); 13670 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13671 if (Idx == 0) 13672 Op = S.getOperand(0); 13673 } else { 13674 // Operand can't be combined - bail out. 13675 break; 13676 } 13677 } 13678 Ops.push_back(Op); 13679 } 13680 if (Ops.size() == VT.getVectorNumElements()) { 13681 // BUILD_VECTOR requires all inputs to be of the same type, find the 13682 // maximum type and extend them all. 13683 EVT SVT = VT.getScalarType(); 13684 if (SVT.isInteger()) 13685 for (SDValue &Op : Ops) 13686 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13687 if (SVT != VT.getScalarType()) 13688 for (SDValue &Op : Ops) 13689 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13690 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13691 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13692 return DAG.getBuildVector(VT, SDLoc(N), Ops); 13693 } 13694 } 13695 13696 // If this shuffle only has a single input that is a bitcasted shuffle, 13697 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13698 // back to their original types. 13699 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13700 N1.isUndef() && Level < AfterLegalizeVectorOps && 13701 TLI.isTypeLegal(VT)) { 13702 13703 // Peek through the bitcast only if there is one user. 13704 SDValue BC0 = N0; 13705 while (BC0.getOpcode() == ISD::BITCAST) { 13706 if (!BC0.hasOneUse()) 13707 break; 13708 BC0 = BC0.getOperand(0); 13709 } 13710 13711 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13712 if (Scale == 1) 13713 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13714 13715 SmallVector<int, 8> NewMask; 13716 for (int M : Mask) 13717 for (int s = 0; s != Scale; ++s) 13718 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13719 return NewMask; 13720 }; 13721 13722 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13723 EVT SVT = VT.getScalarType(); 13724 EVT InnerVT = BC0->getValueType(0); 13725 EVT InnerSVT = InnerVT.getScalarType(); 13726 13727 // Determine which shuffle works with the smaller scalar type. 13728 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13729 EVT ScaleSVT = ScaleVT.getScalarType(); 13730 13731 if (TLI.isTypeLegal(ScaleVT) && 13732 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13733 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13734 13735 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13736 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13737 13738 // Scale the shuffle masks to the smaller scalar type. 13739 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13740 SmallVector<int, 8> InnerMask = 13741 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13742 SmallVector<int, 8> OuterMask = 13743 ScaleShuffleMask(SVN->getMask(), OuterScale); 13744 13745 // Merge the shuffle masks. 13746 SmallVector<int, 8> NewMask; 13747 for (int M : OuterMask) 13748 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13749 13750 // Test for shuffle mask legality over both commutations. 13751 SDValue SV0 = BC0->getOperand(0); 13752 SDValue SV1 = BC0->getOperand(1); 13753 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13754 if (!LegalMask) { 13755 std::swap(SV0, SV1); 13756 ShuffleVectorSDNode::commuteMask(NewMask); 13757 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13758 } 13759 13760 if (LegalMask) { 13761 SV0 = DAG.getBitcast(ScaleVT, SV0); 13762 SV1 = DAG.getBitcast(ScaleVT, SV1); 13763 return DAG.getBitcast( 13764 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13765 } 13766 } 13767 } 13768 } 13769 13770 // Canonicalize shuffles according to rules: 13771 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13772 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13773 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13774 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13775 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13776 TLI.isTypeLegal(VT)) { 13777 // The incoming shuffle must be of the same type as the result of the 13778 // current shuffle. 13779 assert(N1->getOperand(0).getValueType() == VT && 13780 "Shuffle types don't match"); 13781 13782 SDValue SV0 = N1->getOperand(0); 13783 SDValue SV1 = N1->getOperand(1); 13784 bool HasSameOp0 = N0 == SV0; 13785 bool IsSV1Undef = SV1.isUndef(); 13786 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13787 // Commute the operands of this shuffle so that next rule 13788 // will trigger. 13789 return DAG.getCommutedVectorShuffle(*SVN); 13790 } 13791 13792 // Try to fold according to rules: 13793 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13794 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13795 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13796 // Don't try to fold shuffles with illegal type. 13797 // Only fold if this shuffle is the only user of the other shuffle. 13798 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13799 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13800 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13801 13802 // The incoming shuffle must be of the same type as the result of the 13803 // current shuffle. 13804 assert(OtherSV->getOperand(0).getValueType() == VT && 13805 "Shuffle types don't match"); 13806 13807 SDValue SV0, SV1; 13808 SmallVector<int, 4> Mask; 13809 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13810 // operand, and SV1 as the second operand. 13811 for (unsigned i = 0; i != NumElts; ++i) { 13812 int Idx = SVN->getMaskElt(i); 13813 if (Idx < 0) { 13814 // Propagate Undef. 13815 Mask.push_back(Idx); 13816 continue; 13817 } 13818 13819 SDValue CurrentVec; 13820 if (Idx < (int)NumElts) { 13821 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13822 // shuffle mask to identify which vector is actually referenced. 13823 Idx = OtherSV->getMaskElt(Idx); 13824 if (Idx < 0) { 13825 // Propagate Undef. 13826 Mask.push_back(Idx); 13827 continue; 13828 } 13829 13830 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13831 : OtherSV->getOperand(1); 13832 } else { 13833 // This shuffle index references an element within N1. 13834 CurrentVec = N1; 13835 } 13836 13837 // Simple case where 'CurrentVec' is UNDEF. 13838 if (CurrentVec.isUndef()) { 13839 Mask.push_back(-1); 13840 continue; 13841 } 13842 13843 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13844 // will be the first or second operand of the combined shuffle. 13845 Idx = Idx % NumElts; 13846 if (!SV0.getNode() || SV0 == CurrentVec) { 13847 // Ok. CurrentVec is the left hand side. 13848 // Update the mask accordingly. 13849 SV0 = CurrentVec; 13850 Mask.push_back(Idx); 13851 continue; 13852 } 13853 13854 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13855 if (SV1.getNode() && SV1 != CurrentVec) 13856 return SDValue(); 13857 13858 // Ok. CurrentVec is the right hand side. 13859 // Update the mask accordingly. 13860 SV1 = CurrentVec; 13861 Mask.push_back(Idx + NumElts); 13862 } 13863 13864 // Check if all indices in Mask are Undef. In case, propagate Undef. 13865 bool isUndefMask = true; 13866 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13867 isUndefMask &= Mask[i] < 0; 13868 13869 if (isUndefMask) 13870 return DAG.getUNDEF(VT); 13871 13872 if (!SV0.getNode()) 13873 SV0 = DAG.getUNDEF(VT); 13874 if (!SV1.getNode()) 13875 SV1 = DAG.getUNDEF(VT); 13876 13877 // Avoid introducing shuffles with illegal mask. 13878 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13879 ShuffleVectorSDNode::commuteMask(Mask); 13880 13881 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13882 return SDValue(); 13883 13884 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13885 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13886 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13887 std::swap(SV0, SV1); 13888 } 13889 13890 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13891 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13892 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13893 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 13894 } 13895 13896 return SDValue(); 13897 } 13898 13899 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13900 SDValue InVal = N->getOperand(0); 13901 EVT VT = N->getValueType(0); 13902 13903 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13904 // with a VECTOR_SHUFFLE. 13905 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13906 SDValue InVec = InVal->getOperand(0); 13907 SDValue EltNo = InVal->getOperand(1); 13908 13909 // FIXME: We could support implicit truncation if the shuffle can be 13910 // scaled to a smaller vector scalar type. 13911 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13912 if (C0 && VT == InVec.getValueType() && 13913 VT.getScalarType() == InVal.getValueType()) { 13914 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13915 int Elt = C0->getZExtValue(); 13916 NewMask[0] = Elt; 13917 13918 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13919 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13920 NewMask); 13921 } 13922 } 13923 13924 return SDValue(); 13925 } 13926 13927 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13928 EVT VT = N->getValueType(0); 13929 SDValue N0 = N->getOperand(0); 13930 SDValue N1 = N->getOperand(1); 13931 SDValue N2 = N->getOperand(2); 13932 13933 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 13934 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 13935 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 13936 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 13937 N0.getOperand(1).getValueType() == N1.getValueType() && 13938 N0.getOperand(2) == N2) 13939 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 13940 N1, N2); 13941 13942 if (N0.getValueType() != N1.getValueType()) 13943 return SDValue(); 13944 13945 // If the input vector is a concatenation, and the insert replaces 13946 // one of the halves, we can optimize into a single concat_vectors. 13947 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 && 13948 N2.getOpcode() == ISD::Constant) { 13949 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13950 13951 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13952 // (concat_vectors Z, Y) 13953 if (InsIdx == 0) 13954 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1, 13955 N0.getOperand(1)); 13956 13957 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13958 // (concat_vectors X, Z) 13959 if (InsIdx == VT.getVectorNumElements() / 2) 13960 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0), 13961 N1); 13962 } 13963 13964 return SDValue(); 13965 } 13966 13967 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13968 SDValue N0 = N->getOperand(0); 13969 13970 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13971 if (N0->getOpcode() == ISD::FP16_TO_FP) 13972 return N0->getOperand(0); 13973 13974 return SDValue(); 13975 } 13976 13977 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13978 SDValue N0 = N->getOperand(0); 13979 13980 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13981 if (N0->getOpcode() == ISD::AND) { 13982 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13983 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13984 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13985 N0.getOperand(0)); 13986 } 13987 } 13988 13989 return SDValue(); 13990 } 13991 13992 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13993 /// with the destination vector and a zero vector. 13994 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13995 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13996 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13997 EVT VT = N->getValueType(0); 13998 SDValue LHS = N->getOperand(0); 13999 SDValue RHS = N->getOperand(1); 14000 SDLoc dl(N); 14001 14002 // Make sure we're not running after operation legalization where it 14003 // may have custom lowered the vector shuffles. 14004 if (LegalOperations) 14005 return SDValue(); 14006 14007 if (N->getOpcode() != ISD::AND) 14008 return SDValue(); 14009 14010 if (RHS.getOpcode() == ISD::BITCAST) 14011 RHS = RHS.getOperand(0); 14012 14013 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 14014 return SDValue(); 14015 14016 EVT RVT = RHS.getValueType(); 14017 unsigned NumElts = RHS.getNumOperands(); 14018 14019 // Attempt to create a valid clear mask, splitting the mask into 14020 // sub elements and checking to see if each is 14021 // all zeros or all ones - suitable for shuffle masking. 14022 auto BuildClearMask = [&](int Split) { 14023 int NumSubElts = NumElts * Split; 14024 int NumSubBits = RVT.getScalarSizeInBits() / Split; 14025 14026 SmallVector<int, 8> Indices; 14027 for (int i = 0; i != NumSubElts; ++i) { 14028 int EltIdx = i / Split; 14029 int SubIdx = i % Split; 14030 SDValue Elt = RHS.getOperand(EltIdx); 14031 if (Elt.isUndef()) { 14032 Indices.push_back(-1); 14033 continue; 14034 } 14035 14036 APInt Bits; 14037 if (isa<ConstantSDNode>(Elt)) 14038 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 14039 else if (isa<ConstantFPSDNode>(Elt)) 14040 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 14041 else 14042 return SDValue(); 14043 14044 // Extract the sub element from the constant bit mask. 14045 if (DAG.getDataLayout().isBigEndian()) { 14046 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 14047 } else { 14048 Bits = Bits.lshr(SubIdx * NumSubBits); 14049 } 14050 14051 if (Split > 1) 14052 Bits = Bits.trunc(NumSubBits); 14053 14054 if (Bits.isAllOnesValue()) 14055 Indices.push_back(i); 14056 else if (Bits == 0) 14057 Indices.push_back(i + NumSubElts); 14058 else 14059 return SDValue(); 14060 } 14061 14062 // Let's see if the target supports this vector_shuffle. 14063 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 14064 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 14065 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 14066 return SDValue(); 14067 14068 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 14069 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 14070 DAG.getBitcast(ClearVT, LHS), 14071 Zero, Indices)); 14072 }; 14073 14074 // Determine maximum split level (byte level masking). 14075 int MaxSplit = 1; 14076 if (RVT.getScalarSizeInBits() % 8 == 0) 14077 MaxSplit = RVT.getScalarSizeInBits() / 8; 14078 14079 for (int Split = 1; Split <= MaxSplit; ++Split) 14080 if (RVT.getScalarSizeInBits() % Split == 0) 14081 if (SDValue S = BuildClearMask(Split)) 14082 return S; 14083 14084 return SDValue(); 14085 } 14086 14087 /// Visit a binary vector operation, like ADD. 14088 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 14089 assert(N->getValueType(0).isVector() && 14090 "SimplifyVBinOp only works on vectors!"); 14091 14092 SDValue LHS = N->getOperand(0); 14093 SDValue RHS = N->getOperand(1); 14094 SDValue Ops[] = {LHS, RHS}; 14095 14096 // See if we can constant fold the vector operation. 14097 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 14098 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 14099 return Fold; 14100 14101 // Try to convert a constant mask AND into a shuffle clear mask. 14102 if (SDValue Shuffle = XformToShuffleWithZero(N)) 14103 return Shuffle; 14104 14105 // Type legalization might introduce new shuffles in the DAG. 14106 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 14107 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 14108 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 14109 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 14110 LHS.getOperand(1).isUndef() && 14111 RHS.getOperand(1).isUndef()) { 14112 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 14113 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 14114 14115 if (SVN0->getMask().equals(SVN1->getMask())) { 14116 EVT VT = N->getValueType(0); 14117 SDValue UndefVector = LHS.getOperand(1); 14118 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 14119 LHS.getOperand(0), RHS.getOperand(0), 14120 N->getFlags()); 14121 AddUsersToWorklist(N); 14122 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 14123 SVN0->getMask()); 14124 } 14125 } 14126 14127 return SDValue(); 14128 } 14129 14130 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 14131 SDValue N2) { 14132 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 14133 14134 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 14135 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 14136 14137 // If we got a simplified select_cc node back from SimplifySelectCC, then 14138 // break it down into a new SETCC node, and a new SELECT node, and then return 14139 // the SELECT node, since we were called with a SELECT node. 14140 if (SCC.getNode()) { 14141 // Check to see if we got a select_cc back (to turn into setcc/select). 14142 // Otherwise, just return whatever node we got back, like fabs. 14143 if (SCC.getOpcode() == ISD::SELECT_CC) { 14144 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 14145 N0.getValueType(), 14146 SCC.getOperand(0), SCC.getOperand(1), 14147 SCC.getOperand(4)); 14148 AddToWorklist(SETCC.getNode()); 14149 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 14150 SCC.getOperand(2), SCC.getOperand(3)); 14151 } 14152 14153 return SCC; 14154 } 14155 return SDValue(); 14156 } 14157 14158 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 14159 /// being selected between, see if we can simplify the select. Callers of this 14160 /// should assume that TheSelect is deleted if this returns true. As such, they 14161 /// should return the appropriate thing (e.g. the node) back to the top-level of 14162 /// the DAG combiner loop to avoid it being looked at. 14163 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 14164 SDValue RHS) { 14165 14166 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14167 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 14168 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 14169 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 14170 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 14171 SDValue Sqrt = RHS; 14172 ISD::CondCode CC; 14173 SDValue CmpLHS; 14174 const ConstantFPSDNode *Zero = nullptr; 14175 14176 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 14177 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 14178 CmpLHS = TheSelect->getOperand(0); 14179 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 14180 } else { 14181 // SELECT or VSELECT 14182 SDValue Cmp = TheSelect->getOperand(0); 14183 if (Cmp.getOpcode() == ISD::SETCC) { 14184 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 14185 CmpLHS = Cmp.getOperand(0); 14186 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 14187 } 14188 } 14189 if (Zero && Zero->isZero() && 14190 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 14191 CC == ISD::SETULT || CC == ISD::SETLT)) { 14192 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14193 CombineTo(TheSelect, Sqrt); 14194 return true; 14195 } 14196 } 14197 } 14198 // Cannot simplify select with vector condition 14199 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 14200 14201 // If this is a select from two identical things, try to pull the operation 14202 // through the select. 14203 if (LHS.getOpcode() != RHS.getOpcode() || 14204 !LHS.hasOneUse() || !RHS.hasOneUse()) 14205 return false; 14206 14207 // If this is a load and the token chain is identical, replace the select 14208 // of two loads with a load through a select of the address to load from. 14209 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 14210 // constants have been dropped into the constant pool. 14211 if (LHS.getOpcode() == ISD::LOAD) { 14212 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 14213 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 14214 14215 // Token chains must be identical. 14216 if (LHS.getOperand(0) != RHS.getOperand(0) || 14217 // Do not let this transformation reduce the number of volatile loads. 14218 LLD->isVolatile() || RLD->isVolatile() || 14219 // FIXME: If either is a pre/post inc/dec load, 14220 // we'd need to split out the address adjustment. 14221 LLD->isIndexed() || RLD->isIndexed() || 14222 // If this is an EXTLOAD, the VT's must match. 14223 LLD->getMemoryVT() != RLD->getMemoryVT() || 14224 // If this is an EXTLOAD, the kind of extension must match. 14225 (LLD->getExtensionType() != RLD->getExtensionType() && 14226 // The only exception is if one of the extensions is anyext. 14227 LLD->getExtensionType() != ISD::EXTLOAD && 14228 RLD->getExtensionType() != ISD::EXTLOAD) || 14229 // FIXME: this discards src value information. This is 14230 // over-conservative. It would be beneficial to be able to remember 14231 // both potential memory locations. Since we are discarding 14232 // src value info, don't do the transformation if the memory 14233 // locations are not in the default address space. 14234 LLD->getPointerInfo().getAddrSpace() != 0 || 14235 RLD->getPointerInfo().getAddrSpace() != 0 || 14236 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 14237 LLD->getBasePtr().getValueType())) 14238 return false; 14239 14240 // Check that the select condition doesn't reach either load. If so, 14241 // folding this will induce a cycle into the DAG. If not, this is safe to 14242 // xform, so create a select of the addresses. 14243 SDValue Addr; 14244 if (TheSelect->getOpcode() == ISD::SELECT) { 14245 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 14246 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 14247 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 14248 return false; 14249 // The loads must not depend on one another. 14250 if (LLD->isPredecessorOf(RLD) || 14251 RLD->isPredecessorOf(LLD)) 14252 return false; 14253 Addr = DAG.getSelect(SDLoc(TheSelect), 14254 LLD->getBasePtr().getValueType(), 14255 TheSelect->getOperand(0), LLD->getBasePtr(), 14256 RLD->getBasePtr()); 14257 } else { // Otherwise SELECT_CC 14258 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 14259 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 14260 14261 if ((LLD->hasAnyUseOfValue(1) && 14262 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 14263 (RLD->hasAnyUseOfValue(1) && 14264 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 14265 return false; 14266 14267 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 14268 LLD->getBasePtr().getValueType(), 14269 TheSelect->getOperand(0), 14270 TheSelect->getOperand(1), 14271 LLD->getBasePtr(), RLD->getBasePtr(), 14272 TheSelect->getOperand(4)); 14273 } 14274 14275 SDValue Load; 14276 // It is safe to replace the two loads if they have different alignments, 14277 // but the new load must be the minimum (most restrictive) alignment of the 14278 // inputs. 14279 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 14280 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 14281 if (!RLD->isInvariant()) 14282 MMOFlags &= ~MachineMemOperand::MOInvariant; 14283 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 14284 // FIXME: Discards pointer and AA info. 14285 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 14286 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 14287 MMOFlags); 14288 } else { 14289 // FIXME: Discards pointer and AA info. 14290 Load = DAG.getExtLoad( 14291 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 14292 : LLD->getExtensionType(), 14293 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 14294 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 14295 } 14296 14297 // Users of the select now use the result of the load. 14298 CombineTo(TheSelect, Load); 14299 14300 // Users of the old loads now use the new load's chain. We know the 14301 // old-load value is dead now. 14302 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 14303 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 14304 return true; 14305 } 14306 14307 return false; 14308 } 14309 14310 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 14311 /// where 'cond' is the comparison specified by CC. 14312 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 14313 SDValue N2, SDValue N3, ISD::CondCode CC, 14314 bool NotExtCompare) { 14315 // (x ? y : y) -> y. 14316 if (N2 == N3) return N2; 14317 14318 EVT VT = N2.getValueType(); 14319 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 14320 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 14321 14322 // Determine if the condition we're dealing with is constant 14323 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 14324 N0, N1, CC, DL, false); 14325 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 14326 14327 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 14328 // fold select_cc true, x, y -> x 14329 // fold select_cc false, x, y -> y 14330 return !SCCC->isNullValue() ? N2 : N3; 14331 } 14332 14333 // Check to see if we can simplify the select into an fabs node 14334 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 14335 // Allow either -0.0 or 0.0 14336 if (CFP->isZero()) { 14337 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 14338 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 14339 N0 == N2 && N3.getOpcode() == ISD::FNEG && 14340 N2 == N3.getOperand(0)) 14341 return DAG.getNode(ISD::FABS, DL, VT, N0); 14342 14343 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 14344 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 14345 N0 == N3 && N2.getOpcode() == ISD::FNEG && 14346 N2.getOperand(0) == N3) 14347 return DAG.getNode(ISD::FABS, DL, VT, N3); 14348 } 14349 } 14350 14351 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 14352 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 14353 // in it. This is a win when the constant is not otherwise available because 14354 // it replaces two constant pool loads with one. We only do this if the FP 14355 // type is known to be legal, because if it isn't, then we are before legalize 14356 // types an we want the other legalization to happen first (e.g. to avoid 14357 // messing with soft float) and if the ConstantFP is not legal, because if 14358 // it is legal, we may not need to store the FP constant in a constant pool. 14359 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 14360 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 14361 if (TLI.isTypeLegal(N2.getValueType()) && 14362 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 14363 TargetLowering::Legal && 14364 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 14365 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 14366 // If both constants have multiple uses, then we won't need to do an 14367 // extra load, they are likely around in registers for other users. 14368 (TV->hasOneUse() || FV->hasOneUse())) { 14369 Constant *Elts[] = { 14370 const_cast<ConstantFP*>(FV->getConstantFPValue()), 14371 const_cast<ConstantFP*>(TV->getConstantFPValue()) 14372 }; 14373 Type *FPTy = Elts[0]->getType(); 14374 const DataLayout &TD = DAG.getDataLayout(); 14375 14376 // Create a ConstantArray of the two constants. 14377 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 14378 SDValue CPIdx = 14379 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 14380 TD.getPrefTypeAlignment(FPTy)); 14381 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 14382 14383 // Get the offsets to the 0 and 1 element of the array so that we can 14384 // select between them. 14385 SDValue Zero = DAG.getIntPtrConstant(0, DL); 14386 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 14387 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 14388 14389 SDValue Cond = DAG.getSetCC(DL, 14390 getSetCCResultType(N0.getValueType()), 14391 N0, N1, CC); 14392 AddToWorklist(Cond.getNode()); 14393 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 14394 Cond, One, Zero); 14395 AddToWorklist(CstOffset.getNode()); 14396 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 14397 CstOffset); 14398 AddToWorklist(CPIdx.getNode()); 14399 return DAG.getLoad( 14400 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 14401 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 14402 Alignment); 14403 } 14404 } 14405 14406 // Check to see if we can perform the "gzip trick", transforming 14407 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 14408 if (isNullConstant(N3) && CC == ISD::SETLT && 14409 (isNullConstant(N1) || // (a < 0) ? b : 0 14410 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 14411 EVT XType = N0.getValueType(); 14412 EVT AType = N2.getValueType(); 14413 if (XType.bitsGE(AType)) { 14414 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 14415 // single-bit constant. 14416 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14417 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 14418 ShCtV = XType.getSizeInBits() - ShCtV - 1; 14419 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 14420 getShiftAmountTy(N0.getValueType())); 14421 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 14422 XType, N0, ShCt); 14423 AddToWorklist(Shift.getNode()); 14424 14425 if (XType.bitsGT(AType)) { 14426 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14427 AddToWorklist(Shift.getNode()); 14428 } 14429 14430 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14431 } 14432 14433 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 14434 XType, N0, 14435 DAG.getConstant(XType.getSizeInBits() - 1, 14436 SDLoc(N0), 14437 getShiftAmountTy(N0.getValueType()))); 14438 AddToWorklist(Shift.getNode()); 14439 14440 if (XType.bitsGT(AType)) { 14441 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14442 AddToWorklist(Shift.getNode()); 14443 } 14444 14445 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14446 } 14447 } 14448 14449 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14450 // where y is has a single bit set. 14451 // A plaintext description would be, we can turn the SELECT_CC into an AND 14452 // when the condition can be materialized as an all-ones register. Any 14453 // single bit-test can be materialized as an all-ones register with 14454 // shift-left and shift-right-arith. 14455 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14456 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14457 SDValue AndLHS = N0->getOperand(0); 14458 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14459 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14460 // Shift the tested bit over the sign bit. 14461 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 14462 SDValue ShlAmt = 14463 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14464 getShiftAmountTy(AndLHS.getValueType())); 14465 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14466 14467 // Now arithmetic right shift it all the way over, so the result is either 14468 // all-ones, or zero. 14469 SDValue ShrAmt = 14470 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14471 getShiftAmountTy(Shl.getValueType())); 14472 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14473 14474 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14475 } 14476 } 14477 14478 // fold select C, 16, 0 -> shl C, 4 14479 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14480 TLI.getBooleanContents(N0.getValueType()) == 14481 TargetLowering::ZeroOrOneBooleanContent) { 14482 14483 // If the caller doesn't want us to simplify this into a zext of a compare, 14484 // don't do it. 14485 if (NotExtCompare && N2C->isOne()) 14486 return SDValue(); 14487 14488 // Get a SetCC of the condition 14489 // NOTE: Don't create a SETCC if it's not legal on this target. 14490 if (!LegalOperations || 14491 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14492 SDValue Temp, SCC; 14493 // cast from setcc result type to select result type 14494 if (LegalTypes) { 14495 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14496 N0, N1, CC); 14497 if (N2.getValueType().bitsLT(SCC.getValueType())) 14498 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14499 N2.getValueType()); 14500 else 14501 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14502 N2.getValueType(), SCC); 14503 } else { 14504 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14505 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14506 N2.getValueType(), SCC); 14507 } 14508 14509 AddToWorklist(SCC.getNode()); 14510 AddToWorklist(Temp.getNode()); 14511 14512 if (N2C->isOne()) 14513 return Temp; 14514 14515 // shl setcc result by log2 n2c 14516 return DAG.getNode( 14517 ISD::SHL, DL, N2.getValueType(), Temp, 14518 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14519 getShiftAmountTy(Temp.getValueType()))); 14520 } 14521 } 14522 14523 // Check to see if this is an integer abs. 14524 // select_cc setg[te] X, 0, X, -X -> 14525 // select_cc setgt X, -1, X, -X -> 14526 // select_cc setl[te] X, 0, -X, X -> 14527 // select_cc setlt X, 1, -X, X -> 14528 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14529 if (N1C) { 14530 ConstantSDNode *SubC = nullptr; 14531 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14532 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14533 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14534 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14535 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14536 (N1C->isOne() && CC == ISD::SETLT)) && 14537 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14538 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14539 14540 EVT XType = N0.getValueType(); 14541 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14542 SDLoc DL(N0); 14543 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14544 N0, 14545 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14546 getShiftAmountTy(N0.getValueType()))); 14547 SDValue Add = DAG.getNode(ISD::ADD, DL, 14548 XType, N0, Shift); 14549 AddToWorklist(Shift.getNode()); 14550 AddToWorklist(Add.getNode()); 14551 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14552 } 14553 } 14554 14555 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 14556 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 14557 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 14558 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 14559 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 14560 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 14561 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 14562 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 14563 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 14564 SDValue ValueOnZero = N2; 14565 SDValue Count = N3; 14566 // If the condition is NE instead of E, swap the operands. 14567 if (CC == ISD::SETNE) 14568 std::swap(ValueOnZero, Count); 14569 // Check if the value on zero is a constant equal to the bits in the type. 14570 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 14571 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 14572 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 14573 // legal, combine to just cttz. 14574 if ((Count.getOpcode() == ISD::CTTZ || 14575 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 14576 N0 == Count.getOperand(0) && 14577 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 14578 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 14579 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 14580 // legal, combine to just ctlz. 14581 if ((Count.getOpcode() == ISD::CTLZ || 14582 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 14583 N0 == Count.getOperand(0) && 14584 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 14585 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 14586 } 14587 } 14588 } 14589 14590 return SDValue(); 14591 } 14592 14593 /// This is a stub for TargetLowering::SimplifySetCC. 14594 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 14595 ISD::CondCode Cond, const SDLoc &DL, 14596 bool foldBooleans) { 14597 TargetLowering::DAGCombinerInfo 14598 DagCombineInfo(DAG, Level, false, this); 14599 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14600 } 14601 14602 /// Given an ISD::SDIV node expressing a divide by constant, return 14603 /// a DAG expression to select that will generate the same value by multiplying 14604 /// by a magic number. 14605 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14606 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14607 // when optimising for minimum size, we don't want to expand a div to a mul 14608 // and a shift. 14609 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 14610 return SDValue(); 14611 14612 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14613 if (!C) 14614 return SDValue(); 14615 14616 // Avoid division by zero. 14617 if (C->isNullValue()) 14618 return SDValue(); 14619 14620 std::vector<SDNode*> Built; 14621 SDValue S = 14622 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14623 14624 for (SDNode *N : Built) 14625 AddToWorklist(N); 14626 return S; 14627 } 14628 14629 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14630 /// DAG expression that will generate the same value by right shifting. 14631 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14632 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14633 if (!C) 14634 return SDValue(); 14635 14636 // Avoid division by zero. 14637 if (C->isNullValue()) 14638 return SDValue(); 14639 14640 std::vector<SDNode *> Built; 14641 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14642 14643 for (SDNode *N : Built) 14644 AddToWorklist(N); 14645 return S; 14646 } 14647 14648 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14649 /// expression that will generate the same value by multiplying by a magic 14650 /// number. 14651 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14652 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14653 // when optimising for minimum size, we don't want to expand a div to a mul 14654 // and a shift. 14655 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 14656 return SDValue(); 14657 14658 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14659 if (!C) 14660 return SDValue(); 14661 14662 // Avoid division by zero. 14663 if (C->isNullValue()) 14664 return SDValue(); 14665 14666 std::vector<SDNode*> Built; 14667 SDValue S = 14668 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14669 14670 for (SDNode *N : Built) 14671 AddToWorklist(N); 14672 return S; 14673 } 14674 14675 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14676 if (Level >= AfterLegalizeDAG) 14677 return SDValue(); 14678 14679 // Expose the DAG combiner to the target combiner implementations. 14680 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14681 14682 unsigned Iterations = 0; 14683 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14684 if (Iterations) { 14685 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14686 // For the reciprocal, we need to find the zero of the function: 14687 // F(X) = A X - 1 [which has a zero at X = 1/A] 14688 // => 14689 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14690 // does not require additional intermediate precision] 14691 EVT VT = Op.getValueType(); 14692 SDLoc DL(Op); 14693 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14694 14695 AddToWorklist(Est.getNode()); 14696 14697 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14698 for (unsigned i = 0; i < Iterations; ++i) { 14699 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14700 AddToWorklist(NewEst.getNode()); 14701 14702 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14703 AddToWorklist(NewEst.getNode()); 14704 14705 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14706 AddToWorklist(NewEst.getNode()); 14707 14708 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14709 AddToWorklist(Est.getNode()); 14710 } 14711 } 14712 return Est; 14713 } 14714 14715 return SDValue(); 14716 } 14717 14718 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14719 /// For the reciprocal sqrt, we need to find the zero of the function: 14720 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14721 /// => 14722 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14723 /// As a result, we precompute A/2 prior to the iteration loop. 14724 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 14725 unsigned Iterations, 14726 SDNodeFlags *Flags, bool Reciprocal) { 14727 EVT VT = Arg.getValueType(); 14728 SDLoc DL(Arg); 14729 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14730 14731 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14732 // this entire sequence requires only one FP constant. 14733 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14734 AddToWorklist(HalfArg.getNode()); 14735 14736 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14737 AddToWorklist(HalfArg.getNode()); 14738 14739 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14740 for (unsigned i = 0; i < Iterations; ++i) { 14741 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14742 AddToWorklist(NewEst.getNode()); 14743 14744 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14745 AddToWorklist(NewEst.getNode()); 14746 14747 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14748 AddToWorklist(NewEst.getNode()); 14749 14750 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14751 AddToWorklist(Est.getNode()); 14752 } 14753 14754 // If non-reciprocal square root is requested, multiply the result by Arg. 14755 if (!Reciprocal) { 14756 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14757 AddToWorklist(Est.getNode()); 14758 } 14759 14760 return Est; 14761 } 14762 14763 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14764 /// For the reciprocal sqrt, we need to find the zero of the function: 14765 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14766 /// => 14767 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14768 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 14769 unsigned Iterations, 14770 SDNodeFlags *Flags, bool Reciprocal) { 14771 EVT VT = Arg.getValueType(); 14772 SDLoc DL(Arg); 14773 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14774 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14775 14776 // This routine must enter the loop below to work correctly 14777 // when (Reciprocal == false). 14778 assert(Iterations > 0); 14779 14780 // Newton iterations for reciprocal square root: 14781 // E = (E * -0.5) * ((A * E) * E + -3.0) 14782 for (unsigned i = 0; i < Iterations; ++i) { 14783 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 14784 AddToWorklist(AE.getNode()); 14785 14786 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 14787 AddToWorklist(AEE.getNode()); 14788 14789 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 14790 AddToWorklist(RHS.getNode()); 14791 14792 // When calculating a square root at the last iteration build: 14793 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 14794 // (notice a common subexpression) 14795 SDValue LHS; 14796 if (Reciprocal || (i + 1) < Iterations) { 14797 // RSQRT: LHS = (E * -0.5) 14798 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14799 } else { 14800 // SQRT: LHS = (A * E) * -0.5 14801 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 14802 } 14803 AddToWorklist(LHS.getNode()); 14804 14805 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 14806 AddToWorklist(Est.getNode()); 14807 } 14808 14809 return Est; 14810 } 14811 14812 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 14813 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 14814 /// Op can be zero. 14815 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, 14816 bool Reciprocal) { 14817 if (Level >= AfterLegalizeDAG) 14818 return SDValue(); 14819 14820 // Expose the DAG combiner to the target combiner implementations. 14821 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14822 unsigned Iterations = 0; 14823 bool UseOneConstNR = false; 14824 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14825 AddToWorklist(Est.getNode()); 14826 if (Iterations) { 14827 Est = UseOneConstNR 14828 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 14829 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 14830 } 14831 return Est; 14832 } 14833 14834 return SDValue(); 14835 } 14836 14837 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14838 return buildSqrtEstimateImpl(Op, Flags, true); 14839 } 14840 14841 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14842 SDValue Est = buildSqrtEstimateImpl(Op, Flags, false); 14843 if (!Est) 14844 return SDValue(); 14845 14846 // Unfortunately, Est is now NaN if the input was exactly 0. 14847 // Select out this case and force the answer to 0. 14848 EVT VT = Est.getValueType(); 14849 SDLoc DL(Op); 14850 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 14851 EVT CCVT = getSetCCResultType(VT); 14852 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ); 14853 AddToWorklist(ZeroCmp.getNode()); 14854 14855 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp, 14856 Zero, Est); 14857 AddToWorklist(Est.getNode()); 14858 return Est; 14859 } 14860 14861 /// Return true if base is a frame index, which is known not to alias with 14862 /// anything but itself. Provides base object and offset as results. 14863 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14864 const GlobalValue *&GV, const void *&CV) { 14865 // Assume it is a primitive operation. 14866 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14867 14868 // If it's an adding a simple constant then integrate the offset. 14869 if (Base.getOpcode() == ISD::ADD) { 14870 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14871 Base = Base.getOperand(0); 14872 Offset += C->getZExtValue(); 14873 } 14874 } 14875 14876 // Return the underlying GlobalValue, and update the Offset. Return false 14877 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14878 // by multiple nodes with different offsets. 14879 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14880 GV = G->getGlobal(); 14881 Offset += G->getOffset(); 14882 return false; 14883 } 14884 14885 // Return the underlying Constant value, and update the Offset. Return false 14886 // for ConstantSDNodes since the same constant pool entry may be represented 14887 // by multiple nodes with different offsets. 14888 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14889 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14890 : (const void *)C->getConstVal(); 14891 Offset += C->getOffset(); 14892 return false; 14893 } 14894 // If it's any of the following then it can't alias with anything but itself. 14895 return isa<FrameIndexSDNode>(Base); 14896 } 14897 14898 /// Return true if there is any possibility that the two addresses overlap. 14899 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14900 // If they are the same then they must be aliases. 14901 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14902 14903 // If they are both volatile then they cannot be reordered. 14904 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14905 14906 // If one operation reads from invariant memory, and the other may store, they 14907 // cannot alias. These should really be checking the equivalent of mayWrite, 14908 // but it only matters for memory nodes other than load /store. 14909 if (Op0->isInvariant() && Op1->writeMem()) 14910 return false; 14911 14912 if (Op1->isInvariant() && Op0->writeMem()) 14913 return false; 14914 14915 // Gather base node and offset information. 14916 SDValue Base1, Base2; 14917 int64_t Offset1, Offset2; 14918 const GlobalValue *GV1, *GV2; 14919 const void *CV1, *CV2; 14920 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14921 Base1, Offset1, GV1, CV1); 14922 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14923 Base2, Offset2, GV2, CV2); 14924 14925 // If they have a same base address then check to see if they overlap. 14926 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14927 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14928 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14929 14930 // It is possible for different frame indices to alias each other, mostly 14931 // when tail call optimization reuses return address slots for arguments. 14932 // To catch this case, look up the actual index of frame indices to compute 14933 // the real alias relationship. 14934 if (isFrameIndex1 && isFrameIndex2) { 14935 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 14936 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14937 Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14938 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14939 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14940 } 14941 14942 // Otherwise, if we know what the bases are, and they aren't identical, then 14943 // we know they cannot alias. 14944 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14945 return false; 14946 14947 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14948 // compared to the size and offset of the access, we may be able to prove they 14949 // do not alias. This check is conservative for now to catch cases created by 14950 // splitting vector types. 14951 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14952 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14953 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14954 Op1->getMemoryVT().getSizeInBits() >> 3) && 14955 (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) { 14956 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14957 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14958 14959 // There is no overlap between these relatively aligned accesses of similar 14960 // size, return no alias. 14961 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14962 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14963 return false; 14964 } 14965 14966 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14967 ? CombinerGlobalAA 14968 : DAG.getSubtarget().useAA(); 14969 #ifndef NDEBUG 14970 if (CombinerAAOnlyFunc.getNumOccurrences() && 14971 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14972 UseAA = false; 14973 #endif 14974 if (UseAA && 14975 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14976 // Use alias analysis information. 14977 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14978 Op1->getSrcValueOffset()); 14979 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14980 Op0->getSrcValueOffset() - MinOffset; 14981 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14982 Op1->getSrcValueOffset() - MinOffset; 14983 AliasResult AAResult = 14984 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14985 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14986 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14987 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14988 if (AAResult == NoAlias) 14989 return false; 14990 } 14991 14992 // Otherwise we have to assume they alias. 14993 return true; 14994 } 14995 14996 /// Walk up chain skipping non-aliasing memory nodes, 14997 /// looking for aliasing nodes and adding them to the Aliases vector. 14998 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14999 SmallVectorImpl<SDValue> &Aliases) { 15000 SmallVector<SDValue, 8> Chains; // List of chains to visit. 15001 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 15002 15003 // Get alias information for node. 15004 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 15005 15006 // Starting off. 15007 Chains.push_back(OriginalChain); 15008 unsigned Depth = 0; 15009 15010 // Look at each chain and determine if it is an alias. If so, add it to the 15011 // aliases list. If not, then continue up the chain looking for the next 15012 // candidate. 15013 while (!Chains.empty()) { 15014 SDValue Chain = Chains.pop_back_val(); 15015 15016 // For TokenFactor nodes, look at each operand and only continue up the 15017 // chain until we reach the depth limit. 15018 // 15019 // FIXME: The depth check could be made to return the last non-aliasing 15020 // chain we found before we hit a tokenfactor rather than the original 15021 // chain. 15022 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 15023 Aliases.clear(); 15024 Aliases.push_back(OriginalChain); 15025 return; 15026 } 15027 15028 // Don't bother if we've been before. 15029 if (!Visited.insert(Chain.getNode()).second) 15030 continue; 15031 15032 switch (Chain.getOpcode()) { 15033 case ISD::EntryToken: 15034 // Entry token is ideal chain operand, but handled in FindBetterChain. 15035 break; 15036 15037 case ISD::LOAD: 15038 case ISD::STORE: { 15039 // Get alias information for Chain. 15040 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 15041 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 15042 15043 // If chain is alias then stop here. 15044 if (!(IsLoad && IsOpLoad) && 15045 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 15046 Aliases.push_back(Chain); 15047 } else { 15048 // Look further up the chain. 15049 Chains.push_back(Chain.getOperand(0)); 15050 ++Depth; 15051 } 15052 break; 15053 } 15054 15055 case ISD::TokenFactor: 15056 // We have to check each of the operands of the token factor for "small" 15057 // token factors, so we queue them up. Adding the operands to the queue 15058 // (stack) in reverse order maintains the original order and increases the 15059 // likelihood that getNode will find a matching token factor (CSE.) 15060 if (Chain.getNumOperands() > 16) { 15061 Aliases.push_back(Chain); 15062 break; 15063 } 15064 for (unsigned n = Chain.getNumOperands(); n;) 15065 Chains.push_back(Chain.getOperand(--n)); 15066 ++Depth; 15067 break; 15068 15069 default: 15070 // For all other instructions we will just have to take what we can get. 15071 Aliases.push_back(Chain); 15072 break; 15073 } 15074 } 15075 } 15076 15077 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 15078 /// (aliasing node.) 15079 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 15080 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 15081 15082 // Accumulate all the aliases to this node. 15083 GatherAllAliases(N, OldChain, Aliases); 15084 15085 // If no operands then chain to entry token. 15086 if (Aliases.size() == 0) 15087 return DAG.getEntryNode(); 15088 15089 // If a single operand then chain to it. We don't need to revisit it. 15090 if (Aliases.size() == 1) 15091 return Aliases[0]; 15092 15093 // Construct a custom tailored token factor. 15094 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 15095 } 15096 15097 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 15098 // This holds the base pointer, index, and the offset in bytes from the base 15099 // pointer. 15100 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 15101 15102 // We must have a base and an offset. 15103 if (!BasePtr.Base.getNode()) 15104 return false; 15105 15106 // Do not handle stores to undef base pointers. 15107 if (BasePtr.Base.isUndef()) 15108 return false; 15109 15110 SmallVector<StoreSDNode *, 8> ChainedStores; 15111 ChainedStores.push_back(St); 15112 15113 // Walk up the chain and look for nodes with offsets from the same 15114 // base pointer. Stop when reaching an instruction with a different kind 15115 // or instruction which has a different base pointer. 15116 StoreSDNode *Index = St; 15117 while (Index) { 15118 // If the chain has more than one use, then we can't reorder the mem ops. 15119 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 15120 break; 15121 15122 if (Index->isVolatile() || Index->isIndexed()) 15123 break; 15124 15125 // Find the base pointer and offset for this memory node. 15126 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 15127 15128 // Check that the base pointer is the same as the original one. 15129 if (!Ptr.equalBaseIndex(BasePtr)) 15130 break; 15131 15132 // Find the next memory operand in the chain. If the next operand in the 15133 // chain is a store then move up and continue the scan with the next 15134 // memory operand. If the next operand is a load save it and use alias 15135 // information to check if it interferes with anything. 15136 SDNode *NextInChain = Index->getChain().getNode(); 15137 while (true) { 15138 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 15139 // We found a store node. Use it for the next iteration. 15140 if (STn->isVolatile() || STn->isIndexed()) { 15141 Index = nullptr; 15142 break; 15143 } 15144 ChainedStores.push_back(STn); 15145 Index = STn; 15146 break; 15147 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 15148 NextInChain = Ldn->getChain().getNode(); 15149 continue; 15150 } else { 15151 Index = nullptr; 15152 break; 15153 } 15154 } 15155 } 15156 15157 bool MadeChangeToSt = false; 15158 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 15159 15160 for (StoreSDNode *ChainedStore : ChainedStores) { 15161 SDValue Chain = ChainedStore->getChain(); 15162 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 15163 15164 if (Chain != BetterChain) { 15165 if (ChainedStore == St) 15166 MadeChangeToSt = true; 15167 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 15168 } 15169 } 15170 15171 // Do all replacements after finding the replacements to make to avoid making 15172 // the chains more complicated by introducing new TokenFactors. 15173 for (auto Replacement : BetterChains) 15174 replaceStoreChain(Replacement.first, Replacement.second); 15175 15176 return MadeChangeToSt; 15177 } 15178 15179 /// This is the entry point for the file. 15180 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 15181 CodeGenOpt::Level OptLevel) { 15182 /// This is the main entry point to this class. 15183 DAGCombiner(*this, AA, OptLevel).Run(Level); 15184 } 15185