1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/SelectionDAG.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetLowering.h" 37 #include "llvm/Target/TargetOptions.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 #define DEBUG_TYPE "dagcombine" 44 45 STATISTIC(NodesCombined , "Number of dag nodes combined"); 46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 50 STATISTIC(SlicedLoads, "Number of load sliced"); 51 52 namespace { 53 static cl::opt<bool> 54 CombinerAA("combiner-alias-analysis", cl::Hidden, 55 cl::desc("Enable DAG combiner alias-analysis heuristics")); 56 57 static cl::opt<bool> 58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 59 cl::desc("Enable DAG combiner's use of IR alias analysis")); 60 61 static cl::opt<bool> 62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 63 cl::desc("Enable DAG combiner's use of TBAA")); 64 65 #ifndef NDEBUG 66 static cl::opt<std::string> 67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 68 cl::desc("Only use DAG-combiner alias analysis in this" 69 " function")); 70 #endif 71 72 /// Hidden option to stress test load slicing, i.e., when this option 73 /// is enabled, load slicing bypasses most of its profitability guards. 74 static cl::opt<bool> 75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 76 cl::desc("Bypass the profitability model of load " 77 "slicing"), 78 cl::init(false)); 79 80 static cl::opt<bool> 81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 82 cl::desc("DAG combiner may split indexing from loads")); 83 84 //------------------------------ DAGCombiner ---------------------------------// 85 86 class DAGCombiner { 87 SelectionDAG &DAG; 88 const TargetLowering &TLI; 89 CombineLevel Level; 90 CodeGenOpt::Level OptLevel; 91 bool LegalOperations; 92 bool LegalTypes; 93 bool ForCodeSize; 94 95 /// \brief Worklist of all of the nodes that need to be simplified. 96 /// 97 /// This must behave as a stack -- new nodes to process are pushed onto the 98 /// back and when processing we pop off of the back. 99 /// 100 /// The worklist will not contain duplicates but may contain null entries 101 /// due to nodes being deleted from the underlying DAG. 102 SmallVector<SDNode *, 64> Worklist; 103 104 /// \brief Mapping from an SDNode to its position on the worklist. 105 /// 106 /// This is used to find and remove nodes from the worklist (by nulling 107 /// them) when they are deleted from the underlying DAG. It relies on 108 /// stable indices of nodes within the worklist. 109 DenseMap<SDNode *, unsigned> WorklistMap; 110 111 /// \brief Set of nodes which have been combined (at least once). 112 /// 113 /// This is used to allow us to reliably add any operands of a DAG node 114 /// which have not yet been combined to the worklist. 115 SmallPtrSet<SDNode *, 64> CombinedNodes; 116 117 // AA - Used for DAG load/store alias analysis. 118 AliasAnalysis &AA; 119 120 /// When an instruction is simplified, add all users of the instruction to 121 /// the work lists because they might get more simplified now. 122 void AddUsersToWorklist(SDNode *N) { 123 for (SDNode *Node : N->uses()) 124 AddToWorklist(Node); 125 } 126 127 /// Call the node-specific routine that folds each particular type of node. 128 SDValue visit(SDNode *N); 129 130 public: 131 /// Add to the worklist making sure its instance is at the back (next to be 132 /// processed.) 133 void AddToWorklist(SDNode *N) { 134 // Skip handle nodes as they can't usefully be combined and confuse the 135 // zero-use deletion strategy. 136 if (N->getOpcode() == ISD::HANDLENODE) 137 return; 138 139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 140 Worklist.push_back(N); 141 } 142 143 /// Remove all instances of N from the worklist. 144 void removeFromWorklist(SDNode *N) { 145 CombinedNodes.erase(N); 146 147 auto It = WorklistMap.find(N); 148 if (It == WorklistMap.end()) 149 return; // Not in the worklist. 150 151 // Null out the entry rather than erasing it to avoid a linear operation. 152 Worklist[It->second] = nullptr; 153 WorklistMap.erase(It); 154 } 155 156 void deleteAndRecombine(SDNode *N); 157 bool recursivelyDeleteUnusedNodes(SDNode *N); 158 159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 160 bool AddTo = true); 161 162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 163 return CombineTo(N, &Res, 1, AddTo); 164 } 165 166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 167 bool AddTo = true) { 168 SDValue To[] = { Res0, Res1 }; 169 return CombineTo(N, To, 2, AddTo); 170 } 171 172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 173 174 private: 175 176 /// Check the specified integer node value to see if it can be simplified or 177 /// if things it uses can be simplified by bit propagation. 178 /// If so, return true. 179 bool SimplifyDemandedBits(SDValue Op) { 180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 181 APInt Demanded = APInt::getAllOnesValue(BitWidth); 182 return SimplifyDemandedBits(Op, Demanded); 183 } 184 185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 186 187 bool CombineToPreIndexedLoadStore(SDNode *N); 188 bool CombineToPostIndexedLoadStore(SDNode *N); 189 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 190 bool SliceUpLoad(SDNode *N); 191 192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 193 /// load. 194 /// 195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 197 /// \param EltNo index of the vector element to load. 198 /// \param OriginalLoad load that EVE came from to be replaced. 199 /// \returns EVE on success SDValue() on failure. 200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 206 SDValue PromoteIntBinOp(SDValue Op); 207 SDValue PromoteIntShiftOp(SDValue Op); 208 SDValue PromoteExtend(SDValue Op); 209 bool PromoteLoad(SDValue Op); 210 211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 212 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 213 ISD::NodeType ExtType); 214 215 /// Call the node-specific routine that knows how to fold each 216 /// particular type of node. If that doesn't do anything, try the 217 /// target-specific DAG combines. 218 SDValue combine(SDNode *N); 219 220 // Visitation implementation - Implement dag node combining for different 221 // node types. The semantics are as follows: 222 // Return Value: 223 // SDValue.getNode() == 0 - No change was made 224 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 225 // otherwise - N should be replaced by the returned Operand. 226 // 227 SDValue visitTokenFactor(SDNode *N); 228 SDValue visitMERGE_VALUES(SDNode *N); 229 SDValue visitADD(SDNode *N); 230 SDValue visitSUB(SDNode *N); 231 SDValue visitADDC(SDNode *N); 232 SDValue visitSUBC(SDNode *N); 233 SDValue visitADDE(SDNode *N); 234 SDValue visitSUBE(SDNode *N); 235 SDValue visitMUL(SDNode *N); 236 SDValue visitSDIV(SDNode *N); 237 SDValue visitUDIV(SDNode *N); 238 SDValue visitSREM(SDNode *N); 239 SDValue visitUREM(SDNode *N); 240 SDValue visitMULHU(SDNode *N); 241 SDValue visitMULHS(SDNode *N); 242 SDValue visitSMUL_LOHI(SDNode *N); 243 SDValue visitUMUL_LOHI(SDNode *N); 244 SDValue visitSMULO(SDNode *N); 245 SDValue visitUMULO(SDNode *N); 246 SDValue visitSDIVREM(SDNode *N); 247 SDValue visitUDIVREM(SDNode *N); 248 SDValue visitIMINMAX(SDNode *N); 249 SDValue visitAND(SDNode *N); 250 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 251 SDValue visitOR(SDNode *N); 252 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 253 SDValue visitXOR(SDNode *N); 254 SDValue SimplifyVBinOp(SDNode *N); 255 SDValue visitSHL(SDNode *N); 256 SDValue visitSRA(SDNode *N); 257 SDValue visitSRL(SDNode *N); 258 SDValue visitRotate(SDNode *N); 259 SDValue visitBSWAP(SDNode *N); 260 SDValue visitCTLZ(SDNode *N); 261 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 262 SDValue visitCTTZ(SDNode *N); 263 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 264 SDValue visitCTPOP(SDNode *N); 265 SDValue visitSELECT(SDNode *N); 266 SDValue visitVSELECT(SDNode *N); 267 SDValue visitSELECT_CC(SDNode *N); 268 SDValue visitSETCC(SDNode *N); 269 SDValue visitSIGN_EXTEND(SDNode *N); 270 SDValue visitZERO_EXTEND(SDNode *N); 271 SDValue visitANY_EXTEND(SDNode *N); 272 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 273 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 274 SDValue visitTRUNCATE(SDNode *N); 275 SDValue visitBITCAST(SDNode *N); 276 SDValue visitBUILD_PAIR(SDNode *N); 277 SDValue visitFADD(SDNode *N); 278 SDValue visitFSUB(SDNode *N); 279 SDValue visitFMUL(SDNode *N); 280 SDValue visitFMA(SDNode *N); 281 SDValue visitFDIV(SDNode *N); 282 SDValue visitFREM(SDNode *N); 283 SDValue visitFSQRT(SDNode *N); 284 SDValue visitFCOPYSIGN(SDNode *N); 285 SDValue visitSINT_TO_FP(SDNode *N); 286 SDValue visitUINT_TO_FP(SDNode *N); 287 SDValue visitFP_TO_SINT(SDNode *N); 288 SDValue visitFP_TO_UINT(SDNode *N); 289 SDValue visitFP_ROUND(SDNode *N); 290 SDValue visitFP_ROUND_INREG(SDNode *N); 291 SDValue visitFP_EXTEND(SDNode *N); 292 SDValue visitFNEG(SDNode *N); 293 SDValue visitFABS(SDNode *N); 294 SDValue visitFCEIL(SDNode *N); 295 SDValue visitFTRUNC(SDNode *N); 296 SDValue visitFFLOOR(SDNode *N); 297 SDValue visitFMINNUM(SDNode *N); 298 SDValue visitFMAXNUM(SDNode *N); 299 SDValue visitBRCOND(SDNode *N); 300 SDValue visitBR_CC(SDNode *N); 301 SDValue visitLOAD(SDNode *N); 302 303 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 304 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 305 306 SDValue visitSTORE(SDNode *N); 307 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 308 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 309 SDValue visitBUILD_VECTOR(SDNode *N); 310 SDValue visitCONCAT_VECTORS(SDNode *N); 311 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 312 SDValue visitVECTOR_SHUFFLE(SDNode *N); 313 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 314 SDValue visitINSERT_SUBVECTOR(SDNode *N); 315 SDValue visitMLOAD(SDNode *N); 316 SDValue visitMSTORE(SDNode *N); 317 SDValue visitMGATHER(SDNode *N); 318 SDValue visitMSCATTER(SDNode *N); 319 SDValue visitFP_TO_FP16(SDNode *N); 320 SDValue visitFP16_TO_FP(SDNode *N); 321 322 SDValue visitFADDForFMACombine(SDNode *N); 323 SDValue visitFSUBForFMACombine(SDNode *N); 324 SDValue visitFMULForFMACombine(SDNode *N); 325 326 SDValue XformToShuffleWithZero(SDNode *N); 327 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 328 329 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 330 331 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 332 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 333 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 334 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 335 SDValue N3, ISD::CondCode CC, 336 bool NotExtCompare = false); 337 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 338 SDLoc DL, bool foldBooleans = true); 339 340 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 341 SDValue &CC) const; 342 bool isOneUseSetCC(SDValue N) const; 343 344 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 345 unsigned HiOp); 346 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 347 SDValue CombineExtLoad(SDNode *N); 348 SDValue combineRepeatedFPDivisors(SDNode *N); 349 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 350 SDValue BuildSDIV(SDNode *N); 351 SDValue BuildSDIVPow2(SDNode *N); 352 SDValue BuildUDIV(SDNode *N); 353 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 354 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 355 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 356 SDNodeFlags *Flags); 357 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 358 SDNodeFlags *Flags); 359 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 360 bool DemandHighBits = true); 361 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 362 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 363 SDValue InnerPos, SDValue InnerNeg, 364 unsigned PosOpcode, unsigned NegOpcode, 365 SDLoc DL); 366 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 367 SDValue ReduceLoadWidth(SDNode *N); 368 SDValue ReduceLoadOpStoreWidth(SDNode *N); 369 SDValue TransformFPLoadStorePair(SDNode *N); 370 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 371 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 372 373 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 374 375 /// Walk up chain skipping non-aliasing memory nodes, 376 /// looking for aliasing nodes and adding them to the Aliases vector. 377 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 378 SmallVectorImpl<SDValue> &Aliases); 379 380 /// Return true if there is any possibility that the two addresses overlap. 381 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 382 383 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 384 /// chain (aliasing node.) 385 SDValue FindBetterChain(SDNode *N, SDValue Chain); 386 387 /// Do FindBetterChain for a store and any possibly adjacent stores on 388 /// consecutive chains. 389 bool findBetterNeighborChains(StoreSDNode *St); 390 391 /// Holds a pointer to an LSBaseSDNode as well as information on where it 392 /// is located in a sequence of memory operations connected by a chain. 393 struct MemOpLink { 394 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 395 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 396 // Ptr to the mem node. 397 LSBaseSDNode *MemNode; 398 // Offset from the base ptr. 399 int64_t OffsetFromBase; 400 // What is the sequence number of this mem node. 401 // Lowest mem operand in the DAG starts at zero. 402 unsigned SequenceNum; 403 }; 404 405 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 406 /// constant build_vector of the stored constant values in Stores. 407 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, 408 SDLoc SL, 409 ArrayRef<MemOpLink> Stores, 410 SmallVectorImpl<SDValue> &Chains, 411 EVT Ty) const; 412 413 /// This is a helper function for MergeConsecutiveStores. When the source 414 /// elements of the consecutive stores are all constants or all extracted 415 /// vector elements, try to merge them into one larger store. 416 /// \return True if a merged store was created. 417 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 418 EVT MemVT, unsigned NumStores, 419 bool IsConstantSrc, bool UseVector); 420 421 /// This is a helper function for MergeConsecutiveStores. 422 /// Stores that may be merged are placed in StoreNodes. 423 /// Loads that may alias with those stores are placed in AliasLoadNodes. 424 void getStoreMergeAndAliasCandidates( 425 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 426 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 427 428 /// Merge consecutive store operations into a wide store. 429 /// This optimization uses wide integers or vectors when possible. 430 /// \return True if some memory operations were changed. 431 bool MergeConsecutiveStores(StoreSDNode *N); 432 433 /// \brief Try to transform a truncation where C is a constant: 434 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 435 /// 436 /// \p N needs to be a truncation and its first operand an AND. Other 437 /// requirements are checked by the function (e.g. that trunc is 438 /// single-use) and if missed an empty SDValue is returned. 439 SDValue distributeTruncateThroughAnd(SDNode *N); 440 441 public: 442 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 443 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 444 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 445 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 446 } 447 448 /// Runs the dag combiner on all nodes in the work list 449 void Run(CombineLevel AtLevel); 450 451 SelectionDAG &getDAG() const { return DAG; } 452 453 /// Returns a type large enough to hold any valid shift amount - before type 454 /// legalization these can be huge. 455 EVT getShiftAmountTy(EVT LHSTy) { 456 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 457 if (LHSTy.isVector()) 458 return LHSTy; 459 auto &DL = DAG.getDataLayout(); 460 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 461 : TLI.getPointerTy(DL); 462 } 463 464 /// This method returns true if we are running before type legalization or 465 /// if the specified VT is legal. 466 bool isTypeLegal(const EVT &VT) { 467 if (!LegalTypes) return true; 468 return TLI.isTypeLegal(VT); 469 } 470 471 /// Convenience wrapper around TargetLowering::getSetCCResultType 472 EVT getSetCCResultType(EVT VT) const { 473 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 474 } 475 }; 476 } 477 478 479 namespace { 480 /// This class is a DAGUpdateListener that removes any deleted 481 /// nodes from the worklist. 482 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 483 DAGCombiner &DC; 484 public: 485 explicit WorklistRemover(DAGCombiner &dc) 486 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 487 488 void NodeDeleted(SDNode *N, SDNode *E) override { 489 DC.removeFromWorklist(N); 490 } 491 }; 492 } 493 494 //===----------------------------------------------------------------------===// 495 // TargetLowering::DAGCombinerInfo implementation 496 //===----------------------------------------------------------------------===// 497 498 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 499 ((DAGCombiner*)DC)->AddToWorklist(N); 500 } 501 502 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 503 ((DAGCombiner*)DC)->removeFromWorklist(N); 504 } 505 506 SDValue TargetLowering::DAGCombinerInfo:: 507 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 508 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 509 } 510 511 SDValue TargetLowering::DAGCombinerInfo:: 512 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 513 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 514 } 515 516 517 SDValue TargetLowering::DAGCombinerInfo:: 518 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 519 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 520 } 521 522 void TargetLowering::DAGCombinerInfo:: 523 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 524 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 525 } 526 527 //===----------------------------------------------------------------------===// 528 // Helper Functions 529 //===----------------------------------------------------------------------===// 530 531 void DAGCombiner::deleteAndRecombine(SDNode *N) { 532 removeFromWorklist(N); 533 534 // If the operands of this node are only used by the node, they will now be 535 // dead. Make sure to re-visit them and recursively delete dead nodes. 536 for (const SDValue &Op : N->ops()) 537 // For an operand generating multiple values, one of the values may 538 // become dead allowing further simplification (e.g. split index 539 // arithmetic from an indexed load). 540 if (Op->hasOneUse() || Op->getNumValues() > 1) 541 AddToWorklist(Op.getNode()); 542 543 DAG.DeleteNode(N); 544 } 545 546 /// Return 1 if we can compute the negated form of the specified expression for 547 /// the same cost as the expression itself, or 2 if we can compute the negated 548 /// form more cheaply than the expression itself. 549 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 550 const TargetLowering &TLI, 551 const TargetOptions *Options, 552 unsigned Depth = 0) { 553 // fneg is removable even if it has multiple uses. 554 if (Op.getOpcode() == ISD::FNEG) return 2; 555 556 // Don't allow anything with multiple uses. 557 if (!Op.hasOneUse()) return 0; 558 559 // Don't recurse exponentially. 560 if (Depth > 6) return 0; 561 562 switch (Op.getOpcode()) { 563 default: return false; 564 case ISD::ConstantFP: 565 // Don't invert constant FP values after legalize. The negated constant 566 // isn't necessarily legal. 567 return LegalOperations ? 0 : 1; 568 case ISD::FADD: 569 // FIXME: determine better conditions for this xform. 570 if (!Options->UnsafeFPMath) return 0; 571 572 // After operation legalization, it might not be legal to create new FSUBs. 573 if (LegalOperations && 574 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 575 return 0; 576 577 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 578 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 579 Options, Depth + 1)) 580 return V; 581 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 582 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 583 Depth + 1); 584 case ISD::FSUB: 585 // We can't turn -(A-B) into B-A when we honor signed zeros. 586 if (!Options->UnsafeFPMath) return 0; 587 588 // fold (fneg (fsub A, B)) -> (fsub B, A) 589 return 1; 590 591 case ISD::FMUL: 592 case ISD::FDIV: 593 if (Options->HonorSignDependentRoundingFPMath()) return 0; 594 595 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 596 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 597 Options, Depth + 1)) 598 return V; 599 600 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 601 Depth + 1); 602 603 case ISD::FP_EXTEND: 604 case ISD::FP_ROUND: 605 case ISD::FSIN: 606 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 607 Depth + 1); 608 } 609 } 610 611 /// If isNegatibleForFree returns true, return the newly negated expression. 612 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 613 bool LegalOperations, unsigned Depth = 0) { 614 const TargetOptions &Options = DAG.getTarget().Options; 615 // fneg is removable even if it has multiple uses. 616 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 617 618 // Don't allow anything with multiple uses. 619 assert(Op.hasOneUse() && "Unknown reuse!"); 620 621 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 622 623 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 624 625 switch (Op.getOpcode()) { 626 default: llvm_unreachable("Unknown code"); 627 case ISD::ConstantFP: { 628 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 629 V.changeSign(); 630 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 631 } 632 case ISD::FADD: 633 // FIXME: determine better conditions for this xform. 634 assert(Options.UnsafeFPMath); 635 636 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 637 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 638 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 639 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 640 GetNegatedExpression(Op.getOperand(0), DAG, 641 LegalOperations, Depth+1), 642 Op.getOperand(1), Flags); 643 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 644 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 645 GetNegatedExpression(Op.getOperand(1), DAG, 646 LegalOperations, Depth+1), 647 Op.getOperand(0), Flags); 648 case ISD::FSUB: 649 // We can't turn -(A-B) into B-A when we honor signed zeros. 650 assert(Options.UnsafeFPMath); 651 652 // fold (fneg (fsub 0, B)) -> B 653 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 654 if (N0CFP->isZero()) 655 return Op.getOperand(1); 656 657 // fold (fneg (fsub A, B)) -> (fsub B, A) 658 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 659 Op.getOperand(1), Op.getOperand(0), Flags); 660 661 case ISD::FMUL: 662 case ISD::FDIV: 663 assert(!Options.HonorSignDependentRoundingFPMath()); 664 665 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 666 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 667 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 668 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 669 GetNegatedExpression(Op.getOperand(0), DAG, 670 LegalOperations, Depth+1), 671 Op.getOperand(1), Flags); 672 673 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 674 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 675 Op.getOperand(0), 676 GetNegatedExpression(Op.getOperand(1), DAG, 677 LegalOperations, Depth+1), Flags); 678 679 case ISD::FP_EXTEND: 680 case ISD::FSIN: 681 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 682 GetNegatedExpression(Op.getOperand(0), DAG, 683 LegalOperations, Depth+1)); 684 case ISD::FP_ROUND: 685 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 686 GetNegatedExpression(Op.getOperand(0), DAG, 687 LegalOperations, Depth+1), 688 Op.getOperand(1)); 689 } 690 } 691 692 // Return true if this node is a setcc, or is a select_cc 693 // that selects between the target values used for true and false, making it 694 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 695 // the appropriate nodes based on the type of node we are checking. This 696 // simplifies life a bit for the callers. 697 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 698 SDValue &CC) const { 699 if (N.getOpcode() == ISD::SETCC) { 700 LHS = N.getOperand(0); 701 RHS = N.getOperand(1); 702 CC = N.getOperand(2); 703 return true; 704 } 705 706 if (N.getOpcode() != ISD::SELECT_CC || 707 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 708 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 709 return false; 710 711 if (TLI.getBooleanContents(N.getValueType()) == 712 TargetLowering::UndefinedBooleanContent) 713 return false; 714 715 LHS = N.getOperand(0); 716 RHS = N.getOperand(1); 717 CC = N.getOperand(4); 718 return true; 719 } 720 721 /// Return true if this is a SetCC-equivalent operation with only one use. 722 /// If this is true, it allows the users to invert the operation for free when 723 /// it is profitable to do so. 724 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 725 SDValue N0, N1, N2; 726 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 727 return true; 728 return false; 729 } 730 731 /// Returns true if N is a BUILD_VECTOR node whose 732 /// elements are all the same constant or undefined. 733 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 734 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 735 if (!C) 736 return false; 737 738 APInt SplatUndef; 739 unsigned SplatBitSize; 740 bool HasAnyUndefs; 741 EVT EltVT = N->getValueType(0).getVectorElementType(); 742 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 743 HasAnyUndefs) && 744 EltVT.getSizeInBits() >= SplatBitSize); 745 } 746 747 // \brief Returns the SDNode if it is a constant integer BuildVector 748 // or constant integer. 749 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) { 750 if (isa<ConstantSDNode>(N)) 751 return N.getNode(); 752 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 753 return N.getNode(); 754 return nullptr; 755 } 756 757 // \brief Returns the SDNode if it is a constant float BuildVector 758 // or constant float. 759 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 760 if (isa<ConstantFPSDNode>(N)) 761 return N.getNode(); 762 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 763 return N.getNode(); 764 return nullptr; 765 } 766 767 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 768 // int. 769 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 770 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 771 return CN; 772 773 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 774 BitVector UndefElements; 775 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 776 777 // BuildVectors can truncate their operands. Ignore that case here. 778 // FIXME: We blindly ignore splats which include undef which is overly 779 // pessimistic. 780 if (CN && UndefElements.none() && 781 CN->getValueType(0) == N.getValueType().getScalarType()) 782 return CN; 783 } 784 785 return nullptr; 786 } 787 788 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 789 // float. 790 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 791 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 792 return CN; 793 794 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 795 BitVector UndefElements; 796 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 797 798 if (CN && UndefElements.none()) 799 return CN; 800 } 801 802 return nullptr; 803 } 804 805 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 806 SDValue N0, SDValue N1) { 807 EVT VT = N0.getValueType(); 808 if (N0.getOpcode() == Opc) { 809 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 810 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) { 811 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 812 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 813 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 814 return SDValue(); 815 } 816 if (N0.hasOneUse()) { 817 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 818 // use 819 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 820 if (!OpNode.getNode()) 821 return SDValue(); 822 AddToWorklist(OpNode.getNode()); 823 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 824 } 825 } 826 } 827 828 if (N1.getOpcode() == Opc) { 829 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 830 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) { 831 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 832 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 833 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 834 return SDValue(); 835 } 836 if (N1.hasOneUse()) { 837 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 838 // use 839 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 840 if (!OpNode.getNode()) 841 return SDValue(); 842 AddToWorklist(OpNode.getNode()); 843 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 844 } 845 } 846 } 847 848 return SDValue(); 849 } 850 851 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 852 bool AddTo) { 853 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 854 ++NodesCombined; 855 DEBUG(dbgs() << "\nReplacing.1 "; 856 N->dump(&DAG); 857 dbgs() << "\nWith: "; 858 To[0].getNode()->dump(&DAG); 859 dbgs() << " and " << NumTo-1 << " other values\n"); 860 for (unsigned i = 0, e = NumTo; i != e; ++i) 861 assert((!To[i].getNode() || 862 N->getValueType(i) == To[i].getValueType()) && 863 "Cannot combine value to value of different type!"); 864 865 WorklistRemover DeadNodes(*this); 866 DAG.ReplaceAllUsesWith(N, To); 867 if (AddTo) { 868 // Push the new nodes and any users onto the worklist 869 for (unsigned i = 0, e = NumTo; i != e; ++i) { 870 if (To[i].getNode()) { 871 AddToWorklist(To[i].getNode()); 872 AddUsersToWorklist(To[i].getNode()); 873 } 874 } 875 } 876 877 // Finally, if the node is now dead, remove it from the graph. The node 878 // may not be dead if the replacement process recursively simplified to 879 // something else needing this node. 880 if (N->use_empty()) 881 deleteAndRecombine(N); 882 return SDValue(N, 0); 883 } 884 885 void DAGCombiner:: 886 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 887 // Replace all uses. If any nodes become isomorphic to other nodes and 888 // are deleted, make sure to remove them from our worklist. 889 WorklistRemover DeadNodes(*this); 890 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 891 892 // Push the new node and any (possibly new) users onto the worklist. 893 AddToWorklist(TLO.New.getNode()); 894 AddUsersToWorklist(TLO.New.getNode()); 895 896 // Finally, if the node is now dead, remove it from the graph. The node 897 // may not be dead if the replacement process recursively simplified to 898 // something else needing this node. 899 if (TLO.Old.getNode()->use_empty()) 900 deleteAndRecombine(TLO.Old.getNode()); 901 } 902 903 /// Check the specified integer node value to see if it can be simplified or if 904 /// things it uses can be simplified by bit propagation. If so, return true. 905 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 906 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 907 APInt KnownZero, KnownOne; 908 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 909 return false; 910 911 // Revisit the node. 912 AddToWorklist(Op.getNode()); 913 914 // Replace the old value with the new one. 915 ++NodesCombined; 916 DEBUG(dbgs() << "\nReplacing.2 "; 917 TLO.Old.getNode()->dump(&DAG); 918 dbgs() << "\nWith: "; 919 TLO.New.getNode()->dump(&DAG); 920 dbgs() << '\n'); 921 922 CommitTargetLoweringOpt(TLO); 923 return true; 924 } 925 926 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 927 SDLoc dl(Load); 928 EVT VT = Load->getValueType(0); 929 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 930 931 DEBUG(dbgs() << "\nReplacing.9 "; 932 Load->dump(&DAG); 933 dbgs() << "\nWith: "; 934 Trunc.getNode()->dump(&DAG); 935 dbgs() << '\n'); 936 WorklistRemover DeadNodes(*this); 937 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 938 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 939 deleteAndRecombine(Load); 940 AddToWorklist(Trunc.getNode()); 941 } 942 943 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 944 Replace = false; 945 SDLoc dl(Op); 946 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 947 EVT MemVT = LD->getMemoryVT(); 948 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 949 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 950 : ISD::EXTLOAD) 951 : LD->getExtensionType(); 952 Replace = true; 953 return DAG.getExtLoad(ExtType, dl, PVT, 954 LD->getChain(), LD->getBasePtr(), 955 MemVT, LD->getMemOperand()); 956 } 957 958 unsigned Opc = Op.getOpcode(); 959 switch (Opc) { 960 default: break; 961 case ISD::AssertSext: 962 return DAG.getNode(ISD::AssertSext, dl, PVT, 963 SExtPromoteOperand(Op.getOperand(0), PVT), 964 Op.getOperand(1)); 965 case ISD::AssertZext: 966 return DAG.getNode(ISD::AssertZext, dl, PVT, 967 ZExtPromoteOperand(Op.getOperand(0), PVT), 968 Op.getOperand(1)); 969 case ISD::Constant: { 970 unsigned ExtOpc = 971 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 972 return DAG.getNode(ExtOpc, dl, PVT, Op); 973 } 974 } 975 976 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 977 return SDValue(); 978 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 979 } 980 981 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 982 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 983 return SDValue(); 984 EVT OldVT = Op.getValueType(); 985 SDLoc dl(Op); 986 bool Replace = false; 987 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 988 if (!NewOp.getNode()) 989 return SDValue(); 990 AddToWorklist(NewOp.getNode()); 991 992 if (Replace) 993 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 994 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 995 DAG.getValueType(OldVT)); 996 } 997 998 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 999 EVT OldVT = Op.getValueType(); 1000 SDLoc dl(Op); 1001 bool Replace = false; 1002 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1003 if (!NewOp.getNode()) 1004 return SDValue(); 1005 AddToWorklist(NewOp.getNode()); 1006 1007 if (Replace) 1008 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1009 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1010 } 1011 1012 /// Promote the specified integer binary operation if the target indicates it is 1013 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1014 /// i32 since i16 instructions are longer. 1015 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1016 if (!LegalOperations) 1017 return SDValue(); 1018 1019 EVT VT = Op.getValueType(); 1020 if (VT.isVector() || !VT.isInteger()) 1021 return SDValue(); 1022 1023 // If operation type is 'undesirable', e.g. i16 on x86, consider 1024 // promoting it. 1025 unsigned Opc = Op.getOpcode(); 1026 if (TLI.isTypeDesirableForOp(Opc, VT)) 1027 return SDValue(); 1028 1029 EVT PVT = VT; 1030 // Consult target whether it is a good idea to promote this operation and 1031 // what's the right type to promote it to. 1032 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1033 assert(PVT != VT && "Don't know what type to promote to!"); 1034 1035 bool Replace0 = false; 1036 SDValue N0 = Op.getOperand(0); 1037 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1038 if (!NN0.getNode()) 1039 return SDValue(); 1040 1041 bool Replace1 = false; 1042 SDValue N1 = Op.getOperand(1); 1043 SDValue NN1; 1044 if (N0 == N1) 1045 NN1 = NN0; 1046 else { 1047 NN1 = PromoteOperand(N1, PVT, Replace1); 1048 if (!NN1.getNode()) 1049 return SDValue(); 1050 } 1051 1052 AddToWorklist(NN0.getNode()); 1053 if (NN1.getNode()) 1054 AddToWorklist(NN1.getNode()); 1055 1056 if (Replace0) 1057 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1058 if (Replace1) 1059 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1060 1061 DEBUG(dbgs() << "\nPromoting "; 1062 Op.getNode()->dump(&DAG)); 1063 SDLoc dl(Op); 1064 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1065 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1066 } 1067 return SDValue(); 1068 } 1069 1070 /// Promote the specified integer shift operation if the target indicates it is 1071 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1072 /// i32 since i16 instructions are longer. 1073 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1074 if (!LegalOperations) 1075 return SDValue(); 1076 1077 EVT VT = Op.getValueType(); 1078 if (VT.isVector() || !VT.isInteger()) 1079 return SDValue(); 1080 1081 // If operation type is 'undesirable', e.g. i16 on x86, consider 1082 // promoting it. 1083 unsigned Opc = Op.getOpcode(); 1084 if (TLI.isTypeDesirableForOp(Opc, VT)) 1085 return SDValue(); 1086 1087 EVT PVT = VT; 1088 // Consult target whether it is a good idea to promote this operation and 1089 // what's the right type to promote it to. 1090 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1091 assert(PVT != VT && "Don't know what type to promote to!"); 1092 1093 bool Replace = false; 1094 SDValue N0 = Op.getOperand(0); 1095 if (Opc == ISD::SRA) 1096 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1097 else if (Opc == ISD::SRL) 1098 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1099 else 1100 N0 = PromoteOperand(N0, PVT, Replace); 1101 if (!N0.getNode()) 1102 return SDValue(); 1103 1104 AddToWorklist(N0.getNode()); 1105 if (Replace) 1106 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1107 1108 DEBUG(dbgs() << "\nPromoting "; 1109 Op.getNode()->dump(&DAG)); 1110 SDLoc dl(Op); 1111 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1112 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1113 } 1114 return SDValue(); 1115 } 1116 1117 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1118 if (!LegalOperations) 1119 return SDValue(); 1120 1121 EVT VT = Op.getValueType(); 1122 if (VT.isVector() || !VT.isInteger()) 1123 return SDValue(); 1124 1125 // If operation type is 'undesirable', e.g. i16 on x86, consider 1126 // promoting it. 1127 unsigned Opc = Op.getOpcode(); 1128 if (TLI.isTypeDesirableForOp(Opc, VT)) 1129 return SDValue(); 1130 1131 EVT PVT = VT; 1132 // Consult target whether it is a good idea to promote this operation and 1133 // what's the right type to promote it to. 1134 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1135 assert(PVT != VT && "Don't know what type to promote to!"); 1136 // fold (aext (aext x)) -> (aext x) 1137 // fold (aext (zext x)) -> (zext x) 1138 // fold (aext (sext x)) -> (sext x) 1139 DEBUG(dbgs() << "\nPromoting "; 1140 Op.getNode()->dump(&DAG)); 1141 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1142 } 1143 return SDValue(); 1144 } 1145 1146 bool DAGCombiner::PromoteLoad(SDValue Op) { 1147 if (!LegalOperations) 1148 return false; 1149 1150 EVT VT = Op.getValueType(); 1151 if (VT.isVector() || !VT.isInteger()) 1152 return false; 1153 1154 // If operation type is 'undesirable', e.g. i16 on x86, consider 1155 // promoting it. 1156 unsigned Opc = Op.getOpcode(); 1157 if (TLI.isTypeDesirableForOp(Opc, VT)) 1158 return false; 1159 1160 EVT PVT = VT; 1161 // Consult target whether it is a good idea to promote this operation and 1162 // what's the right type to promote it to. 1163 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1164 assert(PVT != VT && "Don't know what type to promote to!"); 1165 1166 SDLoc dl(Op); 1167 SDNode *N = Op.getNode(); 1168 LoadSDNode *LD = cast<LoadSDNode>(N); 1169 EVT MemVT = LD->getMemoryVT(); 1170 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1171 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1172 : ISD::EXTLOAD) 1173 : LD->getExtensionType(); 1174 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1175 LD->getChain(), LD->getBasePtr(), 1176 MemVT, LD->getMemOperand()); 1177 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1178 1179 DEBUG(dbgs() << "\nPromoting "; 1180 N->dump(&DAG); 1181 dbgs() << "\nTo: "; 1182 Result.getNode()->dump(&DAG); 1183 dbgs() << '\n'); 1184 WorklistRemover DeadNodes(*this); 1185 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1186 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1187 deleteAndRecombine(N); 1188 AddToWorklist(Result.getNode()); 1189 return true; 1190 } 1191 return false; 1192 } 1193 1194 /// \brief Recursively delete a node which has no uses and any operands for 1195 /// which it is the only use. 1196 /// 1197 /// Note that this both deletes the nodes and removes them from the worklist. 1198 /// It also adds any nodes who have had a user deleted to the worklist as they 1199 /// may now have only one use and subject to other combines. 1200 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1201 if (!N->use_empty()) 1202 return false; 1203 1204 SmallSetVector<SDNode *, 16> Nodes; 1205 Nodes.insert(N); 1206 do { 1207 N = Nodes.pop_back_val(); 1208 if (!N) 1209 continue; 1210 1211 if (N->use_empty()) { 1212 for (const SDValue &ChildN : N->op_values()) 1213 Nodes.insert(ChildN.getNode()); 1214 1215 removeFromWorklist(N); 1216 DAG.DeleteNode(N); 1217 } else { 1218 AddToWorklist(N); 1219 } 1220 } while (!Nodes.empty()); 1221 return true; 1222 } 1223 1224 //===----------------------------------------------------------------------===// 1225 // Main DAG Combiner implementation 1226 //===----------------------------------------------------------------------===// 1227 1228 void DAGCombiner::Run(CombineLevel AtLevel) { 1229 // set the instance variables, so that the various visit routines may use it. 1230 Level = AtLevel; 1231 LegalOperations = Level >= AfterLegalizeVectorOps; 1232 LegalTypes = Level >= AfterLegalizeTypes; 1233 1234 // Add all the dag nodes to the worklist. 1235 for (SDNode &Node : DAG.allnodes()) 1236 AddToWorklist(&Node); 1237 1238 // Create a dummy node (which is not added to allnodes), that adds a reference 1239 // to the root node, preventing it from being deleted, and tracking any 1240 // changes of the root. 1241 HandleSDNode Dummy(DAG.getRoot()); 1242 1243 // while the worklist isn't empty, find a node and 1244 // try and combine it. 1245 while (!WorklistMap.empty()) { 1246 SDNode *N; 1247 // The Worklist holds the SDNodes in order, but it may contain null entries. 1248 do { 1249 N = Worklist.pop_back_val(); 1250 } while (!N); 1251 1252 bool GoodWorklistEntry = WorklistMap.erase(N); 1253 (void)GoodWorklistEntry; 1254 assert(GoodWorklistEntry && 1255 "Found a worklist entry without a corresponding map entry!"); 1256 1257 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1258 // N is deleted from the DAG, since they too may now be dead or may have a 1259 // reduced number of uses, allowing other xforms. 1260 if (recursivelyDeleteUnusedNodes(N)) 1261 continue; 1262 1263 WorklistRemover DeadNodes(*this); 1264 1265 // If this combine is running after legalizing the DAG, re-legalize any 1266 // nodes pulled off the worklist. 1267 if (Level == AfterLegalizeDAG) { 1268 SmallSetVector<SDNode *, 16> UpdatedNodes; 1269 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1270 1271 for (SDNode *LN : UpdatedNodes) { 1272 AddToWorklist(LN); 1273 AddUsersToWorklist(LN); 1274 } 1275 if (!NIsValid) 1276 continue; 1277 } 1278 1279 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1280 1281 // Add any operands of the new node which have not yet been combined to the 1282 // worklist as well. Because the worklist uniques things already, this 1283 // won't repeatedly process the same operand. 1284 CombinedNodes.insert(N); 1285 for (const SDValue &ChildN : N->op_values()) 1286 if (!CombinedNodes.count(ChildN.getNode())) 1287 AddToWorklist(ChildN.getNode()); 1288 1289 SDValue RV = combine(N); 1290 1291 if (!RV.getNode()) 1292 continue; 1293 1294 ++NodesCombined; 1295 1296 // If we get back the same node we passed in, rather than a new node or 1297 // zero, we know that the node must have defined multiple values and 1298 // CombineTo was used. Since CombineTo takes care of the worklist 1299 // mechanics for us, we have no work to do in this case. 1300 if (RV.getNode() == N) 1301 continue; 1302 1303 assert(N->getOpcode() != ISD::DELETED_NODE && 1304 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1305 "Node was deleted but visit returned new node!"); 1306 1307 DEBUG(dbgs() << " ... into: "; 1308 RV.getNode()->dump(&DAG)); 1309 1310 // Transfer debug value. 1311 DAG.TransferDbgValues(SDValue(N, 0), RV); 1312 if (N->getNumValues() == RV.getNode()->getNumValues()) 1313 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1314 else { 1315 assert(N->getValueType(0) == RV.getValueType() && 1316 N->getNumValues() == 1 && "Type mismatch"); 1317 SDValue OpV = RV; 1318 DAG.ReplaceAllUsesWith(N, &OpV); 1319 } 1320 1321 // Push the new node and any users onto the worklist 1322 AddToWorklist(RV.getNode()); 1323 AddUsersToWorklist(RV.getNode()); 1324 1325 // Finally, if the node is now dead, remove it from the graph. The node 1326 // may not be dead if the replacement process recursively simplified to 1327 // something else needing this node. This will also take care of adding any 1328 // operands which have lost a user to the worklist. 1329 recursivelyDeleteUnusedNodes(N); 1330 } 1331 1332 // If the root changed (e.g. it was a dead load, update the root). 1333 DAG.setRoot(Dummy.getValue()); 1334 DAG.RemoveDeadNodes(); 1335 } 1336 1337 SDValue DAGCombiner::visit(SDNode *N) { 1338 switch (N->getOpcode()) { 1339 default: break; 1340 case ISD::TokenFactor: return visitTokenFactor(N); 1341 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1342 case ISD::ADD: return visitADD(N); 1343 case ISD::SUB: return visitSUB(N); 1344 case ISD::ADDC: return visitADDC(N); 1345 case ISD::SUBC: return visitSUBC(N); 1346 case ISD::ADDE: return visitADDE(N); 1347 case ISD::SUBE: return visitSUBE(N); 1348 case ISD::MUL: return visitMUL(N); 1349 case ISD::SDIV: return visitSDIV(N); 1350 case ISD::UDIV: return visitUDIV(N); 1351 case ISD::SREM: return visitSREM(N); 1352 case ISD::UREM: return visitUREM(N); 1353 case ISD::MULHU: return visitMULHU(N); 1354 case ISD::MULHS: return visitMULHS(N); 1355 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1356 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1357 case ISD::SMULO: return visitSMULO(N); 1358 case ISD::UMULO: return visitUMULO(N); 1359 case ISD::SDIVREM: return visitSDIVREM(N); 1360 case ISD::UDIVREM: return visitUDIVREM(N); 1361 case ISD::SMIN: 1362 case ISD::SMAX: 1363 case ISD::UMIN: 1364 case ISD::UMAX: return visitIMINMAX(N); 1365 case ISD::AND: return visitAND(N); 1366 case ISD::OR: return visitOR(N); 1367 case ISD::XOR: return visitXOR(N); 1368 case ISD::SHL: return visitSHL(N); 1369 case ISD::SRA: return visitSRA(N); 1370 case ISD::SRL: return visitSRL(N); 1371 case ISD::ROTR: 1372 case ISD::ROTL: return visitRotate(N); 1373 case ISD::BSWAP: return visitBSWAP(N); 1374 case ISD::CTLZ: return visitCTLZ(N); 1375 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1376 case ISD::CTTZ: return visitCTTZ(N); 1377 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1378 case ISD::CTPOP: return visitCTPOP(N); 1379 case ISD::SELECT: return visitSELECT(N); 1380 case ISD::VSELECT: return visitVSELECT(N); 1381 case ISD::SELECT_CC: return visitSELECT_CC(N); 1382 case ISD::SETCC: return visitSETCC(N); 1383 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1384 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1385 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1386 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1387 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1388 case ISD::TRUNCATE: return visitTRUNCATE(N); 1389 case ISD::BITCAST: return visitBITCAST(N); 1390 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1391 case ISD::FADD: return visitFADD(N); 1392 case ISD::FSUB: return visitFSUB(N); 1393 case ISD::FMUL: return visitFMUL(N); 1394 case ISD::FMA: return visitFMA(N); 1395 case ISD::FDIV: return visitFDIV(N); 1396 case ISD::FREM: return visitFREM(N); 1397 case ISD::FSQRT: return visitFSQRT(N); 1398 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1399 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1400 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1401 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1402 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1403 case ISD::FP_ROUND: return visitFP_ROUND(N); 1404 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1405 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1406 case ISD::FNEG: return visitFNEG(N); 1407 case ISD::FABS: return visitFABS(N); 1408 case ISD::FFLOOR: return visitFFLOOR(N); 1409 case ISD::FMINNUM: return visitFMINNUM(N); 1410 case ISD::FMAXNUM: return visitFMAXNUM(N); 1411 case ISD::FCEIL: return visitFCEIL(N); 1412 case ISD::FTRUNC: return visitFTRUNC(N); 1413 case ISD::BRCOND: return visitBRCOND(N); 1414 case ISD::BR_CC: return visitBR_CC(N); 1415 case ISD::LOAD: return visitLOAD(N); 1416 case ISD::STORE: return visitSTORE(N); 1417 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1418 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1419 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1420 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1421 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1422 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1423 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1424 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1425 case ISD::MGATHER: return visitMGATHER(N); 1426 case ISD::MLOAD: return visitMLOAD(N); 1427 case ISD::MSCATTER: return visitMSCATTER(N); 1428 case ISD::MSTORE: return visitMSTORE(N); 1429 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1430 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1431 } 1432 return SDValue(); 1433 } 1434 1435 SDValue DAGCombiner::combine(SDNode *N) { 1436 SDValue RV = visit(N); 1437 1438 // If nothing happened, try a target-specific DAG combine. 1439 if (!RV.getNode()) { 1440 assert(N->getOpcode() != ISD::DELETED_NODE && 1441 "Node was deleted but visit returned NULL!"); 1442 1443 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1444 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1445 1446 // Expose the DAG combiner to the target combiner impls. 1447 TargetLowering::DAGCombinerInfo 1448 DagCombineInfo(DAG, Level, false, this); 1449 1450 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1451 } 1452 } 1453 1454 // If nothing happened still, try promoting the operation. 1455 if (!RV.getNode()) { 1456 switch (N->getOpcode()) { 1457 default: break; 1458 case ISD::ADD: 1459 case ISD::SUB: 1460 case ISD::MUL: 1461 case ISD::AND: 1462 case ISD::OR: 1463 case ISD::XOR: 1464 RV = PromoteIntBinOp(SDValue(N, 0)); 1465 break; 1466 case ISD::SHL: 1467 case ISD::SRA: 1468 case ISD::SRL: 1469 RV = PromoteIntShiftOp(SDValue(N, 0)); 1470 break; 1471 case ISD::SIGN_EXTEND: 1472 case ISD::ZERO_EXTEND: 1473 case ISD::ANY_EXTEND: 1474 RV = PromoteExtend(SDValue(N, 0)); 1475 break; 1476 case ISD::LOAD: 1477 if (PromoteLoad(SDValue(N, 0))) 1478 RV = SDValue(N, 0); 1479 break; 1480 } 1481 } 1482 1483 // If N is a commutative binary node, try commuting it to enable more 1484 // sdisel CSE. 1485 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1486 N->getNumValues() == 1) { 1487 SDValue N0 = N->getOperand(0); 1488 SDValue N1 = N->getOperand(1); 1489 1490 // Constant operands are canonicalized to RHS. 1491 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1492 SDValue Ops[] = {N1, N0}; 1493 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1494 N->getFlags()); 1495 if (CSENode) 1496 return SDValue(CSENode, 0); 1497 } 1498 } 1499 1500 return RV; 1501 } 1502 1503 /// Given a node, return its input chain if it has one, otherwise return a null 1504 /// sd operand. 1505 static SDValue getInputChainForNode(SDNode *N) { 1506 if (unsigned NumOps = N->getNumOperands()) { 1507 if (N->getOperand(0).getValueType() == MVT::Other) 1508 return N->getOperand(0); 1509 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1510 return N->getOperand(NumOps-1); 1511 for (unsigned i = 1; i < NumOps-1; ++i) 1512 if (N->getOperand(i).getValueType() == MVT::Other) 1513 return N->getOperand(i); 1514 } 1515 return SDValue(); 1516 } 1517 1518 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1519 // If N has two operands, where one has an input chain equal to the other, 1520 // the 'other' chain is redundant. 1521 if (N->getNumOperands() == 2) { 1522 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1523 return N->getOperand(0); 1524 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1525 return N->getOperand(1); 1526 } 1527 1528 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1529 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1530 SmallPtrSet<SDNode*, 16> SeenOps; 1531 bool Changed = false; // If we should replace this token factor. 1532 1533 // Start out with this token factor. 1534 TFs.push_back(N); 1535 1536 // Iterate through token factors. The TFs grows when new token factors are 1537 // encountered. 1538 for (unsigned i = 0; i < TFs.size(); ++i) { 1539 SDNode *TF = TFs[i]; 1540 1541 // Check each of the operands. 1542 for (const SDValue &Op : TF->op_values()) { 1543 1544 switch (Op.getOpcode()) { 1545 case ISD::EntryToken: 1546 // Entry tokens don't need to be added to the list. They are 1547 // redundant. 1548 Changed = true; 1549 break; 1550 1551 case ISD::TokenFactor: 1552 if (Op.hasOneUse() && 1553 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1554 // Queue up for processing. 1555 TFs.push_back(Op.getNode()); 1556 // Clean up in case the token factor is removed. 1557 AddToWorklist(Op.getNode()); 1558 Changed = true; 1559 break; 1560 } 1561 // Fall thru 1562 1563 default: 1564 // Only add if it isn't already in the list. 1565 if (SeenOps.insert(Op.getNode()).second) 1566 Ops.push_back(Op); 1567 else 1568 Changed = true; 1569 break; 1570 } 1571 } 1572 } 1573 1574 SDValue Result; 1575 1576 // If we've changed things around then replace token factor. 1577 if (Changed) { 1578 if (Ops.empty()) { 1579 // The entry token is the only possible outcome. 1580 Result = DAG.getEntryNode(); 1581 } else { 1582 // New and improved token factor. 1583 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1584 } 1585 1586 // Add users to worklist if AA is enabled, since it may introduce 1587 // a lot of new chained token factors while removing memory deps. 1588 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1589 : DAG.getSubtarget().useAA(); 1590 return CombineTo(N, Result, UseAA /*add to worklist*/); 1591 } 1592 1593 return Result; 1594 } 1595 1596 /// MERGE_VALUES can always be eliminated. 1597 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1598 WorklistRemover DeadNodes(*this); 1599 // Replacing results may cause a different MERGE_VALUES to suddenly 1600 // be CSE'd with N, and carry its uses with it. Iterate until no 1601 // uses remain, to ensure that the node can be safely deleted. 1602 // First add the users of this node to the work list so that they 1603 // can be tried again once they have new operands. 1604 AddUsersToWorklist(N); 1605 do { 1606 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1607 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1608 } while (!N->use_empty()); 1609 deleteAndRecombine(N); 1610 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1611 } 1612 1613 static bool isNullConstant(SDValue V) { 1614 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1615 return Const != nullptr && Const->isNullValue(); 1616 } 1617 1618 static bool isNullFPConstant(SDValue V) { 1619 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 1620 return Const != nullptr && Const->isZero() && !Const->isNegative(); 1621 } 1622 1623 static bool isAllOnesConstant(SDValue V) { 1624 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1625 return Const != nullptr && Const->isAllOnesValue(); 1626 } 1627 1628 static bool isOneConstant(SDValue V) { 1629 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1630 return Const != nullptr && Const->isOne(); 1631 } 1632 1633 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a 1634 /// ContantSDNode pointer else nullptr. 1635 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1636 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1637 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1638 } 1639 1640 SDValue DAGCombiner::visitADD(SDNode *N) { 1641 SDValue N0 = N->getOperand(0); 1642 SDValue N1 = N->getOperand(1); 1643 EVT VT = N0.getValueType(); 1644 1645 // fold vector ops 1646 if (VT.isVector()) { 1647 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1648 return FoldedVOp; 1649 1650 // fold (add x, 0) -> x, vector edition 1651 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1652 return N0; 1653 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1654 return N1; 1655 } 1656 1657 // fold (add x, undef) -> undef 1658 if (N0.getOpcode() == ISD::UNDEF) 1659 return N0; 1660 if (N1.getOpcode() == ISD::UNDEF) 1661 return N1; 1662 // fold (add c1, c2) -> c1+c2 1663 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1664 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1665 if (N0C && N1C) 1666 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C); 1667 // canonicalize constant to RHS 1668 if (isConstantIntBuildVectorOrConstantInt(N0) && 1669 !isConstantIntBuildVectorOrConstantInt(N1)) 1670 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1671 // fold (add x, 0) -> x 1672 if (isNullConstant(N1)) 1673 return N0; 1674 // fold (add Sym, c) -> Sym+c 1675 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1676 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1677 GA->getOpcode() == ISD::GlobalAddress) 1678 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1679 GA->getOffset() + 1680 (uint64_t)N1C->getSExtValue()); 1681 // fold ((c1-A)+c2) -> (c1+c2)-A 1682 if (N1C && N0.getOpcode() == ISD::SUB) 1683 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1684 SDLoc DL(N); 1685 return DAG.getNode(ISD::SUB, DL, VT, 1686 DAG.getConstant(N1C->getAPIntValue()+ 1687 N0C->getAPIntValue(), DL, VT), 1688 N0.getOperand(1)); 1689 } 1690 // reassociate add 1691 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1692 return RADD; 1693 // fold ((0-A) + B) -> B-A 1694 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1695 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1696 // fold (A + (0-B)) -> A-B 1697 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1698 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1699 // fold (A+(B-A)) -> B 1700 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1701 return N1.getOperand(0); 1702 // fold ((B-A)+A) -> B 1703 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1704 return N0.getOperand(0); 1705 // fold (A+(B-(A+C))) to (B-C) 1706 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1707 N0 == N1.getOperand(1).getOperand(0)) 1708 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1709 N1.getOperand(1).getOperand(1)); 1710 // fold (A+(B-(C+A))) to (B-C) 1711 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1712 N0 == N1.getOperand(1).getOperand(1)) 1713 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1714 N1.getOperand(1).getOperand(0)); 1715 // fold (A+((B-A)+or-C)) to (B+or-C) 1716 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1717 N1.getOperand(0).getOpcode() == ISD::SUB && 1718 N0 == N1.getOperand(0).getOperand(1)) 1719 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1720 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1721 1722 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1723 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1724 SDValue N00 = N0.getOperand(0); 1725 SDValue N01 = N0.getOperand(1); 1726 SDValue N10 = N1.getOperand(0); 1727 SDValue N11 = N1.getOperand(1); 1728 1729 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1730 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1731 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1732 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1733 } 1734 1735 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1736 return SDValue(N, 0); 1737 1738 // fold (a+b) -> (a|b) iff a and b share no bits. 1739 if (VT.isInteger() && !VT.isVector()) { 1740 APInt LHSZero, LHSOne; 1741 APInt RHSZero, RHSOne; 1742 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1743 1744 if (LHSZero.getBoolValue()) { 1745 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1746 1747 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1748 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1749 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1750 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1751 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1752 } 1753 } 1754 } 1755 1756 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1757 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1758 isNullConstant(N1.getOperand(0).getOperand(0))) 1759 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1760 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1761 N1.getOperand(0).getOperand(1), 1762 N1.getOperand(1))); 1763 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1764 isNullConstant(N0.getOperand(0).getOperand(0))) 1765 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1766 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1767 N0.getOperand(0).getOperand(1), 1768 N0.getOperand(1))); 1769 1770 if (N1.getOpcode() == ISD::AND) { 1771 SDValue AndOp0 = N1.getOperand(0); 1772 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1773 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1774 1775 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1776 // and similar xforms where the inner op is either ~0 or 0. 1777 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1778 SDLoc DL(N); 1779 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1780 } 1781 } 1782 1783 // add (sext i1), X -> sub X, (zext i1) 1784 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1785 N0.getOperand(0).getValueType() == MVT::i1 && 1786 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1787 SDLoc DL(N); 1788 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1789 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1790 } 1791 1792 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1793 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1794 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1795 if (TN->getVT() == MVT::i1) { 1796 SDLoc DL(N); 1797 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1798 DAG.getConstant(1, DL, VT)); 1799 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1800 } 1801 } 1802 1803 return SDValue(); 1804 } 1805 1806 SDValue DAGCombiner::visitADDC(SDNode *N) { 1807 SDValue N0 = N->getOperand(0); 1808 SDValue N1 = N->getOperand(1); 1809 EVT VT = N0.getValueType(); 1810 1811 // If the flag result is dead, turn this into an ADD. 1812 if (!N->hasAnyUseOfValue(1)) 1813 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1814 DAG.getNode(ISD::CARRY_FALSE, 1815 SDLoc(N), MVT::Glue)); 1816 1817 // canonicalize constant to RHS. 1818 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1819 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1820 if (N0C && !N1C) 1821 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1822 1823 // fold (addc x, 0) -> x + no carry out 1824 if (isNullConstant(N1)) 1825 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1826 SDLoc(N), MVT::Glue)); 1827 1828 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1829 APInt LHSZero, LHSOne; 1830 APInt RHSZero, RHSOne; 1831 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1832 1833 if (LHSZero.getBoolValue()) { 1834 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1835 1836 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1837 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1838 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1839 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1840 DAG.getNode(ISD::CARRY_FALSE, 1841 SDLoc(N), MVT::Glue)); 1842 } 1843 1844 return SDValue(); 1845 } 1846 1847 SDValue DAGCombiner::visitADDE(SDNode *N) { 1848 SDValue N0 = N->getOperand(0); 1849 SDValue N1 = N->getOperand(1); 1850 SDValue CarryIn = N->getOperand(2); 1851 1852 // canonicalize constant to RHS 1853 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1854 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1855 if (N0C && !N1C) 1856 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1857 N1, N0, CarryIn); 1858 1859 // fold (adde x, y, false) -> (addc x, y) 1860 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1861 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1862 1863 return SDValue(); 1864 } 1865 1866 // Since it may not be valid to emit a fold to zero for vector initializers 1867 // check if we can before folding. 1868 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1869 SelectionDAG &DAG, 1870 bool LegalOperations, bool LegalTypes) { 1871 if (!VT.isVector()) 1872 return DAG.getConstant(0, DL, VT); 1873 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1874 return DAG.getConstant(0, DL, VT); 1875 return SDValue(); 1876 } 1877 1878 SDValue DAGCombiner::visitSUB(SDNode *N) { 1879 SDValue N0 = N->getOperand(0); 1880 SDValue N1 = N->getOperand(1); 1881 EVT VT = N0.getValueType(); 1882 1883 // fold vector ops 1884 if (VT.isVector()) { 1885 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1886 return FoldedVOp; 1887 1888 // fold (sub x, 0) -> x, vector edition 1889 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1890 return N0; 1891 } 1892 1893 // fold (sub x, x) -> 0 1894 // FIXME: Refactor this and xor and other similar operations together. 1895 if (N0 == N1) 1896 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1897 // fold (sub c1, c2) -> c1-c2 1898 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1899 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1900 if (N0C && N1C) 1901 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C); 1902 // fold (sub x, c) -> (add x, -c) 1903 if (N1C) { 1904 SDLoc DL(N); 1905 return DAG.getNode(ISD::ADD, DL, VT, N0, 1906 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1907 } 1908 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1909 if (isAllOnesConstant(N0)) 1910 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1911 // fold A-(A-B) -> B 1912 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1913 return N1.getOperand(1); 1914 // fold (A+B)-A -> B 1915 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1916 return N0.getOperand(1); 1917 // fold (A+B)-B -> A 1918 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1919 return N0.getOperand(0); 1920 // fold C2-(A+C1) -> (C2-C1)-A 1921 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1922 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1923 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1924 SDLoc DL(N); 1925 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1926 DL, VT); 1927 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1928 N1.getOperand(0)); 1929 } 1930 // fold ((A+(B+or-C))-B) -> A+or-C 1931 if (N0.getOpcode() == ISD::ADD && 1932 (N0.getOperand(1).getOpcode() == ISD::SUB || 1933 N0.getOperand(1).getOpcode() == ISD::ADD) && 1934 N0.getOperand(1).getOperand(0) == N1) 1935 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1936 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1937 // fold ((A+(C+B))-B) -> A+C 1938 if (N0.getOpcode() == ISD::ADD && 1939 N0.getOperand(1).getOpcode() == ISD::ADD && 1940 N0.getOperand(1).getOperand(1) == N1) 1941 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1942 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1943 // fold ((A-(B-C))-C) -> A-B 1944 if (N0.getOpcode() == ISD::SUB && 1945 N0.getOperand(1).getOpcode() == ISD::SUB && 1946 N0.getOperand(1).getOperand(1) == N1) 1947 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1948 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1949 1950 // If either operand of a sub is undef, the result is undef 1951 if (N0.getOpcode() == ISD::UNDEF) 1952 return N0; 1953 if (N1.getOpcode() == ISD::UNDEF) 1954 return N1; 1955 1956 // If the relocation model supports it, consider symbol offsets. 1957 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1958 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1959 // fold (sub Sym, c) -> Sym-c 1960 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1961 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1962 GA->getOffset() - 1963 (uint64_t)N1C->getSExtValue()); 1964 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1965 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1966 if (GA->getGlobal() == GB->getGlobal()) 1967 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1968 SDLoc(N), VT); 1969 } 1970 1971 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1972 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1973 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1974 if (TN->getVT() == MVT::i1) { 1975 SDLoc DL(N); 1976 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1977 DAG.getConstant(1, DL, VT)); 1978 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1979 } 1980 } 1981 1982 return SDValue(); 1983 } 1984 1985 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1986 SDValue N0 = N->getOperand(0); 1987 SDValue N1 = N->getOperand(1); 1988 EVT VT = N0.getValueType(); 1989 1990 // If the flag result is dead, turn this into an SUB. 1991 if (!N->hasAnyUseOfValue(1)) 1992 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1993 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1994 MVT::Glue)); 1995 1996 // fold (subc x, x) -> 0 + no borrow 1997 if (N0 == N1) { 1998 SDLoc DL(N); 1999 return CombineTo(N, DAG.getConstant(0, DL, VT), 2000 DAG.getNode(ISD::CARRY_FALSE, DL, 2001 MVT::Glue)); 2002 } 2003 2004 // fold (subc x, 0) -> x + no borrow 2005 if (isNullConstant(N1)) 2006 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 2007 MVT::Glue)); 2008 2009 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2010 if (isAllOnesConstant(N0)) 2011 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 2012 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 2013 MVT::Glue)); 2014 2015 return SDValue(); 2016 } 2017 2018 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2019 SDValue N0 = N->getOperand(0); 2020 SDValue N1 = N->getOperand(1); 2021 SDValue CarryIn = N->getOperand(2); 2022 2023 // fold (sube x, y, false) -> (subc x, y) 2024 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2025 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2026 2027 return SDValue(); 2028 } 2029 2030 SDValue DAGCombiner::visitMUL(SDNode *N) { 2031 SDValue N0 = N->getOperand(0); 2032 SDValue N1 = N->getOperand(1); 2033 EVT VT = N0.getValueType(); 2034 2035 // fold (mul x, undef) -> 0 2036 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2037 return DAG.getConstant(0, SDLoc(N), VT); 2038 2039 bool N0IsConst = false; 2040 bool N1IsConst = false; 2041 bool N1IsOpaqueConst = false; 2042 bool N0IsOpaqueConst = false; 2043 APInt ConstValue0, ConstValue1; 2044 // fold vector ops 2045 if (VT.isVector()) { 2046 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2047 return FoldedVOp; 2048 2049 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2050 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2051 } else { 2052 N0IsConst = isa<ConstantSDNode>(N0); 2053 if (N0IsConst) { 2054 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2055 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2056 } 2057 N1IsConst = isa<ConstantSDNode>(N1); 2058 if (N1IsConst) { 2059 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2060 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2061 } 2062 } 2063 2064 // fold (mul c1, c2) -> c1*c2 2065 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2066 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2067 N0.getNode(), N1.getNode()); 2068 2069 // canonicalize constant to RHS (vector doesn't have to splat) 2070 if (isConstantIntBuildVectorOrConstantInt(N0) && 2071 !isConstantIntBuildVectorOrConstantInt(N1)) 2072 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2073 // fold (mul x, 0) -> 0 2074 if (N1IsConst && ConstValue1 == 0) 2075 return N1; 2076 // We require a splat of the entire scalar bit width for non-contiguous 2077 // bit patterns. 2078 bool IsFullSplat = 2079 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2080 // fold (mul x, 1) -> x 2081 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2082 return N0; 2083 // fold (mul x, -1) -> 0-x 2084 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2085 SDLoc DL(N); 2086 return DAG.getNode(ISD::SUB, DL, VT, 2087 DAG.getConstant(0, DL, VT), N0); 2088 } 2089 // fold (mul x, (1 << c)) -> x << c 2090 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2091 IsFullSplat) { 2092 SDLoc DL(N); 2093 return DAG.getNode(ISD::SHL, DL, VT, N0, 2094 DAG.getConstant(ConstValue1.logBase2(), DL, 2095 getShiftAmountTy(N0.getValueType()))); 2096 } 2097 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2098 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2099 IsFullSplat) { 2100 unsigned Log2Val = (-ConstValue1).logBase2(); 2101 SDLoc DL(N); 2102 // FIXME: If the input is something that is easily negated (e.g. a 2103 // single-use add), we should put the negate there. 2104 return DAG.getNode(ISD::SUB, DL, VT, 2105 DAG.getConstant(0, DL, VT), 2106 DAG.getNode(ISD::SHL, DL, VT, N0, 2107 DAG.getConstant(Log2Val, DL, 2108 getShiftAmountTy(N0.getValueType())))); 2109 } 2110 2111 APInt Val; 2112 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2113 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2114 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2115 isa<ConstantSDNode>(N0.getOperand(1)))) { 2116 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2117 N1, N0.getOperand(1)); 2118 AddToWorklist(C3.getNode()); 2119 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2120 N0.getOperand(0), C3); 2121 } 2122 2123 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2124 // use. 2125 { 2126 SDValue Sh(nullptr,0), Y(nullptr,0); 2127 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2128 if (N0.getOpcode() == ISD::SHL && 2129 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2130 isa<ConstantSDNode>(N0.getOperand(1))) && 2131 N0.getNode()->hasOneUse()) { 2132 Sh = N0; Y = N1; 2133 } else if (N1.getOpcode() == ISD::SHL && 2134 isa<ConstantSDNode>(N1.getOperand(1)) && 2135 N1.getNode()->hasOneUse()) { 2136 Sh = N1; Y = N0; 2137 } 2138 2139 if (Sh.getNode()) { 2140 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2141 Sh.getOperand(0), Y); 2142 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2143 Mul, Sh.getOperand(1)); 2144 } 2145 } 2146 2147 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2148 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 2149 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2150 isa<ConstantSDNode>(N0.getOperand(1)))) 2151 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2152 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2153 N0.getOperand(0), N1), 2154 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2155 N0.getOperand(1), N1)); 2156 2157 // reassociate mul 2158 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2159 return RMUL; 2160 2161 return SDValue(); 2162 } 2163 2164 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2165 SDValue N0 = N->getOperand(0); 2166 SDValue N1 = N->getOperand(1); 2167 EVT VT = N->getValueType(0); 2168 2169 // fold vector ops 2170 if (VT.isVector()) 2171 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2172 return FoldedVOp; 2173 2174 // fold (sdiv c1, c2) -> c1/c2 2175 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2176 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2177 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2178 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C); 2179 // fold (sdiv X, 1) -> X 2180 if (N1C && N1C->isOne()) 2181 return N0; 2182 // fold (sdiv X, -1) -> 0-X 2183 if (N1C && N1C->isAllOnesValue()) { 2184 SDLoc DL(N); 2185 return DAG.getNode(ISD::SUB, DL, VT, 2186 DAG.getConstant(0, DL, VT), N0); 2187 } 2188 // If we know the sign bits of both operands are zero, strength reduce to a 2189 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2190 if (!VT.isVector()) { 2191 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2192 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2193 N0, N1); 2194 } 2195 2196 // fold (sdiv X, pow2) -> simple ops after legalize 2197 // FIXME: We check for the exact bit here because the generic lowering gives 2198 // better results in that case. The target-specific lowering should learn how 2199 // to handle exact sdivs efficiently. 2200 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2201 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2202 (N1C->getAPIntValue().isPowerOf2() || 2203 (-N1C->getAPIntValue()).isPowerOf2())) { 2204 // Target-specific implementation of sdiv x, pow2. 2205 if (SDValue Res = BuildSDIVPow2(N)) 2206 return Res; 2207 2208 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2209 SDLoc DL(N); 2210 2211 // Splat the sign bit into the register 2212 SDValue SGN = 2213 DAG.getNode(ISD::SRA, DL, VT, N0, 2214 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2215 getShiftAmountTy(N0.getValueType()))); 2216 AddToWorklist(SGN.getNode()); 2217 2218 // Add (N0 < 0) ? abs2 - 1 : 0; 2219 SDValue SRL = 2220 DAG.getNode(ISD::SRL, DL, VT, SGN, 2221 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2222 getShiftAmountTy(SGN.getValueType()))); 2223 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2224 AddToWorklist(SRL.getNode()); 2225 AddToWorklist(ADD.getNode()); // Divide by pow2 2226 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2227 DAG.getConstant(lg2, DL, 2228 getShiftAmountTy(ADD.getValueType()))); 2229 2230 // If we're dividing by a positive value, we're done. Otherwise, we must 2231 // negate the result. 2232 if (N1C->getAPIntValue().isNonNegative()) 2233 return SRA; 2234 2235 AddToWorklist(SRA.getNode()); 2236 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2237 } 2238 2239 // If integer divide is expensive and we satisfy the requirements, emit an 2240 // alternate sequence. Targets may check function attributes for size/speed 2241 // trade-offs. 2242 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2243 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2244 if (SDValue Op = BuildSDIV(N)) 2245 return Op; 2246 2247 // undef / X -> 0 2248 if (N0.getOpcode() == ISD::UNDEF) 2249 return DAG.getConstant(0, SDLoc(N), VT); 2250 // X / undef -> undef 2251 if (N1.getOpcode() == ISD::UNDEF) 2252 return N1; 2253 2254 return SDValue(); 2255 } 2256 2257 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2258 SDValue N0 = N->getOperand(0); 2259 SDValue N1 = N->getOperand(1); 2260 EVT VT = N->getValueType(0); 2261 2262 // fold vector ops 2263 if (VT.isVector()) 2264 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2265 return FoldedVOp; 2266 2267 // fold (udiv c1, c2) -> c1/c2 2268 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2269 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2270 if (N0C && N1C) 2271 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, 2272 N0C, N1C)) 2273 return Folded; 2274 // fold (udiv x, (1 << c)) -> x >>u c 2275 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) { 2276 SDLoc DL(N); 2277 return DAG.getNode(ISD::SRL, DL, VT, N0, 2278 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2279 getShiftAmountTy(N0.getValueType()))); 2280 } 2281 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2282 if (N1.getOpcode() == ISD::SHL) { 2283 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2284 if (SHC->getAPIntValue().isPowerOf2()) { 2285 EVT ADDVT = N1.getOperand(1).getValueType(); 2286 SDLoc DL(N); 2287 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2288 N1.getOperand(1), 2289 DAG.getConstant(SHC->getAPIntValue() 2290 .logBase2(), 2291 DL, ADDVT)); 2292 AddToWorklist(Add.getNode()); 2293 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2294 } 2295 } 2296 } 2297 2298 // fold (udiv x, c) -> alternate 2299 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2300 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2301 if (SDValue Op = BuildUDIV(N)) 2302 return Op; 2303 2304 // undef / X -> 0 2305 if (N0.getOpcode() == ISD::UNDEF) 2306 return DAG.getConstant(0, SDLoc(N), VT); 2307 // X / undef -> undef 2308 if (N1.getOpcode() == ISD::UNDEF) 2309 return N1; 2310 2311 return SDValue(); 2312 } 2313 2314 SDValue DAGCombiner::visitSREM(SDNode *N) { 2315 SDValue N0 = N->getOperand(0); 2316 SDValue N1 = N->getOperand(1); 2317 EVT VT = N->getValueType(0); 2318 2319 // fold (srem c1, c2) -> c1%c2 2320 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2321 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2322 if (N0C && N1C) 2323 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, 2324 N0C, N1C)) 2325 return Folded; 2326 // If we know the sign bits of both operands are zero, strength reduce to a 2327 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2328 if (!VT.isVector()) { 2329 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2330 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2331 } 2332 2333 // If X/C can be simplified by the division-by-constant logic, lower 2334 // X%C to the equivalent of X-X/C*C. 2335 if (N1C && !N1C->isNullValue()) { 2336 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2337 AddToWorklist(Div.getNode()); 2338 SDValue OptimizedDiv = combine(Div.getNode()); 2339 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2340 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2341 OptimizedDiv, N1); 2342 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2343 AddToWorklist(Mul.getNode()); 2344 return Sub; 2345 } 2346 } 2347 2348 // undef % X -> 0 2349 if (N0.getOpcode() == ISD::UNDEF) 2350 return DAG.getConstant(0, SDLoc(N), VT); 2351 // X % undef -> undef 2352 if (N1.getOpcode() == ISD::UNDEF) 2353 return N1; 2354 2355 return SDValue(); 2356 } 2357 2358 SDValue DAGCombiner::visitUREM(SDNode *N) { 2359 SDValue N0 = N->getOperand(0); 2360 SDValue N1 = N->getOperand(1); 2361 EVT VT = N->getValueType(0); 2362 2363 // fold (urem c1, c2) -> c1%c2 2364 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2365 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2366 if (N0C && N1C) 2367 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, 2368 N0C, N1C)) 2369 return Folded; 2370 // fold (urem x, pow2) -> (and x, pow2-1) 2371 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2372 N1C->getAPIntValue().isPowerOf2()) { 2373 SDLoc DL(N); 2374 return DAG.getNode(ISD::AND, DL, VT, N0, 2375 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2376 } 2377 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2378 if (N1.getOpcode() == ISD::SHL) { 2379 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2380 if (SHC->getAPIntValue().isPowerOf2()) { 2381 SDLoc DL(N); 2382 SDValue Add = 2383 DAG.getNode(ISD::ADD, DL, VT, N1, 2384 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2385 VT)); 2386 AddToWorklist(Add.getNode()); 2387 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2388 } 2389 } 2390 } 2391 2392 // If X/C can be simplified by the division-by-constant logic, lower 2393 // X%C to the equivalent of X-X/C*C. 2394 if (N1C && !N1C->isNullValue()) { 2395 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2396 AddToWorklist(Div.getNode()); 2397 SDValue OptimizedDiv = combine(Div.getNode()); 2398 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2399 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2400 OptimizedDiv, N1); 2401 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2402 AddToWorklist(Mul.getNode()); 2403 return Sub; 2404 } 2405 } 2406 2407 // undef % X -> 0 2408 if (N0.getOpcode() == ISD::UNDEF) 2409 return DAG.getConstant(0, SDLoc(N), VT); 2410 // X % undef -> undef 2411 if (N1.getOpcode() == ISD::UNDEF) 2412 return N1; 2413 2414 return SDValue(); 2415 } 2416 2417 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2418 SDValue N0 = N->getOperand(0); 2419 SDValue N1 = N->getOperand(1); 2420 EVT VT = N->getValueType(0); 2421 SDLoc DL(N); 2422 2423 // fold (mulhs x, 0) -> 0 2424 if (isNullConstant(N1)) 2425 return N1; 2426 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2427 if (isOneConstant(N1)) { 2428 SDLoc DL(N); 2429 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2430 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2431 DL, 2432 getShiftAmountTy(N0.getValueType()))); 2433 } 2434 // fold (mulhs x, undef) -> 0 2435 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2436 return DAG.getConstant(0, SDLoc(N), VT); 2437 2438 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2439 // plus a shift. 2440 if (VT.isSimple() && !VT.isVector()) { 2441 MVT Simple = VT.getSimpleVT(); 2442 unsigned SimpleSize = Simple.getSizeInBits(); 2443 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2444 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2445 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2446 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2447 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2448 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2449 DAG.getConstant(SimpleSize, DL, 2450 getShiftAmountTy(N1.getValueType()))); 2451 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2452 } 2453 } 2454 2455 return SDValue(); 2456 } 2457 2458 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2459 SDValue N0 = N->getOperand(0); 2460 SDValue N1 = N->getOperand(1); 2461 EVT VT = N->getValueType(0); 2462 SDLoc DL(N); 2463 2464 // fold (mulhu x, 0) -> 0 2465 if (isNullConstant(N1)) 2466 return N1; 2467 // fold (mulhu x, 1) -> 0 2468 if (isOneConstant(N1)) 2469 return DAG.getConstant(0, DL, N0.getValueType()); 2470 // fold (mulhu x, undef) -> 0 2471 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2472 return DAG.getConstant(0, DL, VT); 2473 2474 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2475 // plus a shift. 2476 if (VT.isSimple() && !VT.isVector()) { 2477 MVT Simple = VT.getSimpleVT(); 2478 unsigned SimpleSize = Simple.getSizeInBits(); 2479 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2480 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2481 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2482 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2483 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2484 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2485 DAG.getConstant(SimpleSize, DL, 2486 getShiftAmountTy(N1.getValueType()))); 2487 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2488 } 2489 } 2490 2491 return SDValue(); 2492 } 2493 2494 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2495 /// give the opcodes for the two computations that are being performed. Return 2496 /// true if a simplification was made. 2497 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2498 unsigned HiOp) { 2499 // If the high half is not needed, just compute the low half. 2500 bool HiExists = N->hasAnyUseOfValue(1); 2501 if (!HiExists && 2502 (!LegalOperations || 2503 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2504 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2505 return CombineTo(N, Res, Res); 2506 } 2507 2508 // If the low half is not needed, just compute the high half. 2509 bool LoExists = N->hasAnyUseOfValue(0); 2510 if (!LoExists && 2511 (!LegalOperations || 2512 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2513 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2514 return CombineTo(N, Res, Res); 2515 } 2516 2517 // If both halves are used, return as it is. 2518 if (LoExists && HiExists) 2519 return SDValue(); 2520 2521 // If the two computed results can be simplified separately, separate them. 2522 if (LoExists) { 2523 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2524 AddToWorklist(Lo.getNode()); 2525 SDValue LoOpt = combine(Lo.getNode()); 2526 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2527 (!LegalOperations || 2528 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2529 return CombineTo(N, LoOpt, LoOpt); 2530 } 2531 2532 if (HiExists) { 2533 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2534 AddToWorklist(Hi.getNode()); 2535 SDValue HiOpt = combine(Hi.getNode()); 2536 if (HiOpt.getNode() && HiOpt != Hi && 2537 (!LegalOperations || 2538 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2539 return CombineTo(N, HiOpt, HiOpt); 2540 } 2541 2542 return SDValue(); 2543 } 2544 2545 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2546 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2547 return Res; 2548 2549 EVT VT = N->getValueType(0); 2550 SDLoc DL(N); 2551 2552 // If the type is twice as wide is legal, transform the mulhu to a wider 2553 // multiply plus a shift. 2554 if (VT.isSimple() && !VT.isVector()) { 2555 MVT Simple = VT.getSimpleVT(); 2556 unsigned SimpleSize = Simple.getSizeInBits(); 2557 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2558 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2559 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2560 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2561 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2562 // Compute the high part as N1. 2563 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2564 DAG.getConstant(SimpleSize, DL, 2565 getShiftAmountTy(Lo.getValueType()))); 2566 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2567 // Compute the low part as N0. 2568 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2569 return CombineTo(N, Lo, Hi); 2570 } 2571 } 2572 2573 return SDValue(); 2574 } 2575 2576 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2577 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2578 return Res; 2579 2580 EVT VT = N->getValueType(0); 2581 SDLoc DL(N); 2582 2583 // If the type is twice as wide is legal, transform the mulhu to a wider 2584 // multiply plus a shift. 2585 if (VT.isSimple() && !VT.isVector()) { 2586 MVT Simple = VT.getSimpleVT(); 2587 unsigned SimpleSize = Simple.getSizeInBits(); 2588 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2589 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2590 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2591 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2592 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2593 // Compute the high part as N1. 2594 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2595 DAG.getConstant(SimpleSize, DL, 2596 getShiftAmountTy(Lo.getValueType()))); 2597 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2598 // Compute the low part as N0. 2599 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2600 return CombineTo(N, Lo, Hi); 2601 } 2602 } 2603 2604 return SDValue(); 2605 } 2606 2607 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2608 // (smulo x, 2) -> (saddo x, x) 2609 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2610 if (C2->getAPIntValue() == 2) 2611 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2612 N->getOperand(0), N->getOperand(0)); 2613 2614 return SDValue(); 2615 } 2616 2617 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2618 // (umulo x, 2) -> (uaddo x, x) 2619 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2620 if (C2->getAPIntValue() == 2) 2621 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2622 N->getOperand(0), N->getOperand(0)); 2623 2624 return SDValue(); 2625 } 2626 2627 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2628 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM)) 2629 return Res; 2630 2631 return SDValue(); 2632 } 2633 2634 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2635 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM)) 2636 return Res; 2637 2638 return SDValue(); 2639 } 2640 2641 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2642 SDValue N0 = N->getOperand(0); 2643 SDValue N1 = N->getOperand(1); 2644 EVT VT = N0.getValueType(); 2645 2646 // fold vector ops 2647 if (VT.isVector()) 2648 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2649 return FoldedVOp; 2650 2651 // fold (add c1, c2) -> c1+c2 2652 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2653 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2654 if (N0C && N1C) 2655 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2656 2657 // canonicalize constant to RHS 2658 if (isConstantIntBuildVectorOrConstantInt(N0) && 2659 !isConstantIntBuildVectorOrConstantInt(N1)) 2660 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2661 2662 return SDValue(); 2663 } 2664 2665 /// If this is a binary operator with two operands of the same opcode, try to 2666 /// simplify it. 2667 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2668 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2669 EVT VT = N0.getValueType(); 2670 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2671 2672 // Bail early if none of these transforms apply. 2673 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2674 2675 // For each of OP in AND/OR/XOR: 2676 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2677 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2678 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2679 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2680 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2681 // 2682 // do not sink logical op inside of a vector extend, since it may combine 2683 // into a vsetcc. 2684 EVT Op0VT = N0.getOperand(0).getValueType(); 2685 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2686 N0.getOpcode() == ISD::SIGN_EXTEND || 2687 N0.getOpcode() == ISD::BSWAP || 2688 // Avoid infinite looping with PromoteIntBinOp. 2689 (N0.getOpcode() == ISD::ANY_EXTEND && 2690 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2691 (N0.getOpcode() == ISD::TRUNCATE && 2692 (!TLI.isZExtFree(VT, Op0VT) || 2693 !TLI.isTruncateFree(Op0VT, VT)) && 2694 TLI.isTypeLegal(Op0VT))) && 2695 !VT.isVector() && 2696 Op0VT == N1.getOperand(0).getValueType() && 2697 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2698 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2699 N0.getOperand(0).getValueType(), 2700 N0.getOperand(0), N1.getOperand(0)); 2701 AddToWorklist(ORNode.getNode()); 2702 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2703 } 2704 2705 // For each of OP in SHL/SRL/SRA/AND... 2706 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2707 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2708 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2709 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2710 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2711 N0.getOperand(1) == N1.getOperand(1)) { 2712 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2713 N0.getOperand(0).getValueType(), 2714 N0.getOperand(0), N1.getOperand(0)); 2715 AddToWorklist(ORNode.getNode()); 2716 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2717 ORNode, N0.getOperand(1)); 2718 } 2719 2720 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2721 // Only perform this optimization after type legalization and before 2722 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2723 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2724 // we don't want to undo this promotion. 2725 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2726 // on scalars. 2727 if ((N0.getOpcode() == ISD::BITCAST || 2728 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2729 Level == AfterLegalizeTypes) { 2730 SDValue In0 = N0.getOperand(0); 2731 SDValue In1 = N1.getOperand(0); 2732 EVT In0Ty = In0.getValueType(); 2733 EVT In1Ty = In1.getValueType(); 2734 SDLoc DL(N); 2735 // If both incoming values are integers, and the original types are the 2736 // same. 2737 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2738 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2739 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2740 AddToWorklist(Op.getNode()); 2741 return BC; 2742 } 2743 } 2744 2745 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2746 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2747 // If both shuffles use the same mask, and both shuffle within a single 2748 // vector, then it is worthwhile to move the swizzle after the operation. 2749 // The type-legalizer generates this pattern when loading illegal 2750 // vector types from memory. In many cases this allows additional shuffle 2751 // optimizations. 2752 // There are other cases where moving the shuffle after the xor/and/or 2753 // is profitable even if shuffles don't perform a swizzle. 2754 // If both shuffles use the same mask, and both shuffles have the same first 2755 // or second operand, then it might still be profitable to move the shuffle 2756 // after the xor/and/or operation. 2757 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2758 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2759 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2760 2761 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2762 "Inputs to shuffles are not the same type"); 2763 2764 // Check that both shuffles use the same mask. The masks are known to be of 2765 // the same length because the result vector type is the same. 2766 // Check also that shuffles have only one use to avoid introducing extra 2767 // instructions. 2768 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2769 SVN0->getMask().equals(SVN1->getMask())) { 2770 SDValue ShOp = N0->getOperand(1); 2771 2772 // Don't try to fold this node if it requires introducing a 2773 // build vector of all zeros that might be illegal at this stage. 2774 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2775 if (!LegalTypes) 2776 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2777 else 2778 ShOp = SDValue(); 2779 } 2780 2781 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2782 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2783 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2784 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2785 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2786 N0->getOperand(0), N1->getOperand(0)); 2787 AddToWorklist(NewNode.getNode()); 2788 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2789 &SVN0->getMask()[0]); 2790 } 2791 2792 // Don't try to fold this node if it requires introducing a 2793 // build vector of all zeros that might be illegal at this stage. 2794 ShOp = N0->getOperand(0); 2795 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2796 if (!LegalTypes) 2797 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2798 else 2799 ShOp = SDValue(); 2800 } 2801 2802 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2803 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2804 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2805 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2806 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2807 N0->getOperand(1), N1->getOperand(1)); 2808 AddToWorklist(NewNode.getNode()); 2809 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2810 &SVN0->getMask()[0]); 2811 } 2812 } 2813 } 2814 2815 return SDValue(); 2816 } 2817 2818 /// This contains all DAGCombine rules which reduce two values combined by 2819 /// an And operation to a single value. This makes them reusable in the context 2820 /// of visitSELECT(). Rules involving constants are not included as 2821 /// visitSELECT() already handles those cases. 2822 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2823 SDNode *LocReference) { 2824 EVT VT = N1.getValueType(); 2825 2826 // fold (and x, undef) -> 0 2827 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2828 return DAG.getConstant(0, SDLoc(LocReference), VT); 2829 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2830 SDValue LL, LR, RL, RR, CC0, CC1; 2831 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2832 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2833 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2834 2835 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2836 LL.getValueType().isInteger()) { 2837 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2838 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2839 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2840 LR.getValueType(), LL, RL); 2841 AddToWorklist(ORNode.getNode()); 2842 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2843 } 2844 if (isAllOnesConstant(LR)) { 2845 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2846 if (Op1 == ISD::SETEQ) { 2847 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2848 LR.getValueType(), LL, RL); 2849 AddToWorklist(ANDNode.getNode()); 2850 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2851 } 2852 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2853 if (Op1 == ISD::SETGT) { 2854 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2855 LR.getValueType(), LL, RL); 2856 AddToWorklist(ORNode.getNode()); 2857 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2858 } 2859 } 2860 } 2861 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2862 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2863 Op0 == Op1 && LL.getValueType().isInteger() && 2864 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2865 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2866 SDLoc DL(N0); 2867 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2868 LL, DAG.getConstant(1, DL, 2869 LL.getValueType())); 2870 AddToWorklist(ADDNode.getNode()); 2871 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2872 DAG.getConstant(2, DL, LL.getValueType()), 2873 ISD::SETUGE); 2874 } 2875 // canonicalize equivalent to ll == rl 2876 if (LL == RR && LR == RL) { 2877 Op1 = ISD::getSetCCSwappedOperands(Op1); 2878 std::swap(RL, RR); 2879 } 2880 if (LL == RL && LR == RR) { 2881 bool isInteger = LL.getValueType().isInteger(); 2882 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2883 if (Result != ISD::SETCC_INVALID && 2884 (!LegalOperations || 2885 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2886 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2887 EVT CCVT = getSetCCResultType(LL.getValueType()); 2888 if (N0.getValueType() == CCVT || 2889 (!LegalOperations && N0.getValueType() == MVT::i1)) 2890 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2891 LL, LR, Result); 2892 } 2893 } 2894 } 2895 2896 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2897 VT.getSizeInBits() <= 64) { 2898 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2899 APInt ADDC = ADDI->getAPIntValue(); 2900 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2901 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2902 // immediate for an add, but it is legal if its top c2 bits are set, 2903 // transform the ADD so the immediate doesn't need to be materialized 2904 // in a register. 2905 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2906 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2907 SRLI->getZExtValue()); 2908 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2909 ADDC |= Mask; 2910 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2911 SDLoc DL(N0); 2912 SDValue NewAdd = 2913 DAG.getNode(ISD::ADD, DL, VT, 2914 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2915 CombineTo(N0.getNode(), NewAdd); 2916 // Return N so it doesn't get rechecked! 2917 return SDValue(LocReference, 0); 2918 } 2919 } 2920 } 2921 } 2922 } 2923 } 2924 2925 return SDValue(); 2926 } 2927 2928 SDValue DAGCombiner::visitAND(SDNode *N) { 2929 SDValue N0 = N->getOperand(0); 2930 SDValue N1 = N->getOperand(1); 2931 EVT VT = N1.getValueType(); 2932 2933 // fold vector ops 2934 if (VT.isVector()) { 2935 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2936 return FoldedVOp; 2937 2938 // fold (and x, 0) -> 0, vector edition 2939 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2940 // do not return N0, because undef node may exist in N0 2941 return DAG.getConstant( 2942 APInt::getNullValue( 2943 N0.getValueType().getScalarType().getSizeInBits()), 2944 SDLoc(N), N0.getValueType()); 2945 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2946 // do not return N1, because undef node may exist in N1 2947 return DAG.getConstant( 2948 APInt::getNullValue( 2949 N1.getValueType().getScalarType().getSizeInBits()), 2950 SDLoc(N), N1.getValueType()); 2951 2952 // fold (and x, -1) -> x, vector edition 2953 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2954 return N1; 2955 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2956 return N0; 2957 } 2958 2959 // fold (and c1, c2) -> c1&c2 2960 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2961 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2962 if (N0C && N1C && !N1C->isOpaque()) 2963 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 2964 // canonicalize constant to RHS 2965 if (isConstantIntBuildVectorOrConstantInt(N0) && 2966 !isConstantIntBuildVectorOrConstantInt(N1)) 2967 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2968 // fold (and x, -1) -> x 2969 if (isAllOnesConstant(N1)) 2970 return N0; 2971 // if (and x, c) is known to be zero, return 0 2972 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2973 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2974 APInt::getAllOnesValue(BitWidth))) 2975 return DAG.getConstant(0, SDLoc(N), VT); 2976 // reassociate and 2977 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 2978 return RAND; 2979 // fold (and (or x, C), D) -> D if (C & D) == D 2980 if (N1C && N0.getOpcode() == ISD::OR) 2981 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2982 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2983 return N1; 2984 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2985 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2986 SDValue N0Op0 = N0.getOperand(0); 2987 APInt Mask = ~N1C->getAPIntValue(); 2988 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2989 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2990 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2991 N0.getValueType(), N0Op0); 2992 2993 // Replace uses of the AND with uses of the Zero extend node. 2994 CombineTo(N, Zext); 2995 2996 // We actually want to replace all uses of the any_extend with the 2997 // zero_extend, to avoid duplicating things. This will later cause this 2998 // AND to be folded. 2999 CombineTo(N0.getNode(), Zext); 3000 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3001 } 3002 } 3003 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3004 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3005 // already be zero by virtue of the width of the base type of the load. 3006 // 3007 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3008 // more cases. 3009 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3010 N0.getOperand(0).getOpcode() == ISD::LOAD) || 3011 N0.getOpcode() == ISD::LOAD) { 3012 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3013 N0 : N0.getOperand(0) ); 3014 3015 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3016 // This can be a pure constant or a vector splat, in which case we treat the 3017 // vector as a scalar and use the splat value. 3018 APInt Constant = APInt::getNullValue(1); 3019 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3020 Constant = C->getAPIntValue(); 3021 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3022 APInt SplatValue, SplatUndef; 3023 unsigned SplatBitSize; 3024 bool HasAnyUndefs; 3025 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3026 SplatBitSize, HasAnyUndefs); 3027 if (IsSplat) { 3028 // Undef bits can contribute to a possible optimisation if set, so 3029 // set them. 3030 SplatValue |= SplatUndef; 3031 3032 // The splat value may be something like "0x00FFFFFF", which means 0 for 3033 // the first vector value and FF for the rest, repeating. We need a mask 3034 // that will apply equally to all members of the vector, so AND all the 3035 // lanes of the constant together. 3036 EVT VT = Vector->getValueType(0); 3037 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3038 3039 // If the splat value has been compressed to a bitlength lower 3040 // than the size of the vector lane, we need to re-expand it to 3041 // the lane size. 3042 if (BitWidth > SplatBitSize) 3043 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3044 SplatBitSize < BitWidth; 3045 SplatBitSize = SplatBitSize * 2) 3046 SplatValue |= SplatValue.shl(SplatBitSize); 3047 3048 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3049 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3050 if (SplatBitSize % BitWidth == 0) { 3051 Constant = APInt::getAllOnesValue(BitWidth); 3052 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3053 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3054 } 3055 } 3056 } 3057 3058 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3059 // actually legal and isn't going to get expanded, else this is a false 3060 // optimisation. 3061 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3062 Load->getValueType(0), 3063 Load->getMemoryVT()); 3064 3065 // Resize the constant to the same size as the original memory access before 3066 // extension. If it is still the AllOnesValue then this AND is completely 3067 // unneeded. 3068 Constant = 3069 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3070 3071 bool B; 3072 switch (Load->getExtensionType()) { 3073 default: B = false; break; 3074 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3075 case ISD::ZEXTLOAD: 3076 case ISD::NON_EXTLOAD: B = true; break; 3077 } 3078 3079 if (B && Constant.isAllOnesValue()) { 3080 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3081 // preserve semantics once we get rid of the AND. 3082 SDValue NewLoad(Load, 0); 3083 if (Load->getExtensionType() == ISD::EXTLOAD) { 3084 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3085 Load->getValueType(0), SDLoc(Load), 3086 Load->getChain(), Load->getBasePtr(), 3087 Load->getOffset(), Load->getMemoryVT(), 3088 Load->getMemOperand()); 3089 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3090 if (Load->getNumValues() == 3) { 3091 // PRE/POST_INC loads have 3 values. 3092 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3093 NewLoad.getValue(2) }; 3094 CombineTo(Load, To, 3, true); 3095 } else { 3096 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3097 } 3098 } 3099 3100 // Fold the AND away, taking care not to fold to the old load node if we 3101 // replaced it. 3102 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3103 3104 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3105 } 3106 } 3107 3108 // fold (and (load x), 255) -> (zextload x, i8) 3109 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3110 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3111 if (N1C && (N0.getOpcode() == ISD::LOAD || 3112 (N0.getOpcode() == ISD::ANY_EXTEND && 3113 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3114 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3115 LoadSDNode *LN0 = HasAnyExt 3116 ? cast<LoadSDNode>(N0.getOperand(0)) 3117 : cast<LoadSDNode>(N0); 3118 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3119 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3120 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 3121 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 3122 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3123 EVT LoadedVT = LN0->getMemoryVT(); 3124 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3125 3126 if (ExtVT == LoadedVT && 3127 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3128 ExtVT))) { 3129 3130 SDValue NewLoad = 3131 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3132 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3133 LN0->getMemOperand()); 3134 AddToWorklist(N); 3135 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3136 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3137 } 3138 3139 // Do not change the width of a volatile load. 3140 // Do not generate loads of non-round integer types since these can 3141 // be expensive (and would be wrong if the type is not byte sized). 3142 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 3143 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3144 ExtVT))) { 3145 EVT PtrType = LN0->getOperand(1).getValueType(); 3146 3147 unsigned Alignment = LN0->getAlignment(); 3148 SDValue NewPtr = LN0->getBasePtr(); 3149 3150 // For big endian targets, we need to add an offset to the pointer 3151 // to load the correct bytes. For little endian systems, we merely 3152 // need to read fewer bytes from the same pointer. 3153 if (DAG.getDataLayout().isBigEndian()) { 3154 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3155 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3156 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3157 SDLoc DL(LN0); 3158 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3159 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3160 Alignment = MinAlign(Alignment, PtrOff); 3161 } 3162 3163 AddToWorklist(NewPtr.getNode()); 3164 3165 SDValue Load = 3166 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3167 LN0->getChain(), NewPtr, 3168 LN0->getPointerInfo(), 3169 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3170 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3171 AddToWorklist(N); 3172 CombineTo(LN0, Load, Load.getValue(1)); 3173 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3174 } 3175 } 3176 } 3177 } 3178 3179 if (SDValue Combined = visitANDLike(N0, N1, N)) 3180 return Combined; 3181 3182 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3183 if (N0.getOpcode() == N1.getOpcode()) 3184 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3185 return Tmp; 3186 3187 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3188 // fold (and (sra)) -> (and (srl)) when possible. 3189 if (!VT.isVector() && 3190 SimplifyDemandedBits(SDValue(N, 0))) 3191 return SDValue(N, 0); 3192 3193 // fold (zext_inreg (extload x)) -> (zextload x) 3194 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3195 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3196 EVT MemVT = LN0->getMemoryVT(); 3197 // If we zero all the possible extended bits, then we can turn this into 3198 // a zextload if we are running before legalize or the operation is legal. 3199 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3200 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3201 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3202 ((!LegalOperations && !LN0->isVolatile()) || 3203 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3204 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3205 LN0->getChain(), LN0->getBasePtr(), 3206 MemVT, LN0->getMemOperand()); 3207 AddToWorklist(N); 3208 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3209 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3210 } 3211 } 3212 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3213 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3214 N0.hasOneUse()) { 3215 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3216 EVT MemVT = LN0->getMemoryVT(); 3217 // If we zero all the possible extended bits, then we can turn this into 3218 // a zextload if we are running before legalize or the operation is legal. 3219 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3220 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3221 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3222 ((!LegalOperations && !LN0->isVolatile()) || 3223 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3224 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3225 LN0->getChain(), LN0->getBasePtr(), 3226 MemVT, LN0->getMemOperand()); 3227 AddToWorklist(N); 3228 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3229 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3230 } 3231 } 3232 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3233 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3234 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3235 N0.getOperand(1), false); 3236 if (BSwap.getNode()) 3237 return BSwap; 3238 } 3239 3240 return SDValue(); 3241 } 3242 3243 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3244 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3245 bool DemandHighBits) { 3246 if (!LegalOperations) 3247 return SDValue(); 3248 3249 EVT VT = N->getValueType(0); 3250 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3251 return SDValue(); 3252 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3253 return SDValue(); 3254 3255 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3256 bool LookPassAnd0 = false; 3257 bool LookPassAnd1 = false; 3258 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3259 std::swap(N0, N1); 3260 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3261 std::swap(N0, N1); 3262 if (N0.getOpcode() == ISD::AND) { 3263 if (!N0.getNode()->hasOneUse()) 3264 return SDValue(); 3265 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3266 if (!N01C || N01C->getZExtValue() != 0xFF00) 3267 return SDValue(); 3268 N0 = N0.getOperand(0); 3269 LookPassAnd0 = true; 3270 } 3271 3272 if (N1.getOpcode() == ISD::AND) { 3273 if (!N1.getNode()->hasOneUse()) 3274 return SDValue(); 3275 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3276 if (!N11C || N11C->getZExtValue() != 0xFF) 3277 return SDValue(); 3278 N1 = N1.getOperand(0); 3279 LookPassAnd1 = true; 3280 } 3281 3282 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3283 std::swap(N0, N1); 3284 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3285 return SDValue(); 3286 if (!N0.getNode()->hasOneUse() || 3287 !N1.getNode()->hasOneUse()) 3288 return SDValue(); 3289 3290 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3291 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3292 if (!N01C || !N11C) 3293 return SDValue(); 3294 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3295 return SDValue(); 3296 3297 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3298 SDValue N00 = N0->getOperand(0); 3299 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3300 if (!N00.getNode()->hasOneUse()) 3301 return SDValue(); 3302 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3303 if (!N001C || N001C->getZExtValue() != 0xFF) 3304 return SDValue(); 3305 N00 = N00.getOperand(0); 3306 LookPassAnd0 = true; 3307 } 3308 3309 SDValue N10 = N1->getOperand(0); 3310 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3311 if (!N10.getNode()->hasOneUse()) 3312 return SDValue(); 3313 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3314 if (!N101C || N101C->getZExtValue() != 0xFF00) 3315 return SDValue(); 3316 N10 = N10.getOperand(0); 3317 LookPassAnd1 = true; 3318 } 3319 3320 if (N00 != N10) 3321 return SDValue(); 3322 3323 // Make sure everything beyond the low halfword gets set to zero since the SRL 3324 // 16 will clear the top bits. 3325 unsigned OpSizeInBits = VT.getSizeInBits(); 3326 if (DemandHighBits && OpSizeInBits > 16) { 3327 // If the left-shift isn't masked out then the only way this is a bswap is 3328 // if all bits beyond the low 8 are 0. In that case the entire pattern 3329 // reduces to a left shift anyway: leave it for other parts of the combiner. 3330 if (!LookPassAnd0) 3331 return SDValue(); 3332 3333 // However, if the right shift isn't masked out then it might be because 3334 // it's not needed. See if we can spot that too. 3335 if (!LookPassAnd1 && 3336 !DAG.MaskedValueIsZero( 3337 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3338 return SDValue(); 3339 } 3340 3341 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3342 if (OpSizeInBits > 16) { 3343 SDLoc DL(N); 3344 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3345 DAG.getConstant(OpSizeInBits - 16, DL, 3346 getShiftAmountTy(VT))); 3347 } 3348 return Res; 3349 } 3350 3351 /// Return true if the specified node is an element that makes up a 32-bit 3352 /// packed halfword byteswap. 3353 /// ((x & 0x000000ff) << 8) | 3354 /// ((x & 0x0000ff00) >> 8) | 3355 /// ((x & 0x00ff0000) << 8) | 3356 /// ((x & 0xff000000) >> 8) 3357 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3358 if (!N.getNode()->hasOneUse()) 3359 return false; 3360 3361 unsigned Opc = N.getOpcode(); 3362 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3363 return false; 3364 3365 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3366 if (!N1C) 3367 return false; 3368 3369 unsigned Num; 3370 switch (N1C->getZExtValue()) { 3371 default: 3372 return false; 3373 case 0xFF: Num = 0; break; 3374 case 0xFF00: Num = 1; break; 3375 case 0xFF0000: Num = 2; break; 3376 case 0xFF000000: Num = 3; break; 3377 } 3378 3379 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3380 SDValue N0 = N.getOperand(0); 3381 if (Opc == ISD::AND) { 3382 if (Num == 0 || Num == 2) { 3383 // (x >> 8) & 0xff 3384 // (x >> 8) & 0xff0000 3385 if (N0.getOpcode() != ISD::SRL) 3386 return false; 3387 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3388 if (!C || C->getZExtValue() != 8) 3389 return false; 3390 } else { 3391 // (x << 8) & 0xff00 3392 // (x << 8) & 0xff000000 3393 if (N0.getOpcode() != ISD::SHL) 3394 return false; 3395 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3396 if (!C || C->getZExtValue() != 8) 3397 return false; 3398 } 3399 } else if (Opc == ISD::SHL) { 3400 // (x & 0xff) << 8 3401 // (x & 0xff0000) << 8 3402 if (Num != 0 && Num != 2) 3403 return false; 3404 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3405 if (!C || C->getZExtValue() != 8) 3406 return false; 3407 } else { // Opc == ISD::SRL 3408 // (x & 0xff00) >> 8 3409 // (x & 0xff000000) >> 8 3410 if (Num != 1 && Num != 3) 3411 return false; 3412 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3413 if (!C || C->getZExtValue() != 8) 3414 return false; 3415 } 3416 3417 if (Parts[Num]) 3418 return false; 3419 3420 Parts[Num] = N0.getOperand(0).getNode(); 3421 return true; 3422 } 3423 3424 /// Match a 32-bit packed halfword bswap. That is 3425 /// ((x & 0x000000ff) << 8) | 3426 /// ((x & 0x0000ff00) >> 8) | 3427 /// ((x & 0x00ff0000) << 8) | 3428 /// ((x & 0xff000000) >> 8) 3429 /// => (rotl (bswap x), 16) 3430 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3431 if (!LegalOperations) 3432 return SDValue(); 3433 3434 EVT VT = N->getValueType(0); 3435 if (VT != MVT::i32) 3436 return SDValue(); 3437 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3438 return SDValue(); 3439 3440 // Look for either 3441 // (or (or (and), (and)), (or (and), (and))) 3442 // (or (or (or (and), (and)), (and)), (and)) 3443 if (N0.getOpcode() != ISD::OR) 3444 return SDValue(); 3445 SDValue N00 = N0.getOperand(0); 3446 SDValue N01 = N0.getOperand(1); 3447 SDNode *Parts[4] = {}; 3448 3449 if (N1.getOpcode() == ISD::OR && 3450 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3451 // (or (or (and), (and)), (or (and), (and))) 3452 SDValue N000 = N00.getOperand(0); 3453 if (!isBSwapHWordElement(N000, Parts)) 3454 return SDValue(); 3455 3456 SDValue N001 = N00.getOperand(1); 3457 if (!isBSwapHWordElement(N001, Parts)) 3458 return SDValue(); 3459 SDValue N010 = N01.getOperand(0); 3460 if (!isBSwapHWordElement(N010, Parts)) 3461 return SDValue(); 3462 SDValue N011 = N01.getOperand(1); 3463 if (!isBSwapHWordElement(N011, Parts)) 3464 return SDValue(); 3465 } else { 3466 // (or (or (or (and), (and)), (and)), (and)) 3467 if (!isBSwapHWordElement(N1, Parts)) 3468 return SDValue(); 3469 if (!isBSwapHWordElement(N01, Parts)) 3470 return SDValue(); 3471 if (N00.getOpcode() != ISD::OR) 3472 return SDValue(); 3473 SDValue N000 = N00.getOperand(0); 3474 if (!isBSwapHWordElement(N000, Parts)) 3475 return SDValue(); 3476 SDValue N001 = N00.getOperand(1); 3477 if (!isBSwapHWordElement(N001, Parts)) 3478 return SDValue(); 3479 } 3480 3481 // Make sure the parts are all coming from the same node. 3482 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3483 return SDValue(); 3484 3485 SDLoc DL(N); 3486 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3487 SDValue(Parts[0], 0)); 3488 3489 // Result of the bswap should be rotated by 16. If it's not legal, then 3490 // do (x << 16) | (x >> 16). 3491 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3492 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3493 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3494 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3495 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3496 return DAG.getNode(ISD::OR, DL, VT, 3497 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3498 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3499 } 3500 3501 /// This contains all DAGCombine rules which reduce two values combined by 3502 /// an Or operation to a single value \see visitANDLike(). 3503 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3504 EVT VT = N1.getValueType(); 3505 // fold (or x, undef) -> -1 3506 if (!LegalOperations && 3507 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3508 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3509 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3510 SDLoc(LocReference), VT); 3511 } 3512 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3513 SDValue LL, LR, RL, RR, CC0, CC1; 3514 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3515 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3516 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3517 3518 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3519 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3520 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3521 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3522 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3523 LR.getValueType(), LL, RL); 3524 AddToWorklist(ORNode.getNode()); 3525 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3526 } 3527 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3528 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3529 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3530 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3531 LR.getValueType(), LL, RL); 3532 AddToWorklist(ANDNode.getNode()); 3533 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3534 } 3535 } 3536 // canonicalize equivalent to ll == rl 3537 if (LL == RR && LR == RL) { 3538 Op1 = ISD::getSetCCSwappedOperands(Op1); 3539 std::swap(RL, RR); 3540 } 3541 if (LL == RL && LR == RR) { 3542 bool isInteger = LL.getValueType().isInteger(); 3543 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3544 if (Result != ISD::SETCC_INVALID && 3545 (!LegalOperations || 3546 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3547 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3548 EVT CCVT = getSetCCResultType(LL.getValueType()); 3549 if (N0.getValueType() == CCVT || 3550 (!LegalOperations && N0.getValueType() == MVT::i1)) 3551 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3552 LL, LR, Result); 3553 } 3554 } 3555 } 3556 3557 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3558 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3559 // Don't increase # computations. 3560 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3561 // We can only do this xform if we know that bits from X that are set in C2 3562 // but not in C1 are already zero. Likewise for Y. 3563 if (const ConstantSDNode *N0O1C = 3564 getAsNonOpaqueConstant(N0.getOperand(1))) { 3565 if (const ConstantSDNode *N1O1C = 3566 getAsNonOpaqueConstant(N1.getOperand(1))) { 3567 // We can only do this xform if we know that bits from X that are set in 3568 // C2 but not in C1 are already zero. Likewise for Y. 3569 const APInt &LHSMask = N0O1C->getAPIntValue(); 3570 const APInt &RHSMask = N1O1C->getAPIntValue(); 3571 3572 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3573 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3574 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3575 N0.getOperand(0), N1.getOperand(0)); 3576 SDLoc DL(LocReference); 3577 return DAG.getNode(ISD::AND, DL, VT, X, 3578 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3579 } 3580 } 3581 } 3582 } 3583 3584 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3585 if (N0.getOpcode() == ISD::AND && 3586 N1.getOpcode() == ISD::AND && 3587 N0.getOperand(0) == N1.getOperand(0) && 3588 // Don't increase # computations. 3589 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3590 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3591 N0.getOperand(1), N1.getOperand(1)); 3592 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3593 } 3594 3595 return SDValue(); 3596 } 3597 3598 SDValue DAGCombiner::visitOR(SDNode *N) { 3599 SDValue N0 = N->getOperand(0); 3600 SDValue N1 = N->getOperand(1); 3601 EVT VT = N1.getValueType(); 3602 3603 // fold vector ops 3604 if (VT.isVector()) { 3605 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3606 return FoldedVOp; 3607 3608 // fold (or x, 0) -> x, vector edition 3609 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3610 return N1; 3611 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3612 return N0; 3613 3614 // fold (or x, -1) -> -1, vector edition 3615 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3616 // do not return N0, because undef node may exist in N0 3617 return DAG.getConstant( 3618 APInt::getAllOnesValue( 3619 N0.getValueType().getScalarType().getSizeInBits()), 3620 SDLoc(N), N0.getValueType()); 3621 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3622 // do not return N1, because undef node may exist in N1 3623 return DAG.getConstant( 3624 APInt::getAllOnesValue( 3625 N1.getValueType().getScalarType().getSizeInBits()), 3626 SDLoc(N), N1.getValueType()); 3627 3628 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3629 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3630 // Do this only if the resulting shuffle is legal. 3631 if (isa<ShuffleVectorSDNode>(N0) && 3632 isa<ShuffleVectorSDNode>(N1) && 3633 // Avoid folding a node with illegal type. 3634 TLI.isTypeLegal(VT) && 3635 N0->getOperand(1) == N1->getOperand(1) && 3636 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3637 bool CanFold = true; 3638 unsigned NumElts = VT.getVectorNumElements(); 3639 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3640 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3641 // We construct two shuffle masks: 3642 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3643 // and N1 as the second operand. 3644 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3645 // and N0 as the second operand. 3646 // We do this because OR is commutable and therefore there might be 3647 // two ways to fold this node into a shuffle. 3648 SmallVector<int,4> Mask1; 3649 SmallVector<int,4> Mask2; 3650 3651 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3652 int M0 = SV0->getMaskElt(i); 3653 int M1 = SV1->getMaskElt(i); 3654 3655 // Both shuffle indexes are undef. Propagate Undef. 3656 if (M0 < 0 && M1 < 0) { 3657 Mask1.push_back(M0); 3658 Mask2.push_back(M0); 3659 continue; 3660 } 3661 3662 if (M0 < 0 || M1 < 0 || 3663 (M0 < (int)NumElts && M1 < (int)NumElts) || 3664 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3665 CanFold = false; 3666 break; 3667 } 3668 3669 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3670 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3671 } 3672 3673 if (CanFold) { 3674 // Fold this sequence only if the resulting shuffle is 'legal'. 3675 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3676 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3677 N1->getOperand(0), &Mask1[0]); 3678 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3679 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3680 N0->getOperand(0), &Mask2[0]); 3681 } 3682 } 3683 } 3684 3685 // fold (or c1, c2) -> c1|c2 3686 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3687 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3688 if (N0C && N1C && !N1C->isOpaque()) 3689 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3690 // canonicalize constant to RHS 3691 if (isConstantIntBuildVectorOrConstantInt(N0) && 3692 !isConstantIntBuildVectorOrConstantInt(N1)) 3693 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3694 // fold (or x, 0) -> x 3695 if (isNullConstant(N1)) 3696 return N0; 3697 // fold (or x, -1) -> -1 3698 if (isAllOnesConstant(N1)) 3699 return N1; 3700 // fold (or x, c) -> c iff (x & ~c) == 0 3701 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3702 return N1; 3703 3704 if (SDValue Combined = visitORLike(N0, N1, N)) 3705 return Combined; 3706 3707 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3708 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3709 return BSwap; 3710 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3711 return BSwap; 3712 3713 // reassociate or 3714 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3715 return ROR; 3716 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3717 // iff (c1 & c2) == 0. 3718 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3719 isa<ConstantSDNode>(N0.getOperand(1))) { 3720 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3721 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3722 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3723 N1C, C1)) 3724 return DAG.getNode( 3725 ISD::AND, SDLoc(N), VT, 3726 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3727 return SDValue(); 3728 } 3729 } 3730 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3731 if (N0.getOpcode() == N1.getOpcode()) 3732 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3733 return Tmp; 3734 3735 // See if this is some rotate idiom. 3736 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3737 return SDValue(Rot, 0); 3738 3739 // Simplify the operands using demanded-bits information. 3740 if (!VT.isVector() && 3741 SimplifyDemandedBits(SDValue(N, 0))) 3742 return SDValue(N, 0); 3743 3744 return SDValue(); 3745 } 3746 3747 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3748 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3749 if (Op.getOpcode() == ISD::AND) { 3750 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3751 Mask = Op.getOperand(1); 3752 Op = Op.getOperand(0); 3753 } else { 3754 return false; 3755 } 3756 } 3757 3758 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3759 Shift = Op; 3760 return true; 3761 } 3762 3763 return false; 3764 } 3765 3766 // Return true if we can prove that, whenever Neg and Pos are both in the 3767 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3768 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3769 // 3770 // (or (shift1 X, Neg), (shift2 X, Pos)) 3771 // 3772 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3773 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3774 // to consider shift amounts with defined behavior. 3775 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3776 // If OpSize is a power of 2 then: 3777 // 3778 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3779 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3780 // 3781 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3782 // for the stronger condition: 3783 // 3784 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3785 // 3786 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3787 // we can just replace Neg with Neg' for the rest of the function. 3788 // 3789 // In other cases we check for the even stronger condition: 3790 // 3791 // Neg == OpSize - Pos [B] 3792 // 3793 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3794 // behavior if Pos == 0 (and consequently Neg == OpSize). 3795 // 3796 // We could actually use [A] whenever OpSize is a power of 2, but the 3797 // only extra cases that it would match are those uninteresting ones 3798 // where Neg and Pos are never in range at the same time. E.g. for 3799 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3800 // as well as (sub 32, Pos), but: 3801 // 3802 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3803 // 3804 // always invokes undefined behavior for 32-bit X. 3805 // 3806 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3807 unsigned MaskLoBits = 0; 3808 if (Neg.getOpcode() == ISD::AND && 3809 isPowerOf2_64(OpSize) && 3810 Neg.getOperand(1).getOpcode() == ISD::Constant && 3811 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3812 Neg = Neg.getOperand(0); 3813 MaskLoBits = Log2_64(OpSize); 3814 } 3815 3816 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3817 if (Neg.getOpcode() != ISD::SUB) 3818 return 0; 3819 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3820 if (!NegC) 3821 return 0; 3822 SDValue NegOp1 = Neg.getOperand(1); 3823 3824 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3825 // Pos'. The truncation is redundant for the purpose of the equality. 3826 if (MaskLoBits && 3827 Pos.getOpcode() == ISD::AND && 3828 Pos.getOperand(1).getOpcode() == ISD::Constant && 3829 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3830 Pos = Pos.getOperand(0); 3831 3832 // The condition we need is now: 3833 // 3834 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3835 // 3836 // If NegOp1 == Pos then we need: 3837 // 3838 // OpSize & Mask == NegC & Mask 3839 // 3840 // (because "x & Mask" is a truncation and distributes through subtraction). 3841 APInt Width; 3842 if (Pos == NegOp1) 3843 Width = NegC->getAPIntValue(); 3844 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3845 // Then the condition we want to prove becomes: 3846 // 3847 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3848 // 3849 // which, again because "x & Mask" is a truncation, becomes: 3850 // 3851 // NegC & Mask == (OpSize - PosC) & Mask 3852 // OpSize & Mask == (NegC + PosC) & Mask 3853 else if (Pos.getOpcode() == ISD::ADD && 3854 Pos.getOperand(0) == NegOp1 && 3855 Pos.getOperand(1).getOpcode() == ISD::Constant) 3856 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3857 NegC->getAPIntValue()); 3858 else 3859 return false; 3860 3861 // Now we just need to check that OpSize & Mask == Width & Mask. 3862 if (MaskLoBits) 3863 // Opsize & Mask is 0 since Mask is Opsize - 1. 3864 return Width.getLoBits(MaskLoBits) == 0; 3865 return Width == OpSize; 3866 } 3867 3868 // A subroutine of MatchRotate used once we have found an OR of two opposite 3869 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3870 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3871 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3872 // Neg with outer conversions stripped away. 3873 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3874 SDValue Neg, SDValue InnerPos, 3875 SDValue InnerNeg, unsigned PosOpcode, 3876 unsigned NegOpcode, SDLoc DL) { 3877 // fold (or (shl x, (*ext y)), 3878 // (srl x, (*ext (sub 32, y)))) -> 3879 // (rotl x, y) or (rotr x, (sub 32, y)) 3880 // 3881 // fold (or (shl x, (*ext (sub 32, y))), 3882 // (srl x, (*ext y))) -> 3883 // (rotr x, y) or (rotl x, (sub 32, y)) 3884 EVT VT = Shifted.getValueType(); 3885 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3886 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3887 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3888 HasPos ? Pos : Neg).getNode(); 3889 } 3890 3891 return nullptr; 3892 } 3893 3894 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3895 // idioms for rotate, and if the target supports rotation instructions, generate 3896 // a rot[lr]. 3897 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3898 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3899 EVT VT = LHS.getValueType(); 3900 if (!TLI.isTypeLegal(VT)) return nullptr; 3901 3902 // The target must have at least one rotate flavor. 3903 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3904 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3905 if (!HasROTL && !HasROTR) return nullptr; 3906 3907 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3908 SDValue LHSShift; // The shift. 3909 SDValue LHSMask; // AND value if any. 3910 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3911 return nullptr; // Not part of a rotate. 3912 3913 SDValue RHSShift; // The shift. 3914 SDValue RHSMask; // AND value if any. 3915 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3916 return nullptr; // Not part of a rotate. 3917 3918 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3919 return nullptr; // Not shifting the same value. 3920 3921 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3922 return nullptr; // Shifts must disagree. 3923 3924 // Canonicalize shl to left side in a shl/srl pair. 3925 if (RHSShift.getOpcode() == ISD::SHL) { 3926 std::swap(LHS, RHS); 3927 std::swap(LHSShift, RHSShift); 3928 std::swap(LHSMask , RHSMask ); 3929 } 3930 3931 unsigned OpSizeInBits = VT.getSizeInBits(); 3932 SDValue LHSShiftArg = LHSShift.getOperand(0); 3933 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3934 SDValue RHSShiftArg = RHSShift.getOperand(0); 3935 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3936 3937 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3938 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3939 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3940 RHSShiftAmt.getOpcode() == ISD::Constant) { 3941 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3942 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3943 if ((LShVal + RShVal) != OpSizeInBits) 3944 return nullptr; 3945 3946 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3947 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3948 3949 // If there is an AND of either shifted operand, apply it to the result. 3950 if (LHSMask.getNode() || RHSMask.getNode()) { 3951 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3952 3953 if (LHSMask.getNode()) { 3954 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3955 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3956 } 3957 if (RHSMask.getNode()) { 3958 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3959 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3960 } 3961 3962 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT)); 3963 } 3964 3965 return Rot.getNode(); 3966 } 3967 3968 // If there is a mask here, and we have a variable shift, we can't be sure 3969 // that we're masking out the right stuff. 3970 if (LHSMask.getNode() || RHSMask.getNode()) 3971 return nullptr; 3972 3973 // If the shift amount is sign/zext/any-extended just peel it off. 3974 SDValue LExtOp0 = LHSShiftAmt; 3975 SDValue RExtOp0 = RHSShiftAmt; 3976 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3977 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3978 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3979 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3980 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3981 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3982 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3983 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3984 LExtOp0 = LHSShiftAmt.getOperand(0); 3985 RExtOp0 = RHSShiftAmt.getOperand(0); 3986 } 3987 3988 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3989 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3990 if (TryL) 3991 return TryL; 3992 3993 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3994 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3995 if (TryR) 3996 return TryR; 3997 3998 return nullptr; 3999 } 4000 4001 SDValue DAGCombiner::visitXOR(SDNode *N) { 4002 SDValue N0 = N->getOperand(0); 4003 SDValue N1 = N->getOperand(1); 4004 EVT VT = N0.getValueType(); 4005 4006 // fold vector ops 4007 if (VT.isVector()) { 4008 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4009 return FoldedVOp; 4010 4011 // fold (xor x, 0) -> x, vector edition 4012 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4013 return N1; 4014 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4015 return N0; 4016 } 4017 4018 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4019 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 4020 return DAG.getConstant(0, SDLoc(N), VT); 4021 // fold (xor x, undef) -> undef 4022 if (N0.getOpcode() == ISD::UNDEF) 4023 return N0; 4024 if (N1.getOpcode() == ISD::UNDEF) 4025 return N1; 4026 // fold (xor c1, c2) -> c1^c2 4027 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4028 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4029 if (N0C && N1C) 4030 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4031 // canonicalize constant to RHS 4032 if (isConstantIntBuildVectorOrConstantInt(N0) && 4033 !isConstantIntBuildVectorOrConstantInt(N1)) 4034 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4035 // fold (xor x, 0) -> x 4036 if (isNullConstant(N1)) 4037 return N0; 4038 // reassociate xor 4039 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4040 return RXOR; 4041 4042 // fold !(x cc y) -> (x !cc y) 4043 SDValue LHS, RHS, CC; 4044 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4045 bool isInt = LHS.getValueType().isInteger(); 4046 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4047 isInt); 4048 4049 if (!LegalOperations || 4050 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4051 switch (N0.getOpcode()) { 4052 default: 4053 llvm_unreachable("Unhandled SetCC Equivalent!"); 4054 case ISD::SETCC: 4055 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4056 case ISD::SELECT_CC: 4057 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4058 N0.getOperand(3), NotCC); 4059 } 4060 } 4061 } 4062 4063 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4064 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4065 N0.getNode()->hasOneUse() && 4066 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4067 SDValue V = N0.getOperand(0); 4068 SDLoc DL(N0); 4069 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4070 DAG.getConstant(1, DL, V.getValueType())); 4071 AddToWorklist(V.getNode()); 4072 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4073 } 4074 4075 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4076 if (isOneConstant(N1) && VT == MVT::i1 && 4077 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4078 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4079 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4080 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4081 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4082 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4083 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4084 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4085 } 4086 } 4087 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4088 if (isAllOnesConstant(N1) && 4089 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4090 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4091 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4092 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4093 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4094 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4095 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4096 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4097 } 4098 } 4099 // fold (xor (and x, y), y) -> (and (not x), y) 4100 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4101 N0->getOperand(1) == N1) { 4102 SDValue X = N0->getOperand(0); 4103 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4104 AddToWorklist(NotX.getNode()); 4105 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4106 } 4107 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4108 if (N1C && N0.getOpcode() == ISD::XOR) { 4109 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4110 SDLoc DL(N); 4111 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4112 DAG.getConstant(N1C->getAPIntValue() ^ 4113 N00C->getAPIntValue(), DL, VT)); 4114 } 4115 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4116 SDLoc DL(N); 4117 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4118 DAG.getConstant(N1C->getAPIntValue() ^ 4119 N01C->getAPIntValue(), DL, VT)); 4120 } 4121 } 4122 // fold (xor x, x) -> 0 4123 if (N0 == N1) 4124 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4125 4126 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4127 // Here is a concrete example of this equivalence: 4128 // i16 x == 14 4129 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4130 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4131 // 4132 // => 4133 // 4134 // i16 ~1 == 0b1111111111111110 4135 // i16 rol(~1, 14) == 0b1011111111111111 4136 // 4137 // Some additional tips to help conceptualize this transform: 4138 // - Try to see the operation as placing a single zero in a value of all ones. 4139 // - There exists no value for x which would allow the result to contain zero. 4140 // - Values of x larger than the bitwidth are undefined and do not require a 4141 // consistent result. 4142 // - Pushing the zero left requires shifting one bits in from the right. 4143 // A rotate left of ~1 is a nice way of achieving the desired result. 4144 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4145 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4146 SDLoc DL(N); 4147 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4148 N0.getOperand(1)); 4149 } 4150 4151 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4152 if (N0.getOpcode() == N1.getOpcode()) 4153 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4154 return Tmp; 4155 4156 // Simplify the expression using non-local knowledge. 4157 if (!VT.isVector() && 4158 SimplifyDemandedBits(SDValue(N, 0))) 4159 return SDValue(N, 0); 4160 4161 return SDValue(); 4162 } 4163 4164 /// Handle transforms common to the three shifts, when the shift amount is a 4165 /// constant. 4166 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4167 SDNode *LHS = N->getOperand(0).getNode(); 4168 if (!LHS->hasOneUse()) return SDValue(); 4169 4170 // We want to pull some binops through shifts, so that we have (and (shift)) 4171 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4172 // thing happens with address calculations, so it's important to canonicalize 4173 // it. 4174 bool HighBitSet = false; // Can we transform this if the high bit is set? 4175 4176 switch (LHS->getOpcode()) { 4177 default: return SDValue(); 4178 case ISD::OR: 4179 case ISD::XOR: 4180 HighBitSet = false; // We can only transform sra if the high bit is clear. 4181 break; 4182 case ISD::AND: 4183 HighBitSet = true; // We can only transform sra if the high bit is set. 4184 break; 4185 case ISD::ADD: 4186 if (N->getOpcode() != ISD::SHL) 4187 return SDValue(); // only shl(add) not sr[al](add). 4188 HighBitSet = false; // We can only transform sra if the high bit is clear. 4189 break; 4190 } 4191 4192 // We require the RHS of the binop to be a constant and not opaque as well. 4193 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4194 if (!BinOpCst) return SDValue(); 4195 4196 // FIXME: disable this unless the input to the binop is a shift by a constant. 4197 // If it is not a shift, it pessimizes some common cases like: 4198 // 4199 // void foo(int *X, int i) { X[i & 1235] = 1; } 4200 // int bar(int *X, int i) { return X[i & 255]; } 4201 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4202 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4203 BinOpLHSVal->getOpcode() != ISD::SRA && 4204 BinOpLHSVal->getOpcode() != ISD::SRL) || 4205 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4206 return SDValue(); 4207 4208 EVT VT = N->getValueType(0); 4209 4210 // If this is a signed shift right, and the high bit is modified by the 4211 // logical operation, do not perform the transformation. The highBitSet 4212 // boolean indicates the value of the high bit of the constant which would 4213 // cause it to be modified for this operation. 4214 if (N->getOpcode() == ISD::SRA) { 4215 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4216 if (BinOpRHSSignSet != HighBitSet) 4217 return SDValue(); 4218 } 4219 4220 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4221 return SDValue(); 4222 4223 // Fold the constants, shifting the binop RHS by the shift amount. 4224 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4225 N->getValueType(0), 4226 LHS->getOperand(1), N->getOperand(1)); 4227 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4228 4229 // Create the new shift. 4230 SDValue NewShift = DAG.getNode(N->getOpcode(), 4231 SDLoc(LHS->getOperand(0)), 4232 VT, LHS->getOperand(0), N->getOperand(1)); 4233 4234 // Create the new binop. 4235 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4236 } 4237 4238 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4239 assert(N->getOpcode() == ISD::TRUNCATE); 4240 assert(N->getOperand(0).getOpcode() == ISD::AND); 4241 4242 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4243 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4244 SDValue N01 = N->getOperand(0).getOperand(1); 4245 4246 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4247 if (!N01C->isOpaque()) { 4248 EVT TruncVT = N->getValueType(0); 4249 SDValue N00 = N->getOperand(0).getOperand(0); 4250 APInt TruncC = N01C->getAPIntValue(); 4251 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4252 SDLoc DL(N); 4253 4254 return DAG.getNode(ISD::AND, DL, TruncVT, 4255 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4256 DAG.getConstant(TruncC, DL, TruncVT)); 4257 } 4258 } 4259 } 4260 4261 return SDValue(); 4262 } 4263 4264 SDValue DAGCombiner::visitRotate(SDNode *N) { 4265 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4266 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4267 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4268 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4269 if (NewOp1.getNode()) 4270 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4271 N->getOperand(0), NewOp1); 4272 } 4273 return SDValue(); 4274 } 4275 4276 SDValue DAGCombiner::visitSHL(SDNode *N) { 4277 SDValue N0 = N->getOperand(0); 4278 SDValue N1 = N->getOperand(1); 4279 EVT VT = N0.getValueType(); 4280 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4281 4282 // fold vector ops 4283 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4284 if (VT.isVector()) { 4285 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4286 return FoldedVOp; 4287 4288 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4289 // If setcc produces all-one true value then: 4290 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4291 if (N1CV && N1CV->isConstant()) { 4292 if (N0.getOpcode() == ISD::AND) { 4293 SDValue N00 = N0->getOperand(0); 4294 SDValue N01 = N0->getOperand(1); 4295 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4296 4297 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4298 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4299 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4300 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4301 N01CV, N1CV)) 4302 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4303 } 4304 } else { 4305 N1C = isConstOrConstSplat(N1); 4306 } 4307 } 4308 } 4309 4310 // fold (shl c1, c2) -> c1<<c2 4311 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4312 if (N0C && N1C && !N1C->isOpaque()) 4313 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4314 // fold (shl 0, x) -> 0 4315 if (isNullConstant(N0)) 4316 return N0; 4317 // fold (shl x, c >= size(x)) -> undef 4318 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4319 return DAG.getUNDEF(VT); 4320 // fold (shl x, 0) -> x 4321 if (N1C && N1C->isNullValue()) 4322 return N0; 4323 // fold (shl undef, x) -> 0 4324 if (N0.getOpcode() == ISD::UNDEF) 4325 return DAG.getConstant(0, SDLoc(N), VT); 4326 // if (shl x, c) is known to be zero, return 0 4327 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4328 APInt::getAllOnesValue(OpSizeInBits))) 4329 return DAG.getConstant(0, SDLoc(N), VT); 4330 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4331 if (N1.getOpcode() == ISD::TRUNCATE && 4332 N1.getOperand(0).getOpcode() == ISD::AND) { 4333 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4334 if (NewOp1.getNode()) 4335 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4336 } 4337 4338 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4339 return SDValue(N, 0); 4340 4341 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4342 if (N1C && N0.getOpcode() == ISD::SHL) { 4343 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4344 uint64_t c1 = N0C1->getZExtValue(); 4345 uint64_t c2 = N1C->getZExtValue(); 4346 SDLoc DL(N); 4347 if (c1 + c2 >= OpSizeInBits) 4348 return DAG.getConstant(0, DL, VT); 4349 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4350 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4351 } 4352 } 4353 4354 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4355 // For this to be valid, the second form must not preserve any of the bits 4356 // that are shifted out by the inner shift in the first form. This means 4357 // the outer shift size must be >= the number of bits added by the ext. 4358 // As a corollary, we don't care what kind of ext it is. 4359 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4360 N0.getOpcode() == ISD::ANY_EXTEND || 4361 N0.getOpcode() == ISD::SIGN_EXTEND) && 4362 N0.getOperand(0).getOpcode() == ISD::SHL) { 4363 SDValue N0Op0 = N0.getOperand(0); 4364 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4365 uint64_t c1 = N0Op0C1->getZExtValue(); 4366 uint64_t c2 = N1C->getZExtValue(); 4367 EVT InnerShiftVT = N0Op0.getValueType(); 4368 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4369 if (c2 >= OpSizeInBits - InnerShiftSize) { 4370 SDLoc DL(N0); 4371 if (c1 + c2 >= OpSizeInBits) 4372 return DAG.getConstant(0, DL, VT); 4373 return DAG.getNode(ISD::SHL, DL, VT, 4374 DAG.getNode(N0.getOpcode(), DL, VT, 4375 N0Op0->getOperand(0)), 4376 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4377 } 4378 } 4379 } 4380 4381 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4382 // Only fold this if the inner zext has no other uses to avoid increasing 4383 // the total number of instructions. 4384 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4385 N0.getOperand(0).getOpcode() == ISD::SRL) { 4386 SDValue N0Op0 = N0.getOperand(0); 4387 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4388 uint64_t c1 = N0Op0C1->getZExtValue(); 4389 if (c1 < VT.getScalarSizeInBits()) { 4390 uint64_t c2 = N1C->getZExtValue(); 4391 if (c1 == c2) { 4392 SDValue NewOp0 = N0.getOperand(0); 4393 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4394 SDLoc DL(N); 4395 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4396 NewOp0, 4397 DAG.getConstant(c2, DL, CountVT)); 4398 AddToWorklist(NewSHL.getNode()); 4399 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4400 } 4401 } 4402 } 4403 } 4404 4405 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4406 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4407 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4408 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4409 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4410 uint64_t C1 = N0C1->getZExtValue(); 4411 uint64_t C2 = N1C->getZExtValue(); 4412 SDLoc DL(N); 4413 if (C1 <= C2) 4414 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4415 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4416 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4417 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4418 } 4419 } 4420 4421 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4422 // (and (srl x, (sub c1, c2), MASK) 4423 // Only fold this if the inner shift has no other uses -- if it does, folding 4424 // this will increase the total number of instructions. 4425 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4426 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4427 uint64_t c1 = N0C1->getZExtValue(); 4428 if (c1 < OpSizeInBits) { 4429 uint64_t c2 = N1C->getZExtValue(); 4430 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4431 SDValue Shift; 4432 if (c2 > c1) { 4433 Mask = Mask.shl(c2 - c1); 4434 SDLoc DL(N); 4435 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4436 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4437 } else { 4438 Mask = Mask.lshr(c1 - c2); 4439 SDLoc DL(N); 4440 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4441 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4442 } 4443 SDLoc DL(N0); 4444 return DAG.getNode(ISD::AND, DL, VT, Shift, 4445 DAG.getConstant(Mask, DL, VT)); 4446 } 4447 } 4448 } 4449 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4450 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4451 unsigned BitSize = VT.getScalarSizeInBits(); 4452 SDLoc DL(N); 4453 SDValue HiBitsMask = 4454 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4455 BitSize - N1C->getZExtValue()), 4456 DL, VT); 4457 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4458 HiBitsMask); 4459 } 4460 4461 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4462 // Variant of version done on multiply, except mul by a power of 2 is turned 4463 // into a shift. 4464 APInt Val; 4465 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4466 (isa<ConstantSDNode>(N0.getOperand(1)) || 4467 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4468 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4469 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4470 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4471 } 4472 4473 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4474 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4475 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4476 if (SDValue Folded = 4477 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4478 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4479 } 4480 } 4481 4482 if (N1C && !N1C->isOpaque()) 4483 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4484 return NewSHL; 4485 4486 return SDValue(); 4487 } 4488 4489 SDValue DAGCombiner::visitSRA(SDNode *N) { 4490 SDValue N0 = N->getOperand(0); 4491 SDValue N1 = N->getOperand(1); 4492 EVT VT = N0.getValueType(); 4493 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4494 4495 // fold vector ops 4496 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4497 if (VT.isVector()) { 4498 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4499 return FoldedVOp; 4500 4501 N1C = isConstOrConstSplat(N1); 4502 } 4503 4504 // fold (sra c1, c2) -> (sra c1, c2) 4505 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4506 if (N0C && N1C && !N1C->isOpaque()) 4507 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4508 // fold (sra 0, x) -> 0 4509 if (isNullConstant(N0)) 4510 return N0; 4511 // fold (sra -1, x) -> -1 4512 if (isAllOnesConstant(N0)) 4513 return N0; 4514 // fold (sra x, (setge c, size(x))) -> undef 4515 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4516 return DAG.getUNDEF(VT); 4517 // fold (sra x, 0) -> x 4518 if (N1C && N1C->isNullValue()) 4519 return N0; 4520 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4521 // sext_inreg. 4522 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4523 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4524 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4525 if (VT.isVector()) 4526 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4527 ExtVT, VT.getVectorNumElements()); 4528 if ((!LegalOperations || 4529 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4530 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4531 N0.getOperand(0), DAG.getValueType(ExtVT)); 4532 } 4533 4534 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4535 if (N1C && N0.getOpcode() == ISD::SRA) { 4536 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4537 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4538 if (Sum >= OpSizeInBits) 4539 Sum = OpSizeInBits - 1; 4540 SDLoc DL(N); 4541 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4542 DAG.getConstant(Sum, DL, N1.getValueType())); 4543 } 4544 } 4545 4546 // fold (sra (shl X, m), (sub result_size, n)) 4547 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4548 // result_size - n != m. 4549 // If truncate is free for the target sext(shl) is likely to result in better 4550 // code. 4551 if (N0.getOpcode() == ISD::SHL && N1C) { 4552 // Get the two constanst of the shifts, CN0 = m, CN = n. 4553 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4554 if (N01C) { 4555 LLVMContext &Ctx = *DAG.getContext(); 4556 // Determine what the truncate's result bitsize and type would be. 4557 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4558 4559 if (VT.isVector()) 4560 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4561 4562 // Determine the residual right-shift amount. 4563 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4564 4565 // If the shift is not a no-op (in which case this should be just a sign 4566 // extend already), the truncated to type is legal, sign_extend is legal 4567 // on that type, and the truncate to that type is both legal and free, 4568 // perform the transform. 4569 if ((ShiftAmt > 0) && 4570 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4571 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4572 TLI.isTruncateFree(VT, TruncVT)) { 4573 4574 SDLoc DL(N); 4575 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4576 getShiftAmountTy(N0.getOperand(0).getValueType())); 4577 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4578 N0.getOperand(0), Amt); 4579 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4580 Shift); 4581 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4582 N->getValueType(0), Trunc); 4583 } 4584 } 4585 } 4586 4587 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4588 if (N1.getOpcode() == ISD::TRUNCATE && 4589 N1.getOperand(0).getOpcode() == ISD::AND) { 4590 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4591 if (NewOp1.getNode()) 4592 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4593 } 4594 4595 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4596 // if c1 is equal to the number of bits the trunc removes 4597 if (N0.getOpcode() == ISD::TRUNCATE && 4598 (N0.getOperand(0).getOpcode() == ISD::SRL || 4599 N0.getOperand(0).getOpcode() == ISD::SRA) && 4600 N0.getOperand(0).hasOneUse() && 4601 N0.getOperand(0).getOperand(1).hasOneUse() && 4602 N1C) { 4603 SDValue N0Op0 = N0.getOperand(0); 4604 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4605 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4606 EVT LargeVT = N0Op0.getValueType(); 4607 4608 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4609 SDLoc DL(N); 4610 SDValue Amt = 4611 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4612 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4613 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4614 N0Op0.getOperand(0), Amt); 4615 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4616 } 4617 } 4618 } 4619 4620 // Simplify, based on bits shifted out of the LHS. 4621 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4622 return SDValue(N, 0); 4623 4624 4625 // If the sign bit is known to be zero, switch this to a SRL. 4626 if (DAG.SignBitIsZero(N0)) 4627 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4628 4629 if (N1C && !N1C->isOpaque()) 4630 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4631 return NewSRA; 4632 4633 return SDValue(); 4634 } 4635 4636 SDValue DAGCombiner::visitSRL(SDNode *N) { 4637 SDValue N0 = N->getOperand(0); 4638 SDValue N1 = N->getOperand(1); 4639 EVT VT = N0.getValueType(); 4640 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4641 4642 // fold vector ops 4643 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4644 if (VT.isVector()) { 4645 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4646 return FoldedVOp; 4647 4648 N1C = isConstOrConstSplat(N1); 4649 } 4650 4651 // fold (srl c1, c2) -> c1 >>u c2 4652 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4653 if (N0C && N1C && !N1C->isOpaque()) 4654 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4655 // fold (srl 0, x) -> 0 4656 if (isNullConstant(N0)) 4657 return N0; 4658 // fold (srl x, c >= size(x)) -> undef 4659 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4660 return DAG.getUNDEF(VT); 4661 // fold (srl x, 0) -> x 4662 if (N1C && N1C->isNullValue()) 4663 return N0; 4664 // if (srl x, c) is known to be zero, return 0 4665 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4666 APInt::getAllOnesValue(OpSizeInBits))) 4667 return DAG.getConstant(0, SDLoc(N), VT); 4668 4669 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4670 if (N1C && N0.getOpcode() == ISD::SRL) { 4671 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4672 uint64_t c1 = N01C->getZExtValue(); 4673 uint64_t c2 = N1C->getZExtValue(); 4674 SDLoc DL(N); 4675 if (c1 + c2 >= OpSizeInBits) 4676 return DAG.getConstant(0, DL, VT); 4677 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4678 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4679 } 4680 } 4681 4682 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4683 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4684 N0.getOperand(0).getOpcode() == ISD::SRL && 4685 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4686 uint64_t c1 = 4687 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4688 uint64_t c2 = N1C->getZExtValue(); 4689 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4690 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4691 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4692 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4693 if (c1 + OpSizeInBits == InnerShiftSize) { 4694 SDLoc DL(N0); 4695 if (c1 + c2 >= InnerShiftSize) 4696 return DAG.getConstant(0, DL, VT); 4697 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4698 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4699 N0.getOperand(0)->getOperand(0), 4700 DAG.getConstant(c1 + c2, DL, 4701 ShiftCountVT))); 4702 } 4703 } 4704 4705 // fold (srl (shl x, c), c) -> (and x, cst2) 4706 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4707 unsigned BitSize = N0.getScalarValueSizeInBits(); 4708 if (BitSize <= 64) { 4709 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4710 SDLoc DL(N); 4711 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4712 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4713 } 4714 } 4715 4716 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4717 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4718 // Shifting in all undef bits? 4719 EVT SmallVT = N0.getOperand(0).getValueType(); 4720 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4721 if (N1C->getZExtValue() >= BitSize) 4722 return DAG.getUNDEF(VT); 4723 4724 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4725 uint64_t ShiftAmt = N1C->getZExtValue(); 4726 SDLoc DL0(N0); 4727 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4728 N0.getOperand(0), 4729 DAG.getConstant(ShiftAmt, DL0, 4730 getShiftAmountTy(SmallVT))); 4731 AddToWorklist(SmallShift.getNode()); 4732 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4733 SDLoc DL(N); 4734 return DAG.getNode(ISD::AND, DL, VT, 4735 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4736 DAG.getConstant(Mask, DL, VT)); 4737 } 4738 } 4739 4740 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4741 // bit, which is unmodified by sra. 4742 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4743 if (N0.getOpcode() == ISD::SRA) 4744 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4745 } 4746 4747 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4748 if (N1C && N0.getOpcode() == ISD::CTLZ && 4749 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4750 APInt KnownZero, KnownOne; 4751 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4752 4753 // If any of the input bits are KnownOne, then the input couldn't be all 4754 // zeros, thus the result of the srl will always be zero. 4755 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4756 4757 // If all of the bits input the to ctlz node are known to be zero, then 4758 // the result of the ctlz is "32" and the result of the shift is one. 4759 APInt UnknownBits = ~KnownZero; 4760 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4761 4762 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4763 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4764 // Okay, we know that only that the single bit specified by UnknownBits 4765 // could be set on input to the CTLZ node. If this bit is set, the SRL 4766 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4767 // to an SRL/XOR pair, which is likely to simplify more. 4768 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4769 SDValue Op = N0.getOperand(0); 4770 4771 if (ShAmt) { 4772 SDLoc DL(N0); 4773 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4774 DAG.getConstant(ShAmt, DL, 4775 getShiftAmountTy(Op.getValueType()))); 4776 AddToWorklist(Op.getNode()); 4777 } 4778 4779 SDLoc DL(N); 4780 return DAG.getNode(ISD::XOR, DL, VT, 4781 Op, DAG.getConstant(1, DL, VT)); 4782 } 4783 } 4784 4785 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4786 if (N1.getOpcode() == ISD::TRUNCATE && 4787 N1.getOperand(0).getOpcode() == ISD::AND) { 4788 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4789 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4790 } 4791 4792 // fold operands of srl based on knowledge that the low bits are not 4793 // demanded. 4794 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4795 return SDValue(N, 0); 4796 4797 if (N1C && !N1C->isOpaque()) 4798 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4799 return NewSRL; 4800 4801 // Attempt to convert a srl of a load into a narrower zero-extending load. 4802 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4803 return NarrowLoad; 4804 4805 // Here is a common situation. We want to optimize: 4806 // 4807 // %a = ... 4808 // %b = and i32 %a, 2 4809 // %c = srl i32 %b, 1 4810 // brcond i32 %c ... 4811 // 4812 // into 4813 // 4814 // %a = ... 4815 // %b = and %a, 2 4816 // %c = setcc eq %b, 0 4817 // brcond %c ... 4818 // 4819 // However when after the source operand of SRL is optimized into AND, the SRL 4820 // itself may not be optimized further. Look for it and add the BRCOND into 4821 // the worklist. 4822 if (N->hasOneUse()) { 4823 SDNode *Use = *N->use_begin(); 4824 if (Use->getOpcode() == ISD::BRCOND) 4825 AddToWorklist(Use); 4826 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4827 // Also look pass the truncate. 4828 Use = *Use->use_begin(); 4829 if (Use->getOpcode() == ISD::BRCOND) 4830 AddToWorklist(Use); 4831 } 4832 } 4833 4834 return SDValue(); 4835 } 4836 4837 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4838 SDValue N0 = N->getOperand(0); 4839 EVT VT = N->getValueType(0); 4840 4841 // fold (bswap c1) -> c2 4842 if (isConstantIntBuildVectorOrConstantInt(N0)) 4843 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4844 // fold (bswap (bswap x)) -> x 4845 if (N0.getOpcode() == ISD::BSWAP) 4846 return N0->getOperand(0); 4847 return SDValue(); 4848 } 4849 4850 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4851 SDValue N0 = N->getOperand(0); 4852 EVT VT = N->getValueType(0); 4853 4854 // fold (ctlz c1) -> c2 4855 if (isConstantIntBuildVectorOrConstantInt(N0)) 4856 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4857 return SDValue(); 4858 } 4859 4860 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4861 SDValue N0 = N->getOperand(0); 4862 EVT VT = N->getValueType(0); 4863 4864 // fold (ctlz_zero_undef c1) -> c2 4865 if (isConstantIntBuildVectorOrConstantInt(N0)) 4866 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4867 return SDValue(); 4868 } 4869 4870 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4871 SDValue N0 = N->getOperand(0); 4872 EVT VT = N->getValueType(0); 4873 4874 // fold (cttz c1) -> c2 4875 if (isConstantIntBuildVectorOrConstantInt(N0)) 4876 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4877 return SDValue(); 4878 } 4879 4880 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4881 SDValue N0 = N->getOperand(0); 4882 EVT VT = N->getValueType(0); 4883 4884 // fold (cttz_zero_undef c1) -> c2 4885 if (isConstantIntBuildVectorOrConstantInt(N0)) 4886 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4887 return SDValue(); 4888 } 4889 4890 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4891 SDValue N0 = N->getOperand(0); 4892 EVT VT = N->getValueType(0); 4893 4894 // fold (ctpop c1) -> c2 4895 if (isConstantIntBuildVectorOrConstantInt(N0)) 4896 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4897 return SDValue(); 4898 } 4899 4900 4901 /// \brief Generate Min/Max node 4902 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4903 SDValue True, SDValue False, 4904 ISD::CondCode CC, const TargetLowering &TLI, 4905 SelectionDAG &DAG) { 4906 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4907 return SDValue(); 4908 4909 switch (CC) { 4910 case ISD::SETOLT: 4911 case ISD::SETOLE: 4912 case ISD::SETLT: 4913 case ISD::SETLE: 4914 case ISD::SETULT: 4915 case ISD::SETULE: { 4916 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4917 if (TLI.isOperationLegal(Opcode, VT)) 4918 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4919 return SDValue(); 4920 } 4921 case ISD::SETOGT: 4922 case ISD::SETOGE: 4923 case ISD::SETGT: 4924 case ISD::SETGE: 4925 case ISD::SETUGT: 4926 case ISD::SETUGE: { 4927 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4928 if (TLI.isOperationLegal(Opcode, VT)) 4929 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4930 return SDValue(); 4931 } 4932 default: 4933 return SDValue(); 4934 } 4935 } 4936 4937 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4938 SDValue N0 = N->getOperand(0); 4939 SDValue N1 = N->getOperand(1); 4940 SDValue N2 = N->getOperand(2); 4941 EVT VT = N->getValueType(0); 4942 EVT VT0 = N0.getValueType(); 4943 4944 // fold (select C, X, X) -> X 4945 if (N1 == N2) 4946 return N1; 4947 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 4948 // fold (select true, X, Y) -> X 4949 // fold (select false, X, Y) -> Y 4950 return !N0C->isNullValue() ? N1 : N2; 4951 } 4952 // fold (select C, 1, X) -> (or C, X) 4953 if (VT == MVT::i1 && isOneConstant(N1)) 4954 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4955 // fold (select C, 0, 1) -> (xor C, 1) 4956 // We can't do this reliably if integer based booleans have different contents 4957 // to floating point based booleans. This is because we can't tell whether we 4958 // have an integer-based boolean or a floating-point-based boolean unless we 4959 // can find the SETCC that produced it and inspect its operands. This is 4960 // fairly easy if C is the SETCC node, but it can potentially be 4961 // undiscoverable (or not reasonably discoverable). For example, it could be 4962 // in another basic block or it could require searching a complicated 4963 // expression. 4964 if (VT.isInteger() && 4965 (VT0 == MVT::i1 || (VT0.isInteger() && 4966 TLI.getBooleanContents(false, false) == 4967 TLI.getBooleanContents(false, true) && 4968 TLI.getBooleanContents(false, false) == 4969 TargetLowering::ZeroOrOneBooleanContent)) && 4970 isNullConstant(N1) && isOneConstant(N2)) { 4971 SDValue XORNode; 4972 if (VT == VT0) { 4973 SDLoc DL(N); 4974 return DAG.getNode(ISD::XOR, DL, VT0, 4975 N0, DAG.getConstant(1, DL, VT0)); 4976 } 4977 SDLoc DL0(N0); 4978 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 4979 N0, DAG.getConstant(1, DL0, VT0)); 4980 AddToWorklist(XORNode.getNode()); 4981 if (VT.bitsGT(VT0)) 4982 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4983 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4984 } 4985 // fold (select C, 0, X) -> (and (not C), X) 4986 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 4987 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4988 AddToWorklist(NOTNode.getNode()); 4989 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4990 } 4991 // fold (select C, X, 1) -> (or (not C), X) 4992 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 4993 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4994 AddToWorklist(NOTNode.getNode()); 4995 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4996 } 4997 // fold (select C, X, 0) -> (and C, X) 4998 if (VT == MVT::i1 && isNullConstant(N2)) 4999 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5000 // fold (select X, X, Y) -> (or X, Y) 5001 // fold (select X, 1, Y) -> (or X, Y) 5002 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5003 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5004 // fold (select X, Y, X) -> (and X, Y) 5005 // fold (select X, Y, 0) -> (and X, Y) 5006 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5007 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5008 5009 // If we can fold this based on the true/false value, do so. 5010 if (SimplifySelectOps(N, N1, N2)) 5011 return SDValue(N, 0); // Don't revisit N. 5012 5013 if (VT0 == MVT::i1) { 5014 // The code in this block deals with the following 2 equivalences: 5015 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5016 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5017 // The target can specify its prefered form with the 5018 // shouldNormalizeToSelectSequence() callback. However we always transform 5019 // to the right anyway if we find the inner select exists in the DAG anyway 5020 // and we always transform to the left side if we know that we can further 5021 // optimize the combination of the conditions. 5022 bool normalizeToSequence 5023 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5024 // select (and Cond0, Cond1), X, Y 5025 // -> select Cond0, (select Cond1, X, Y), Y 5026 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5027 SDValue Cond0 = N0->getOperand(0); 5028 SDValue Cond1 = N0->getOperand(1); 5029 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5030 N1.getValueType(), Cond1, N1, N2); 5031 if (normalizeToSequence || !InnerSelect.use_empty()) 5032 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5033 InnerSelect, N2); 5034 } 5035 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5036 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5037 SDValue Cond0 = N0->getOperand(0); 5038 SDValue Cond1 = N0->getOperand(1); 5039 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5040 N1.getValueType(), Cond1, N1, N2); 5041 if (normalizeToSequence || !InnerSelect.use_empty()) 5042 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5043 InnerSelect); 5044 } 5045 5046 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5047 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5048 SDValue N1_0 = N1->getOperand(0); 5049 SDValue N1_1 = N1->getOperand(1); 5050 SDValue N1_2 = N1->getOperand(2); 5051 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5052 // Create the actual and node if we can generate good code for it. 5053 if (!normalizeToSequence) { 5054 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5055 N0, N1_0); 5056 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5057 N1_1, N2); 5058 } 5059 // Otherwise see if we can optimize the "and" to a better pattern. 5060 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5061 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5062 N1_1, N2); 5063 } 5064 } 5065 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5066 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5067 SDValue N2_0 = N2->getOperand(0); 5068 SDValue N2_1 = N2->getOperand(1); 5069 SDValue N2_2 = N2->getOperand(2); 5070 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5071 // Create the actual or node if we can generate good code for it. 5072 if (!normalizeToSequence) { 5073 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5074 N0, N2_0); 5075 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5076 N1, N2_2); 5077 } 5078 // Otherwise see if we can optimize to a better pattern. 5079 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5080 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5081 N1, N2_2); 5082 } 5083 } 5084 } 5085 5086 // fold selects based on a setcc into other things, such as min/max/abs 5087 if (N0.getOpcode() == ISD::SETCC) { 5088 // select x, y (fcmp lt x, y) -> fminnum x, y 5089 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5090 // 5091 // This is OK if we don't care about what happens if either operand is a 5092 // NaN. 5093 // 5094 5095 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5096 // no signed zeros as well as no nans. 5097 const TargetOptions &Options = DAG.getTarget().Options; 5098 if (Options.UnsafeFPMath && 5099 VT.isFloatingPoint() && N0.hasOneUse() && 5100 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5101 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5102 5103 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5104 N0.getOperand(1), N1, N2, CC, 5105 TLI, DAG)) 5106 return FMinMax; 5107 } 5108 5109 if ((!LegalOperations && 5110 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5111 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5112 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5113 N0.getOperand(0), N0.getOperand(1), 5114 N1, N2, N0.getOperand(2)); 5115 return SimplifySelect(SDLoc(N), N0, N1, N2); 5116 } 5117 5118 return SDValue(); 5119 } 5120 5121 static 5122 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5123 SDLoc DL(N); 5124 EVT LoVT, HiVT; 5125 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5126 5127 // Split the inputs. 5128 SDValue Lo, Hi, LL, LH, RL, RH; 5129 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5130 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5131 5132 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5133 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5134 5135 return std::make_pair(Lo, Hi); 5136 } 5137 5138 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5139 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5140 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5141 SDLoc dl(N); 5142 SDValue Cond = N->getOperand(0); 5143 SDValue LHS = N->getOperand(1); 5144 SDValue RHS = N->getOperand(2); 5145 EVT VT = N->getValueType(0); 5146 int NumElems = VT.getVectorNumElements(); 5147 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5148 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5149 Cond.getOpcode() == ISD::BUILD_VECTOR); 5150 5151 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5152 // binary ones here. 5153 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5154 return SDValue(); 5155 5156 // We're sure we have an even number of elements due to the 5157 // concat_vectors we have as arguments to vselect. 5158 // Skip BV elements until we find one that's not an UNDEF 5159 // After we find an UNDEF element, keep looping until we get to half the 5160 // length of the BV and see if all the non-undef nodes are the same. 5161 ConstantSDNode *BottomHalf = nullptr; 5162 for (int i = 0; i < NumElems / 2; ++i) { 5163 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5164 continue; 5165 5166 if (BottomHalf == nullptr) 5167 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5168 else if (Cond->getOperand(i).getNode() != BottomHalf) 5169 return SDValue(); 5170 } 5171 5172 // Do the same for the second half of the BuildVector 5173 ConstantSDNode *TopHalf = nullptr; 5174 for (int i = NumElems / 2; i < NumElems; ++i) { 5175 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5176 continue; 5177 5178 if (TopHalf == nullptr) 5179 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5180 else if (Cond->getOperand(i).getNode() != TopHalf) 5181 return SDValue(); 5182 } 5183 5184 assert(TopHalf && BottomHalf && 5185 "One half of the selector was all UNDEFs and the other was all the " 5186 "same value. This should have been addressed before this function."); 5187 return DAG.getNode( 5188 ISD::CONCAT_VECTORS, dl, VT, 5189 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5190 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5191 } 5192 5193 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5194 5195 if (Level >= AfterLegalizeTypes) 5196 return SDValue(); 5197 5198 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5199 SDValue Mask = MSC->getMask(); 5200 SDValue Data = MSC->getValue(); 5201 SDLoc DL(N); 5202 5203 // If the MSCATTER data type requires splitting and the mask is provided by a 5204 // SETCC, then split both nodes and its operands before legalization. This 5205 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5206 // and enables future optimizations (e.g. min/max pattern matching on X86). 5207 if (Mask.getOpcode() != ISD::SETCC) 5208 return SDValue(); 5209 5210 // Check if any splitting is required. 5211 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5212 TargetLowering::TypeSplitVector) 5213 return SDValue(); 5214 SDValue MaskLo, MaskHi, Lo, Hi; 5215 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5216 5217 EVT LoVT, HiVT; 5218 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5219 5220 SDValue Chain = MSC->getChain(); 5221 5222 EVT MemoryVT = MSC->getMemoryVT(); 5223 unsigned Alignment = MSC->getOriginalAlignment(); 5224 5225 EVT LoMemVT, HiMemVT; 5226 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5227 5228 SDValue DataLo, DataHi; 5229 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5230 5231 SDValue BasePtr = MSC->getBasePtr(); 5232 SDValue IndexLo, IndexHi; 5233 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5234 5235 MachineMemOperand *MMO = DAG.getMachineFunction(). 5236 getMachineMemOperand(MSC->getPointerInfo(), 5237 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5238 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5239 5240 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5241 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5242 DL, OpsLo, MMO); 5243 5244 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5245 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5246 DL, OpsHi, MMO); 5247 5248 AddToWorklist(Lo.getNode()); 5249 AddToWorklist(Hi.getNode()); 5250 5251 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5252 } 5253 5254 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5255 5256 if (Level >= AfterLegalizeTypes) 5257 return SDValue(); 5258 5259 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5260 SDValue Mask = MST->getMask(); 5261 SDValue Data = MST->getValue(); 5262 SDLoc DL(N); 5263 5264 // If the MSTORE data type requires splitting and the mask is provided by a 5265 // SETCC, then split both nodes and its operands before legalization. This 5266 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5267 // and enables future optimizations (e.g. min/max pattern matching on X86). 5268 if (Mask.getOpcode() == ISD::SETCC) { 5269 5270 // Check if any splitting is required. 5271 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5272 TargetLowering::TypeSplitVector) 5273 return SDValue(); 5274 5275 SDValue MaskLo, MaskHi, Lo, Hi; 5276 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5277 5278 EVT LoVT, HiVT; 5279 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5280 5281 SDValue Chain = MST->getChain(); 5282 SDValue Ptr = MST->getBasePtr(); 5283 5284 EVT MemoryVT = MST->getMemoryVT(); 5285 unsigned Alignment = MST->getOriginalAlignment(); 5286 5287 // if Alignment is equal to the vector size, 5288 // take the half of it for the second part 5289 unsigned SecondHalfAlignment = 5290 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5291 Alignment/2 : Alignment; 5292 5293 EVT LoMemVT, HiMemVT; 5294 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5295 5296 SDValue DataLo, DataHi; 5297 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5298 5299 MachineMemOperand *MMO = DAG.getMachineFunction(). 5300 getMachineMemOperand(MST->getPointerInfo(), 5301 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5302 Alignment, MST->getAAInfo(), MST->getRanges()); 5303 5304 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5305 MST->isTruncatingStore()); 5306 5307 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5308 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5309 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5310 5311 MMO = DAG.getMachineFunction(). 5312 getMachineMemOperand(MST->getPointerInfo(), 5313 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5314 SecondHalfAlignment, MST->getAAInfo(), 5315 MST->getRanges()); 5316 5317 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5318 MST->isTruncatingStore()); 5319 5320 AddToWorklist(Lo.getNode()); 5321 AddToWorklist(Hi.getNode()); 5322 5323 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5324 } 5325 return SDValue(); 5326 } 5327 5328 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5329 5330 if (Level >= AfterLegalizeTypes) 5331 return SDValue(); 5332 5333 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5334 SDValue Mask = MGT->getMask(); 5335 SDLoc DL(N); 5336 5337 // If the MGATHER result requires splitting and the mask is provided by a 5338 // SETCC, then split both nodes and its operands before legalization. This 5339 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5340 // and enables future optimizations (e.g. min/max pattern matching on X86). 5341 5342 if (Mask.getOpcode() != ISD::SETCC) 5343 return SDValue(); 5344 5345 EVT VT = N->getValueType(0); 5346 5347 // Check if any splitting is required. 5348 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5349 TargetLowering::TypeSplitVector) 5350 return SDValue(); 5351 5352 SDValue MaskLo, MaskHi, Lo, Hi; 5353 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5354 5355 SDValue Src0 = MGT->getValue(); 5356 SDValue Src0Lo, Src0Hi; 5357 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5358 5359 EVT LoVT, HiVT; 5360 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5361 5362 SDValue Chain = MGT->getChain(); 5363 EVT MemoryVT = MGT->getMemoryVT(); 5364 unsigned Alignment = MGT->getOriginalAlignment(); 5365 5366 EVT LoMemVT, HiMemVT; 5367 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5368 5369 SDValue BasePtr = MGT->getBasePtr(); 5370 SDValue Index = MGT->getIndex(); 5371 SDValue IndexLo, IndexHi; 5372 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5373 5374 MachineMemOperand *MMO = DAG.getMachineFunction(). 5375 getMachineMemOperand(MGT->getPointerInfo(), 5376 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5377 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5378 5379 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5380 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5381 MMO); 5382 5383 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5384 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5385 MMO); 5386 5387 AddToWorklist(Lo.getNode()); 5388 AddToWorklist(Hi.getNode()); 5389 5390 // Build a factor node to remember that this load is independent of the 5391 // other one. 5392 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5393 Hi.getValue(1)); 5394 5395 // Legalized the chain result - switch anything that used the old chain to 5396 // use the new one. 5397 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5398 5399 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5400 5401 SDValue RetOps[] = { GatherRes, Chain }; 5402 return DAG.getMergeValues(RetOps, DL); 5403 } 5404 5405 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5406 5407 if (Level >= AfterLegalizeTypes) 5408 return SDValue(); 5409 5410 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5411 SDValue Mask = MLD->getMask(); 5412 SDLoc DL(N); 5413 5414 // If the MLOAD result requires splitting and the mask is provided by a 5415 // SETCC, then split both nodes and its operands before legalization. This 5416 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5417 // and enables future optimizations (e.g. min/max pattern matching on X86). 5418 5419 if (Mask.getOpcode() == ISD::SETCC) { 5420 EVT VT = N->getValueType(0); 5421 5422 // Check if any splitting is required. 5423 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5424 TargetLowering::TypeSplitVector) 5425 return SDValue(); 5426 5427 SDValue MaskLo, MaskHi, Lo, Hi; 5428 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5429 5430 SDValue Src0 = MLD->getSrc0(); 5431 SDValue Src0Lo, Src0Hi; 5432 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5433 5434 EVT LoVT, HiVT; 5435 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5436 5437 SDValue Chain = MLD->getChain(); 5438 SDValue Ptr = MLD->getBasePtr(); 5439 EVT MemoryVT = MLD->getMemoryVT(); 5440 unsigned Alignment = MLD->getOriginalAlignment(); 5441 5442 // if Alignment is equal to the vector size, 5443 // take the half of it for the second part 5444 unsigned SecondHalfAlignment = 5445 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5446 Alignment/2 : Alignment; 5447 5448 EVT LoMemVT, HiMemVT; 5449 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5450 5451 MachineMemOperand *MMO = DAG.getMachineFunction(). 5452 getMachineMemOperand(MLD->getPointerInfo(), 5453 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5454 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5455 5456 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5457 ISD::NON_EXTLOAD); 5458 5459 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5460 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5461 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5462 5463 MMO = DAG.getMachineFunction(). 5464 getMachineMemOperand(MLD->getPointerInfo(), 5465 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5466 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5467 5468 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5469 ISD::NON_EXTLOAD); 5470 5471 AddToWorklist(Lo.getNode()); 5472 AddToWorklist(Hi.getNode()); 5473 5474 // Build a factor node to remember that this load is independent of the 5475 // other one. 5476 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5477 Hi.getValue(1)); 5478 5479 // Legalized the chain result - switch anything that used the old chain to 5480 // use the new one. 5481 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5482 5483 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5484 5485 SDValue RetOps[] = { LoadRes, Chain }; 5486 return DAG.getMergeValues(RetOps, DL); 5487 } 5488 return SDValue(); 5489 } 5490 5491 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5492 SDValue N0 = N->getOperand(0); 5493 SDValue N1 = N->getOperand(1); 5494 SDValue N2 = N->getOperand(2); 5495 SDLoc DL(N); 5496 5497 // Canonicalize integer abs. 5498 // vselect (setg[te] X, 0), X, -X -> 5499 // vselect (setgt X, -1), X, -X -> 5500 // vselect (setl[te] X, 0), -X, X -> 5501 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5502 if (N0.getOpcode() == ISD::SETCC) { 5503 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5504 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5505 bool isAbs = false; 5506 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5507 5508 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5509 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5510 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5511 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5512 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5513 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5514 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5515 5516 if (isAbs) { 5517 EVT VT = LHS.getValueType(); 5518 SDValue Shift = DAG.getNode( 5519 ISD::SRA, DL, VT, LHS, 5520 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5521 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5522 AddToWorklist(Shift.getNode()); 5523 AddToWorklist(Add.getNode()); 5524 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5525 } 5526 } 5527 5528 if (SimplifySelectOps(N, N1, N2)) 5529 return SDValue(N, 0); // Don't revisit N. 5530 5531 // If the VSELECT result requires splitting and the mask is provided by a 5532 // SETCC, then split both nodes and its operands before legalization. This 5533 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5534 // and enables future optimizations (e.g. min/max pattern matching on X86). 5535 if (N0.getOpcode() == ISD::SETCC) { 5536 EVT VT = N->getValueType(0); 5537 5538 // Check if any splitting is required. 5539 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5540 TargetLowering::TypeSplitVector) 5541 return SDValue(); 5542 5543 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5544 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5545 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5546 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5547 5548 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5549 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5550 5551 // Add the new VSELECT nodes to the work list in case they need to be split 5552 // again. 5553 AddToWorklist(Lo.getNode()); 5554 AddToWorklist(Hi.getNode()); 5555 5556 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5557 } 5558 5559 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5560 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5561 return N1; 5562 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5563 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5564 return N2; 5565 5566 // The ConvertSelectToConcatVector function is assuming both the above 5567 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5568 // and addressed. 5569 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5570 N2.getOpcode() == ISD::CONCAT_VECTORS && 5571 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5572 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5573 return CV; 5574 } 5575 5576 return SDValue(); 5577 } 5578 5579 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5580 SDValue N0 = N->getOperand(0); 5581 SDValue N1 = N->getOperand(1); 5582 SDValue N2 = N->getOperand(2); 5583 SDValue N3 = N->getOperand(3); 5584 SDValue N4 = N->getOperand(4); 5585 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5586 5587 // fold select_cc lhs, rhs, x, x, cc -> x 5588 if (N2 == N3) 5589 return N2; 5590 5591 // Determine if the condition we're dealing with is constant 5592 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5593 N0, N1, CC, SDLoc(N), false); 5594 if (SCC.getNode()) { 5595 AddToWorklist(SCC.getNode()); 5596 5597 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5598 if (!SCCC->isNullValue()) 5599 return N2; // cond always true -> true val 5600 else 5601 return N3; // cond always false -> false val 5602 } else if (SCC->getOpcode() == ISD::UNDEF) { 5603 // When the condition is UNDEF, just return the first operand. This is 5604 // coherent the DAG creation, no setcc node is created in this case 5605 return N2; 5606 } else if (SCC.getOpcode() == ISD::SETCC) { 5607 // Fold to a simpler select_cc 5608 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5609 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5610 SCC.getOperand(2)); 5611 } 5612 } 5613 5614 // If we can fold this based on the true/false value, do so. 5615 if (SimplifySelectOps(N, N2, N3)) 5616 return SDValue(N, 0); // Don't revisit N. 5617 5618 // fold select_cc into other things, such as min/max/abs 5619 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5620 } 5621 5622 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5623 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5624 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5625 SDLoc(N)); 5626 } 5627 5628 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5629 /// a build_vector of constants. 5630 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5631 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5632 /// Vector extends are not folded if operations are legal; this is to 5633 /// avoid introducing illegal build_vector dag nodes. 5634 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5635 SelectionDAG &DAG, bool LegalTypes, 5636 bool LegalOperations) { 5637 unsigned Opcode = N->getOpcode(); 5638 SDValue N0 = N->getOperand(0); 5639 EVT VT = N->getValueType(0); 5640 5641 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5642 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5643 && "Expected EXTEND dag node in input!"); 5644 5645 // fold (sext c1) -> c1 5646 // fold (zext c1) -> c1 5647 // fold (aext c1) -> c1 5648 if (isa<ConstantSDNode>(N0)) 5649 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5650 5651 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5652 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5653 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5654 EVT SVT = VT.getScalarType(); 5655 if (!(VT.isVector() && 5656 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5657 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5658 return nullptr; 5659 5660 // We can fold this node into a build_vector. 5661 unsigned VTBits = SVT.getSizeInBits(); 5662 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5663 SmallVector<SDValue, 8> Elts; 5664 unsigned NumElts = VT.getVectorNumElements(); 5665 SDLoc DL(N); 5666 5667 for (unsigned i=0; i != NumElts; ++i) { 5668 SDValue Op = N0->getOperand(i); 5669 if (Op->getOpcode() == ISD::UNDEF) { 5670 Elts.push_back(DAG.getUNDEF(SVT)); 5671 continue; 5672 } 5673 5674 SDLoc DL(Op); 5675 // Get the constant value and if needed trunc it to the size of the type. 5676 // Nodes like build_vector might have constants wider than the scalar type. 5677 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5678 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5679 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5680 else 5681 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5682 } 5683 5684 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5685 } 5686 5687 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5688 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5689 // transformation. Returns true if extension are possible and the above 5690 // mentioned transformation is profitable. 5691 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5692 unsigned ExtOpc, 5693 SmallVectorImpl<SDNode *> &ExtendNodes, 5694 const TargetLowering &TLI) { 5695 bool HasCopyToRegUses = false; 5696 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5697 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5698 UE = N0.getNode()->use_end(); 5699 UI != UE; ++UI) { 5700 SDNode *User = *UI; 5701 if (User == N) 5702 continue; 5703 if (UI.getUse().getResNo() != N0.getResNo()) 5704 continue; 5705 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5706 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5707 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5708 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5709 // Sign bits will be lost after a zext. 5710 return false; 5711 bool Add = false; 5712 for (unsigned i = 0; i != 2; ++i) { 5713 SDValue UseOp = User->getOperand(i); 5714 if (UseOp == N0) 5715 continue; 5716 if (!isa<ConstantSDNode>(UseOp)) 5717 return false; 5718 Add = true; 5719 } 5720 if (Add) 5721 ExtendNodes.push_back(User); 5722 continue; 5723 } 5724 // If truncates aren't free and there are users we can't 5725 // extend, it isn't worthwhile. 5726 if (!isTruncFree) 5727 return false; 5728 // Remember if this value is live-out. 5729 if (User->getOpcode() == ISD::CopyToReg) 5730 HasCopyToRegUses = true; 5731 } 5732 5733 if (HasCopyToRegUses) { 5734 bool BothLiveOut = false; 5735 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5736 UI != UE; ++UI) { 5737 SDUse &Use = UI.getUse(); 5738 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5739 BothLiveOut = true; 5740 break; 5741 } 5742 } 5743 if (BothLiveOut) 5744 // Both unextended and extended values are live out. There had better be 5745 // a good reason for the transformation. 5746 return ExtendNodes.size(); 5747 } 5748 return true; 5749 } 5750 5751 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5752 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5753 ISD::NodeType ExtType) { 5754 // Extend SetCC uses if necessary. 5755 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5756 SDNode *SetCC = SetCCs[i]; 5757 SmallVector<SDValue, 4> Ops; 5758 5759 for (unsigned j = 0; j != 2; ++j) { 5760 SDValue SOp = SetCC->getOperand(j); 5761 if (SOp == Trunc) 5762 Ops.push_back(ExtLoad); 5763 else 5764 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5765 } 5766 5767 Ops.push_back(SetCC->getOperand(2)); 5768 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5769 } 5770 } 5771 5772 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5773 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5774 SDValue N0 = N->getOperand(0); 5775 EVT DstVT = N->getValueType(0); 5776 EVT SrcVT = N0.getValueType(); 5777 5778 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5779 N->getOpcode() == ISD::ZERO_EXTEND) && 5780 "Unexpected node type (not an extend)!"); 5781 5782 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5783 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5784 // (v8i32 (sext (v8i16 (load x)))) 5785 // into: 5786 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5787 // (v4i32 (sextload (x + 16))))) 5788 // Where uses of the original load, i.e.: 5789 // (v8i16 (load x)) 5790 // are replaced with: 5791 // (v8i16 (truncate 5792 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5793 // (v4i32 (sextload (x + 16))))))) 5794 // 5795 // This combine is only applicable to illegal, but splittable, vectors. 5796 // All legal types, and illegal non-vector types, are handled elsewhere. 5797 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5798 // 5799 if (N0->getOpcode() != ISD::LOAD) 5800 return SDValue(); 5801 5802 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5803 5804 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5805 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5806 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5807 return SDValue(); 5808 5809 SmallVector<SDNode *, 4> SetCCs; 5810 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5811 return SDValue(); 5812 5813 ISD::LoadExtType ExtType = 5814 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5815 5816 // Try to split the vector types to get down to legal types. 5817 EVT SplitSrcVT = SrcVT; 5818 EVT SplitDstVT = DstVT; 5819 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5820 SplitSrcVT.getVectorNumElements() > 1) { 5821 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5822 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5823 } 5824 5825 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5826 return SDValue(); 5827 5828 SDLoc DL(N); 5829 const unsigned NumSplits = 5830 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5831 const unsigned Stride = SplitSrcVT.getStoreSize(); 5832 SmallVector<SDValue, 4> Loads; 5833 SmallVector<SDValue, 4> Chains; 5834 5835 SDValue BasePtr = LN0->getBasePtr(); 5836 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5837 const unsigned Offset = Idx * Stride; 5838 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5839 5840 SDValue SplitLoad = DAG.getExtLoad( 5841 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5842 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5843 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5844 Align, LN0->getAAInfo()); 5845 5846 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5847 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5848 5849 Loads.push_back(SplitLoad.getValue(0)); 5850 Chains.push_back(SplitLoad.getValue(1)); 5851 } 5852 5853 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5854 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5855 5856 CombineTo(N, NewValue); 5857 5858 // Replace uses of the original load (before extension) 5859 // with a truncate of the concatenated sextloaded vectors. 5860 SDValue Trunc = 5861 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5862 CombineTo(N0.getNode(), Trunc, NewChain); 5863 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5864 (ISD::NodeType)N->getOpcode()); 5865 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5866 } 5867 5868 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5869 SDValue N0 = N->getOperand(0); 5870 EVT VT = N->getValueType(0); 5871 5872 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5873 LegalOperations)) 5874 return SDValue(Res, 0); 5875 5876 // fold (sext (sext x)) -> (sext x) 5877 // fold (sext (aext x)) -> (sext x) 5878 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5879 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5880 N0.getOperand(0)); 5881 5882 if (N0.getOpcode() == ISD::TRUNCATE) { 5883 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5884 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5885 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 5886 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5887 if (NarrowLoad.getNode() != N0.getNode()) { 5888 CombineTo(N0.getNode(), NarrowLoad); 5889 // CombineTo deleted the truncate, if needed, but not what's under it. 5890 AddToWorklist(oye); 5891 } 5892 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5893 } 5894 5895 // See if the value being truncated is already sign extended. If so, just 5896 // eliminate the trunc/sext pair. 5897 SDValue Op = N0.getOperand(0); 5898 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5899 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5900 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5901 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5902 5903 if (OpBits == DestBits) { 5904 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5905 // bits, it is already ready. 5906 if (NumSignBits > DestBits-MidBits) 5907 return Op; 5908 } else if (OpBits < DestBits) { 5909 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5910 // bits, just sext from i32. 5911 if (NumSignBits > OpBits-MidBits) 5912 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5913 } else { 5914 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5915 // bits, just truncate to i32. 5916 if (NumSignBits > OpBits-MidBits) 5917 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5918 } 5919 5920 // fold (sext (truncate x)) -> (sextinreg x). 5921 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5922 N0.getValueType())) { 5923 if (OpBits < DestBits) 5924 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5925 else if (OpBits > DestBits) 5926 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5927 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5928 DAG.getValueType(N0.getValueType())); 5929 } 5930 } 5931 5932 // fold (sext (load x)) -> (sext (truncate (sextload x))) 5933 // Only generate vector extloads when 1) they're legal, and 2) they are 5934 // deemed desirable by the target. 5935 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5936 ((!LegalOperations && !VT.isVector() && 5937 !cast<LoadSDNode>(N0)->isVolatile()) || 5938 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 5939 bool DoXform = true; 5940 SmallVector<SDNode*, 4> SetCCs; 5941 if (!N0.hasOneUse()) 5942 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5943 if (VT.isVector()) 5944 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5945 if (DoXform) { 5946 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5947 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5948 LN0->getChain(), 5949 LN0->getBasePtr(), N0.getValueType(), 5950 LN0->getMemOperand()); 5951 CombineTo(N, ExtLoad); 5952 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5953 N0.getValueType(), ExtLoad); 5954 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5955 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5956 ISD::SIGN_EXTEND); 5957 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5958 } 5959 } 5960 5961 // fold (sext (load x)) to multiple smaller sextloads. 5962 // Only on illegal but splittable vectors. 5963 if (SDValue ExtLoad = CombineExtLoad(N)) 5964 return ExtLoad; 5965 5966 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5967 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5968 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5969 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5970 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5971 EVT MemVT = LN0->getMemoryVT(); 5972 if ((!LegalOperations && !LN0->isVolatile()) || 5973 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 5974 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5975 LN0->getChain(), 5976 LN0->getBasePtr(), MemVT, 5977 LN0->getMemOperand()); 5978 CombineTo(N, ExtLoad); 5979 CombineTo(N0.getNode(), 5980 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5981 N0.getValueType(), ExtLoad), 5982 ExtLoad.getValue(1)); 5983 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5984 } 5985 } 5986 5987 // fold (sext (and/or/xor (load x), cst)) -> 5988 // (and/or/xor (sextload x), (sext cst)) 5989 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5990 N0.getOpcode() == ISD::XOR) && 5991 isa<LoadSDNode>(N0.getOperand(0)) && 5992 N0.getOperand(1).getOpcode() == ISD::Constant && 5993 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 5994 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5995 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5996 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5997 bool DoXform = true; 5998 SmallVector<SDNode*, 4> SetCCs; 5999 if (!N0.hasOneUse()) 6000 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6001 SetCCs, TLI); 6002 if (DoXform) { 6003 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6004 LN0->getChain(), LN0->getBasePtr(), 6005 LN0->getMemoryVT(), 6006 LN0->getMemOperand()); 6007 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6008 Mask = Mask.sext(VT.getSizeInBits()); 6009 SDLoc DL(N); 6010 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6011 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6012 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6013 SDLoc(N0.getOperand(0)), 6014 N0.getOperand(0).getValueType(), ExtLoad); 6015 CombineTo(N, And); 6016 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6017 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6018 ISD::SIGN_EXTEND); 6019 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6020 } 6021 } 6022 } 6023 6024 if (N0.getOpcode() == ISD::SETCC) { 6025 EVT N0VT = N0.getOperand(0).getValueType(); 6026 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6027 // Only do this before legalize for now. 6028 if (VT.isVector() && !LegalOperations && 6029 TLI.getBooleanContents(N0VT) == 6030 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6031 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6032 // of the same size as the compared operands. Only optimize sext(setcc()) 6033 // if this is the case. 6034 EVT SVT = getSetCCResultType(N0VT); 6035 6036 // We know that the # elements of the results is the same as the 6037 // # elements of the compare (and the # elements of the compare result 6038 // for that matter). Check to see that they are the same size. If so, 6039 // we know that the element size of the sext'd result matches the 6040 // element size of the compare operands. 6041 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6042 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6043 N0.getOperand(1), 6044 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6045 6046 // If the desired elements are smaller or larger than the source 6047 // elements we can use a matching integer vector type and then 6048 // truncate/sign extend 6049 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6050 if (SVT == MatchingVectorType) { 6051 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6052 N0.getOperand(0), N0.getOperand(1), 6053 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6054 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6055 } 6056 } 6057 6058 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6059 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6060 SDLoc DL(N); 6061 SDValue NegOne = 6062 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6063 SDValue SCC = 6064 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6065 NegOne, DAG.getConstant(0, DL, VT), 6066 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6067 if (SCC.getNode()) return SCC; 6068 6069 if (!VT.isVector()) { 6070 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6071 if (!LegalOperations || 6072 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6073 SDLoc DL(N); 6074 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6075 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6076 N0.getOperand(0), N0.getOperand(1), CC); 6077 return DAG.getSelect(DL, VT, SetCC, 6078 NegOne, DAG.getConstant(0, DL, VT)); 6079 } 6080 } 6081 } 6082 6083 // fold (sext x) -> (zext x) if the sign bit is known zero. 6084 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6085 DAG.SignBitIsZero(N0)) 6086 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6087 6088 return SDValue(); 6089 } 6090 6091 // isTruncateOf - If N is a truncate of some other value, return true, record 6092 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6093 // This function computes KnownZero to avoid a duplicated call to 6094 // computeKnownBits in the caller. 6095 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6096 APInt &KnownZero) { 6097 APInt KnownOne; 6098 if (N->getOpcode() == ISD::TRUNCATE) { 6099 Op = N->getOperand(0); 6100 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6101 return true; 6102 } 6103 6104 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6105 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6106 return false; 6107 6108 SDValue Op0 = N->getOperand(0); 6109 SDValue Op1 = N->getOperand(1); 6110 assert(Op0.getValueType() == Op1.getValueType()); 6111 6112 if (isNullConstant(Op0)) 6113 Op = Op1; 6114 else if (isNullConstant(Op1)) 6115 Op = Op0; 6116 else 6117 return false; 6118 6119 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6120 6121 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6122 return false; 6123 6124 return true; 6125 } 6126 6127 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6128 SDValue N0 = N->getOperand(0); 6129 EVT VT = N->getValueType(0); 6130 6131 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6132 LegalOperations)) 6133 return SDValue(Res, 0); 6134 6135 // fold (zext (zext x)) -> (zext x) 6136 // fold (zext (aext x)) -> (zext x) 6137 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6138 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6139 N0.getOperand(0)); 6140 6141 // fold (zext (truncate x)) -> (zext x) or 6142 // (zext (truncate x)) -> (truncate x) 6143 // This is valid when the truncated bits of x are already zero. 6144 // FIXME: We should extend this to work for vectors too. 6145 SDValue Op; 6146 APInt KnownZero; 6147 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6148 APInt TruncatedBits = 6149 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6150 APInt(Op.getValueSizeInBits(), 0) : 6151 APInt::getBitsSet(Op.getValueSizeInBits(), 6152 N0.getValueSizeInBits(), 6153 std::min(Op.getValueSizeInBits(), 6154 VT.getSizeInBits())); 6155 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6156 if (VT.bitsGT(Op.getValueType())) 6157 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6158 if (VT.bitsLT(Op.getValueType())) 6159 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6160 6161 return Op; 6162 } 6163 } 6164 6165 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6166 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6167 if (N0.getOpcode() == ISD::TRUNCATE) { 6168 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6169 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6170 if (NarrowLoad.getNode() != N0.getNode()) { 6171 CombineTo(N0.getNode(), NarrowLoad); 6172 // CombineTo deleted the truncate, if needed, but not what's under it. 6173 AddToWorklist(oye); 6174 } 6175 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6176 } 6177 } 6178 6179 // fold (zext (truncate x)) -> (and x, mask) 6180 if (N0.getOpcode() == ISD::TRUNCATE) { 6181 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6182 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6183 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6184 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6185 if (NarrowLoad.getNode() != N0.getNode()) { 6186 CombineTo(N0.getNode(), NarrowLoad); 6187 // CombineTo deleted the truncate, if needed, but not what's under it. 6188 AddToWorklist(oye); 6189 } 6190 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6191 } 6192 6193 EVT SrcVT = N0.getOperand(0).getValueType(); 6194 EVT MinVT = N0.getValueType(); 6195 6196 // Try to mask before the extension to avoid having to generate a larger mask, 6197 // possibly over several sub-vectors. 6198 if (SrcVT.bitsLT(VT)) { 6199 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6200 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6201 SDValue Op = N0.getOperand(0); 6202 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6203 AddToWorklist(Op.getNode()); 6204 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6205 } 6206 } 6207 6208 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6209 SDValue Op = N0.getOperand(0); 6210 if (SrcVT.bitsLT(VT)) { 6211 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6212 AddToWorklist(Op.getNode()); 6213 } else if (SrcVT.bitsGT(VT)) { 6214 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6215 AddToWorklist(Op.getNode()); 6216 } 6217 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6218 } 6219 } 6220 6221 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6222 // if either of the casts is not free. 6223 if (N0.getOpcode() == ISD::AND && 6224 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6225 N0.getOperand(1).getOpcode() == ISD::Constant && 6226 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6227 N0.getValueType()) || 6228 !TLI.isZExtFree(N0.getValueType(), VT))) { 6229 SDValue X = N0.getOperand(0).getOperand(0); 6230 if (X.getValueType().bitsLT(VT)) { 6231 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6232 } else if (X.getValueType().bitsGT(VT)) { 6233 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6234 } 6235 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6236 Mask = Mask.zext(VT.getSizeInBits()); 6237 SDLoc DL(N); 6238 return DAG.getNode(ISD::AND, DL, VT, 6239 X, DAG.getConstant(Mask, DL, VT)); 6240 } 6241 6242 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6243 // Only generate vector extloads when 1) they're legal, and 2) they are 6244 // deemed desirable by the target. 6245 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6246 ((!LegalOperations && !VT.isVector() && 6247 !cast<LoadSDNode>(N0)->isVolatile()) || 6248 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6249 bool DoXform = true; 6250 SmallVector<SDNode*, 4> SetCCs; 6251 if (!N0.hasOneUse()) 6252 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6253 if (VT.isVector()) 6254 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6255 if (DoXform) { 6256 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6257 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6258 LN0->getChain(), 6259 LN0->getBasePtr(), N0.getValueType(), 6260 LN0->getMemOperand()); 6261 CombineTo(N, ExtLoad); 6262 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6263 N0.getValueType(), ExtLoad); 6264 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6265 6266 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6267 ISD::ZERO_EXTEND); 6268 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6269 } 6270 } 6271 6272 // fold (zext (load x)) to multiple smaller zextloads. 6273 // Only on illegal but splittable vectors. 6274 if (SDValue ExtLoad = CombineExtLoad(N)) 6275 return ExtLoad; 6276 6277 // fold (zext (and/or/xor (load x), cst)) -> 6278 // (and/or/xor (zextload x), (zext cst)) 6279 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6280 N0.getOpcode() == ISD::XOR) && 6281 isa<LoadSDNode>(N0.getOperand(0)) && 6282 N0.getOperand(1).getOpcode() == ISD::Constant && 6283 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6284 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6285 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6286 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6287 bool DoXform = true; 6288 SmallVector<SDNode*, 4> SetCCs; 6289 if (!N0.hasOneUse()) 6290 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 6291 SetCCs, TLI); 6292 if (DoXform) { 6293 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6294 LN0->getChain(), LN0->getBasePtr(), 6295 LN0->getMemoryVT(), 6296 LN0->getMemOperand()); 6297 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6298 Mask = Mask.zext(VT.getSizeInBits()); 6299 SDLoc DL(N); 6300 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6301 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6302 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6303 SDLoc(N0.getOperand(0)), 6304 N0.getOperand(0).getValueType(), ExtLoad); 6305 CombineTo(N, And); 6306 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6307 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6308 ISD::ZERO_EXTEND); 6309 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6310 } 6311 } 6312 } 6313 6314 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6315 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6316 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6317 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6318 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6319 EVT MemVT = LN0->getMemoryVT(); 6320 if ((!LegalOperations && !LN0->isVolatile()) || 6321 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6322 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6323 LN0->getChain(), 6324 LN0->getBasePtr(), MemVT, 6325 LN0->getMemOperand()); 6326 CombineTo(N, ExtLoad); 6327 CombineTo(N0.getNode(), 6328 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6329 ExtLoad), 6330 ExtLoad.getValue(1)); 6331 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6332 } 6333 } 6334 6335 if (N0.getOpcode() == ISD::SETCC) { 6336 if (!LegalOperations && VT.isVector() && 6337 N0.getValueType().getVectorElementType() == MVT::i1) { 6338 EVT N0VT = N0.getOperand(0).getValueType(); 6339 if (getSetCCResultType(N0VT) == N0.getValueType()) 6340 return SDValue(); 6341 6342 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6343 // Only do this before legalize for now. 6344 EVT EltVT = VT.getVectorElementType(); 6345 SDLoc DL(N); 6346 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 6347 DAG.getConstant(1, DL, EltVT)); 6348 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6349 // We know that the # elements of the results is the same as the 6350 // # elements of the compare (and the # elements of the compare result 6351 // for that matter). Check to see that they are the same size. If so, 6352 // we know that the element size of the sext'd result matches the 6353 // element size of the compare operands. 6354 return DAG.getNode(ISD::AND, DL, VT, 6355 DAG.getSetCC(DL, VT, N0.getOperand(0), 6356 N0.getOperand(1), 6357 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6358 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 6359 OneOps)); 6360 6361 // If the desired elements are smaller or larger than the source 6362 // elements we can use a matching integer vector type and then 6363 // truncate/sign extend 6364 EVT MatchingElementType = 6365 EVT::getIntegerVT(*DAG.getContext(), 6366 N0VT.getScalarType().getSizeInBits()); 6367 EVT MatchingVectorType = 6368 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6369 N0VT.getVectorNumElements()); 6370 SDValue VsetCC = 6371 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6372 N0.getOperand(1), 6373 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6374 return DAG.getNode(ISD::AND, DL, VT, 6375 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6376 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps)); 6377 } 6378 6379 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6380 SDLoc DL(N); 6381 SDValue SCC = 6382 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6383 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6384 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6385 if (SCC.getNode()) return SCC; 6386 } 6387 6388 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6389 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6390 isa<ConstantSDNode>(N0.getOperand(1)) && 6391 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6392 N0.hasOneUse()) { 6393 SDValue ShAmt = N0.getOperand(1); 6394 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6395 if (N0.getOpcode() == ISD::SHL) { 6396 SDValue InnerZExt = N0.getOperand(0); 6397 // If the original shl may be shifting out bits, do not perform this 6398 // transformation. 6399 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6400 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6401 if (ShAmtVal > KnownZeroBits) 6402 return SDValue(); 6403 } 6404 6405 SDLoc DL(N); 6406 6407 // Ensure that the shift amount is wide enough for the shifted value. 6408 if (VT.getSizeInBits() >= 256) 6409 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6410 6411 return DAG.getNode(N0.getOpcode(), DL, VT, 6412 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6413 ShAmt); 6414 } 6415 6416 return SDValue(); 6417 } 6418 6419 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6420 SDValue N0 = N->getOperand(0); 6421 EVT VT = N->getValueType(0); 6422 6423 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6424 LegalOperations)) 6425 return SDValue(Res, 0); 6426 6427 // fold (aext (aext x)) -> (aext x) 6428 // fold (aext (zext x)) -> (zext x) 6429 // fold (aext (sext x)) -> (sext x) 6430 if (N0.getOpcode() == ISD::ANY_EXTEND || 6431 N0.getOpcode() == ISD::ZERO_EXTEND || 6432 N0.getOpcode() == ISD::SIGN_EXTEND) 6433 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6434 6435 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6436 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6437 if (N0.getOpcode() == ISD::TRUNCATE) { 6438 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6439 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6440 if (NarrowLoad.getNode() != N0.getNode()) { 6441 CombineTo(N0.getNode(), NarrowLoad); 6442 // CombineTo deleted the truncate, if needed, but not what's under it. 6443 AddToWorklist(oye); 6444 } 6445 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6446 } 6447 } 6448 6449 // fold (aext (truncate x)) 6450 if (N0.getOpcode() == ISD::TRUNCATE) { 6451 SDValue TruncOp = N0.getOperand(0); 6452 if (TruncOp.getValueType() == VT) 6453 return TruncOp; // x iff x size == zext size. 6454 if (TruncOp.getValueType().bitsGT(VT)) 6455 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6456 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6457 } 6458 6459 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6460 // if the trunc is not free. 6461 if (N0.getOpcode() == ISD::AND && 6462 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6463 N0.getOperand(1).getOpcode() == ISD::Constant && 6464 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6465 N0.getValueType())) { 6466 SDValue X = N0.getOperand(0).getOperand(0); 6467 if (X.getValueType().bitsLT(VT)) { 6468 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6469 } else if (X.getValueType().bitsGT(VT)) { 6470 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6471 } 6472 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6473 Mask = Mask.zext(VT.getSizeInBits()); 6474 SDLoc DL(N); 6475 return DAG.getNode(ISD::AND, DL, VT, 6476 X, DAG.getConstant(Mask, DL, VT)); 6477 } 6478 6479 // fold (aext (load x)) -> (aext (truncate (extload x))) 6480 // None of the supported targets knows how to perform load and any_ext 6481 // on vectors in one instruction. We only perform this transformation on 6482 // scalars. 6483 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6484 ISD::isUNINDEXEDLoad(N0.getNode()) && 6485 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6486 bool DoXform = true; 6487 SmallVector<SDNode*, 4> SetCCs; 6488 if (!N0.hasOneUse()) 6489 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6490 if (DoXform) { 6491 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6492 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6493 LN0->getChain(), 6494 LN0->getBasePtr(), N0.getValueType(), 6495 LN0->getMemOperand()); 6496 CombineTo(N, ExtLoad); 6497 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6498 N0.getValueType(), ExtLoad); 6499 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6500 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6501 ISD::ANY_EXTEND); 6502 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6503 } 6504 } 6505 6506 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6507 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6508 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6509 if (N0.getOpcode() == ISD::LOAD && 6510 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6511 N0.hasOneUse()) { 6512 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6513 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6514 EVT MemVT = LN0->getMemoryVT(); 6515 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6516 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6517 VT, LN0->getChain(), LN0->getBasePtr(), 6518 MemVT, LN0->getMemOperand()); 6519 CombineTo(N, ExtLoad); 6520 CombineTo(N0.getNode(), 6521 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6522 N0.getValueType(), ExtLoad), 6523 ExtLoad.getValue(1)); 6524 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6525 } 6526 } 6527 6528 if (N0.getOpcode() == ISD::SETCC) { 6529 // For vectors: 6530 // aext(setcc) -> vsetcc 6531 // aext(setcc) -> truncate(vsetcc) 6532 // aext(setcc) -> aext(vsetcc) 6533 // Only do this before legalize for now. 6534 if (VT.isVector() && !LegalOperations) { 6535 EVT N0VT = N0.getOperand(0).getValueType(); 6536 // We know that the # elements of the results is the same as the 6537 // # elements of the compare (and the # elements of the compare result 6538 // for that matter). Check to see that they are the same size. If so, 6539 // we know that the element size of the sext'd result matches the 6540 // element size of the compare operands. 6541 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6542 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6543 N0.getOperand(1), 6544 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6545 // If the desired elements are smaller or larger than the source 6546 // elements we can use a matching integer vector type and then 6547 // truncate/any extend 6548 else { 6549 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6550 SDValue VsetCC = 6551 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6552 N0.getOperand(1), 6553 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6554 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6555 } 6556 } 6557 6558 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6559 SDLoc DL(N); 6560 SDValue SCC = 6561 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6562 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6563 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6564 if (SCC.getNode()) 6565 return SCC; 6566 } 6567 6568 return SDValue(); 6569 } 6570 6571 /// See if the specified operand can be simplified with the knowledge that only 6572 /// the bits specified by Mask are used. If so, return the simpler operand, 6573 /// otherwise return a null SDValue. 6574 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6575 switch (V.getOpcode()) { 6576 default: break; 6577 case ISD::Constant: { 6578 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6579 assert(CV && "Const value should be ConstSDNode."); 6580 const APInt &CVal = CV->getAPIntValue(); 6581 APInt NewVal = CVal & Mask; 6582 if (NewVal != CVal) 6583 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6584 break; 6585 } 6586 case ISD::OR: 6587 case ISD::XOR: 6588 // If the LHS or RHS don't contribute bits to the or, drop them. 6589 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6590 return V.getOperand(1); 6591 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6592 return V.getOperand(0); 6593 break; 6594 case ISD::SRL: 6595 // Only look at single-use SRLs. 6596 if (!V.getNode()->hasOneUse()) 6597 break; 6598 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6599 // See if we can recursively simplify the LHS. 6600 unsigned Amt = RHSC->getZExtValue(); 6601 6602 // Watch out for shift count overflow though. 6603 if (Amt >= Mask.getBitWidth()) break; 6604 APInt NewMask = Mask << Amt; 6605 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6606 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6607 SimplifyLHS, V.getOperand(1)); 6608 } 6609 } 6610 return SDValue(); 6611 } 6612 6613 /// If the result of a wider load is shifted to right of N bits and then 6614 /// truncated to a narrower type and where N is a multiple of number of bits of 6615 /// the narrower type, transform it to a narrower load from address + N / num of 6616 /// bits of new type. If the result is to be extended, also fold the extension 6617 /// to form a extending load. 6618 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6619 unsigned Opc = N->getOpcode(); 6620 6621 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6622 SDValue N0 = N->getOperand(0); 6623 EVT VT = N->getValueType(0); 6624 EVT ExtVT = VT; 6625 6626 // This transformation isn't valid for vector loads. 6627 if (VT.isVector()) 6628 return SDValue(); 6629 6630 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6631 // extended to VT. 6632 if (Opc == ISD::SIGN_EXTEND_INREG) { 6633 ExtType = ISD::SEXTLOAD; 6634 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6635 } else if (Opc == ISD::SRL) { 6636 // Another special-case: SRL is basically zero-extending a narrower value. 6637 ExtType = ISD::ZEXTLOAD; 6638 N0 = SDValue(N, 0); 6639 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6640 if (!N01) return SDValue(); 6641 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6642 VT.getSizeInBits() - N01->getZExtValue()); 6643 } 6644 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6645 return SDValue(); 6646 6647 unsigned EVTBits = ExtVT.getSizeInBits(); 6648 6649 // Do not generate loads of non-round integer types since these can 6650 // be expensive (and would be wrong if the type is not byte sized). 6651 if (!ExtVT.isRound()) 6652 return SDValue(); 6653 6654 unsigned ShAmt = 0; 6655 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6656 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6657 ShAmt = N01->getZExtValue(); 6658 // Is the shift amount a multiple of size of VT? 6659 if ((ShAmt & (EVTBits-1)) == 0) { 6660 N0 = N0.getOperand(0); 6661 // Is the load width a multiple of size of VT? 6662 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6663 return SDValue(); 6664 } 6665 6666 // At this point, we must have a load or else we can't do the transform. 6667 if (!isa<LoadSDNode>(N0)) return SDValue(); 6668 6669 // Because a SRL must be assumed to *need* to zero-extend the high bits 6670 // (as opposed to anyext the high bits), we can't combine the zextload 6671 // lowering of SRL and an sextload. 6672 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6673 return SDValue(); 6674 6675 // If the shift amount is larger than the input type then we're not 6676 // accessing any of the loaded bytes. If the load was a zextload/extload 6677 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6678 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6679 return SDValue(); 6680 } 6681 } 6682 6683 // If the load is shifted left (and the result isn't shifted back right), 6684 // we can fold the truncate through the shift. 6685 unsigned ShLeftAmt = 0; 6686 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6687 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6688 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6689 ShLeftAmt = N01->getZExtValue(); 6690 N0 = N0.getOperand(0); 6691 } 6692 } 6693 6694 // If we haven't found a load, we can't narrow it. Don't transform one with 6695 // multiple uses, this would require adding a new load. 6696 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6697 return SDValue(); 6698 6699 // Don't change the width of a volatile load. 6700 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6701 if (LN0->isVolatile()) 6702 return SDValue(); 6703 6704 // Verify that we are actually reducing a load width here. 6705 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6706 return SDValue(); 6707 6708 // For the transform to be legal, the load must produce only two values 6709 // (the value loaded and the chain). Don't transform a pre-increment 6710 // load, for example, which produces an extra value. Otherwise the 6711 // transformation is not equivalent, and the downstream logic to replace 6712 // uses gets things wrong. 6713 if (LN0->getNumValues() > 2) 6714 return SDValue(); 6715 6716 // If the load that we're shrinking is an extload and we're not just 6717 // discarding the extension we can't simply shrink the load. Bail. 6718 // TODO: It would be possible to merge the extensions in some cases. 6719 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6720 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6721 return SDValue(); 6722 6723 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6724 return SDValue(); 6725 6726 EVT PtrType = N0.getOperand(1).getValueType(); 6727 6728 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6729 // It's not possible to generate a constant of extended or untyped type. 6730 return SDValue(); 6731 6732 // For big endian targets, we need to adjust the offset to the pointer to 6733 // load the correct bytes. 6734 if (DAG.getDataLayout().isBigEndian()) { 6735 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6736 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6737 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6738 } 6739 6740 uint64_t PtrOff = ShAmt / 8; 6741 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6742 SDLoc DL(LN0); 6743 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6744 PtrType, LN0->getBasePtr(), 6745 DAG.getConstant(PtrOff, DL, PtrType)); 6746 AddToWorklist(NewPtr.getNode()); 6747 6748 SDValue Load; 6749 if (ExtType == ISD::NON_EXTLOAD) 6750 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6751 LN0->getPointerInfo().getWithOffset(PtrOff), 6752 LN0->isVolatile(), LN0->isNonTemporal(), 6753 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6754 else 6755 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6756 LN0->getPointerInfo().getWithOffset(PtrOff), 6757 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6758 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6759 6760 // Replace the old load's chain with the new load's chain. 6761 WorklistRemover DeadNodes(*this); 6762 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6763 6764 // Shift the result left, if we've swallowed a left shift. 6765 SDValue Result = Load; 6766 if (ShLeftAmt != 0) { 6767 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6768 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6769 ShImmTy = VT; 6770 // If the shift amount is as large as the result size (but, presumably, 6771 // no larger than the source) then the useful bits of the result are 6772 // zero; we can't simply return the shortened shift, because the result 6773 // of that operation is undefined. 6774 SDLoc DL(N0); 6775 if (ShLeftAmt >= VT.getSizeInBits()) 6776 Result = DAG.getConstant(0, DL, VT); 6777 else 6778 Result = DAG.getNode(ISD::SHL, DL, VT, 6779 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6780 } 6781 6782 // Return the new loaded value. 6783 return Result; 6784 } 6785 6786 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6787 SDValue N0 = N->getOperand(0); 6788 SDValue N1 = N->getOperand(1); 6789 EVT VT = N->getValueType(0); 6790 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6791 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6792 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6793 6794 if (N0.isUndef()) 6795 return DAG.getUNDEF(VT); 6796 6797 // fold (sext_in_reg c1) -> c1 6798 if (isConstantIntBuildVectorOrConstantInt(N0)) 6799 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6800 6801 // If the input is already sign extended, just drop the extension. 6802 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6803 return N0; 6804 6805 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6806 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6807 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6808 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6809 N0.getOperand(0), N1); 6810 6811 // fold (sext_in_reg (sext x)) -> (sext x) 6812 // fold (sext_in_reg (aext x)) -> (sext x) 6813 // if x is small enough. 6814 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6815 SDValue N00 = N0.getOperand(0); 6816 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6817 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6818 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6819 } 6820 6821 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6822 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6823 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6824 6825 // fold operands of sext_in_reg based on knowledge that the top bits are not 6826 // demanded. 6827 if (SimplifyDemandedBits(SDValue(N, 0))) 6828 return SDValue(N, 0); 6829 6830 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6831 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6832 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6833 return NarrowLoad; 6834 6835 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6836 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6837 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6838 if (N0.getOpcode() == ISD::SRL) { 6839 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6840 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6841 // We can turn this into an SRA iff the input to the SRL is already sign 6842 // extended enough. 6843 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6844 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6845 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6846 N0.getOperand(0), N0.getOperand(1)); 6847 } 6848 } 6849 6850 // fold (sext_inreg (extload x)) -> (sextload x) 6851 if (ISD::isEXTLoad(N0.getNode()) && 6852 ISD::isUNINDEXEDLoad(N0.getNode()) && 6853 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6854 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6855 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6856 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6857 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6858 LN0->getChain(), 6859 LN0->getBasePtr(), EVT, 6860 LN0->getMemOperand()); 6861 CombineTo(N, ExtLoad); 6862 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6863 AddToWorklist(ExtLoad.getNode()); 6864 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6865 } 6866 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6867 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6868 N0.hasOneUse() && 6869 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6870 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6871 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6872 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6873 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6874 LN0->getChain(), 6875 LN0->getBasePtr(), EVT, 6876 LN0->getMemOperand()); 6877 CombineTo(N, ExtLoad); 6878 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6879 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6880 } 6881 6882 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6883 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6884 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6885 N0.getOperand(1), false); 6886 if (BSwap.getNode()) 6887 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6888 BSwap, N1); 6889 } 6890 6891 return SDValue(); 6892 } 6893 6894 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 6895 SDValue N0 = N->getOperand(0); 6896 EVT VT = N->getValueType(0); 6897 6898 if (N0.getOpcode() == ISD::UNDEF) 6899 return DAG.getUNDEF(VT); 6900 6901 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6902 LegalOperations)) 6903 return SDValue(Res, 0); 6904 6905 return SDValue(); 6906 } 6907 6908 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6909 SDValue N0 = N->getOperand(0); 6910 EVT VT = N->getValueType(0); 6911 bool isLE = DAG.getDataLayout().isLittleEndian(); 6912 6913 // noop truncate 6914 if (N0.getValueType() == N->getValueType(0)) 6915 return N0; 6916 // fold (truncate c1) -> c1 6917 if (isConstantIntBuildVectorOrConstantInt(N0)) 6918 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6919 // fold (truncate (truncate x)) -> (truncate x) 6920 if (N0.getOpcode() == ISD::TRUNCATE) 6921 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6922 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6923 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6924 N0.getOpcode() == ISD::SIGN_EXTEND || 6925 N0.getOpcode() == ISD::ANY_EXTEND) { 6926 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6927 // if the source is smaller than the dest, we still need an extend 6928 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6929 N0.getOperand(0)); 6930 if (N0.getOperand(0).getValueType().bitsGT(VT)) 6931 // if the source is larger than the dest, than we just need the truncate 6932 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6933 // if the source and dest are the same type, we can drop both the extend 6934 // and the truncate. 6935 return N0.getOperand(0); 6936 } 6937 6938 // Fold extract-and-trunc into a narrow extract. For example: 6939 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 6940 // i32 y = TRUNCATE(i64 x) 6941 // -- becomes -- 6942 // v16i8 b = BITCAST (v2i64 val) 6943 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 6944 // 6945 // Note: We only run this optimization after type legalization (which often 6946 // creates this pattern) and before operation legalization after which 6947 // we need to be more careful about the vector instructions that we generate. 6948 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6949 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 6950 6951 EVT VecTy = N0.getOperand(0).getValueType(); 6952 EVT ExTy = N0.getValueType(); 6953 EVT TrTy = N->getValueType(0); 6954 6955 unsigned NumElem = VecTy.getVectorNumElements(); 6956 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 6957 6958 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 6959 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 6960 6961 SDValue EltNo = N0->getOperand(1); 6962 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 6963 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6964 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 6965 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6966 6967 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6968 NVT, N0.getOperand(0)); 6969 6970 SDLoc DL(N); 6971 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6972 DL, TrTy, V, 6973 DAG.getConstant(Index, DL, IndexTy)); 6974 } 6975 } 6976 6977 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 6978 if (N0.getOpcode() == ISD::SELECT) { 6979 EVT SrcVT = N0.getValueType(); 6980 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 6981 TLI.isTruncateFree(SrcVT, VT)) { 6982 SDLoc SL(N0); 6983 SDValue Cond = N0.getOperand(0); 6984 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 6985 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 6986 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 6987 } 6988 } 6989 6990 // Fold a series of buildvector, bitcast, and truncate if possible. 6991 // For example fold 6992 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 6993 // (2xi32 (buildvector x, y)). 6994 if (Level == AfterLegalizeVectorOps && VT.isVector() && 6995 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 6996 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 6997 N0.getOperand(0).hasOneUse()) { 6998 6999 SDValue BuildVect = N0.getOperand(0); 7000 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7001 EVT TruncVecEltTy = VT.getVectorElementType(); 7002 7003 // Check that the element types match. 7004 if (BuildVectEltTy == TruncVecEltTy) { 7005 // Now we only need to compute the offset of the truncated elements. 7006 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7007 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7008 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7009 7010 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7011 "Invalid number of elements"); 7012 7013 SmallVector<SDValue, 8> Opnds; 7014 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7015 Opnds.push_back(BuildVect.getOperand(i)); 7016 7017 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 7018 } 7019 } 7020 7021 // See if we can simplify the input to this truncate through knowledge that 7022 // only the low bits are being used. 7023 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7024 // Currently we only perform this optimization on scalars because vectors 7025 // may have different active low bits. 7026 if (!VT.isVector()) { 7027 SDValue Shorter = 7028 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7029 VT.getSizeInBits())); 7030 if (Shorter.getNode()) 7031 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7032 } 7033 // fold (truncate (load x)) -> (smaller load x) 7034 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7035 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7036 if (SDValue Reduced = ReduceLoadWidth(N)) 7037 return Reduced; 7038 7039 // Handle the case where the load remains an extending load even 7040 // after truncation. 7041 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7042 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7043 if (!LN0->isVolatile() && 7044 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7045 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7046 VT, LN0->getChain(), LN0->getBasePtr(), 7047 LN0->getMemoryVT(), 7048 LN0->getMemOperand()); 7049 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7050 return NewLoad; 7051 } 7052 } 7053 } 7054 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7055 // where ... are all 'undef'. 7056 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7057 SmallVector<EVT, 8> VTs; 7058 SDValue V; 7059 unsigned Idx = 0; 7060 unsigned NumDefs = 0; 7061 7062 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7063 SDValue X = N0.getOperand(i); 7064 if (X.getOpcode() != ISD::UNDEF) { 7065 V = X; 7066 Idx = i; 7067 NumDefs++; 7068 } 7069 // Stop if more than one members are non-undef. 7070 if (NumDefs > 1) 7071 break; 7072 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7073 VT.getVectorElementType(), 7074 X.getValueType().getVectorNumElements())); 7075 } 7076 7077 if (NumDefs == 0) 7078 return DAG.getUNDEF(VT); 7079 7080 if (NumDefs == 1) { 7081 assert(V.getNode() && "The single defined operand is empty!"); 7082 SmallVector<SDValue, 8> Opnds; 7083 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7084 if (i != Idx) { 7085 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7086 continue; 7087 } 7088 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7089 AddToWorklist(NV.getNode()); 7090 Opnds.push_back(NV); 7091 } 7092 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7093 } 7094 } 7095 7096 // Simplify the operands using demanded-bits information. 7097 if (!VT.isVector() && 7098 SimplifyDemandedBits(SDValue(N, 0))) 7099 return SDValue(N, 0); 7100 7101 return SDValue(); 7102 } 7103 7104 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7105 SDValue Elt = N->getOperand(i); 7106 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7107 return Elt.getNode(); 7108 return Elt.getOperand(Elt.getResNo()).getNode(); 7109 } 7110 7111 /// build_pair (load, load) -> load 7112 /// if load locations are consecutive. 7113 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7114 assert(N->getOpcode() == ISD::BUILD_PAIR); 7115 7116 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7117 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7118 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7119 LD1->getAddressSpace() != LD2->getAddressSpace()) 7120 return SDValue(); 7121 EVT LD1VT = LD1->getValueType(0); 7122 7123 if (ISD::isNON_EXTLoad(LD2) && 7124 LD2->hasOneUse() && 7125 // If both are volatile this would reduce the number of volatile loads. 7126 // If one is volatile it might be ok, but play conservative and bail out. 7127 !LD1->isVolatile() && 7128 !LD2->isVolatile() && 7129 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 7130 unsigned Align = LD1->getAlignment(); 7131 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7132 VT.getTypeForEVT(*DAG.getContext())); 7133 7134 if (NewAlign <= Align && 7135 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7136 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7137 LD1->getBasePtr(), LD1->getPointerInfo(), 7138 false, false, false, Align); 7139 } 7140 7141 return SDValue(); 7142 } 7143 7144 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7145 SDValue N0 = N->getOperand(0); 7146 EVT VT = N->getValueType(0); 7147 7148 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7149 // Only do this before legalize, since afterward the target may be depending 7150 // on the bitconvert. 7151 // First check to see if this is all constant. 7152 if (!LegalTypes && 7153 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7154 VT.isVector()) { 7155 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7156 7157 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7158 assert(!DestEltVT.isVector() && 7159 "Element type of vector ValueType must not be vector!"); 7160 if (isSimple) 7161 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7162 } 7163 7164 // If the input is a constant, let getNode fold it. 7165 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7166 // If we can't allow illegal operations, we need to check that this is just 7167 // a fp -> int or int -> conversion and that the resulting operation will 7168 // be legal. 7169 if (!LegalOperations || 7170 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7171 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7172 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7173 TLI.isOperationLegal(ISD::Constant, VT))) 7174 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7175 } 7176 7177 // (conv (conv x, t1), t2) -> (conv x, t2) 7178 if (N0.getOpcode() == ISD::BITCAST) 7179 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7180 N0.getOperand(0)); 7181 7182 // fold (conv (load x)) -> (load (conv*)x) 7183 // If the resultant load doesn't need a higher alignment than the original! 7184 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7185 // Do not change the width of a volatile load. 7186 !cast<LoadSDNode>(N0)->isVolatile() && 7187 // Do not remove the cast if the types differ in endian layout. 7188 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7189 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7190 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7191 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7192 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7193 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 7194 VT.getTypeForEVT(*DAG.getContext())); 7195 unsigned OrigAlign = LN0->getAlignment(); 7196 7197 if (Align <= OrigAlign) { 7198 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7199 LN0->getBasePtr(), LN0->getPointerInfo(), 7200 LN0->isVolatile(), LN0->isNonTemporal(), 7201 LN0->isInvariant(), OrigAlign, 7202 LN0->getAAInfo()); 7203 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7204 return Load; 7205 } 7206 } 7207 7208 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7209 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7210 // This often reduces constant pool loads. 7211 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7212 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7213 N0.getNode()->hasOneUse() && VT.isInteger() && 7214 !VT.isVector() && !N0.getValueType().isVector()) { 7215 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7216 N0.getOperand(0)); 7217 AddToWorklist(NewConv.getNode()); 7218 7219 SDLoc DL(N); 7220 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7221 if (N0.getOpcode() == ISD::FNEG) 7222 return DAG.getNode(ISD::XOR, DL, VT, 7223 NewConv, DAG.getConstant(SignBit, DL, VT)); 7224 assert(N0.getOpcode() == ISD::FABS); 7225 return DAG.getNode(ISD::AND, DL, VT, 7226 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7227 } 7228 7229 // fold (bitconvert (fcopysign cst, x)) -> 7230 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7231 // Note that we don't handle (copysign x, cst) because this can always be 7232 // folded to an fneg or fabs. 7233 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7234 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7235 VT.isInteger() && !VT.isVector()) { 7236 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7237 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7238 if (isTypeLegal(IntXVT)) { 7239 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7240 IntXVT, N0.getOperand(1)); 7241 AddToWorklist(X.getNode()); 7242 7243 // If X has a different width than the result/lhs, sext it or truncate it. 7244 unsigned VTWidth = VT.getSizeInBits(); 7245 if (OrigXWidth < VTWidth) { 7246 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7247 AddToWorklist(X.getNode()); 7248 } else if (OrigXWidth > VTWidth) { 7249 // To get the sign bit in the right place, we have to shift it right 7250 // before truncating. 7251 SDLoc DL(X); 7252 X = DAG.getNode(ISD::SRL, DL, 7253 X.getValueType(), X, 7254 DAG.getConstant(OrigXWidth-VTWidth, DL, 7255 X.getValueType())); 7256 AddToWorklist(X.getNode()); 7257 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7258 AddToWorklist(X.getNode()); 7259 } 7260 7261 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7262 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7263 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7264 AddToWorklist(X.getNode()); 7265 7266 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7267 VT, N0.getOperand(0)); 7268 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7269 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7270 AddToWorklist(Cst.getNode()); 7271 7272 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7273 } 7274 } 7275 7276 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7277 if (N0.getOpcode() == ISD::BUILD_PAIR) 7278 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7279 return CombineLD; 7280 7281 // Remove double bitcasts from shuffles - this is often a legacy of 7282 // XformToShuffleWithZero being used to combine bitmaskings (of 7283 // float vectors bitcast to integer vectors) into shuffles. 7284 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7285 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7286 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7287 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7288 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7289 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7290 7291 // If operands are a bitcast, peek through if it casts the original VT. 7292 // If operands are a constant, just bitcast back to original VT. 7293 auto PeekThroughBitcast = [&](SDValue Op) { 7294 if (Op.getOpcode() == ISD::BITCAST && 7295 Op.getOperand(0).getValueType() == VT) 7296 return SDValue(Op.getOperand(0)); 7297 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7298 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7299 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7300 return SDValue(); 7301 }; 7302 7303 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7304 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7305 if (!(SV0 && SV1)) 7306 return SDValue(); 7307 7308 int MaskScale = 7309 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7310 SmallVector<int, 8> NewMask; 7311 for (int M : SVN->getMask()) 7312 for (int i = 0; i != MaskScale; ++i) 7313 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7314 7315 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7316 if (!LegalMask) { 7317 std::swap(SV0, SV1); 7318 ShuffleVectorSDNode::commuteMask(NewMask); 7319 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7320 } 7321 7322 if (LegalMask) 7323 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7324 } 7325 7326 return SDValue(); 7327 } 7328 7329 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7330 EVT VT = N->getValueType(0); 7331 return CombineConsecutiveLoads(N, VT); 7332 } 7333 7334 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7335 /// operands. DstEltVT indicates the destination element value type. 7336 SDValue DAGCombiner:: 7337 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7338 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7339 7340 // If this is already the right type, we're done. 7341 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7342 7343 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7344 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7345 7346 // If this is a conversion of N elements of one type to N elements of another 7347 // type, convert each element. This handles FP<->INT cases. 7348 if (SrcBitSize == DstBitSize) { 7349 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7350 BV->getValueType(0).getVectorNumElements()); 7351 7352 // Due to the FP element handling below calling this routine recursively, 7353 // we can end up with a scalar-to-vector node here. 7354 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7355 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7356 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7357 DstEltVT, BV->getOperand(0))); 7358 7359 SmallVector<SDValue, 8> Ops; 7360 for (SDValue Op : BV->op_values()) { 7361 // If the vector element type is not legal, the BUILD_VECTOR operands 7362 // are promoted and implicitly truncated. Make that explicit here. 7363 if (Op.getValueType() != SrcEltVT) 7364 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7365 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7366 DstEltVT, Op)); 7367 AddToWorklist(Ops.back().getNode()); 7368 } 7369 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7370 } 7371 7372 // Otherwise, we're growing or shrinking the elements. To avoid having to 7373 // handle annoying details of growing/shrinking FP values, we convert them to 7374 // int first. 7375 if (SrcEltVT.isFloatingPoint()) { 7376 // Convert the input float vector to a int vector where the elements are the 7377 // same sizes. 7378 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7379 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7380 SrcEltVT = IntVT; 7381 } 7382 7383 // Now we know the input is an integer vector. If the output is a FP type, 7384 // convert to integer first, then to FP of the right size. 7385 if (DstEltVT.isFloatingPoint()) { 7386 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7387 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7388 7389 // Next, convert to FP elements of the same size. 7390 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7391 } 7392 7393 SDLoc DL(BV); 7394 7395 // Okay, we know the src/dst types are both integers of differing types. 7396 // Handling growing first. 7397 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7398 if (SrcBitSize < DstBitSize) { 7399 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7400 7401 SmallVector<SDValue, 8> Ops; 7402 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7403 i += NumInputsPerOutput) { 7404 bool isLE = DAG.getDataLayout().isLittleEndian(); 7405 APInt NewBits = APInt(DstBitSize, 0); 7406 bool EltIsUndef = true; 7407 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7408 // Shift the previously computed bits over. 7409 NewBits <<= SrcBitSize; 7410 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7411 if (Op.getOpcode() == ISD::UNDEF) continue; 7412 EltIsUndef = false; 7413 7414 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7415 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7416 } 7417 7418 if (EltIsUndef) 7419 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7420 else 7421 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7422 } 7423 7424 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7425 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7426 } 7427 7428 // Finally, this must be the case where we are shrinking elements: each input 7429 // turns into multiple outputs. 7430 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7431 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7432 NumOutputsPerInput*BV->getNumOperands()); 7433 SmallVector<SDValue, 8> Ops; 7434 7435 for (const SDValue &Op : BV->op_values()) { 7436 if (Op.getOpcode() == ISD::UNDEF) { 7437 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7438 continue; 7439 } 7440 7441 APInt OpVal = cast<ConstantSDNode>(Op)-> 7442 getAPIntValue().zextOrTrunc(SrcBitSize); 7443 7444 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7445 APInt ThisVal = OpVal.trunc(DstBitSize); 7446 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7447 OpVal = OpVal.lshr(DstBitSize); 7448 } 7449 7450 // For big endian targets, swap the order of the pieces of each element. 7451 if (DAG.getDataLayout().isBigEndian()) 7452 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7453 } 7454 7455 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7456 } 7457 7458 /// Try to perform FMA combining on a given FADD node. 7459 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7460 SDValue N0 = N->getOperand(0); 7461 SDValue N1 = N->getOperand(1); 7462 EVT VT = N->getValueType(0); 7463 SDLoc SL(N); 7464 7465 const TargetOptions &Options = DAG.getTarget().Options; 7466 bool AllowFusion = 7467 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7468 7469 // Floating-point multiply-add with intermediate rounding. 7470 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7471 7472 // Floating-point multiply-add without intermediate rounding. 7473 bool HasFMA = 7474 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7475 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7476 7477 // No valid opcode, do not combine. 7478 if (!HasFMAD && !HasFMA) 7479 return SDValue(); 7480 7481 // Always prefer FMAD to FMA for precision. 7482 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7483 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7484 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7485 7486 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7487 // prefer to fold the multiply with fewer uses. 7488 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7489 N1.getOpcode() == ISD::FMUL) { 7490 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7491 std::swap(N0, N1); 7492 } 7493 7494 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7495 if (N0.getOpcode() == ISD::FMUL && 7496 (Aggressive || N0->hasOneUse())) { 7497 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7498 N0.getOperand(0), N0.getOperand(1), N1); 7499 } 7500 7501 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7502 // Note: Commutes FADD operands. 7503 if (N1.getOpcode() == ISD::FMUL && 7504 (Aggressive || N1->hasOneUse())) { 7505 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7506 N1.getOperand(0), N1.getOperand(1), N0); 7507 } 7508 7509 // Look through FP_EXTEND nodes to do more combining. 7510 if (AllowFusion && LookThroughFPExt) { 7511 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7512 if (N0.getOpcode() == ISD::FP_EXTEND) { 7513 SDValue N00 = N0.getOperand(0); 7514 if (N00.getOpcode() == ISD::FMUL) 7515 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7516 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7517 N00.getOperand(0)), 7518 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7519 N00.getOperand(1)), N1); 7520 } 7521 7522 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7523 // Note: Commutes FADD operands. 7524 if (N1.getOpcode() == ISD::FP_EXTEND) { 7525 SDValue N10 = N1.getOperand(0); 7526 if (N10.getOpcode() == ISD::FMUL) 7527 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7528 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7529 N10.getOperand(0)), 7530 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7531 N10.getOperand(1)), N0); 7532 } 7533 } 7534 7535 // More folding opportunities when target permits. 7536 if ((AllowFusion || HasFMAD) && Aggressive) { 7537 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7538 if (N0.getOpcode() == PreferredFusedOpcode && 7539 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7540 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7541 N0.getOperand(0), N0.getOperand(1), 7542 DAG.getNode(PreferredFusedOpcode, SL, VT, 7543 N0.getOperand(2).getOperand(0), 7544 N0.getOperand(2).getOperand(1), 7545 N1)); 7546 } 7547 7548 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7549 if (N1->getOpcode() == PreferredFusedOpcode && 7550 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7551 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7552 N1.getOperand(0), N1.getOperand(1), 7553 DAG.getNode(PreferredFusedOpcode, SL, VT, 7554 N1.getOperand(2).getOperand(0), 7555 N1.getOperand(2).getOperand(1), 7556 N0)); 7557 } 7558 7559 if (AllowFusion && LookThroughFPExt) { 7560 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7561 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7562 auto FoldFAddFMAFPExtFMul = [&] ( 7563 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7564 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7565 DAG.getNode(PreferredFusedOpcode, SL, VT, 7566 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7567 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7568 Z)); 7569 }; 7570 if (N0.getOpcode() == PreferredFusedOpcode) { 7571 SDValue N02 = N0.getOperand(2); 7572 if (N02.getOpcode() == ISD::FP_EXTEND) { 7573 SDValue N020 = N02.getOperand(0); 7574 if (N020.getOpcode() == ISD::FMUL) 7575 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7576 N020.getOperand(0), N020.getOperand(1), 7577 N1); 7578 } 7579 } 7580 7581 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7582 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7583 // FIXME: This turns two single-precision and one double-precision 7584 // operation into two double-precision operations, which might not be 7585 // interesting for all targets, especially GPUs. 7586 auto FoldFAddFPExtFMAFMul = [&] ( 7587 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7588 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7589 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7590 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7591 DAG.getNode(PreferredFusedOpcode, SL, VT, 7592 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7593 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7594 Z)); 7595 }; 7596 if (N0.getOpcode() == ISD::FP_EXTEND) { 7597 SDValue N00 = N0.getOperand(0); 7598 if (N00.getOpcode() == PreferredFusedOpcode) { 7599 SDValue N002 = N00.getOperand(2); 7600 if (N002.getOpcode() == ISD::FMUL) 7601 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7602 N002.getOperand(0), N002.getOperand(1), 7603 N1); 7604 } 7605 } 7606 7607 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7608 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7609 if (N1.getOpcode() == PreferredFusedOpcode) { 7610 SDValue N12 = N1.getOperand(2); 7611 if (N12.getOpcode() == ISD::FP_EXTEND) { 7612 SDValue N120 = N12.getOperand(0); 7613 if (N120.getOpcode() == ISD::FMUL) 7614 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7615 N120.getOperand(0), N120.getOperand(1), 7616 N0); 7617 } 7618 } 7619 7620 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7621 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7622 // FIXME: This turns two single-precision and one double-precision 7623 // operation into two double-precision operations, which might not be 7624 // interesting for all targets, especially GPUs. 7625 if (N1.getOpcode() == ISD::FP_EXTEND) { 7626 SDValue N10 = N1.getOperand(0); 7627 if (N10.getOpcode() == PreferredFusedOpcode) { 7628 SDValue N102 = N10.getOperand(2); 7629 if (N102.getOpcode() == ISD::FMUL) 7630 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7631 N102.getOperand(0), N102.getOperand(1), 7632 N0); 7633 } 7634 } 7635 } 7636 } 7637 7638 return SDValue(); 7639 } 7640 7641 /// Try to perform FMA combining on a given FSUB node. 7642 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7643 SDValue N0 = N->getOperand(0); 7644 SDValue N1 = N->getOperand(1); 7645 EVT VT = N->getValueType(0); 7646 SDLoc SL(N); 7647 7648 const TargetOptions &Options = DAG.getTarget().Options; 7649 bool AllowFusion = 7650 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7651 7652 // Floating-point multiply-add with intermediate rounding. 7653 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7654 7655 // Floating-point multiply-add without intermediate rounding. 7656 bool HasFMA = 7657 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7658 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7659 7660 // No valid opcode, do not combine. 7661 if (!HasFMAD && !HasFMA) 7662 return SDValue(); 7663 7664 // Always prefer FMAD to FMA for precision. 7665 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7666 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7667 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7668 7669 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7670 if (N0.getOpcode() == ISD::FMUL && 7671 (Aggressive || N0->hasOneUse())) { 7672 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7673 N0.getOperand(0), N0.getOperand(1), 7674 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7675 } 7676 7677 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7678 // Note: Commutes FSUB operands. 7679 if (N1.getOpcode() == ISD::FMUL && 7680 (Aggressive || N1->hasOneUse())) 7681 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7682 DAG.getNode(ISD::FNEG, SL, VT, 7683 N1.getOperand(0)), 7684 N1.getOperand(1), N0); 7685 7686 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7687 if (N0.getOpcode() == ISD::FNEG && 7688 N0.getOperand(0).getOpcode() == ISD::FMUL && 7689 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7690 SDValue N00 = N0.getOperand(0).getOperand(0); 7691 SDValue N01 = N0.getOperand(0).getOperand(1); 7692 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7693 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7694 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7695 } 7696 7697 // Look through FP_EXTEND nodes to do more combining. 7698 if (AllowFusion && LookThroughFPExt) { 7699 // fold (fsub (fpext (fmul x, y)), z) 7700 // -> (fma (fpext x), (fpext y), (fneg z)) 7701 if (N0.getOpcode() == ISD::FP_EXTEND) { 7702 SDValue N00 = N0.getOperand(0); 7703 if (N00.getOpcode() == ISD::FMUL) 7704 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7705 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7706 N00.getOperand(0)), 7707 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7708 N00.getOperand(1)), 7709 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7710 } 7711 7712 // fold (fsub x, (fpext (fmul y, z))) 7713 // -> (fma (fneg (fpext y)), (fpext z), x) 7714 // Note: Commutes FSUB operands. 7715 if (N1.getOpcode() == ISD::FP_EXTEND) { 7716 SDValue N10 = N1.getOperand(0); 7717 if (N10.getOpcode() == ISD::FMUL) 7718 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7719 DAG.getNode(ISD::FNEG, SL, VT, 7720 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7721 N10.getOperand(0))), 7722 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7723 N10.getOperand(1)), 7724 N0); 7725 } 7726 7727 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7728 // -> (fneg (fma (fpext x), (fpext y), z)) 7729 // Note: This could be removed with appropriate canonicalization of the 7730 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7731 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7732 // from implementing the canonicalization in visitFSUB. 7733 if (N0.getOpcode() == ISD::FP_EXTEND) { 7734 SDValue N00 = N0.getOperand(0); 7735 if (N00.getOpcode() == ISD::FNEG) { 7736 SDValue N000 = N00.getOperand(0); 7737 if (N000.getOpcode() == ISD::FMUL) { 7738 return DAG.getNode(ISD::FNEG, SL, VT, 7739 DAG.getNode(PreferredFusedOpcode, SL, VT, 7740 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7741 N000.getOperand(0)), 7742 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7743 N000.getOperand(1)), 7744 N1)); 7745 } 7746 } 7747 } 7748 7749 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7750 // -> (fneg (fma (fpext x)), (fpext y), z) 7751 // Note: This could be removed with appropriate canonicalization of the 7752 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7753 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7754 // from implementing the canonicalization in visitFSUB. 7755 if (N0.getOpcode() == ISD::FNEG) { 7756 SDValue N00 = N0.getOperand(0); 7757 if (N00.getOpcode() == ISD::FP_EXTEND) { 7758 SDValue N000 = N00.getOperand(0); 7759 if (N000.getOpcode() == ISD::FMUL) { 7760 return DAG.getNode(ISD::FNEG, SL, VT, 7761 DAG.getNode(PreferredFusedOpcode, SL, VT, 7762 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7763 N000.getOperand(0)), 7764 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7765 N000.getOperand(1)), 7766 N1)); 7767 } 7768 } 7769 } 7770 7771 } 7772 7773 // More folding opportunities when target permits. 7774 if ((AllowFusion || HasFMAD) && Aggressive) { 7775 // fold (fsub (fma x, y, (fmul u, v)), z) 7776 // -> (fma x, y (fma u, v, (fneg z))) 7777 if (N0.getOpcode() == PreferredFusedOpcode && 7778 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7779 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7780 N0.getOperand(0), N0.getOperand(1), 7781 DAG.getNode(PreferredFusedOpcode, SL, VT, 7782 N0.getOperand(2).getOperand(0), 7783 N0.getOperand(2).getOperand(1), 7784 DAG.getNode(ISD::FNEG, SL, VT, 7785 N1))); 7786 } 7787 7788 // fold (fsub x, (fma y, z, (fmul u, v))) 7789 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7790 if (N1.getOpcode() == PreferredFusedOpcode && 7791 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7792 SDValue N20 = N1.getOperand(2).getOperand(0); 7793 SDValue N21 = N1.getOperand(2).getOperand(1); 7794 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7795 DAG.getNode(ISD::FNEG, SL, VT, 7796 N1.getOperand(0)), 7797 N1.getOperand(1), 7798 DAG.getNode(PreferredFusedOpcode, SL, VT, 7799 DAG.getNode(ISD::FNEG, SL, VT, N20), 7800 7801 N21, N0)); 7802 } 7803 7804 if (AllowFusion && LookThroughFPExt) { 7805 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7806 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 7807 if (N0.getOpcode() == PreferredFusedOpcode) { 7808 SDValue N02 = N0.getOperand(2); 7809 if (N02.getOpcode() == ISD::FP_EXTEND) { 7810 SDValue N020 = N02.getOperand(0); 7811 if (N020.getOpcode() == ISD::FMUL) 7812 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7813 N0.getOperand(0), N0.getOperand(1), 7814 DAG.getNode(PreferredFusedOpcode, SL, VT, 7815 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7816 N020.getOperand(0)), 7817 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7818 N020.getOperand(1)), 7819 DAG.getNode(ISD::FNEG, SL, VT, 7820 N1))); 7821 } 7822 } 7823 7824 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 7825 // -> (fma (fpext x), (fpext y), 7826 // (fma (fpext u), (fpext v), (fneg z))) 7827 // FIXME: This turns two single-precision and one double-precision 7828 // operation into two double-precision operations, which might not be 7829 // interesting for all targets, especially GPUs. 7830 if (N0.getOpcode() == ISD::FP_EXTEND) { 7831 SDValue N00 = N0.getOperand(0); 7832 if (N00.getOpcode() == PreferredFusedOpcode) { 7833 SDValue N002 = N00.getOperand(2); 7834 if (N002.getOpcode() == ISD::FMUL) 7835 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7836 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7837 N00.getOperand(0)), 7838 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7839 N00.getOperand(1)), 7840 DAG.getNode(PreferredFusedOpcode, SL, VT, 7841 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7842 N002.getOperand(0)), 7843 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7844 N002.getOperand(1)), 7845 DAG.getNode(ISD::FNEG, SL, VT, 7846 N1))); 7847 } 7848 } 7849 7850 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 7851 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 7852 if (N1.getOpcode() == PreferredFusedOpcode && 7853 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 7854 SDValue N120 = N1.getOperand(2).getOperand(0); 7855 if (N120.getOpcode() == ISD::FMUL) { 7856 SDValue N1200 = N120.getOperand(0); 7857 SDValue N1201 = N120.getOperand(1); 7858 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7859 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 7860 N1.getOperand(1), 7861 DAG.getNode(PreferredFusedOpcode, SL, VT, 7862 DAG.getNode(ISD::FNEG, SL, VT, 7863 DAG.getNode(ISD::FP_EXTEND, SL, 7864 VT, N1200)), 7865 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7866 N1201), 7867 N0)); 7868 } 7869 } 7870 7871 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 7872 // -> (fma (fneg (fpext y)), (fpext z), 7873 // (fma (fneg (fpext u)), (fpext v), x)) 7874 // FIXME: This turns two single-precision and one double-precision 7875 // operation into two double-precision operations, which might not be 7876 // interesting for all targets, especially GPUs. 7877 if (N1.getOpcode() == ISD::FP_EXTEND && 7878 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 7879 SDValue N100 = N1.getOperand(0).getOperand(0); 7880 SDValue N101 = N1.getOperand(0).getOperand(1); 7881 SDValue N102 = N1.getOperand(0).getOperand(2); 7882 if (N102.getOpcode() == ISD::FMUL) { 7883 SDValue N1020 = N102.getOperand(0); 7884 SDValue N1021 = N102.getOperand(1); 7885 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7886 DAG.getNode(ISD::FNEG, SL, VT, 7887 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7888 N100)), 7889 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 7890 DAG.getNode(PreferredFusedOpcode, SL, VT, 7891 DAG.getNode(ISD::FNEG, SL, VT, 7892 DAG.getNode(ISD::FP_EXTEND, SL, 7893 VT, N1020)), 7894 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7895 N1021), 7896 N0)); 7897 } 7898 } 7899 } 7900 } 7901 7902 return SDValue(); 7903 } 7904 7905 /// Try to perform FMA combining on a given FMUL node. 7906 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 7907 SDValue N0 = N->getOperand(0); 7908 SDValue N1 = N->getOperand(1); 7909 EVT VT = N->getValueType(0); 7910 SDLoc SL(N); 7911 7912 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 7913 7914 const TargetOptions &Options = DAG.getTarget().Options; 7915 bool AllowFusion = 7916 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7917 7918 // Floating-point multiply-add with intermediate rounding. 7919 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7920 7921 // Floating-point multiply-add without intermediate rounding. 7922 bool HasFMA = 7923 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7924 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7925 7926 // No valid opcode, do not combine. 7927 if (!HasFMAD && !HasFMA) 7928 return SDValue(); 7929 7930 // Always prefer FMAD to FMA for precision. 7931 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7932 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7933 7934 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 7935 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 7936 auto FuseFADD = [&](SDValue X, SDValue Y) { 7937 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 7938 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 7939 if (XC1 && XC1->isExactlyValue(+1.0)) 7940 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 7941 if (XC1 && XC1->isExactlyValue(-1.0)) 7942 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 7943 DAG.getNode(ISD::FNEG, SL, VT, Y)); 7944 } 7945 return SDValue(); 7946 }; 7947 7948 if (SDValue FMA = FuseFADD(N0, N1)) 7949 return FMA; 7950 if (SDValue FMA = FuseFADD(N1, N0)) 7951 return FMA; 7952 7953 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 7954 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 7955 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 7956 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 7957 auto FuseFSUB = [&](SDValue X, SDValue Y) { 7958 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 7959 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 7960 if (XC0 && XC0->isExactlyValue(+1.0)) 7961 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7962 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 7963 Y); 7964 if (XC0 && XC0->isExactlyValue(-1.0)) 7965 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7966 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 7967 DAG.getNode(ISD::FNEG, SL, VT, Y)); 7968 7969 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 7970 if (XC1 && XC1->isExactlyValue(+1.0)) 7971 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 7972 DAG.getNode(ISD::FNEG, SL, VT, Y)); 7973 if (XC1 && XC1->isExactlyValue(-1.0)) 7974 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 7975 } 7976 return SDValue(); 7977 }; 7978 7979 if (SDValue FMA = FuseFSUB(N0, N1)) 7980 return FMA; 7981 if (SDValue FMA = FuseFSUB(N1, N0)) 7982 return FMA; 7983 7984 return SDValue(); 7985 } 7986 7987 SDValue DAGCombiner::visitFADD(SDNode *N) { 7988 SDValue N0 = N->getOperand(0); 7989 SDValue N1 = N->getOperand(1); 7990 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 7991 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 7992 EVT VT = N->getValueType(0); 7993 SDLoc DL(N); 7994 const TargetOptions &Options = DAG.getTarget().Options; 7995 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 7996 7997 // fold vector ops 7998 if (VT.isVector()) 7999 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8000 return FoldedVOp; 8001 8002 // fold (fadd c1, c2) -> c1 + c2 8003 if (N0CFP && N1CFP) 8004 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8005 8006 // canonicalize constant to RHS 8007 if (N0CFP && !N1CFP) 8008 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8009 8010 // fold (fadd A, (fneg B)) -> (fsub A, B) 8011 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8012 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8013 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8014 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8015 8016 // fold (fadd (fneg A), B) -> (fsub B, A) 8017 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8018 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8019 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8020 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8021 8022 // If 'unsafe math' is enabled, fold lots of things. 8023 if (Options.UnsafeFPMath) { 8024 // No FP constant should be created after legalization as Instruction 8025 // Selection pass has a hard time dealing with FP constants. 8026 bool AllowNewConst = (Level < AfterLegalizeDAG); 8027 8028 // fold (fadd A, 0) -> A 8029 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8030 if (N1C->isZero()) 8031 return N0; 8032 8033 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8034 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8035 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8036 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8037 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8038 Flags), 8039 Flags); 8040 8041 // If allowed, fold (fadd (fneg x), x) -> 0.0 8042 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8043 return DAG.getConstantFP(0.0, DL, VT); 8044 8045 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8046 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8047 return DAG.getConstantFP(0.0, DL, VT); 8048 8049 // We can fold chains of FADD's of the same value into multiplications. 8050 // This transform is not safe in general because we are reducing the number 8051 // of rounding steps. 8052 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8053 if (N0.getOpcode() == ISD::FMUL) { 8054 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8055 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8056 8057 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8058 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8059 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8060 DAG.getConstantFP(1.0, DL, VT), Flags); 8061 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8062 } 8063 8064 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8065 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8066 N1.getOperand(0) == N1.getOperand(1) && 8067 N0.getOperand(0) == N1.getOperand(0)) { 8068 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8069 DAG.getConstantFP(2.0, DL, VT), Flags); 8070 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8071 } 8072 } 8073 8074 if (N1.getOpcode() == ISD::FMUL) { 8075 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8076 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8077 8078 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8079 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8080 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8081 DAG.getConstantFP(1.0, DL, VT), Flags); 8082 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8083 } 8084 8085 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8086 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8087 N0.getOperand(0) == N0.getOperand(1) && 8088 N1.getOperand(0) == N0.getOperand(0)) { 8089 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8090 DAG.getConstantFP(2.0, DL, VT), Flags); 8091 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8092 } 8093 } 8094 8095 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8096 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8097 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8098 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8099 (N0.getOperand(0) == N1)) { 8100 return DAG.getNode(ISD::FMUL, DL, VT, 8101 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8102 } 8103 } 8104 8105 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8106 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8107 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8108 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8109 N1.getOperand(0) == N0) { 8110 return DAG.getNode(ISD::FMUL, DL, VT, 8111 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8112 } 8113 } 8114 8115 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8116 if (AllowNewConst && 8117 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8118 N0.getOperand(0) == N0.getOperand(1) && 8119 N1.getOperand(0) == N1.getOperand(1) && 8120 N0.getOperand(0) == N1.getOperand(0)) { 8121 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8122 DAG.getConstantFP(4.0, DL, VT), Flags); 8123 } 8124 } 8125 } // enable-unsafe-fp-math 8126 8127 // FADD -> FMA combines: 8128 if (SDValue Fused = visitFADDForFMACombine(N)) { 8129 AddToWorklist(Fused.getNode()); 8130 return Fused; 8131 } 8132 8133 return SDValue(); 8134 } 8135 8136 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8137 SDValue N0 = N->getOperand(0); 8138 SDValue N1 = N->getOperand(1); 8139 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8140 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8141 EVT VT = N->getValueType(0); 8142 SDLoc dl(N); 8143 const TargetOptions &Options = DAG.getTarget().Options; 8144 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8145 8146 // fold vector ops 8147 if (VT.isVector()) 8148 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8149 return FoldedVOp; 8150 8151 // fold (fsub c1, c2) -> c1-c2 8152 if (N0CFP && N1CFP) 8153 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8154 8155 // fold (fsub A, (fneg B)) -> (fadd A, B) 8156 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8157 return DAG.getNode(ISD::FADD, dl, VT, N0, 8158 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8159 8160 // If 'unsafe math' is enabled, fold lots of things. 8161 if (Options.UnsafeFPMath) { 8162 // (fsub A, 0) -> A 8163 if (N1CFP && N1CFP->isZero()) 8164 return N0; 8165 8166 // (fsub 0, B) -> -B 8167 if (N0CFP && N0CFP->isZero()) { 8168 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8169 return GetNegatedExpression(N1, DAG, LegalOperations); 8170 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8171 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8172 } 8173 8174 // (fsub x, x) -> 0.0 8175 if (N0 == N1) 8176 return DAG.getConstantFP(0.0f, dl, VT); 8177 8178 // (fsub x, (fadd x, y)) -> (fneg y) 8179 // (fsub x, (fadd y, x)) -> (fneg y) 8180 if (N1.getOpcode() == ISD::FADD) { 8181 SDValue N10 = N1->getOperand(0); 8182 SDValue N11 = N1->getOperand(1); 8183 8184 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8185 return GetNegatedExpression(N11, DAG, LegalOperations); 8186 8187 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8188 return GetNegatedExpression(N10, DAG, LegalOperations); 8189 } 8190 } 8191 8192 // FSUB -> FMA combines: 8193 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8194 AddToWorklist(Fused.getNode()); 8195 return Fused; 8196 } 8197 8198 return SDValue(); 8199 } 8200 8201 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8202 SDValue N0 = N->getOperand(0); 8203 SDValue N1 = N->getOperand(1); 8204 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8205 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8206 EVT VT = N->getValueType(0); 8207 SDLoc DL(N); 8208 const TargetOptions &Options = DAG.getTarget().Options; 8209 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8210 8211 // fold vector ops 8212 if (VT.isVector()) { 8213 // This just handles C1 * C2 for vectors. Other vector folds are below. 8214 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8215 return FoldedVOp; 8216 } 8217 8218 // fold (fmul c1, c2) -> c1*c2 8219 if (N0CFP && N1CFP) 8220 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8221 8222 // canonicalize constant to RHS 8223 if (isConstantFPBuildVectorOrConstantFP(N0) && 8224 !isConstantFPBuildVectorOrConstantFP(N1)) 8225 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8226 8227 // fold (fmul A, 1.0) -> A 8228 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8229 return N0; 8230 8231 if (Options.UnsafeFPMath) { 8232 // fold (fmul A, 0) -> 0 8233 if (N1CFP && N1CFP->isZero()) 8234 return N1; 8235 8236 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8237 if (N0.getOpcode() == ISD::FMUL) { 8238 // Fold scalars or any vector constants (not just splats). 8239 // This fold is done in general by InstCombine, but extra fmul insts 8240 // may have been generated during lowering. 8241 SDValue N00 = N0.getOperand(0); 8242 SDValue N01 = N0.getOperand(1); 8243 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8244 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8245 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8246 8247 // Check 1: Make sure that the first operand of the inner multiply is NOT 8248 // a constant. Otherwise, we may induce infinite looping. 8249 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8250 // Check 2: Make sure that the second operand of the inner multiply and 8251 // the second operand of the outer multiply are constants. 8252 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8253 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8254 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8255 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8256 } 8257 } 8258 } 8259 8260 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8261 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8262 // during an early run of DAGCombiner can prevent folding with fmuls 8263 // inserted during lowering. 8264 if (N0.getOpcode() == ISD::FADD && 8265 (N0.getOperand(0) == N0.getOperand(1)) && 8266 N0.hasOneUse()) { 8267 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8268 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8269 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8270 } 8271 } 8272 8273 // fold (fmul X, 2.0) -> (fadd X, X) 8274 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8275 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8276 8277 // fold (fmul X, -1.0) -> (fneg X) 8278 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8279 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8280 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8281 8282 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8283 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8284 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8285 // Both can be negated for free, check to see if at least one is cheaper 8286 // negated. 8287 if (LHSNeg == 2 || RHSNeg == 2) 8288 return DAG.getNode(ISD::FMUL, DL, VT, 8289 GetNegatedExpression(N0, DAG, LegalOperations), 8290 GetNegatedExpression(N1, DAG, LegalOperations), 8291 Flags); 8292 } 8293 } 8294 8295 // FMUL -> FMA combines: 8296 if (SDValue Fused = visitFMULForFMACombine(N)) { 8297 AddToWorklist(Fused.getNode()); 8298 return Fused; 8299 } 8300 8301 return SDValue(); 8302 } 8303 8304 SDValue DAGCombiner::visitFMA(SDNode *N) { 8305 SDValue N0 = N->getOperand(0); 8306 SDValue N1 = N->getOperand(1); 8307 SDValue N2 = N->getOperand(2); 8308 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8309 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8310 EVT VT = N->getValueType(0); 8311 SDLoc dl(N); 8312 const TargetOptions &Options = DAG.getTarget().Options; 8313 8314 // Constant fold FMA. 8315 if (isa<ConstantFPSDNode>(N0) && 8316 isa<ConstantFPSDNode>(N1) && 8317 isa<ConstantFPSDNode>(N2)) { 8318 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8319 } 8320 8321 if (Options.UnsafeFPMath) { 8322 if (N0CFP && N0CFP->isZero()) 8323 return N2; 8324 if (N1CFP && N1CFP->isZero()) 8325 return N2; 8326 } 8327 // TODO: The FMA node should have flags that propagate to these nodes. 8328 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8329 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8330 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8331 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8332 8333 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8334 if (N0CFP && !N1CFP) 8335 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8336 8337 // TODO: FMA nodes should have flags that propagate to the created nodes. 8338 // For now, create a Flags object for use with all unsafe math transforms. 8339 SDNodeFlags Flags; 8340 Flags.setUnsafeAlgebra(true); 8341 8342 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8343 if (Options.UnsafeFPMath && N1CFP && 8344 N2.getOpcode() == ISD::FMUL && 8345 N0 == N2.getOperand(0) && 8346 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 8347 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8348 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8349 &Flags), &Flags); 8350 } 8351 8352 8353 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8354 if (Options.UnsafeFPMath && 8355 N0.getOpcode() == ISD::FMUL && N1CFP && 8356 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 8357 return DAG.getNode(ISD::FMA, dl, VT, 8358 N0.getOperand(0), 8359 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8360 &Flags), 8361 N2); 8362 } 8363 8364 // (fma x, 1, y) -> (fadd x, y) 8365 // (fma x, -1, y) -> (fadd (fneg x), y) 8366 if (N1CFP) { 8367 if (N1CFP->isExactlyValue(1.0)) 8368 // TODO: The FMA node should have flags that propagate to this node. 8369 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8370 8371 if (N1CFP->isExactlyValue(-1.0) && 8372 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8373 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8374 AddToWorklist(RHSNeg.getNode()); 8375 // TODO: The FMA node should have flags that propagate to this node. 8376 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8377 } 8378 } 8379 8380 // (fma x, c, x) -> (fmul x, (c+1)) 8381 if (Options.UnsafeFPMath && N1CFP && N0 == N2) { 8382 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8383 DAG.getNode(ISD::FADD, dl, VT, 8384 N1, DAG.getConstantFP(1.0, dl, VT), 8385 &Flags), &Flags); 8386 } 8387 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8388 if (Options.UnsafeFPMath && N1CFP && 8389 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8390 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8391 DAG.getNode(ISD::FADD, dl, VT, 8392 N1, DAG.getConstantFP(-1.0, dl, VT), 8393 &Flags), &Flags); 8394 } 8395 8396 return SDValue(); 8397 } 8398 8399 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8400 // reciprocal. 8401 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8402 // Notice that this is not always beneficial. One reason is different target 8403 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8404 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8405 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8406 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8407 if (!DAG.getTarget().Options.UnsafeFPMath) 8408 return SDValue(); 8409 8410 // Skip if current node is a reciprocal. 8411 SDValue N0 = N->getOperand(0); 8412 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8413 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8414 return SDValue(); 8415 8416 // Exit early if the target does not want this transform or if there can't 8417 // possibly be enough uses of the divisor to make the transform worthwhile. 8418 SDValue N1 = N->getOperand(1); 8419 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8420 if (!MinUses || N1->use_size() < MinUses) 8421 return SDValue(); 8422 8423 // Find all FDIV users of the same divisor. 8424 // Use a set because duplicates may be present in the user list. 8425 SetVector<SDNode *> Users; 8426 for (auto *U : N1->uses()) 8427 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) 8428 Users.insert(U); 8429 8430 // Now that we have the actual number of divisor uses, make sure it meets 8431 // the minimum threshold specified by the target. 8432 if (Users.size() < MinUses) 8433 return SDValue(); 8434 8435 EVT VT = N->getValueType(0); 8436 SDLoc DL(N); 8437 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8438 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8439 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8440 8441 // Dividend / Divisor -> Dividend * Reciprocal 8442 for (auto *U : Users) { 8443 SDValue Dividend = U->getOperand(0); 8444 if (Dividend != FPOne) { 8445 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8446 Reciprocal, Flags); 8447 CombineTo(U, NewNode); 8448 } else if (U != Reciprocal.getNode()) { 8449 // In the absence of fast-math-flags, this user node is always the 8450 // same node as Reciprocal, but with FMF they may be different nodes. 8451 CombineTo(U, Reciprocal); 8452 } 8453 } 8454 return SDValue(N, 0); // N was replaced. 8455 } 8456 8457 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8458 SDValue N0 = N->getOperand(0); 8459 SDValue N1 = N->getOperand(1); 8460 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8461 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8462 EVT VT = N->getValueType(0); 8463 SDLoc DL(N); 8464 const TargetOptions &Options = DAG.getTarget().Options; 8465 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8466 8467 // fold vector ops 8468 if (VT.isVector()) 8469 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8470 return FoldedVOp; 8471 8472 // fold (fdiv c1, c2) -> c1/c2 8473 if (N0CFP && N1CFP) 8474 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8475 8476 if (Options.UnsafeFPMath) { 8477 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8478 if (N1CFP) { 8479 // Compute the reciprocal 1.0 / c2. 8480 APFloat N1APF = N1CFP->getValueAPF(); 8481 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8482 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8483 // Only do the transform if the reciprocal is a legal fp immediate that 8484 // isn't too nasty (eg NaN, denormal, ...). 8485 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8486 (!LegalOperations || 8487 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8488 // backend)... we should handle this gracefully after Legalize. 8489 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8490 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8491 TLI.isFPImmLegal(Recip, VT))) 8492 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8493 DAG.getConstantFP(Recip, DL, VT), Flags); 8494 } 8495 8496 // If this FDIV is part of a reciprocal square root, it may be folded 8497 // into a target-specific square root estimate instruction. 8498 if (N1.getOpcode() == ISD::FSQRT) { 8499 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) { 8500 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8501 } 8502 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8503 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8504 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8505 Flags)) { 8506 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8507 AddToWorklist(RV.getNode()); 8508 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8509 } 8510 } else if (N1.getOpcode() == ISD::FP_ROUND && 8511 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8512 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8513 Flags)) { 8514 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8515 AddToWorklist(RV.getNode()); 8516 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8517 } 8518 } else if (N1.getOpcode() == ISD::FMUL) { 8519 // Look through an FMUL. Even though this won't remove the FDIV directly, 8520 // it's still worthwhile to get rid of the FSQRT if possible. 8521 SDValue SqrtOp; 8522 SDValue OtherOp; 8523 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8524 SqrtOp = N1.getOperand(0); 8525 OtherOp = N1.getOperand(1); 8526 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8527 SqrtOp = N1.getOperand(1); 8528 OtherOp = N1.getOperand(0); 8529 } 8530 if (SqrtOp.getNode()) { 8531 // We found a FSQRT, so try to make this fold: 8532 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8533 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8534 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8535 AddToWorklist(RV.getNode()); 8536 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8537 } 8538 } 8539 } 8540 8541 // Fold into a reciprocal estimate and multiply instead of a real divide. 8542 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8543 AddToWorklist(RV.getNode()); 8544 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8545 } 8546 } 8547 8548 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8549 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8550 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8551 // Both can be negated for free, check to see if at least one is cheaper 8552 // negated. 8553 if (LHSNeg == 2 || RHSNeg == 2) 8554 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8555 GetNegatedExpression(N0, DAG, LegalOperations), 8556 GetNegatedExpression(N1, DAG, LegalOperations), 8557 Flags); 8558 } 8559 } 8560 8561 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8562 return CombineRepeatedDivisors; 8563 8564 return SDValue(); 8565 } 8566 8567 SDValue DAGCombiner::visitFREM(SDNode *N) { 8568 SDValue N0 = N->getOperand(0); 8569 SDValue N1 = N->getOperand(1); 8570 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8571 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8572 EVT VT = N->getValueType(0); 8573 8574 // fold (frem c1, c2) -> fmod(c1,c2) 8575 if (N0CFP && N1CFP) 8576 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8577 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8578 8579 return SDValue(); 8580 } 8581 8582 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8583 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8584 return SDValue(); 8585 8586 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8587 // For now, create a Flags object for use with all unsafe math transforms. 8588 SDNodeFlags Flags; 8589 Flags.setUnsafeAlgebra(true); 8590 8591 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8592 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags); 8593 if (!RV) 8594 return SDValue(); 8595 8596 EVT VT = RV.getValueType(); 8597 SDLoc DL(N); 8598 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags); 8599 AddToWorklist(RV.getNode()); 8600 8601 // Unfortunately, RV is now NaN if the input was exactly 0. 8602 // Select out this case and force the answer to 0. 8603 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8604 EVT CCVT = getSetCCResultType(VT); 8605 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ); 8606 AddToWorklist(ZeroCmp.getNode()); 8607 AddToWorklist(RV.getNode()); 8608 8609 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 8610 ZeroCmp, Zero, RV); 8611 } 8612 8613 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8614 SDValue N0 = N->getOperand(0); 8615 SDValue N1 = N->getOperand(1); 8616 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8617 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8618 EVT VT = N->getValueType(0); 8619 8620 if (N0CFP && N1CFP) // Constant fold 8621 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8622 8623 if (N1CFP) { 8624 const APFloat& V = N1CFP->getValueAPF(); 8625 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8626 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8627 if (!V.isNegative()) { 8628 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8629 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8630 } else { 8631 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8632 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8633 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8634 } 8635 } 8636 8637 // copysign(fabs(x), y) -> copysign(x, y) 8638 // copysign(fneg(x), y) -> copysign(x, y) 8639 // copysign(copysign(x,z), y) -> copysign(x, y) 8640 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8641 N0.getOpcode() == ISD::FCOPYSIGN) 8642 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8643 N0.getOperand(0), N1); 8644 8645 // copysign(x, abs(y)) -> abs(x) 8646 if (N1.getOpcode() == ISD::FABS) 8647 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8648 8649 // copysign(x, copysign(y,z)) -> copysign(x, z) 8650 if (N1.getOpcode() == ISD::FCOPYSIGN) 8651 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8652 N0, N1.getOperand(1)); 8653 8654 // copysign(x, fp_extend(y)) -> copysign(x, y) 8655 // copysign(x, fp_round(y)) -> copysign(x, y) 8656 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 8657 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8658 N0, N1.getOperand(0)); 8659 8660 return SDValue(); 8661 } 8662 8663 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8664 SDValue N0 = N->getOperand(0); 8665 EVT VT = N->getValueType(0); 8666 EVT OpVT = N0.getValueType(); 8667 8668 // fold (sint_to_fp c1) -> c1fp 8669 if (isConstantIntBuildVectorOrConstantInt(N0) && 8670 // ...but only if the target supports immediate floating-point values 8671 (!LegalOperations || 8672 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8673 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8674 8675 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8676 // but UINT_TO_FP is legal on this target, try to convert. 8677 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8678 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8679 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8680 if (DAG.SignBitIsZero(N0)) 8681 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8682 } 8683 8684 // The next optimizations are desirable only if SELECT_CC can be lowered. 8685 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8686 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8687 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8688 !VT.isVector() && 8689 (!LegalOperations || 8690 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8691 SDLoc DL(N); 8692 SDValue Ops[] = 8693 { N0.getOperand(0), N0.getOperand(1), 8694 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8695 N0.getOperand(2) }; 8696 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8697 } 8698 8699 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8700 // (select_cc x, y, 1.0, 0.0,, cc) 8701 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8702 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8703 (!LegalOperations || 8704 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8705 SDLoc DL(N); 8706 SDValue Ops[] = 8707 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8708 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8709 N0.getOperand(0).getOperand(2) }; 8710 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8711 } 8712 } 8713 8714 return SDValue(); 8715 } 8716 8717 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8718 SDValue N0 = N->getOperand(0); 8719 EVT VT = N->getValueType(0); 8720 EVT OpVT = N0.getValueType(); 8721 8722 // fold (uint_to_fp c1) -> c1fp 8723 if (isConstantIntBuildVectorOrConstantInt(N0) && 8724 // ...but only if the target supports immediate floating-point values 8725 (!LegalOperations || 8726 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8727 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8728 8729 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8730 // but SINT_TO_FP is legal on this target, try to convert. 8731 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8732 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8733 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8734 if (DAG.SignBitIsZero(N0)) 8735 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8736 } 8737 8738 // The next optimizations are desirable only if SELECT_CC can be lowered. 8739 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8740 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8741 8742 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8743 (!LegalOperations || 8744 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8745 SDLoc DL(N); 8746 SDValue Ops[] = 8747 { N0.getOperand(0), N0.getOperand(1), 8748 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8749 N0.getOperand(2) }; 8750 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8751 } 8752 } 8753 8754 return SDValue(); 8755 } 8756 8757 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8758 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8759 SDValue N0 = N->getOperand(0); 8760 EVT VT = N->getValueType(0); 8761 8762 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8763 return SDValue(); 8764 8765 SDValue Src = N0.getOperand(0); 8766 EVT SrcVT = Src.getValueType(); 8767 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8768 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8769 8770 // We can safely assume the conversion won't overflow the output range, 8771 // because (for example) (uint8_t)18293.f is undefined behavior. 8772 8773 // Since we can assume the conversion won't overflow, our decision as to 8774 // whether the input will fit in the float should depend on the minimum 8775 // of the input range and output range. 8776 8777 // This means this is also safe for a signed input and unsigned output, since 8778 // a negative input would lead to undefined behavior. 8779 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8780 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8781 unsigned ActualSize = std::min(InputSize, OutputSize); 8782 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8783 8784 // We can only fold away the float conversion if the input range can be 8785 // represented exactly in the float range. 8786 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8787 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8788 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8789 : ISD::ZERO_EXTEND; 8790 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8791 } 8792 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8793 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8794 if (SrcVT == VT) 8795 return Src; 8796 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 8797 } 8798 return SDValue(); 8799 } 8800 8801 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8802 SDValue N0 = N->getOperand(0); 8803 EVT VT = N->getValueType(0); 8804 8805 // fold (fp_to_sint c1fp) -> c1 8806 if (isConstantFPBuildVectorOrConstantFP(N0)) 8807 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8808 8809 return FoldIntToFPToInt(N, DAG); 8810 } 8811 8812 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 8813 SDValue N0 = N->getOperand(0); 8814 EVT VT = N->getValueType(0); 8815 8816 // fold (fp_to_uint c1fp) -> c1 8817 if (isConstantFPBuildVectorOrConstantFP(N0)) 8818 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 8819 8820 return FoldIntToFPToInt(N, DAG); 8821 } 8822 8823 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 8824 SDValue N0 = N->getOperand(0); 8825 SDValue N1 = N->getOperand(1); 8826 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8827 EVT VT = N->getValueType(0); 8828 8829 // fold (fp_round c1fp) -> c1fp 8830 if (N0CFP) 8831 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 8832 8833 // fold (fp_round (fp_extend x)) -> x 8834 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 8835 return N0.getOperand(0); 8836 8837 // fold (fp_round (fp_round x)) -> (fp_round x) 8838 if (N0.getOpcode() == ISD::FP_ROUND) { 8839 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 8840 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 8841 // If the first fp_round isn't a value preserving truncation, it might 8842 // introduce a tie in the second fp_round, that wouldn't occur in the 8843 // single-step fp_round we want to fold to. 8844 // In other words, double rounding isn't the same as rounding. 8845 // Also, this is a value preserving truncation iff both fp_round's are. 8846 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 8847 SDLoc DL(N); 8848 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 8849 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 8850 } 8851 } 8852 8853 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 8854 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 8855 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 8856 N0.getOperand(0), N1); 8857 AddToWorklist(Tmp.getNode()); 8858 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8859 Tmp, N0.getOperand(1)); 8860 } 8861 8862 return SDValue(); 8863 } 8864 8865 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 8866 SDValue N0 = N->getOperand(0); 8867 EVT VT = N->getValueType(0); 8868 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8869 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8870 8871 // fold (fp_round_inreg c1fp) -> c1fp 8872 if (N0CFP && isTypeLegal(EVT)) { 8873 SDLoc DL(N); 8874 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 8875 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 8876 } 8877 8878 return SDValue(); 8879 } 8880 8881 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 8882 SDValue N0 = N->getOperand(0); 8883 EVT VT = N->getValueType(0); 8884 8885 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 8886 if (N->hasOneUse() && 8887 N->use_begin()->getOpcode() == ISD::FP_ROUND) 8888 return SDValue(); 8889 8890 // fold (fp_extend c1fp) -> c1fp 8891 if (isConstantFPBuildVectorOrConstantFP(N0)) 8892 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 8893 8894 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 8895 if (N0.getOpcode() == ISD::FP16_TO_FP && 8896 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 8897 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 8898 8899 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 8900 // value of X. 8901 if (N0.getOpcode() == ISD::FP_ROUND 8902 && N0.getNode()->getConstantOperandVal(1) == 1) { 8903 SDValue In = N0.getOperand(0); 8904 if (In.getValueType() == VT) return In; 8905 if (VT.bitsLT(In.getValueType())) 8906 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 8907 In, N0.getOperand(1)); 8908 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 8909 } 8910 8911 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 8912 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8913 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8914 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8915 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8916 LN0->getChain(), 8917 LN0->getBasePtr(), N0.getValueType(), 8918 LN0->getMemOperand()); 8919 CombineTo(N, ExtLoad); 8920 CombineTo(N0.getNode(), 8921 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 8922 N0.getValueType(), ExtLoad, 8923 DAG.getIntPtrConstant(1, SDLoc(N0))), 8924 ExtLoad.getValue(1)); 8925 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8926 } 8927 8928 return SDValue(); 8929 } 8930 8931 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 8932 SDValue N0 = N->getOperand(0); 8933 EVT VT = N->getValueType(0); 8934 8935 // fold (fceil c1) -> fceil(c1) 8936 if (isConstantFPBuildVectorOrConstantFP(N0)) 8937 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 8938 8939 return SDValue(); 8940 } 8941 8942 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 8943 SDValue N0 = N->getOperand(0); 8944 EVT VT = N->getValueType(0); 8945 8946 // fold (ftrunc c1) -> ftrunc(c1) 8947 if (isConstantFPBuildVectorOrConstantFP(N0)) 8948 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 8949 8950 return SDValue(); 8951 } 8952 8953 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 8954 SDValue N0 = N->getOperand(0); 8955 EVT VT = N->getValueType(0); 8956 8957 // fold (ffloor c1) -> ffloor(c1) 8958 if (isConstantFPBuildVectorOrConstantFP(N0)) 8959 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 8960 8961 return SDValue(); 8962 } 8963 8964 // FIXME: FNEG and FABS have a lot in common; refactor. 8965 SDValue DAGCombiner::visitFNEG(SDNode *N) { 8966 SDValue N0 = N->getOperand(0); 8967 EVT VT = N->getValueType(0); 8968 8969 // Constant fold FNEG. 8970 if (isConstantFPBuildVectorOrConstantFP(N0)) 8971 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 8972 8973 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 8974 &DAG.getTarget().Options)) 8975 return GetNegatedExpression(N0, DAG, LegalOperations); 8976 8977 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 8978 // constant pool values. 8979 if (!TLI.isFNegFree(VT) && 8980 N0.getOpcode() == ISD::BITCAST && 8981 N0.getNode()->hasOneUse()) { 8982 SDValue Int = N0.getOperand(0); 8983 EVT IntVT = Int.getValueType(); 8984 if (IntVT.isInteger() && !IntVT.isVector()) { 8985 APInt SignMask; 8986 if (N0.getValueType().isVector()) { 8987 // For a vector, get a mask such as 0x80... per scalar element 8988 // and splat it. 8989 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8990 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8991 } else { 8992 // For a scalar, just generate 0x80... 8993 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 8994 } 8995 SDLoc DL0(N0); 8996 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 8997 DAG.getConstant(SignMask, DL0, IntVT)); 8998 AddToWorklist(Int.getNode()); 8999 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 9000 } 9001 } 9002 9003 // (fneg (fmul c, x)) -> (fmul -c, x) 9004 if (N0.getOpcode() == ISD::FMUL && 9005 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9006 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9007 if (CFP1) { 9008 APFloat CVal = CFP1->getValueAPF(); 9009 CVal.changeSign(); 9010 if (Level >= AfterLegalizeDAG && 9011 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 9012 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 9013 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9014 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9015 N0.getOperand(1)), 9016 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9017 } 9018 } 9019 9020 return SDValue(); 9021 } 9022 9023 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9024 SDValue N0 = N->getOperand(0); 9025 SDValue N1 = N->getOperand(1); 9026 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9027 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9028 9029 if (N0CFP && N1CFP) { 9030 const APFloat &C0 = N0CFP->getValueAPF(); 9031 const APFloat &C1 = N1CFP->getValueAPF(); 9032 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0)); 9033 } 9034 9035 if (N0CFP) { 9036 EVT VT = N->getValueType(0); 9037 // Canonicalize to constant on RHS. 9038 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9039 } 9040 9041 return SDValue(); 9042 } 9043 9044 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9045 SDValue N0 = N->getOperand(0); 9046 SDValue N1 = N->getOperand(1); 9047 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9048 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9049 9050 if (N0CFP && N1CFP) { 9051 const APFloat &C0 = N0CFP->getValueAPF(); 9052 const APFloat &C1 = N1CFP->getValueAPF(); 9053 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0)); 9054 } 9055 9056 if (N0CFP) { 9057 EVT VT = N->getValueType(0); 9058 // Canonicalize to constant on RHS. 9059 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9060 } 9061 9062 return SDValue(); 9063 } 9064 9065 SDValue DAGCombiner::visitFABS(SDNode *N) { 9066 SDValue N0 = N->getOperand(0); 9067 EVT VT = N->getValueType(0); 9068 9069 // fold (fabs c1) -> fabs(c1) 9070 if (isConstantFPBuildVectorOrConstantFP(N0)) 9071 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9072 9073 // fold (fabs (fabs x)) -> (fabs x) 9074 if (N0.getOpcode() == ISD::FABS) 9075 return N->getOperand(0); 9076 9077 // fold (fabs (fneg x)) -> (fabs x) 9078 // fold (fabs (fcopysign x, y)) -> (fabs x) 9079 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9080 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9081 9082 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9083 // constant pool values. 9084 if (!TLI.isFAbsFree(VT) && 9085 N0.getOpcode() == ISD::BITCAST && 9086 N0.getNode()->hasOneUse()) { 9087 SDValue Int = N0.getOperand(0); 9088 EVT IntVT = Int.getValueType(); 9089 if (IntVT.isInteger() && !IntVT.isVector()) { 9090 APInt SignMask; 9091 if (N0.getValueType().isVector()) { 9092 // For a vector, get a mask such as 0x7f... per scalar element 9093 // and splat it. 9094 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9095 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9096 } else { 9097 // For a scalar, just generate 0x7f... 9098 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9099 } 9100 SDLoc DL(N0); 9101 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9102 DAG.getConstant(SignMask, DL, IntVT)); 9103 AddToWorklist(Int.getNode()); 9104 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 9105 } 9106 } 9107 9108 return SDValue(); 9109 } 9110 9111 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9112 SDValue Chain = N->getOperand(0); 9113 SDValue N1 = N->getOperand(1); 9114 SDValue N2 = N->getOperand(2); 9115 9116 // If N is a constant we could fold this into a fallthrough or unconditional 9117 // branch. However that doesn't happen very often in normal code, because 9118 // Instcombine/SimplifyCFG should have handled the available opportunities. 9119 // If we did this folding here, it would be necessary to update the 9120 // MachineBasicBlock CFG, which is awkward. 9121 9122 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9123 // on the target. 9124 if (N1.getOpcode() == ISD::SETCC && 9125 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9126 N1.getOperand(0).getValueType())) { 9127 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9128 Chain, N1.getOperand(2), 9129 N1.getOperand(0), N1.getOperand(1), N2); 9130 } 9131 9132 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9133 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9134 (N1.getOperand(0).hasOneUse() && 9135 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9136 SDNode *Trunc = nullptr; 9137 if (N1.getOpcode() == ISD::TRUNCATE) { 9138 // Look pass the truncate. 9139 Trunc = N1.getNode(); 9140 N1 = N1.getOperand(0); 9141 } 9142 9143 // Match this pattern so that we can generate simpler code: 9144 // 9145 // %a = ... 9146 // %b = and i32 %a, 2 9147 // %c = srl i32 %b, 1 9148 // brcond i32 %c ... 9149 // 9150 // into 9151 // 9152 // %a = ... 9153 // %b = and i32 %a, 2 9154 // %c = setcc eq %b, 0 9155 // brcond %c ... 9156 // 9157 // This applies only when the AND constant value has one bit set and the 9158 // SRL constant is equal to the log2 of the AND constant. The back-end is 9159 // smart enough to convert the result into a TEST/JMP sequence. 9160 SDValue Op0 = N1.getOperand(0); 9161 SDValue Op1 = N1.getOperand(1); 9162 9163 if (Op0.getOpcode() == ISD::AND && 9164 Op1.getOpcode() == ISD::Constant) { 9165 SDValue AndOp1 = Op0.getOperand(1); 9166 9167 if (AndOp1.getOpcode() == ISD::Constant) { 9168 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9169 9170 if (AndConst.isPowerOf2() && 9171 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9172 SDLoc DL(N); 9173 SDValue SetCC = 9174 DAG.getSetCC(DL, 9175 getSetCCResultType(Op0.getValueType()), 9176 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9177 ISD::SETNE); 9178 9179 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9180 MVT::Other, Chain, SetCC, N2); 9181 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9182 // will convert it back to (X & C1) >> C2. 9183 CombineTo(N, NewBRCond, false); 9184 // Truncate is dead. 9185 if (Trunc) 9186 deleteAndRecombine(Trunc); 9187 // Replace the uses of SRL with SETCC 9188 WorklistRemover DeadNodes(*this); 9189 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9190 deleteAndRecombine(N1.getNode()); 9191 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9192 } 9193 } 9194 } 9195 9196 if (Trunc) 9197 // Restore N1 if the above transformation doesn't match. 9198 N1 = N->getOperand(1); 9199 } 9200 9201 // Transform br(xor(x, y)) -> br(x != y) 9202 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9203 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9204 SDNode *TheXor = N1.getNode(); 9205 SDValue Op0 = TheXor->getOperand(0); 9206 SDValue Op1 = TheXor->getOperand(1); 9207 if (Op0.getOpcode() == Op1.getOpcode()) { 9208 // Avoid missing important xor optimizations. 9209 if (SDValue Tmp = visitXOR(TheXor)) { 9210 if (Tmp.getNode() != TheXor) { 9211 DEBUG(dbgs() << "\nReplacing.8 "; 9212 TheXor->dump(&DAG); 9213 dbgs() << "\nWith: "; 9214 Tmp.getNode()->dump(&DAG); 9215 dbgs() << '\n'); 9216 WorklistRemover DeadNodes(*this); 9217 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9218 deleteAndRecombine(TheXor); 9219 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9220 MVT::Other, Chain, Tmp, N2); 9221 } 9222 9223 // visitXOR has changed XOR's operands or replaced the XOR completely, 9224 // bail out. 9225 return SDValue(N, 0); 9226 } 9227 } 9228 9229 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9230 bool Equal = false; 9231 if (isOneConstant(Op0) && Op0.hasOneUse() && 9232 Op0.getOpcode() == ISD::XOR) { 9233 TheXor = Op0.getNode(); 9234 Equal = true; 9235 } 9236 9237 EVT SetCCVT = N1.getValueType(); 9238 if (LegalTypes) 9239 SetCCVT = getSetCCResultType(SetCCVT); 9240 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9241 SetCCVT, 9242 Op0, Op1, 9243 Equal ? ISD::SETEQ : ISD::SETNE); 9244 // Replace the uses of XOR with SETCC 9245 WorklistRemover DeadNodes(*this); 9246 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9247 deleteAndRecombine(N1.getNode()); 9248 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9249 MVT::Other, Chain, SetCC, N2); 9250 } 9251 } 9252 9253 return SDValue(); 9254 } 9255 9256 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9257 // 9258 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9259 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9260 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9261 9262 // If N is a constant we could fold this into a fallthrough or unconditional 9263 // branch. However that doesn't happen very often in normal code, because 9264 // Instcombine/SimplifyCFG should have handled the available opportunities. 9265 // If we did this folding here, it would be necessary to update the 9266 // MachineBasicBlock CFG, which is awkward. 9267 9268 // Use SimplifySetCC to simplify SETCC's. 9269 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9270 CondLHS, CondRHS, CC->get(), SDLoc(N), 9271 false); 9272 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9273 9274 // fold to a simpler setcc 9275 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9276 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9277 N->getOperand(0), Simp.getOperand(2), 9278 Simp.getOperand(0), Simp.getOperand(1), 9279 N->getOperand(4)); 9280 9281 return SDValue(); 9282 } 9283 9284 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9285 /// and that N may be folded in the load / store addressing mode. 9286 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9287 SelectionDAG &DAG, 9288 const TargetLowering &TLI) { 9289 EVT VT; 9290 unsigned AS; 9291 9292 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9293 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9294 return false; 9295 VT = LD->getMemoryVT(); 9296 AS = LD->getAddressSpace(); 9297 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9298 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9299 return false; 9300 VT = ST->getMemoryVT(); 9301 AS = ST->getAddressSpace(); 9302 } else 9303 return false; 9304 9305 TargetLowering::AddrMode AM; 9306 if (N->getOpcode() == ISD::ADD) { 9307 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9308 if (Offset) 9309 // [reg +/- imm] 9310 AM.BaseOffs = Offset->getSExtValue(); 9311 else 9312 // [reg +/- reg] 9313 AM.Scale = 1; 9314 } else if (N->getOpcode() == ISD::SUB) { 9315 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9316 if (Offset) 9317 // [reg +/- imm] 9318 AM.BaseOffs = -Offset->getSExtValue(); 9319 else 9320 // [reg +/- reg] 9321 AM.Scale = 1; 9322 } else 9323 return false; 9324 9325 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9326 VT.getTypeForEVT(*DAG.getContext()), AS); 9327 } 9328 9329 /// Try turning a load/store into a pre-indexed load/store when the base 9330 /// pointer is an add or subtract and it has other uses besides the load/store. 9331 /// After the transformation, the new indexed load/store has effectively folded 9332 /// the add/subtract in and all of its other uses are redirected to the 9333 /// new load/store. 9334 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9335 if (Level < AfterLegalizeDAG) 9336 return false; 9337 9338 bool isLoad = true; 9339 SDValue Ptr; 9340 EVT VT; 9341 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9342 if (LD->isIndexed()) 9343 return false; 9344 VT = LD->getMemoryVT(); 9345 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9346 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9347 return false; 9348 Ptr = LD->getBasePtr(); 9349 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9350 if (ST->isIndexed()) 9351 return false; 9352 VT = ST->getMemoryVT(); 9353 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9354 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9355 return false; 9356 Ptr = ST->getBasePtr(); 9357 isLoad = false; 9358 } else { 9359 return false; 9360 } 9361 9362 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9363 // out. There is no reason to make this a preinc/predec. 9364 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9365 Ptr.getNode()->hasOneUse()) 9366 return false; 9367 9368 // Ask the target to do addressing mode selection. 9369 SDValue BasePtr; 9370 SDValue Offset; 9371 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9372 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9373 return false; 9374 9375 // Backends without true r+i pre-indexed forms may need to pass a 9376 // constant base with a variable offset so that constant coercion 9377 // will work with the patterns in canonical form. 9378 bool Swapped = false; 9379 if (isa<ConstantSDNode>(BasePtr)) { 9380 std::swap(BasePtr, Offset); 9381 Swapped = true; 9382 } 9383 9384 // Don't create a indexed load / store with zero offset. 9385 if (isNullConstant(Offset)) 9386 return false; 9387 9388 // Try turning it into a pre-indexed load / store except when: 9389 // 1) The new base ptr is a frame index. 9390 // 2) If N is a store and the new base ptr is either the same as or is a 9391 // predecessor of the value being stored. 9392 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9393 // that would create a cycle. 9394 // 4) All uses are load / store ops that use it as old base ptr. 9395 9396 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9397 // (plus the implicit offset) to a register to preinc anyway. 9398 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9399 return false; 9400 9401 // Check #2. 9402 if (!isLoad) { 9403 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9404 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9405 return false; 9406 } 9407 9408 // If the offset is a constant, there may be other adds of constants that 9409 // can be folded with this one. We should do this to avoid having to keep 9410 // a copy of the original base pointer. 9411 SmallVector<SDNode *, 16> OtherUses; 9412 if (isa<ConstantSDNode>(Offset)) 9413 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9414 UE = BasePtr.getNode()->use_end(); 9415 UI != UE; ++UI) { 9416 SDUse &Use = UI.getUse(); 9417 // Skip the use that is Ptr and uses of other results from BasePtr's 9418 // node (important for nodes that return multiple results). 9419 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9420 continue; 9421 9422 if (Use.getUser()->isPredecessorOf(N)) 9423 continue; 9424 9425 if (Use.getUser()->getOpcode() != ISD::ADD && 9426 Use.getUser()->getOpcode() != ISD::SUB) { 9427 OtherUses.clear(); 9428 break; 9429 } 9430 9431 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9432 if (!isa<ConstantSDNode>(Op1)) { 9433 OtherUses.clear(); 9434 break; 9435 } 9436 9437 // FIXME: In some cases, we can be smarter about this. 9438 if (Op1.getValueType() != Offset.getValueType()) { 9439 OtherUses.clear(); 9440 break; 9441 } 9442 9443 OtherUses.push_back(Use.getUser()); 9444 } 9445 9446 if (Swapped) 9447 std::swap(BasePtr, Offset); 9448 9449 // Now check for #3 and #4. 9450 bool RealUse = false; 9451 9452 // Caches for hasPredecessorHelper 9453 SmallPtrSet<const SDNode *, 32> Visited; 9454 SmallVector<const SDNode *, 16> Worklist; 9455 9456 for (SDNode *Use : Ptr.getNode()->uses()) { 9457 if (Use == N) 9458 continue; 9459 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 9460 return false; 9461 9462 // If Ptr may be folded in addressing mode of other use, then it's 9463 // not profitable to do this transformation. 9464 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9465 RealUse = true; 9466 } 9467 9468 if (!RealUse) 9469 return false; 9470 9471 SDValue Result; 9472 if (isLoad) 9473 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9474 BasePtr, Offset, AM); 9475 else 9476 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9477 BasePtr, Offset, AM); 9478 ++PreIndexedNodes; 9479 ++NodesCombined; 9480 DEBUG(dbgs() << "\nReplacing.4 "; 9481 N->dump(&DAG); 9482 dbgs() << "\nWith: "; 9483 Result.getNode()->dump(&DAG); 9484 dbgs() << '\n'); 9485 WorklistRemover DeadNodes(*this); 9486 if (isLoad) { 9487 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9488 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9489 } else { 9490 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9491 } 9492 9493 // Finally, since the node is now dead, remove it from the graph. 9494 deleteAndRecombine(N); 9495 9496 if (Swapped) 9497 std::swap(BasePtr, Offset); 9498 9499 // Replace other uses of BasePtr that can be updated to use Ptr 9500 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9501 unsigned OffsetIdx = 1; 9502 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9503 OffsetIdx = 0; 9504 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9505 BasePtr.getNode() && "Expected BasePtr operand"); 9506 9507 // We need to replace ptr0 in the following expression: 9508 // x0 * offset0 + y0 * ptr0 = t0 9509 // knowing that 9510 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9511 // 9512 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9513 // indexed load/store and the expresion that needs to be re-written. 9514 // 9515 // Therefore, we have: 9516 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9517 9518 ConstantSDNode *CN = 9519 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9520 int X0, X1, Y0, Y1; 9521 APInt Offset0 = CN->getAPIntValue(); 9522 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9523 9524 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9525 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9526 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9527 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9528 9529 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9530 9531 APInt CNV = Offset0; 9532 if (X0 < 0) CNV = -CNV; 9533 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9534 else CNV = CNV - Offset1; 9535 9536 SDLoc DL(OtherUses[i]); 9537 9538 // We can now generate the new expression. 9539 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9540 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9541 9542 SDValue NewUse = DAG.getNode(Opcode, 9543 DL, 9544 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9545 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9546 deleteAndRecombine(OtherUses[i]); 9547 } 9548 9549 // Replace the uses of Ptr with uses of the updated base value. 9550 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9551 deleteAndRecombine(Ptr.getNode()); 9552 9553 return true; 9554 } 9555 9556 /// Try to combine a load/store with a add/sub of the base pointer node into a 9557 /// post-indexed load/store. The transformation folded the add/subtract into the 9558 /// new indexed load/store effectively and all of its uses are redirected to the 9559 /// new load/store. 9560 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9561 if (Level < AfterLegalizeDAG) 9562 return false; 9563 9564 bool isLoad = true; 9565 SDValue Ptr; 9566 EVT VT; 9567 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9568 if (LD->isIndexed()) 9569 return false; 9570 VT = LD->getMemoryVT(); 9571 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9572 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9573 return false; 9574 Ptr = LD->getBasePtr(); 9575 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9576 if (ST->isIndexed()) 9577 return false; 9578 VT = ST->getMemoryVT(); 9579 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9580 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9581 return false; 9582 Ptr = ST->getBasePtr(); 9583 isLoad = false; 9584 } else { 9585 return false; 9586 } 9587 9588 if (Ptr.getNode()->hasOneUse()) 9589 return false; 9590 9591 for (SDNode *Op : Ptr.getNode()->uses()) { 9592 if (Op == N || 9593 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9594 continue; 9595 9596 SDValue BasePtr; 9597 SDValue Offset; 9598 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9599 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9600 // Don't create a indexed load / store with zero offset. 9601 if (isNullConstant(Offset)) 9602 continue; 9603 9604 // Try turning it into a post-indexed load / store except when 9605 // 1) All uses are load / store ops that use it as base ptr (and 9606 // it may be folded as addressing mmode). 9607 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9608 // nor a successor of N. Otherwise, if Op is folded that would 9609 // create a cycle. 9610 9611 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9612 continue; 9613 9614 // Check for #1. 9615 bool TryNext = false; 9616 for (SDNode *Use : BasePtr.getNode()->uses()) { 9617 if (Use == Ptr.getNode()) 9618 continue; 9619 9620 // If all the uses are load / store addresses, then don't do the 9621 // transformation. 9622 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9623 bool RealUse = false; 9624 for (SDNode *UseUse : Use->uses()) { 9625 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9626 RealUse = true; 9627 } 9628 9629 if (!RealUse) { 9630 TryNext = true; 9631 break; 9632 } 9633 } 9634 } 9635 9636 if (TryNext) 9637 continue; 9638 9639 // Check for #2 9640 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9641 SDValue Result = isLoad 9642 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9643 BasePtr, Offset, AM) 9644 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9645 BasePtr, Offset, AM); 9646 ++PostIndexedNodes; 9647 ++NodesCombined; 9648 DEBUG(dbgs() << "\nReplacing.5 "; 9649 N->dump(&DAG); 9650 dbgs() << "\nWith: "; 9651 Result.getNode()->dump(&DAG); 9652 dbgs() << '\n'); 9653 WorklistRemover DeadNodes(*this); 9654 if (isLoad) { 9655 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9656 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9657 } else { 9658 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9659 } 9660 9661 // Finally, since the node is now dead, remove it from the graph. 9662 deleteAndRecombine(N); 9663 9664 // Replace the uses of Use with uses of the updated base value. 9665 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9666 Result.getValue(isLoad ? 1 : 0)); 9667 deleteAndRecombine(Op); 9668 return true; 9669 } 9670 } 9671 } 9672 9673 return false; 9674 } 9675 9676 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9677 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9678 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9679 assert(AM != ISD::UNINDEXED); 9680 SDValue BP = LD->getOperand(1); 9681 SDValue Inc = LD->getOperand(2); 9682 9683 // Some backends use TargetConstants for load offsets, but don't expect 9684 // TargetConstants in general ADD nodes. We can convert these constants into 9685 // regular Constants (if the constant is not opaque). 9686 assert((Inc.getOpcode() != ISD::TargetConstant || 9687 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9688 "Cannot split out indexing using opaque target constants"); 9689 if (Inc.getOpcode() == ISD::TargetConstant) { 9690 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9691 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9692 ConstInc->getValueType(0)); 9693 } 9694 9695 unsigned Opc = 9696 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9697 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9698 } 9699 9700 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9701 LoadSDNode *LD = cast<LoadSDNode>(N); 9702 SDValue Chain = LD->getChain(); 9703 SDValue Ptr = LD->getBasePtr(); 9704 9705 // If load is not volatile and there are no uses of the loaded value (and 9706 // the updated indexed value in case of indexed loads), change uses of the 9707 // chain value into uses of the chain input (i.e. delete the dead load). 9708 if (!LD->isVolatile()) { 9709 if (N->getValueType(1) == MVT::Other) { 9710 // Unindexed loads. 9711 if (!N->hasAnyUseOfValue(0)) { 9712 // It's not safe to use the two value CombineTo variant here. e.g. 9713 // v1, chain2 = load chain1, loc 9714 // v2, chain3 = load chain2, loc 9715 // v3 = add v2, c 9716 // Now we replace use of chain2 with chain1. This makes the second load 9717 // isomorphic to the one we are deleting, and thus makes this load live. 9718 DEBUG(dbgs() << "\nReplacing.6 "; 9719 N->dump(&DAG); 9720 dbgs() << "\nWith chain: "; 9721 Chain.getNode()->dump(&DAG); 9722 dbgs() << "\n"); 9723 WorklistRemover DeadNodes(*this); 9724 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9725 9726 if (N->use_empty()) 9727 deleteAndRecombine(N); 9728 9729 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9730 } 9731 } else { 9732 // Indexed loads. 9733 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9734 9735 // If this load has an opaque TargetConstant offset, then we cannot split 9736 // the indexing into an add/sub directly (that TargetConstant may not be 9737 // valid for a different type of node, and we cannot convert an opaque 9738 // target constant into a regular constant). 9739 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9740 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9741 9742 if (!N->hasAnyUseOfValue(0) && 9743 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9744 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9745 SDValue Index; 9746 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9747 Index = SplitIndexingFromLoad(LD); 9748 // Try to fold the base pointer arithmetic into subsequent loads and 9749 // stores. 9750 AddUsersToWorklist(N); 9751 } else 9752 Index = DAG.getUNDEF(N->getValueType(1)); 9753 DEBUG(dbgs() << "\nReplacing.7 "; 9754 N->dump(&DAG); 9755 dbgs() << "\nWith: "; 9756 Undef.getNode()->dump(&DAG); 9757 dbgs() << " and 2 other values\n"); 9758 WorklistRemover DeadNodes(*this); 9759 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9760 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9761 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9762 deleteAndRecombine(N); 9763 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9764 } 9765 } 9766 } 9767 9768 // If this load is directly stored, replace the load value with the stored 9769 // value. 9770 // TODO: Handle store large -> read small portion. 9771 // TODO: Handle TRUNCSTORE/LOADEXT 9772 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9773 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9774 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9775 if (PrevST->getBasePtr() == Ptr && 9776 PrevST->getValue().getValueType() == N->getValueType(0)) 9777 return CombineTo(N, Chain.getOperand(1), Chain); 9778 } 9779 } 9780 9781 // Try to infer better alignment information than the load already has. 9782 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9783 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9784 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9785 SDValue NewLoad = 9786 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9787 LD->getValueType(0), 9788 Chain, Ptr, LD->getPointerInfo(), 9789 LD->getMemoryVT(), 9790 LD->isVolatile(), LD->isNonTemporal(), 9791 LD->isInvariant(), Align, LD->getAAInfo()); 9792 if (NewLoad.getNode() != N) 9793 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9794 } 9795 } 9796 } 9797 9798 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 9799 : DAG.getSubtarget().useAA(); 9800 #ifndef NDEBUG 9801 if (CombinerAAOnlyFunc.getNumOccurrences() && 9802 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9803 UseAA = false; 9804 #endif 9805 if (UseAA && LD->isUnindexed()) { 9806 // Walk up chain skipping non-aliasing memory nodes. 9807 SDValue BetterChain = FindBetterChain(N, Chain); 9808 9809 // If there is a better chain. 9810 if (Chain != BetterChain) { 9811 SDValue ReplLoad; 9812 9813 // Replace the chain to void dependency. 9814 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 9815 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 9816 BetterChain, Ptr, LD->getMemOperand()); 9817 } else { 9818 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 9819 LD->getValueType(0), 9820 BetterChain, Ptr, LD->getMemoryVT(), 9821 LD->getMemOperand()); 9822 } 9823 9824 // Create token factor to keep old chain connected. 9825 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9826 MVT::Other, Chain, ReplLoad.getValue(1)); 9827 9828 // Make sure the new and old chains are cleaned up. 9829 AddToWorklist(Token.getNode()); 9830 9831 // Replace uses with load result and token factor. Don't add users 9832 // to work list. 9833 return CombineTo(N, ReplLoad.getValue(0), Token, false); 9834 } 9835 } 9836 9837 // Try transforming N to an indexed load. 9838 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9839 return SDValue(N, 0); 9840 9841 // Try to slice up N to more direct loads if the slices are mapped to 9842 // different register banks or pairing can take place. 9843 if (SliceUpLoad(N)) 9844 return SDValue(N, 0); 9845 9846 return SDValue(); 9847 } 9848 9849 namespace { 9850 /// \brief Helper structure used to slice a load in smaller loads. 9851 /// Basically a slice is obtained from the following sequence: 9852 /// Origin = load Ty1, Base 9853 /// Shift = srl Ty1 Origin, CstTy Amount 9854 /// Inst = trunc Shift to Ty2 9855 /// 9856 /// Then, it will be rewriten into: 9857 /// Slice = load SliceTy, Base + SliceOffset 9858 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 9859 /// 9860 /// SliceTy is deduced from the number of bits that are actually used to 9861 /// build Inst. 9862 struct LoadedSlice { 9863 /// \brief Helper structure used to compute the cost of a slice. 9864 struct Cost { 9865 /// Are we optimizing for code size. 9866 bool ForCodeSize; 9867 /// Various cost. 9868 unsigned Loads; 9869 unsigned Truncates; 9870 unsigned CrossRegisterBanksCopies; 9871 unsigned ZExts; 9872 unsigned Shift; 9873 9874 Cost(bool ForCodeSize = false) 9875 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 9876 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 9877 9878 /// \brief Get the cost of one isolated slice. 9879 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 9880 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 9881 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 9882 EVT TruncType = LS.Inst->getValueType(0); 9883 EVT LoadedType = LS.getLoadedType(); 9884 if (TruncType != LoadedType && 9885 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 9886 ZExts = 1; 9887 } 9888 9889 /// \brief Account for slicing gain in the current cost. 9890 /// Slicing provide a few gains like removing a shift or a 9891 /// truncate. This method allows to grow the cost of the original 9892 /// load with the gain from this slice. 9893 void addSliceGain(const LoadedSlice &LS) { 9894 // Each slice saves a truncate. 9895 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 9896 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 9897 LS.Inst->getValueType(0))) 9898 ++Truncates; 9899 // If there is a shift amount, this slice gets rid of it. 9900 if (LS.Shift) 9901 ++Shift; 9902 // If this slice can merge a cross register bank copy, account for it. 9903 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 9904 ++CrossRegisterBanksCopies; 9905 } 9906 9907 Cost &operator+=(const Cost &RHS) { 9908 Loads += RHS.Loads; 9909 Truncates += RHS.Truncates; 9910 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 9911 ZExts += RHS.ZExts; 9912 Shift += RHS.Shift; 9913 return *this; 9914 } 9915 9916 bool operator==(const Cost &RHS) const { 9917 return Loads == RHS.Loads && Truncates == RHS.Truncates && 9918 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 9919 ZExts == RHS.ZExts && Shift == RHS.Shift; 9920 } 9921 9922 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 9923 9924 bool operator<(const Cost &RHS) const { 9925 // Assume cross register banks copies are as expensive as loads. 9926 // FIXME: Do we want some more target hooks? 9927 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 9928 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 9929 // Unless we are optimizing for code size, consider the 9930 // expensive operation first. 9931 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 9932 return ExpensiveOpsLHS < ExpensiveOpsRHS; 9933 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 9934 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 9935 } 9936 9937 bool operator>(const Cost &RHS) const { return RHS < *this; } 9938 9939 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 9940 9941 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 9942 }; 9943 // The last instruction that represent the slice. This should be a 9944 // truncate instruction. 9945 SDNode *Inst; 9946 // The original load instruction. 9947 LoadSDNode *Origin; 9948 // The right shift amount in bits from the original load. 9949 unsigned Shift; 9950 // The DAG from which Origin came from. 9951 // This is used to get some contextual information about legal types, etc. 9952 SelectionDAG *DAG; 9953 9954 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 9955 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 9956 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 9957 9958 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 9959 /// \return Result is \p BitWidth and has used bits set to 1 and 9960 /// not used bits set to 0. 9961 APInt getUsedBits() const { 9962 // Reproduce the trunc(lshr) sequence: 9963 // - Start from the truncated value. 9964 // - Zero extend to the desired bit width. 9965 // - Shift left. 9966 assert(Origin && "No original load to compare against."); 9967 unsigned BitWidth = Origin->getValueSizeInBits(0); 9968 assert(Inst && "This slice is not bound to an instruction"); 9969 assert(Inst->getValueSizeInBits(0) <= BitWidth && 9970 "Extracted slice is bigger than the whole type!"); 9971 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 9972 UsedBits.setAllBits(); 9973 UsedBits = UsedBits.zext(BitWidth); 9974 UsedBits <<= Shift; 9975 return UsedBits; 9976 } 9977 9978 /// \brief Get the size of the slice to be loaded in bytes. 9979 unsigned getLoadedSize() const { 9980 unsigned SliceSize = getUsedBits().countPopulation(); 9981 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 9982 return SliceSize / 8; 9983 } 9984 9985 /// \brief Get the type that will be loaded for this slice. 9986 /// Note: This may not be the final type for the slice. 9987 EVT getLoadedType() const { 9988 assert(DAG && "Missing context"); 9989 LLVMContext &Ctxt = *DAG->getContext(); 9990 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 9991 } 9992 9993 /// \brief Get the alignment of the load used for this slice. 9994 unsigned getAlignment() const { 9995 unsigned Alignment = Origin->getAlignment(); 9996 unsigned Offset = getOffsetFromBase(); 9997 if (Offset != 0) 9998 Alignment = MinAlign(Alignment, Alignment + Offset); 9999 return Alignment; 10000 } 10001 10002 /// \brief Check if this slice can be rewritten with legal operations. 10003 bool isLegal() const { 10004 // An invalid slice is not legal. 10005 if (!Origin || !Inst || !DAG) 10006 return false; 10007 10008 // Offsets are for indexed load only, we do not handle that. 10009 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 10010 return false; 10011 10012 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10013 10014 // Check that the type is legal. 10015 EVT SliceType = getLoadedType(); 10016 if (!TLI.isTypeLegal(SliceType)) 10017 return false; 10018 10019 // Check that the load is legal for this type. 10020 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10021 return false; 10022 10023 // Check that the offset can be computed. 10024 // 1. Check its type. 10025 EVT PtrType = Origin->getBasePtr().getValueType(); 10026 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10027 return false; 10028 10029 // 2. Check that it fits in the immediate. 10030 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10031 return false; 10032 10033 // 3. Check that the computation is legal. 10034 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10035 return false; 10036 10037 // Check that the zext is legal if it needs one. 10038 EVT TruncateType = Inst->getValueType(0); 10039 if (TruncateType != SliceType && 10040 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10041 return false; 10042 10043 return true; 10044 } 10045 10046 /// \brief Get the offset in bytes of this slice in the original chunk of 10047 /// bits. 10048 /// \pre DAG != nullptr. 10049 uint64_t getOffsetFromBase() const { 10050 assert(DAG && "Missing context."); 10051 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10052 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10053 uint64_t Offset = Shift / 8; 10054 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10055 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10056 "The size of the original loaded type is not a multiple of a" 10057 " byte."); 10058 // If Offset is bigger than TySizeInBytes, it means we are loading all 10059 // zeros. This should have been optimized before in the process. 10060 assert(TySizeInBytes > Offset && 10061 "Invalid shift amount for given loaded size"); 10062 if (IsBigEndian) 10063 Offset = TySizeInBytes - Offset - getLoadedSize(); 10064 return Offset; 10065 } 10066 10067 /// \brief Generate the sequence of instructions to load the slice 10068 /// represented by this object and redirect the uses of this slice to 10069 /// this new sequence of instructions. 10070 /// \pre this->Inst && this->Origin are valid Instructions and this 10071 /// object passed the legal check: LoadedSlice::isLegal returned true. 10072 /// \return The last instruction of the sequence used to load the slice. 10073 SDValue loadSlice() const { 10074 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10075 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10076 SDValue BaseAddr = OldBaseAddr; 10077 // Get the offset in that chunk of bytes w.r.t. the endianess. 10078 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10079 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10080 if (Offset) { 10081 // BaseAddr = BaseAddr + Offset. 10082 EVT ArithType = BaseAddr.getValueType(); 10083 SDLoc DL(Origin); 10084 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10085 DAG->getConstant(Offset, DL, ArithType)); 10086 } 10087 10088 // Create the type of the loaded slice according to its size. 10089 EVT SliceType = getLoadedType(); 10090 10091 // Create the load for the slice. 10092 SDValue LastInst = DAG->getLoad( 10093 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10094 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 10095 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 10096 // If the final type is not the same as the loaded type, this means that 10097 // we have to pad with zero. Create a zero extend for that. 10098 EVT FinalType = Inst->getValueType(0); 10099 if (SliceType != FinalType) 10100 LastInst = 10101 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10102 return LastInst; 10103 } 10104 10105 /// \brief Check if this slice can be merged with an expensive cross register 10106 /// bank copy. E.g., 10107 /// i = load i32 10108 /// f = bitcast i32 i to float 10109 bool canMergeExpensiveCrossRegisterBankCopy() const { 10110 if (!Inst || !Inst->hasOneUse()) 10111 return false; 10112 SDNode *Use = *Inst->use_begin(); 10113 if (Use->getOpcode() != ISD::BITCAST) 10114 return false; 10115 assert(DAG && "Missing context"); 10116 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10117 EVT ResVT = Use->getValueType(0); 10118 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10119 const TargetRegisterClass *ArgRC = 10120 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10121 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10122 return false; 10123 10124 // At this point, we know that we perform a cross-register-bank copy. 10125 // Check if it is expensive. 10126 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10127 // Assume bitcasts are cheap, unless both register classes do not 10128 // explicitly share a common sub class. 10129 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10130 return false; 10131 10132 // Check if it will be merged with the load. 10133 // 1. Check the alignment constraint. 10134 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10135 ResVT.getTypeForEVT(*DAG->getContext())); 10136 10137 if (RequiredAlignment > getAlignment()) 10138 return false; 10139 10140 // 2. Check that the load is a legal operation for that type. 10141 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10142 return false; 10143 10144 // 3. Check that we do not have a zext in the way. 10145 if (Inst->getValueType(0) != getLoadedType()) 10146 return false; 10147 10148 return true; 10149 } 10150 }; 10151 } 10152 10153 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10154 /// \p UsedBits looks like 0..0 1..1 0..0. 10155 static bool areUsedBitsDense(const APInt &UsedBits) { 10156 // If all the bits are one, this is dense! 10157 if (UsedBits.isAllOnesValue()) 10158 return true; 10159 10160 // Get rid of the unused bits on the right. 10161 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10162 // Get rid of the unused bits on the left. 10163 if (NarrowedUsedBits.countLeadingZeros()) 10164 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10165 // Check that the chunk of bits is completely used. 10166 return NarrowedUsedBits.isAllOnesValue(); 10167 } 10168 10169 /// \brief Check whether or not \p First and \p Second are next to each other 10170 /// in memory. This means that there is no hole between the bits loaded 10171 /// by \p First and the bits loaded by \p Second. 10172 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10173 const LoadedSlice &Second) { 10174 assert(First.Origin == Second.Origin && First.Origin && 10175 "Unable to match different memory origins."); 10176 APInt UsedBits = First.getUsedBits(); 10177 assert((UsedBits & Second.getUsedBits()) == 0 && 10178 "Slices are not supposed to overlap."); 10179 UsedBits |= Second.getUsedBits(); 10180 return areUsedBitsDense(UsedBits); 10181 } 10182 10183 /// \brief Adjust the \p GlobalLSCost according to the target 10184 /// paring capabilities and the layout of the slices. 10185 /// \pre \p GlobalLSCost should account for at least as many loads as 10186 /// there is in the slices in \p LoadedSlices. 10187 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10188 LoadedSlice::Cost &GlobalLSCost) { 10189 unsigned NumberOfSlices = LoadedSlices.size(); 10190 // If there is less than 2 elements, no pairing is possible. 10191 if (NumberOfSlices < 2) 10192 return; 10193 10194 // Sort the slices so that elements that are likely to be next to each 10195 // other in memory are next to each other in the list. 10196 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10197 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10198 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10199 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10200 }); 10201 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10202 // First (resp. Second) is the first (resp. Second) potentially candidate 10203 // to be placed in a paired load. 10204 const LoadedSlice *First = nullptr; 10205 const LoadedSlice *Second = nullptr; 10206 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10207 // Set the beginning of the pair. 10208 First = Second) { 10209 10210 Second = &LoadedSlices[CurrSlice]; 10211 10212 // If First is NULL, it means we start a new pair. 10213 // Get to the next slice. 10214 if (!First) 10215 continue; 10216 10217 EVT LoadedType = First->getLoadedType(); 10218 10219 // If the types of the slices are different, we cannot pair them. 10220 if (LoadedType != Second->getLoadedType()) 10221 continue; 10222 10223 // Check if the target supplies paired loads for this type. 10224 unsigned RequiredAlignment = 0; 10225 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10226 // move to the next pair, this type is hopeless. 10227 Second = nullptr; 10228 continue; 10229 } 10230 // Check if we meet the alignment requirement. 10231 if (RequiredAlignment > First->getAlignment()) 10232 continue; 10233 10234 // Check that both loads are next to each other in memory. 10235 if (!areSlicesNextToEachOther(*First, *Second)) 10236 continue; 10237 10238 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10239 --GlobalLSCost.Loads; 10240 // Move to the next pair. 10241 Second = nullptr; 10242 } 10243 } 10244 10245 /// \brief Check the profitability of all involved LoadedSlice. 10246 /// Currently, it is considered profitable if there is exactly two 10247 /// involved slices (1) which are (2) next to each other in memory, and 10248 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10249 /// 10250 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10251 /// the elements themselves. 10252 /// 10253 /// FIXME: When the cost model will be mature enough, we can relax 10254 /// constraints (1) and (2). 10255 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10256 const APInt &UsedBits, bool ForCodeSize) { 10257 unsigned NumberOfSlices = LoadedSlices.size(); 10258 if (StressLoadSlicing) 10259 return NumberOfSlices > 1; 10260 10261 // Check (1). 10262 if (NumberOfSlices != 2) 10263 return false; 10264 10265 // Check (2). 10266 if (!areUsedBitsDense(UsedBits)) 10267 return false; 10268 10269 // Check (3). 10270 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10271 // The original code has one big load. 10272 OrigCost.Loads = 1; 10273 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10274 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10275 // Accumulate the cost of all the slices. 10276 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10277 GlobalSlicingCost += SliceCost; 10278 10279 // Account as cost in the original configuration the gain obtained 10280 // with the current slices. 10281 OrigCost.addSliceGain(LS); 10282 } 10283 10284 // If the target supports paired load, adjust the cost accordingly. 10285 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10286 return OrigCost > GlobalSlicingCost; 10287 } 10288 10289 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10290 /// operations, split it in the various pieces being extracted. 10291 /// 10292 /// This sort of thing is introduced by SROA. 10293 /// This slicing takes care not to insert overlapping loads. 10294 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10295 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10296 if (Level < AfterLegalizeDAG) 10297 return false; 10298 10299 LoadSDNode *LD = cast<LoadSDNode>(N); 10300 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10301 !LD->getValueType(0).isInteger()) 10302 return false; 10303 10304 // Keep track of already used bits to detect overlapping values. 10305 // In that case, we will just abort the transformation. 10306 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10307 10308 SmallVector<LoadedSlice, 4> LoadedSlices; 10309 10310 // Check if this load is used as several smaller chunks of bits. 10311 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10312 // of computation for each trunc. 10313 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10314 UI != UIEnd; ++UI) { 10315 // Skip the uses of the chain. 10316 if (UI.getUse().getResNo() != 0) 10317 continue; 10318 10319 SDNode *User = *UI; 10320 unsigned Shift = 0; 10321 10322 // Check if this is a trunc(lshr). 10323 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10324 isa<ConstantSDNode>(User->getOperand(1))) { 10325 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10326 User = *User->use_begin(); 10327 } 10328 10329 // At this point, User is a Truncate, iff we encountered, trunc or 10330 // trunc(lshr). 10331 if (User->getOpcode() != ISD::TRUNCATE) 10332 return false; 10333 10334 // The width of the type must be a power of 2 and greater than 8-bits. 10335 // Otherwise the load cannot be represented in LLVM IR. 10336 // Moreover, if we shifted with a non-8-bits multiple, the slice 10337 // will be across several bytes. We do not support that. 10338 unsigned Width = User->getValueSizeInBits(0); 10339 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10340 return 0; 10341 10342 // Build the slice for this chain of computations. 10343 LoadedSlice LS(User, LD, Shift, &DAG); 10344 APInt CurrentUsedBits = LS.getUsedBits(); 10345 10346 // Check if this slice overlaps with another. 10347 if ((CurrentUsedBits & UsedBits) != 0) 10348 return false; 10349 // Update the bits used globally. 10350 UsedBits |= CurrentUsedBits; 10351 10352 // Check if the new slice would be legal. 10353 if (!LS.isLegal()) 10354 return false; 10355 10356 // Record the slice. 10357 LoadedSlices.push_back(LS); 10358 } 10359 10360 // Abort slicing if it does not seem to be profitable. 10361 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10362 return false; 10363 10364 ++SlicedLoads; 10365 10366 // Rewrite each chain to use an independent load. 10367 // By construction, each chain can be represented by a unique load. 10368 10369 // Prepare the argument for the new token factor for all the slices. 10370 SmallVector<SDValue, 8> ArgChains; 10371 for (SmallVectorImpl<LoadedSlice>::const_iterator 10372 LSIt = LoadedSlices.begin(), 10373 LSItEnd = LoadedSlices.end(); 10374 LSIt != LSItEnd; ++LSIt) { 10375 SDValue SliceInst = LSIt->loadSlice(); 10376 CombineTo(LSIt->Inst, SliceInst, true); 10377 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10378 SliceInst = SliceInst.getOperand(0); 10379 assert(SliceInst->getOpcode() == ISD::LOAD && 10380 "It takes more than a zext to get to the loaded slice!!"); 10381 ArgChains.push_back(SliceInst.getValue(1)); 10382 } 10383 10384 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10385 ArgChains); 10386 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10387 return true; 10388 } 10389 10390 /// Check to see if V is (and load (ptr), imm), where the load is having 10391 /// specific bytes cleared out. If so, return the byte size being masked out 10392 /// and the shift amount. 10393 static std::pair<unsigned, unsigned> 10394 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10395 std::pair<unsigned, unsigned> Result(0, 0); 10396 10397 // Check for the structure we're looking for. 10398 if (V->getOpcode() != ISD::AND || 10399 !isa<ConstantSDNode>(V->getOperand(1)) || 10400 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10401 return Result; 10402 10403 // Check the chain and pointer. 10404 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10405 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10406 10407 // The store should be chained directly to the load or be an operand of a 10408 // tokenfactor. 10409 if (LD == Chain.getNode()) 10410 ; // ok. 10411 else if (Chain->getOpcode() != ISD::TokenFactor) 10412 return Result; // Fail. 10413 else { 10414 bool isOk = false; 10415 for (const SDValue &ChainOp : Chain->op_values()) 10416 if (ChainOp.getNode() == LD) { 10417 isOk = true; 10418 break; 10419 } 10420 if (!isOk) return Result; 10421 } 10422 10423 // This only handles simple types. 10424 if (V.getValueType() != MVT::i16 && 10425 V.getValueType() != MVT::i32 && 10426 V.getValueType() != MVT::i64) 10427 return Result; 10428 10429 // Check the constant mask. Invert it so that the bits being masked out are 10430 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10431 // follow the sign bit for uniformity. 10432 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10433 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10434 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10435 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10436 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10437 if (NotMaskLZ == 64) return Result; // All zero mask. 10438 10439 // See if we have a continuous run of bits. If so, we have 0*1+0* 10440 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10441 return Result; 10442 10443 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10444 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10445 NotMaskLZ -= 64-V.getValueSizeInBits(); 10446 10447 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10448 switch (MaskedBytes) { 10449 case 1: 10450 case 2: 10451 case 4: break; 10452 default: return Result; // All one mask, or 5-byte mask. 10453 } 10454 10455 // Verify that the first bit starts at a multiple of mask so that the access 10456 // is aligned the same as the access width. 10457 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10458 10459 Result.first = MaskedBytes; 10460 Result.second = NotMaskTZ/8; 10461 return Result; 10462 } 10463 10464 10465 /// Check to see if IVal is something that provides a value as specified by 10466 /// MaskInfo. If so, replace the specified store with a narrower store of 10467 /// truncated IVal. 10468 static SDNode * 10469 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10470 SDValue IVal, StoreSDNode *St, 10471 DAGCombiner *DC) { 10472 unsigned NumBytes = MaskInfo.first; 10473 unsigned ByteShift = MaskInfo.second; 10474 SelectionDAG &DAG = DC->getDAG(); 10475 10476 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10477 // that uses this. If not, this is not a replacement. 10478 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10479 ByteShift*8, (ByteShift+NumBytes)*8); 10480 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10481 10482 // Check that it is legal on the target to do this. It is legal if the new 10483 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10484 // legalization. 10485 MVT VT = MVT::getIntegerVT(NumBytes*8); 10486 if (!DC->isTypeLegal(VT)) 10487 return nullptr; 10488 10489 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10490 // shifted by ByteShift and truncated down to NumBytes. 10491 if (ByteShift) { 10492 SDLoc DL(IVal); 10493 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10494 DAG.getConstant(ByteShift*8, DL, 10495 DC->getShiftAmountTy(IVal.getValueType()))); 10496 } 10497 10498 // Figure out the offset for the store and the alignment of the access. 10499 unsigned StOffset; 10500 unsigned NewAlign = St->getAlignment(); 10501 10502 if (DAG.getDataLayout().isLittleEndian()) 10503 StOffset = ByteShift; 10504 else 10505 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10506 10507 SDValue Ptr = St->getBasePtr(); 10508 if (StOffset) { 10509 SDLoc DL(IVal); 10510 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10511 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10512 NewAlign = MinAlign(NewAlign, StOffset); 10513 } 10514 10515 // Truncate down to the new size. 10516 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10517 10518 ++OpsNarrowed; 10519 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10520 St->getPointerInfo().getWithOffset(StOffset), 10521 false, false, NewAlign).getNode(); 10522 } 10523 10524 10525 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10526 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10527 /// narrowing the load and store if it would end up being a win for performance 10528 /// or code size. 10529 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10530 StoreSDNode *ST = cast<StoreSDNode>(N); 10531 if (ST->isVolatile()) 10532 return SDValue(); 10533 10534 SDValue Chain = ST->getChain(); 10535 SDValue Value = ST->getValue(); 10536 SDValue Ptr = ST->getBasePtr(); 10537 EVT VT = Value.getValueType(); 10538 10539 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10540 return SDValue(); 10541 10542 unsigned Opc = Value.getOpcode(); 10543 10544 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10545 // is a byte mask indicating a consecutive number of bytes, check to see if 10546 // Y is known to provide just those bytes. If so, we try to replace the 10547 // load + replace + store sequence with a single (narrower) store, which makes 10548 // the load dead. 10549 if (Opc == ISD::OR) { 10550 std::pair<unsigned, unsigned> MaskedLoad; 10551 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10552 if (MaskedLoad.first) 10553 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10554 Value.getOperand(1), ST,this)) 10555 return SDValue(NewST, 0); 10556 10557 // Or is commutative, so try swapping X and Y. 10558 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10559 if (MaskedLoad.first) 10560 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10561 Value.getOperand(0), ST,this)) 10562 return SDValue(NewST, 0); 10563 } 10564 10565 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10566 Value.getOperand(1).getOpcode() != ISD::Constant) 10567 return SDValue(); 10568 10569 SDValue N0 = Value.getOperand(0); 10570 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10571 Chain == SDValue(N0.getNode(), 1)) { 10572 LoadSDNode *LD = cast<LoadSDNode>(N0); 10573 if (LD->getBasePtr() != Ptr || 10574 LD->getPointerInfo().getAddrSpace() != 10575 ST->getPointerInfo().getAddrSpace()) 10576 return SDValue(); 10577 10578 // Find the type to narrow it the load / op / store to. 10579 SDValue N1 = Value.getOperand(1); 10580 unsigned BitWidth = N1.getValueSizeInBits(); 10581 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10582 if (Opc == ISD::AND) 10583 Imm ^= APInt::getAllOnesValue(BitWidth); 10584 if (Imm == 0 || Imm.isAllOnesValue()) 10585 return SDValue(); 10586 unsigned ShAmt = Imm.countTrailingZeros(); 10587 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10588 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10589 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10590 // The narrowing should be profitable, the load/store operation should be 10591 // legal (or custom) and the store size should be equal to the NewVT width. 10592 while (NewBW < BitWidth && 10593 (NewVT.getStoreSizeInBits() != NewBW || 10594 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10595 !TLI.isNarrowingProfitable(VT, NewVT))) { 10596 NewBW = NextPowerOf2(NewBW); 10597 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10598 } 10599 if (NewBW >= BitWidth) 10600 return SDValue(); 10601 10602 // If the lsb changed does not start at the type bitwidth boundary, 10603 // start at the previous one. 10604 if (ShAmt % NewBW) 10605 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10606 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10607 std::min(BitWidth, ShAmt + NewBW)); 10608 if ((Imm & Mask) == Imm) { 10609 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10610 if (Opc == ISD::AND) 10611 NewImm ^= APInt::getAllOnesValue(NewBW); 10612 uint64_t PtrOff = ShAmt / 8; 10613 // For big endian targets, we need to adjust the offset to the pointer to 10614 // load the correct bytes. 10615 if (DAG.getDataLayout().isBigEndian()) 10616 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10617 10618 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10619 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10620 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10621 return SDValue(); 10622 10623 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10624 Ptr.getValueType(), Ptr, 10625 DAG.getConstant(PtrOff, SDLoc(LD), 10626 Ptr.getValueType())); 10627 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10628 LD->getChain(), NewPtr, 10629 LD->getPointerInfo().getWithOffset(PtrOff), 10630 LD->isVolatile(), LD->isNonTemporal(), 10631 LD->isInvariant(), NewAlign, 10632 LD->getAAInfo()); 10633 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10634 DAG.getConstant(NewImm, SDLoc(Value), 10635 NewVT)); 10636 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10637 NewVal, NewPtr, 10638 ST->getPointerInfo().getWithOffset(PtrOff), 10639 false, false, NewAlign); 10640 10641 AddToWorklist(NewPtr.getNode()); 10642 AddToWorklist(NewLD.getNode()); 10643 AddToWorklist(NewVal.getNode()); 10644 WorklistRemover DeadNodes(*this); 10645 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10646 ++OpsNarrowed; 10647 return NewST; 10648 } 10649 } 10650 10651 return SDValue(); 10652 } 10653 10654 /// For a given floating point load / store pair, if the load value isn't used 10655 /// by any other operations, then consider transforming the pair to integer 10656 /// load / store operations if the target deems the transformation profitable. 10657 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10658 StoreSDNode *ST = cast<StoreSDNode>(N); 10659 SDValue Chain = ST->getChain(); 10660 SDValue Value = ST->getValue(); 10661 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10662 Value.hasOneUse() && 10663 Chain == SDValue(Value.getNode(), 1)) { 10664 LoadSDNode *LD = cast<LoadSDNode>(Value); 10665 EVT VT = LD->getMemoryVT(); 10666 if (!VT.isFloatingPoint() || 10667 VT != ST->getMemoryVT() || 10668 LD->isNonTemporal() || 10669 ST->isNonTemporal() || 10670 LD->getPointerInfo().getAddrSpace() != 0 || 10671 ST->getPointerInfo().getAddrSpace() != 0) 10672 return SDValue(); 10673 10674 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10675 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10676 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10677 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10678 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10679 return SDValue(); 10680 10681 unsigned LDAlign = LD->getAlignment(); 10682 unsigned STAlign = ST->getAlignment(); 10683 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10684 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 10685 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10686 return SDValue(); 10687 10688 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10689 LD->getChain(), LD->getBasePtr(), 10690 LD->getPointerInfo(), 10691 false, false, false, LDAlign); 10692 10693 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10694 NewLD, ST->getBasePtr(), 10695 ST->getPointerInfo(), 10696 false, false, STAlign); 10697 10698 AddToWorklist(NewLD.getNode()); 10699 AddToWorklist(NewST.getNode()); 10700 WorklistRemover DeadNodes(*this); 10701 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10702 ++LdStFP2Int; 10703 return NewST; 10704 } 10705 10706 return SDValue(); 10707 } 10708 10709 namespace { 10710 /// Helper struct to parse and store a memory address as base + index + offset. 10711 /// We ignore sign extensions when it is safe to do so. 10712 /// The following two expressions are not equivalent. To differentiate we need 10713 /// to store whether there was a sign extension involved in the index 10714 /// computation. 10715 /// (load (i64 add (i64 copyfromreg %c) 10716 /// (i64 signextend (add (i8 load %index) 10717 /// (i8 1)))) 10718 /// vs 10719 /// 10720 /// (load (i64 add (i64 copyfromreg %c) 10721 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10722 /// (i32 1))))) 10723 struct BaseIndexOffset { 10724 SDValue Base; 10725 SDValue Index; 10726 int64_t Offset; 10727 bool IsIndexSignExt; 10728 10729 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10730 10731 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10732 bool IsIndexSignExt) : 10733 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10734 10735 bool equalBaseIndex(const BaseIndexOffset &Other) { 10736 return Other.Base == Base && Other.Index == Index && 10737 Other.IsIndexSignExt == IsIndexSignExt; 10738 } 10739 10740 /// Parses tree in Ptr for base, index, offset addresses. 10741 static BaseIndexOffset match(SDValue Ptr) { 10742 bool IsIndexSignExt = false; 10743 10744 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10745 // instruction, then it could be just the BASE or everything else we don't 10746 // know how to handle. Just use Ptr as BASE and give up. 10747 if (Ptr->getOpcode() != ISD::ADD) 10748 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10749 10750 // We know that we have at least an ADD instruction. Try to pattern match 10751 // the simple case of BASE + OFFSET. 10752 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10753 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10754 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10755 IsIndexSignExt); 10756 } 10757 10758 // Inside a loop the current BASE pointer is calculated using an ADD and a 10759 // MUL instruction. In this case Ptr is the actual BASE pointer. 10760 // (i64 add (i64 %array_ptr) 10761 // (i64 mul (i64 %induction_var) 10762 // (i64 %element_size))) 10763 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10764 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10765 10766 // Look at Base + Index + Offset cases. 10767 SDValue Base = Ptr->getOperand(0); 10768 SDValue IndexOffset = Ptr->getOperand(1); 10769 10770 // Skip signextends. 10771 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10772 IndexOffset = IndexOffset->getOperand(0); 10773 IsIndexSignExt = true; 10774 } 10775 10776 // Either the case of Base + Index (no offset) or something else. 10777 if (IndexOffset->getOpcode() != ISD::ADD) 10778 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10779 10780 // Now we have the case of Base + Index + offset. 10781 SDValue Index = IndexOffset->getOperand(0); 10782 SDValue Offset = IndexOffset->getOperand(1); 10783 10784 if (!isa<ConstantSDNode>(Offset)) 10785 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10786 10787 // Ignore signextends. 10788 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 10789 Index = Index->getOperand(0); 10790 IsIndexSignExt = true; 10791 } else IsIndexSignExt = false; 10792 10793 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 10794 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 10795 } 10796 }; 10797 } // namespace 10798 10799 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG, 10800 SDLoc SL, 10801 ArrayRef<MemOpLink> Stores, 10802 SmallVectorImpl<SDValue> &Chains, 10803 EVT Ty) const { 10804 SmallVector<SDValue, 8> BuildVector; 10805 10806 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 10807 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 10808 Chains.push_back(St->getChain()); 10809 BuildVector.push_back(St->getValue()); 10810 } 10811 10812 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector); 10813 } 10814 10815 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 10816 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 10817 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 10818 // Make sure we have something to merge. 10819 if (NumStores < 2) 10820 return false; 10821 10822 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 10823 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10824 unsigned LatestNodeUsed = 0; 10825 10826 for (unsigned i=0; i < NumStores; ++i) { 10827 // Find a chain for the new wide-store operand. Notice that some 10828 // of the store nodes that we found may not be selected for inclusion 10829 // in the wide store. The chain we use needs to be the chain of the 10830 // latest store node which is *used* and replaced by the wide store. 10831 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 10832 LatestNodeUsed = i; 10833 } 10834 10835 SmallVector<SDValue, 8> Chains; 10836 10837 // The latest Node in the DAG. 10838 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 10839 SDLoc DL(StoreNodes[0].MemNode); 10840 10841 SDValue StoredVal; 10842 if (UseVector) { 10843 bool IsVec = MemVT.isVector(); 10844 unsigned Elts = NumStores; 10845 if (IsVec) { 10846 // When merging vector stores, get the total number of elements. 10847 Elts *= MemVT.getVectorNumElements(); 10848 } 10849 // Get the type for the merged vector store. 10850 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 10851 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 10852 10853 if (IsConstantSrc) { 10854 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 10855 } else { 10856 SmallVector<SDValue, 8> Ops; 10857 for (unsigned i = 0; i < NumStores; ++i) { 10858 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10859 SDValue Val = St->getValue(); 10860 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 10861 if (Val.getValueType() != MemVT) 10862 return false; 10863 Ops.push_back(Val); 10864 Chains.push_back(St->getChain()); 10865 } 10866 10867 // Build the extracted vector elements back into a vector. 10868 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 10869 DL, Ty, Ops); } 10870 } else { 10871 // We should always use a vector store when merging extracted vector 10872 // elements, so this path implies a store of constants. 10873 assert(IsConstantSrc && "Merged vector elements should use vector store"); 10874 10875 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 10876 APInt StoreInt(SizeInBits, 0); 10877 10878 // Construct a single integer constant which is made of the smaller 10879 // constant inputs. 10880 bool IsLE = DAG.getDataLayout().isLittleEndian(); 10881 for (unsigned i = 0; i < NumStores; ++i) { 10882 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 10883 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 10884 Chains.push_back(St->getChain()); 10885 10886 SDValue Val = St->getValue(); 10887 StoreInt <<= ElementSizeBytes * 8; 10888 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 10889 StoreInt |= C->getAPIntValue().zext(SizeInBits); 10890 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 10891 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 10892 } else { 10893 llvm_unreachable("Invalid constant element type"); 10894 } 10895 } 10896 10897 // Create the new Load and Store operations. 10898 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 10899 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 10900 } 10901 10902 assert(!Chains.empty()); 10903 10904 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10905 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 10906 FirstInChain->getBasePtr(), 10907 FirstInChain->getPointerInfo(), 10908 false, false, 10909 FirstInChain->getAlignment()); 10910 10911 // Replace the last store with the new store 10912 CombineTo(LatestOp, NewStore); 10913 // Erase all other stores. 10914 for (unsigned i = 0; i < NumStores; ++i) { 10915 if (StoreNodes[i].MemNode == LatestOp) 10916 continue; 10917 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10918 // ReplaceAllUsesWith will replace all uses that existed when it was 10919 // called, but graph optimizations may cause new ones to appear. For 10920 // example, the case in pr14333 looks like 10921 // 10922 // St's chain -> St -> another store -> X 10923 // 10924 // And the only difference from St to the other store is the chain. 10925 // When we change it's chain to be St's chain they become identical, 10926 // get CSEed and the net result is that X is now a use of St. 10927 // Since we know that St is redundant, just iterate. 10928 while (!St->use_empty()) 10929 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 10930 deleteAndRecombine(St); 10931 } 10932 10933 return true; 10934 } 10935 10936 void DAGCombiner::getStoreMergeAndAliasCandidates( 10937 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 10938 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 10939 // This holds the base pointer, index, and the offset in bytes from the base 10940 // pointer. 10941 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 10942 10943 // We must have a base and an offset. 10944 if (!BasePtr.Base.getNode()) 10945 return; 10946 10947 // Do not handle stores to undef base pointers. 10948 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 10949 return; 10950 10951 // Walk up the chain and look for nodes with offsets from the same 10952 // base pointer. Stop when reaching an instruction with a different kind 10953 // or instruction which has a different base pointer. 10954 EVT MemVT = St->getMemoryVT(); 10955 unsigned Seq = 0; 10956 StoreSDNode *Index = St; 10957 10958 10959 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10960 : DAG.getSubtarget().useAA(); 10961 10962 if (UseAA) { 10963 // Look at other users of the same chain. Stores on the same chain do not 10964 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 10965 // to be on the same chain, so don't bother looking at adjacent chains. 10966 10967 SDValue Chain = St->getChain(); 10968 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 10969 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 10970 if (I.getOperandNo() != 0) 10971 continue; 10972 10973 if (OtherST->isVolatile() || OtherST->isIndexed()) 10974 continue; 10975 10976 if (OtherST->getMemoryVT() != MemVT) 10977 continue; 10978 10979 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr()); 10980 10981 if (Ptr.equalBaseIndex(BasePtr)) 10982 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 10983 } 10984 } 10985 10986 return; 10987 } 10988 10989 while (Index) { 10990 // If the chain has more than one use, then we can't reorder the mem ops. 10991 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 10992 break; 10993 10994 // Find the base pointer and offset for this memory node. 10995 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 10996 10997 // Check that the base pointer is the same as the original one. 10998 if (!Ptr.equalBaseIndex(BasePtr)) 10999 break; 11000 11001 // The memory operands must not be volatile. 11002 if (Index->isVolatile() || Index->isIndexed()) 11003 break; 11004 11005 // No truncation. 11006 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 11007 if (St->isTruncatingStore()) 11008 break; 11009 11010 // The stored memory type must be the same. 11011 if (Index->getMemoryVT() != MemVT) 11012 break; 11013 11014 // We found a potential memory operand to merge. 11015 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11016 11017 // Find the next memory operand in the chain. If the next operand in the 11018 // chain is a store then move up and continue the scan with the next 11019 // memory operand. If the next operand is a load save it and use alias 11020 // information to check if it interferes with anything. 11021 SDNode *NextInChain = Index->getChain().getNode(); 11022 while (1) { 11023 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11024 // We found a store node. Use it for the next iteration. 11025 Index = STn; 11026 break; 11027 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11028 if (Ldn->isVolatile()) { 11029 Index = nullptr; 11030 break; 11031 } 11032 11033 // Save the load node for later. Continue the scan. 11034 AliasLoadNodes.push_back(Ldn); 11035 NextInChain = Ldn->getChain().getNode(); 11036 continue; 11037 } else { 11038 Index = nullptr; 11039 break; 11040 } 11041 } 11042 } 11043 } 11044 11045 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11046 if (OptLevel == CodeGenOpt::None) 11047 return false; 11048 11049 EVT MemVT = St->getMemoryVT(); 11050 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11051 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11052 Attribute::NoImplicitFloat); 11053 11054 // This function cannot currently deal with non-byte-sized memory sizes. 11055 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11056 return false; 11057 11058 if (!MemVT.isSimple()) 11059 return false; 11060 11061 // Perform an early exit check. Do not bother looking at stored values that 11062 // are not constants, loads, or extracted vector elements. 11063 SDValue StoredVal = St->getValue(); 11064 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11065 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11066 isa<ConstantFPSDNode>(StoredVal); 11067 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11068 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11069 11070 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11071 return false; 11072 11073 // Don't merge vectors into wider vectors if the source data comes from loads. 11074 // TODO: This restriction can be lifted by using logic similar to the 11075 // ExtractVecSrc case. 11076 if (MemVT.isVector() && IsLoadSrc) 11077 return false; 11078 11079 // Only look at ends of store sequences. 11080 SDValue Chain = SDValue(St, 0); 11081 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11082 return false; 11083 11084 // Save the LoadSDNodes that we find in the chain. 11085 // We need to make sure that these nodes do not interfere with 11086 // any of the store nodes. 11087 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11088 11089 // Save the StoreSDNodes that we find in the chain. 11090 SmallVector<MemOpLink, 8> StoreNodes; 11091 11092 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11093 11094 // Check if there is anything to merge. 11095 if (StoreNodes.size() < 2) 11096 return false; 11097 11098 // Sort the memory operands according to their distance from the base pointer. 11099 std::sort(StoreNodes.begin(), StoreNodes.end(), 11100 [](MemOpLink LHS, MemOpLink RHS) { 11101 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11102 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11103 LHS.SequenceNum > RHS.SequenceNum); 11104 }); 11105 11106 // Scan the memory operations on the chain and find the first non-consecutive 11107 // store memory address. 11108 unsigned LastConsecutiveStore = 0; 11109 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11110 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11111 11112 // Check that the addresses are consecutive starting from the second 11113 // element in the list of stores. 11114 if (i > 0) { 11115 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11116 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11117 break; 11118 } 11119 11120 bool Alias = false; 11121 // Check if this store interferes with any of the loads that we found. 11122 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 11123 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 11124 Alias = true; 11125 break; 11126 } 11127 // We found a load that alias with this store. Stop the sequence. 11128 if (Alias) 11129 break; 11130 11131 // Mark this node as useful. 11132 LastConsecutiveStore = i; 11133 } 11134 11135 // The node with the lowest store address. 11136 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11137 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11138 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11139 LLVMContext &Context = *DAG.getContext(); 11140 const DataLayout &DL = DAG.getDataLayout(); 11141 11142 // Store the constants into memory as one consecutive store. 11143 if (IsConstantSrc) { 11144 unsigned LastLegalType = 0; 11145 unsigned LastLegalVectorType = 0; 11146 bool NonZero = false; 11147 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11148 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11149 SDValue StoredVal = St->getValue(); 11150 11151 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11152 NonZero |= !C->isNullValue(); 11153 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11154 NonZero |= !C->getConstantFPValue()->isNullValue(); 11155 } else { 11156 // Non-constant. 11157 break; 11158 } 11159 11160 // Find a legal type for the constant store. 11161 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11162 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11163 bool IsFast; 11164 if (TLI.isTypeLegal(StoreTy) && 11165 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11166 FirstStoreAlign, &IsFast) && IsFast) { 11167 LastLegalType = i+1; 11168 // Or check whether a truncstore is legal. 11169 } else if (TLI.getTypeAction(Context, StoreTy) == 11170 TargetLowering::TypePromoteInteger) { 11171 EVT LegalizedStoredValueTy = 11172 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11173 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11174 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11175 FirstStoreAS, FirstStoreAlign, &IsFast) && 11176 IsFast) { 11177 LastLegalType = i + 1; 11178 } 11179 } 11180 11181 // We only use vectors if the constant is known to be zero or the target 11182 // allows it and the function is not marked with the noimplicitfloat 11183 // attribute. 11184 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11185 FirstStoreAS)) && 11186 !NoVectors) { 11187 // Find a legal type for the vector store. 11188 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11189 if (TLI.isTypeLegal(Ty) && 11190 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11191 FirstStoreAlign, &IsFast) && IsFast) 11192 LastLegalVectorType = i + 1; 11193 } 11194 } 11195 11196 // Check if we found a legal integer type to store. 11197 if (LastLegalType == 0 && LastLegalVectorType == 0) 11198 return false; 11199 11200 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11201 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11202 11203 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11204 true, UseVector); 11205 } 11206 11207 // When extracting multiple vector elements, try to store them 11208 // in one vector store rather than a sequence of scalar stores. 11209 if (IsExtractVecSrc) { 11210 unsigned NumStoresToMerge = 0; 11211 bool IsVec = MemVT.isVector(); 11212 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11213 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11214 unsigned StoreValOpcode = St->getValue().getOpcode(); 11215 // This restriction could be loosened. 11216 // Bail out if any stored values are not elements extracted from a vector. 11217 // It should be possible to handle mixed sources, but load sources need 11218 // more careful handling (see the block of code below that handles 11219 // consecutive loads). 11220 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11221 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11222 return false; 11223 11224 // Find a legal type for the vector store. 11225 unsigned Elts = i + 1; 11226 if (IsVec) { 11227 // When merging vector stores, get the total number of elements. 11228 Elts *= MemVT.getVectorNumElements(); 11229 } 11230 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11231 bool IsFast; 11232 if (TLI.isTypeLegal(Ty) && 11233 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11234 FirstStoreAlign, &IsFast) && IsFast) 11235 NumStoresToMerge = i + 1; 11236 } 11237 11238 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11239 false, true); 11240 } 11241 11242 // Below we handle the case of multiple consecutive stores that 11243 // come from multiple consecutive loads. We merge them into a single 11244 // wide load and a single wide store. 11245 11246 // Look for load nodes which are used by the stored values. 11247 SmallVector<MemOpLink, 8> LoadNodes; 11248 11249 // Find acceptable loads. Loads need to have the same chain (token factor), 11250 // must not be zext, volatile, indexed, and they must be consecutive. 11251 BaseIndexOffset LdBasePtr; 11252 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11253 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11254 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11255 if (!Ld) break; 11256 11257 // Loads must only have one use. 11258 if (!Ld->hasNUsesOfValue(1, 0)) 11259 break; 11260 11261 // The memory operands must not be volatile. 11262 if (Ld->isVolatile() || Ld->isIndexed()) 11263 break; 11264 11265 // We do not accept ext loads. 11266 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11267 break; 11268 11269 // The stored memory type must be the same. 11270 if (Ld->getMemoryVT() != MemVT) 11271 break; 11272 11273 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 11274 // If this is not the first ptr that we check. 11275 if (LdBasePtr.Base.getNode()) { 11276 // The base ptr must be the same. 11277 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11278 break; 11279 } else { 11280 // Check that all other base pointers are the same as this one. 11281 LdBasePtr = LdPtr; 11282 } 11283 11284 // We found a potential memory operand to merge. 11285 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11286 } 11287 11288 if (LoadNodes.size() < 2) 11289 return false; 11290 11291 // If we have load/store pair instructions and we only have two values, 11292 // don't bother. 11293 unsigned RequiredAlignment; 11294 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11295 St->getAlignment() >= RequiredAlignment) 11296 return false; 11297 11298 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11299 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11300 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11301 11302 // Scan the memory operations on the chain and find the first non-consecutive 11303 // load memory address. These variables hold the index in the store node 11304 // array. 11305 unsigned LastConsecutiveLoad = 0; 11306 // This variable refers to the size and not index in the array. 11307 unsigned LastLegalVectorType = 0; 11308 unsigned LastLegalIntegerType = 0; 11309 StartAddress = LoadNodes[0].OffsetFromBase; 11310 SDValue FirstChain = FirstLoad->getChain(); 11311 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11312 // All loads much share the same chain. 11313 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11314 break; 11315 11316 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11317 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11318 break; 11319 LastConsecutiveLoad = i; 11320 // Find a legal type for the vector store. 11321 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11322 bool IsFastSt, IsFastLd; 11323 if (TLI.isTypeLegal(StoreTy) && 11324 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11325 FirstStoreAlign, &IsFastSt) && IsFastSt && 11326 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11327 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11328 LastLegalVectorType = i + 1; 11329 } 11330 11331 // Find a legal type for the integer store. 11332 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11333 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11334 if (TLI.isTypeLegal(StoreTy) && 11335 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11336 FirstStoreAlign, &IsFastSt) && IsFastSt && 11337 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11338 FirstLoadAlign, &IsFastLd) && IsFastLd) 11339 LastLegalIntegerType = i + 1; 11340 // Or check whether a truncstore and extload is legal. 11341 else if (TLI.getTypeAction(Context, StoreTy) == 11342 TargetLowering::TypePromoteInteger) { 11343 EVT LegalizedStoredValueTy = 11344 TLI.getTypeToTransformTo(Context, StoreTy); 11345 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11346 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11347 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11348 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11349 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11350 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11351 IsFastSt && 11352 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11353 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11354 IsFastLd) 11355 LastLegalIntegerType = i+1; 11356 } 11357 } 11358 11359 // Only use vector types if the vector type is larger than the integer type. 11360 // If they are the same, use integers. 11361 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11362 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11363 11364 // We add +1 here because the LastXXX variables refer to location while 11365 // the NumElem refers to array/index size. 11366 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11367 NumElem = std::min(LastLegalType, NumElem); 11368 11369 if (NumElem < 2) 11370 return false; 11371 11372 // Collect the chains from all merged stores. 11373 SmallVector<SDValue, 8> MergeStoreChains; 11374 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11375 11376 // The latest Node in the DAG. 11377 unsigned LatestNodeUsed = 0; 11378 for (unsigned i=1; i<NumElem; ++i) { 11379 // Find a chain for the new wide-store operand. Notice that some 11380 // of the store nodes that we found may not be selected for inclusion 11381 // in the wide store. The chain we use needs to be the chain of the 11382 // latest store node which is *used* and replaced by the wide store. 11383 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11384 LatestNodeUsed = i; 11385 11386 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11387 } 11388 11389 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11390 11391 // Find if it is better to use vectors or integers to load and store 11392 // to memory. 11393 EVT JointMemOpVT; 11394 if (UseVectorTy) { 11395 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11396 } else { 11397 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11398 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11399 } 11400 11401 SDLoc LoadDL(LoadNodes[0].MemNode); 11402 SDLoc StoreDL(StoreNodes[0].MemNode); 11403 11404 // The merged loads are required to have the same chain, so using the first's 11405 // chain is acceptable. 11406 SDValue NewLoad = DAG.getLoad( 11407 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11408 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11409 11410 SDValue NewStoreChain = 11411 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11412 11413 SDValue NewStore = DAG.getStore( 11414 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11415 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11416 11417 // Replace one of the loads with the new load. 11418 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 11419 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11420 SDValue(NewLoad.getNode(), 1)); 11421 11422 // Remove the rest of the load chains. 11423 for (unsigned i = 1; i < NumElem ; ++i) { 11424 // Replace all chain users of the old load nodes with the chain of the new 11425 // load node. 11426 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11427 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 11428 } 11429 11430 // Replace the last store with the new store. 11431 CombineTo(LatestOp, NewStore); 11432 // Erase all other stores. 11433 for (unsigned i = 0; i < NumElem ; ++i) { 11434 // Remove all Store nodes. 11435 if (StoreNodes[i].MemNode == LatestOp) 11436 continue; 11437 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11438 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11439 deleteAndRecombine(St); 11440 } 11441 11442 return true; 11443 } 11444 11445 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11446 SDLoc SL(ST); 11447 SDValue ReplStore; 11448 11449 // Replace the chain to avoid dependency. 11450 if (ST->isTruncatingStore()) { 11451 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11452 ST->getBasePtr(), ST->getMemoryVT(), 11453 ST->getMemOperand()); 11454 } else { 11455 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11456 ST->getMemOperand()); 11457 } 11458 11459 // Create token to keep both nodes around. 11460 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11461 MVT::Other, ST->getChain(), ReplStore); 11462 11463 // Make sure the new and old chains are cleaned up. 11464 AddToWorklist(Token.getNode()); 11465 11466 // Don't add users to work list. 11467 return CombineTo(ST, Token, false); 11468 } 11469 11470 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11471 SDValue Value = ST->getValue(); 11472 if (Value.getOpcode() == ISD::TargetConstantFP) 11473 return SDValue(); 11474 11475 SDLoc DL(ST); 11476 11477 SDValue Chain = ST->getChain(); 11478 SDValue Ptr = ST->getBasePtr(); 11479 11480 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11481 11482 // NOTE: If the original store is volatile, this transform must not increase 11483 // the number of stores. For example, on x86-32 an f64 can be stored in one 11484 // processor operation but an i64 (which is not legal) requires two. So the 11485 // transform should not be done in this case. 11486 11487 SDValue Tmp; 11488 switch (CFP->getSimpleValueType(0).SimpleTy) { 11489 default: 11490 llvm_unreachable("Unknown FP type"); 11491 case MVT::f16: // We don't do this for these yet. 11492 case MVT::f80: 11493 case MVT::f128: 11494 case MVT::ppcf128: 11495 return SDValue(); 11496 case MVT::f32: 11497 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11498 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11499 ; 11500 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11501 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11502 MVT::i32); 11503 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11504 } 11505 11506 return SDValue(); 11507 case MVT::f64: 11508 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11509 !ST->isVolatile()) || 11510 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11511 ; 11512 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11513 getZExtValue(), SDLoc(CFP), MVT::i64); 11514 return DAG.getStore(Chain, DL, Tmp, 11515 Ptr, ST->getMemOperand()); 11516 } 11517 11518 if (!ST->isVolatile() && 11519 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11520 // Many FP stores are not made apparent until after legalize, e.g. for 11521 // argument passing. Since this is so common, custom legalize the 11522 // 64-bit integer store into two 32-bit stores. 11523 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11524 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11525 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11526 if (DAG.getDataLayout().isBigEndian()) 11527 std::swap(Lo, Hi); 11528 11529 unsigned Alignment = ST->getAlignment(); 11530 bool isVolatile = ST->isVolatile(); 11531 bool isNonTemporal = ST->isNonTemporal(); 11532 AAMDNodes AAInfo = ST->getAAInfo(); 11533 11534 SDValue St0 = DAG.getStore(Chain, DL, Lo, 11535 Ptr, ST->getPointerInfo(), 11536 isVolatile, isNonTemporal, 11537 ST->getAlignment(), AAInfo); 11538 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11539 DAG.getConstant(4, DL, Ptr.getValueType())); 11540 Alignment = MinAlign(Alignment, 4U); 11541 SDValue St1 = DAG.getStore(Chain, DL, Hi, 11542 Ptr, ST->getPointerInfo().getWithOffset(4), 11543 isVolatile, isNonTemporal, 11544 Alignment, AAInfo); 11545 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11546 St0, St1); 11547 } 11548 11549 return SDValue(); 11550 } 11551 } 11552 11553 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11554 StoreSDNode *ST = cast<StoreSDNode>(N); 11555 SDValue Chain = ST->getChain(); 11556 SDValue Value = ST->getValue(); 11557 SDValue Ptr = ST->getBasePtr(); 11558 11559 // If this is a store of a bit convert, store the input value if the 11560 // resultant store does not need a higher alignment than the original. 11561 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11562 ST->isUnindexed()) { 11563 unsigned OrigAlign = ST->getAlignment(); 11564 EVT SVT = Value.getOperand(0).getValueType(); 11565 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 11566 SVT.getTypeForEVT(*DAG.getContext())); 11567 if (Align <= OrigAlign && 11568 ((!LegalOperations && !ST->isVolatile()) || 11569 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 11570 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11571 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11572 ST->isNonTemporal(), OrigAlign, 11573 ST->getAAInfo()); 11574 } 11575 11576 // Turn 'store undef, Ptr' -> nothing. 11577 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 11578 return Chain; 11579 11580 // Try to infer better alignment information than the store already has. 11581 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 11582 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11583 if (Align > ST->getAlignment()) { 11584 SDValue NewStore = 11585 DAG.getTruncStore(Chain, SDLoc(N), Value, 11586 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 11587 ST->isVolatile(), ST->isNonTemporal(), Align, 11588 ST->getAAInfo()); 11589 if (NewStore.getNode() != N) 11590 return CombineTo(ST, NewStore, true); 11591 } 11592 } 11593 } 11594 11595 // Try transforming a pair floating point load / store ops to integer 11596 // load / store ops. 11597 if (SDValue NewST = TransformFPLoadStorePair(N)) 11598 return NewST; 11599 11600 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11601 : DAG.getSubtarget().useAA(); 11602 #ifndef NDEBUG 11603 if (CombinerAAOnlyFunc.getNumOccurrences() && 11604 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11605 UseAA = false; 11606 #endif 11607 if (UseAA && ST->isUnindexed()) { 11608 // FIXME: We should do this even without AA enabled. AA will just allow 11609 // FindBetterChain to work in more situations. The problem with this is that 11610 // any combine that expects memory operations to be on consecutive chains 11611 // first needs to be updated to look for users of the same chain. 11612 11613 // Walk up chain skipping non-aliasing memory nodes, on this store and any 11614 // adjacent stores. 11615 if (findBetterNeighborChains(ST)) { 11616 // replaceStoreChain uses CombineTo, which handled all of the worklist 11617 // manipulation. Return the original node to not do anything else. 11618 return SDValue(ST, 0); 11619 } 11620 } 11621 11622 // Try transforming N to an indexed store. 11623 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11624 return SDValue(N, 0); 11625 11626 // FIXME: is there such a thing as a truncating indexed store? 11627 if (ST->isTruncatingStore() && ST->isUnindexed() && 11628 Value.getValueType().isInteger()) { 11629 // See if we can simplify the input to this truncstore with knowledge that 11630 // only the low bits are being used. For example: 11631 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 11632 SDValue Shorter = 11633 GetDemandedBits(Value, 11634 APInt::getLowBitsSet( 11635 Value.getValueType().getScalarType().getSizeInBits(), 11636 ST->getMemoryVT().getScalarType().getSizeInBits())); 11637 AddToWorklist(Value.getNode()); 11638 if (Shorter.getNode()) 11639 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 11640 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11641 11642 // Otherwise, see if we can simplify the operation with 11643 // SimplifyDemandedBits, which only works if the value has a single use. 11644 if (SimplifyDemandedBits(Value, 11645 APInt::getLowBitsSet( 11646 Value.getValueType().getScalarType().getSizeInBits(), 11647 ST->getMemoryVT().getScalarType().getSizeInBits()))) 11648 return SDValue(N, 0); 11649 } 11650 11651 // If this is a load followed by a store to the same location, then the store 11652 // is dead/noop. 11653 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 11654 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 11655 ST->isUnindexed() && !ST->isVolatile() && 11656 // There can't be any side effects between the load and store, such as 11657 // a call or store. 11658 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 11659 // The store is dead, remove it. 11660 return Chain; 11661 } 11662 } 11663 11664 // If this is a store followed by a store with the same value to the same 11665 // location, then the store is dead/noop. 11666 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 11667 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 11668 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 11669 ST1->isUnindexed() && !ST1->isVolatile()) { 11670 // The store is dead, remove it. 11671 return Chain; 11672 } 11673 } 11674 11675 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 11676 // truncating store. We can do this even if this is already a truncstore. 11677 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 11678 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 11679 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 11680 ST->getMemoryVT())) { 11681 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 11682 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11683 } 11684 11685 // Only perform this optimization before the types are legal, because we 11686 // don't want to perform this optimization on every DAGCombine invocation. 11687 if (!LegalTypes) { 11688 bool EverChanged = false; 11689 11690 do { 11691 // There can be multiple store sequences on the same chain. 11692 // Keep trying to merge store sequences until we are unable to do so 11693 // or until we merge the last store on the chain. 11694 bool Changed = MergeConsecutiveStores(ST); 11695 EverChanged |= Changed; 11696 if (!Changed) break; 11697 } while (ST->getOpcode() != ISD::DELETED_NODE); 11698 11699 if (EverChanged) 11700 return SDValue(N, 0); 11701 } 11702 11703 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 11704 // 11705 // Make sure to do this only after attempting to merge stores in order to 11706 // avoid changing the types of some subset of stores due to visit order, 11707 // preventing their merging. 11708 if (isa<ConstantFPSDNode>(Value)) { 11709 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 11710 return NewSt; 11711 } 11712 11713 return ReduceLoadOpStoreWidth(N); 11714 } 11715 11716 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 11717 SDValue InVec = N->getOperand(0); 11718 SDValue InVal = N->getOperand(1); 11719 SDValue EltNo = N->getOperand(2); 11720 SDLoc dl(N); 11721 11722 // If the inserted element is an UNDEF, just use the input vector. 11723 if (InVal.getOpcode() == ISD::UNDEF) 11724 return InVec; 11725 11726 EVT VT = InVec.getValueType(); 11727 11728 // If we can't generate a legal BUILD_VECTOR, exit 11729 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 11730 return SDValue(); 11731 11732 // Check that we know which element is being inserted 11733 if (!isa<ConstantSDNode>(EltNo)) 11734 return SDValue(); 11735 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11736 11737 // Canonicalize insert_vector_elt dag nodes. 11738 // Example: 11739 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 11740 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 11741 // 11742 // Do this only if the child insert_vector node has one use; also 11743 // do this only if indices are both constants and Idx1 < Idx0. 11744 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 11745 && isa<ConstantSDNode>(InVec.getOperand(2))) { 11746 unsigned OtherElt = 11747 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 11748 if (Elt < OtherElt) { 11749 // Swap nodes. 11750 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 11751 InVec.getOperand(0), InVal, EltNo); 11752 AddToWorklist(NewOp.getNode()); 11753 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 11754 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 11755 } 11756 } 11757 11758 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 11759 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 11760 // vector elements. 11761 SmallVector<SDValue, 8> Ops; 11762 // Do not combine these two vectors if the output vector will not replace 11763 // the input vector. 11764 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 11765 Ops.append(InVec.getNode()->op_begin(), 11766 InVec.getNode()->op_end()); 11767 } else if (InVec.getOpcode() == ISD::UNDEF) { 11768 unsigned NElts = VT.getVectorNumElements(); 11769 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 11770 } else { 11771 return SDValue(); 11772 } 11773 11774 // Insert the element 11775 if (Elt < Ops.size()) { 11776 // All the operands of BUILD_VECTOR must have the same type; 11777 // we enforce that here. 11778 EVT OpVT = Ops[0].getValueType(); 11779 if (InVal.getValueType() != OpVT) 11780 InVal = OpVT.bitsGT(InVal.getValueType()) ? 11781 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 11782 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 11783 Ops[Elt] = InVal; 11784 } 11785 11786 // Return the new vector 11787 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 11788 } 11789 11790 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 11791 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 11792 EVT ResultVT = EVE->getValueType(0); 11793 EVT VecEltVT = InVecVT.getVectorElementType(); 11794 unsigned Align = OriginalLoad->getAlignment(); 11795 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 11796 VecEltVT.getTypeForEVT(*DAG.getContext())); 11797 11798 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 11799 return SDValue(); 11800 11801 Align = NewAlign; 11802 11803 SDValue NewPtr = OriginalLoad->getBasePtr(); 11804 SDValue Offset; 11805 EVT PtrType = NewPtr.getValueType(); 11806 MachinePointerInfo MPI; 11807 SDLoc DL(EVE); 11808 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 11809 int Elt = ConstEltNo->getZExtValue(); 11810 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 11811 Offset = DAG.getConstant(PtrOff, DL, PtrType); 11812 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 11813 } else { 11814 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 11815 Offset = DAG.getNode( 11816 ISD::MUL, DL, PtrType, Offset, 11817 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 11818 MPI = OriginalLoad->getPointerInfo(); 11819 } 11820 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 11821 11822 // The replacement we need to do here is a little tricky: we need to 11823 // replace an extractelement of a load with a load. 11824 // Use ReplaceAllUsesOfValuesWith to do the replacement. 11825 // Note that this replacement assumes that the extractvalue is the only 11826 // use of the load; that's okay because we don't want to perform this 11827 // transformation in other cases anyway. 11828 SDValue Load; 11829 SDValue Chain; 11830 if (ResultVT.bitsGT(VecEltVT)) { 11831 // If the result type of vextract is wider than the load, then issue an 11832 // extending load instead. 11833 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 11834 VecEltVT) 11835 ? ISD::ZEXTLOAD 11836 : ISD::EXTLOAD; 11837 Load = DAG.getExtLoad( 11838 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 11839 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11840 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11841 Chain = Load.getValue(1); 11842 } else { 11843 Load = DAG.getLoad( 11844 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 11845 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11846 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11847 Chain = Load.getValue(1); 11848 if (ResultVT.bitsLT(VecEltVT)) 11849 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 11850 else 11851 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 11852 } 11853 WorklistRemover DeadNodes(*this); 11854 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 11855 SDValue To[] = { Load, Chain }; 11856 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 11857 // Since we're explicitly calling ReplaceAllUses, add the new node to the 11858 // worklist explicitly as well. 11859 AddToWorklist(Load.getNode()); 11860 AddUsersToWorklist(Load.getNode()); // Add users too 11861 // Make sure to revisit this node to clean it up; it will usually be dead. 11862 AddToWorklist(EVE); 11863 ++OpsNarrowed; 11864 return SDValue(EVE, 0); 11865 } 11866 11867 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 11868 // (vextract (scalar_to_vector val, 0) -> val 11869 SDValue InVec = N->getOperand(0); 11870 EVT VT = InVec.getValueType(); 11871 EVT NVT = N->getValueType(0); 11872 11873 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 11874 // Check if the result type doesn't match the inserted element type. A 11875 // SCALAR_TO_VECTOR may truncate the inserted element and the 11876 // EXTRACT_VECTOR_ELT may widen the extracted vector. 11877 SDValue InOp = InVec.getOperand(0); 11878 if (InOp.getValueType() != NVT) { 11879 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11880 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 11881 } 11882 return InOp; 11883 } 11884 11885 SDValue EltNo = N->getOperand(1); 11886 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 11887 11888 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 11889 // We only perform this optimization before the op legalization phase because 11890 // we may introduce new vector instructions which are not backed by TD 11891 // patterns. For example on AVX, extracting elements from a wide vector 11892 // without using extract_subvector. However, if we can find an underlying 11893 // scalar value, then we can always use that. 11894 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 11895 && ConstEltNo) { 11896 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11897 int NumElem = VT.getVectorNumElements(); 11898 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 11899 // Find the new index to extract from. 11900 int OrigElt = SVOp->getMaskElt(Elt); 11901 11902 // Extracting an undef index is undef. 11903 if (OrigElt == -1) 11904 return DAG.getUNDEF(NVT); 11905 11906 // Select the right vector half to extract from. 11907 SDValue SVInVec; 11908 if (OrigElt < NumElem) { 11909 SVInVec = InVec->getOperand(0); 11910 } else { 11911 SVInVec = InVec->getOperand(1); 11912 OrigElt -= NumElem; 11913 } 11914 11915 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 11916 SDValue InOp = SVInVec.getOperand(OrigElt); 11917 if (InOp.getValueType() != NVT) { 11918 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11919 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 11920 } 11921 11922 return InOp; 11923 } 11924 11925 // FIXME: We should handle recursing on other vector shuffles and 11926 // scalar_to_vector here as well. 11927 11928 if (!LegalOperations) { 11929 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 11930 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 11931 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 11932 } 11933 } 11934 11935 bool BCNumEltsChanged = false; 11936 EVT ExtVT = VT.getVectorElementType(); 11937 EVT LVT = ExtVT; 11938 11939 // If the result of load has to be truncated, then it's not necessarily 11940 // profitable. 11941 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 11942 return SDValue(); 11943 11944 if (InVec.getOpcode() == ISD::BITCAST) { 11945 // Don't duplicate a load with other uses. 11946 if (!InVec.hasOneUse()) 11947 return SDValue(); 11948 11949 EVT BCVT = InVec.getOperand(0).getValueType(); 11950 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 11951 return SDValue(); 11952 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 11953 BCNumEltsChanged = true; 11954 InVec = InVec.getOperand(0); 11955 ExtVT = BCVT.getVectorElementType(); 11956 } 11957 11958 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 11959 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 11960 ISD::isNormalLoad(InVec.getNode()) && 11961 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 11962 SDValue Index = N->getOperand(1); 11963 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 11964 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 11965 OrigLoad); 11966 } 11967 11968 // Perform only after legalization to ensure build_vector / vector_shuffle 11969 // optimizations have already been done. 11970 if (!LegalOperations) return SDValue(); 11971 11972 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 11973 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 11974 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 11975 11976 if (ConstEltNo) { 11977 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11978 11979 LoadSDNode *LN0 = nullptr; 11980 const ShuffleVectorSDNode *SVN = nullptr; 11981 if (ISD::isNormalLoad(InVec.getNode())) { 11982 LN0 = cast<LoadSDNode>(InVec); 11983 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 11984 InVec.getOperand(0).getValueType() == ExtVT && 11985 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 11986 // Don't duplicate a load with other uses. 11987 if (!InVec.hasOneUse()) 11988 return SDValue(); 11989 11990 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 11991 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 11992 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 11993 // => 11994 // (load $addr+1*size) 11995 11996 // Don't duplicate a load with other uses. 11997 if (!InVec.hasOneUse()) 11998 return SDValue(); 11999 12000 // If the bit convert changed the number of elements, it is unsafe 12001 // to examine the mask. 12002 if (BCNumEltsChanged) 12003 return SDValue(); 12004 12005 // Select the input vector, guarding against out of range extract vector. 12006 unsigned NumElems = VT.getVectorNumElements(); 12007 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12008 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12009 12010 if (InVec.getOpcode() == ISD::BITCAST) { 12011 // Don't duplicate a load with other uses. 12012 if (!InVec.hasOneUse()) 12013 return SDValue(); 12014 12015 InVec = InVec.getOperand(0); 12016 } 12017 if (ISD::isNormalLoad(InVec.getNode())) { 12018 LN0 = cast<LoadSDNode>(InVec); 12019 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12020 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12021 } 12022 } 12023 12024 // Make sure we found a non-volatile load and the extractelement is 12025 // the only use. 12026 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12027 return SDValue(); 12028 12029 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12030 if (Elt == -1) 12031 return DAG.getUNDEF(LVT); 12032 12033 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12034 } 12035 12036 return SDValue(); 12037 } 12038 12039 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12040 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12041 // We perform this optimization post type-legalization because 12042 // the type-legalizer often scalarizes integer-promoted vectors. 12043 // Performing this optimization before may create bit-casts which 12044 // will be type-legalized to complex code sequences. 12045 // We perform this optimization only before the operation legalizer because we 12046 // may introduce illegal operations. 12047 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12048 return SDValue(); 12049 12050 unsigned NumInScalars = N->getNumOperands(); 12051 SDLoc dl(N); 12052 EVT VT = N->getValueType(0); 12053 12054 // Check to see if this is a BUILD_VECTOR of a bunch of values 12055 // which come from any_extend or zero_extend nodes. If so, we can create 12056 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12057 // optimizations. We do not handle sign-extend because we can't fill the sign 12058 // using shuffles. 12059 EVT SourceType = MVT::Other; 12060 bool AllAnyExt = true; 12061 12062 for (unsigned i = 0; i != NumInScalars; ++i) { 12063 SDValue In = N->getOperand(i); 12064 // Ignore undef inputs. 12065 if (In.getOpcode() == ISD::UNDEF) continue; 12066 12067 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12068 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12069 12070 // Abort if the element is not an extension. 12071 if (!ZeroExt && !AnyExt) { 12072 SourceType = MVT::Other; 12073 break; 12074 } 12075 12076 // The input is a ZeroExt or AnyExt. Check the original type. 12077 EVT InTy = In.getOperand(0).getValueType(); 12078 12079 // Check that all of the widened source types are the same. 12080 if (SourceType == MVT::Other) 12081 // First time. 12082 SourceType = InTy; 12083 else if (InTy != SourceType) { 12084 // Multiple income types. Abort. 12085 SourceType = MVT::Other; 12086 break; 12087 } 12088 12089 // Check if all of the extends are ANY_EXTENDs. 12090 AllAnyExt &= AnyExt; 12091 } 12092 12093 // In order to have valid types, all of the inputs must be extended from the 12094 // same source type and all of the inputs must be any or zero extend. 12095 // Scalar sizes must be a power of two. 12096 EVT OutScalarTy = VT.getScalarType(); 12097 bool ValidTypes = SourceType != MVT::Other && 12098 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12099 isPowerOf2_32(SourceType.getSizeInBits()); 12100 12101 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12102 // turn into a single shuffle instruction. 12103 if (!ValidTypes) 12104 return SDValue(); 12105 12106 bool isLE = DAG.getDataLayout().isLittleEndian(); 12107 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12108 assert(ElemRatio > 1 && "Invalid element size ratio"); 12109 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12110 DAG.getConstant(0, SDLoc(N), SourceType); 12111 12112 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12113 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12114 12115 // Populate the new build_vector 12116 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12117 SDValue Cast = N->getOperand(i); 12118 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12119 Cast.getOpcode() == ISD::ZERO_EXTEND || 12120 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 12121 SDValue In; 12122 if (Cast.getOpcode() == ISD::UNDEF) 12123 In = DAG.getUNDEF(SourceType); 12124 else 12125 In = Cast->getOperand(0); 12126 unsigned Index = isLE ? (i * ElemRatio) : 12127 (i * ElemRatio + (ElemRatio - 1)); 12128 12129 assert(Index < Ops.size() && "Invalid index"); 12130 Ops[Index] = In; 12131 } 12132 12133 // The type of the new BUILD_VECTOR node. 12134 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12135 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12136 "Invalid vector size"); 12137 // Check if the new vector type is legal. 12138 if (!isTypeLegal(VecVT)) return SDValue(); 12139 12140 // Make the new BUILD_VECTOR. 12141 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 12142 12143 // The new BUILD_VECTOR node has the potential to be further optimized. 12144 AddToWorklist(BV.getNode()); 12145 // Bitcast to the desired type. 12146 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12147 } 12148 12149 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12150 EVT VT = N->getValueType(0); 12151 12152 unsigned NumInScalars = N->getNumOperands(); 12153 SDLoc dl(N); 12154 12155 EVT SrcVT = MVT::Other; 12156 unsigned Opcode = ISD::DELETED_NODE; 12157 unsigned NumDefs = 0; 12158 12159 for (unsigned i = 0; i != NumInScalars; ++i) { 12160 SDValue In = N->getOperand(i); 12161 unsigned Opc = In.getOpcode(); 12162 12163 if (Opc == ISD::UNDEF) 12164 continue; 12165 12166 // If all scalar values are floats and converted from integers. 12167 if (Opcode == ISD::DELETED_NODE && 12168 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12169 Opcode = Opc; 12170 } 12171 12172 if (Opc != Opcode) 12173 return SDValue(); 12174 12175 EVT InVT = In.getOperand(0).getValueType(); 12176 12177 // If all scalar values are typed differently, bail out. It's chosen to 12178 // simplify BUILD_VECTOR of integer types. 12179 if (SrcVT == MVT::Other) 12180 SrcVT = InVT; 12181 if (SrcVT != InVT) 12182 return SDValue(); 12183 NumDefs++; 12184 } 12185 12186 // If the vector has just one element defined, it's not worth to fold it into 12187 // a vectorized one. 12188 if (NumDefs < 2) 12189 return SDValue(); 12190 12191 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12192 && "Should only handle conversion from integer to float."); 12193 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12194 12195 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12196 12197 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12198 return SDValue(); 12199 12200 // Just because the floating-point vector type is legal does not necessarily 12201 // mean that the corresponding integer vector type is. 12202 if (!isTypeLegal(NVT)) 12203 return SDValue(); 12204 12205 SmallVector<SDValue, 8> Opnds; 12206 for (unsigned i = 0; i != NumInScalars; ++i) { 12207 SDValue In = N->getOperand(i); 12208 12209 if (In.getOpcode() == ISD::UNDEF) 12210 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12211 else 12212 Opnds.push_back(In.getOperand(0)); 12213 } 12214 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 12215 AddToWorklist(BV.getNode()); 12216 12217 return DAG.getNode(Opcode, dl, VT, BV); 12218 } 12219 12220 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12221 unsigned NumInScalars = N->getNumOperands(); 12222 SDLoc dl(N); 12223 EVT VT = N->getValueType(0); 12224 12225 // A vector built entirely of undefs is undef. 12226 if (ISD::allOperandsUndef(N)) 12227 return DAG.getUNDEF(VT); 12228 12229 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12230 return V; 12231 12232 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12233 return V; 12234 12235 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12236 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12237 // at most two distinct vectors, turn this into a shuffle node. 12238 12239 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12240 if (!isTypeLegal(VT)) 12241 return SDValue(); 12242 12243 // May only combine to shuffle after legalize if shuffle is legal. 12244 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12245 return SDValue(); 12246 12247 SDValue VecIn1, VecIn2; 12248 bool UsesZeroVector = false; 12249 for (unsigned i = 0; i != NumInScalars; ++i) { 12250 SDValue Op = N->getOperand(i); 12251 // Ignore undef inputs. 12252 if (Op.getOpcode() == ISD::UNDEF) continue; 12253 12254 // See if we can combine this build_vector into a blend with a zero vector. 12255 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12256 UsesZeroVector = true; 12257 continue; 12258 } 12259 12260 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12261 // constant index, bail out. 12262 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12263 !isa<ConstantSDNode>(Op.getOperand(1))) { 12264 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12265 break; 12266 } 12267 12268 // We allow up to two distinct input vectors. 12269 SDValue ExtractedFromVec = Op.getOperand(0); 12270 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12271 continue; 12272 12273 if (!VecIn1.getNode()) { 12274 VecIn1 = ExtractedFromVec; 12275 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12276 VecIn2 = ExtractedFromVec; 12277 } else { 12278 // Too many inputs. 12279 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12280 break; 12281 } 12282 } 12283 12284 // If everything is good, we can make a shuffle operation. 12285 if (VecIn1.getNode()) { 12286 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12287 SmallVector<int, 8> Mask; 12288 for (unsigned i = 0; i != NumInScalars; ++i) { 12289 unsigned Opcode = N->getOperand(i).getOpcode(); 12290 if (Opcode == ISD::UNDEF) { 12291 Mask.push_back(-1); 12292 continue; 12293 } 12294 12295 // Operands can also be zero. 12296 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12297 assert(UsesZeroVector && 12298 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12299 "Unexpected node found!"); 12300 Mask.push_back(NumInScalars+i); 12301 continue; 12302 } 12303 12304 // If extracting from the first vector, just use the index directly. 12305 SDValue Extract = N->getOperand(i); 12306 SDValue ExtVal = Extract.getOperand(1); 12307 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12308 if (Extract.getOperand(0) == VecIn1) { 12309 Mask.push_back(ExtIndex); 12310 continue; 12311 } 12312 12313 // Otherwise, use InIdx + InputVecSize 12314 Mask.push_back(InNumElements + ExtIndex); 12315 } 12316 12317 // Avoid introducing illegal shuffles with zero. 12318 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12319 return SDValue(); 12320 12321 // We can't generate a shuffle node with mismatched input and output types. 12322 // Attempt to transform a single input vector to the correct type. 12323 if ((VT != VecIn1.getValueType())) { 12324 // If the input vector type has a different base type to the output 12325 // vector type, bail out. 12326 EVT VTElemType = VT.getVectorElementType(); 12327 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12328 (VecIn2.getNode() && 12329 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12330 return SDValue(); 12331 12332 // If the input vector is too small, widen it. 12333 // We only support widening of vectors which are half the size of the 12334 // output registers. For example XMM->YMM widening on X86 with AVX. 12335 EVT VecInT = VecIn1.getValueType(); 12336 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12337 // If we only have one small input, widen it by adding undef values. 12338 if (!VecIn2.getNode()) 12339 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12340 DAG.getUNDEF(VecIn1.getValueType())); 12341 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12342 // If we have two small inputs of the same type, try to concat them. 12343 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12344 VecIn2 = SDValue(nullptr, 0); 12345 } else 12346 return SDValue(); 12347 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12348 // If the input vector is too large, try to split it. 12349 // We don't support having two input vectors that are too large. 12350 // If the zero vector was used, we can not split the vector, 12351 // since we'd need 3 inputs. 12352 if (UsesZeroVector || VecIn2.getNode()) 12353 return SDValue(); 12354 12355 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12356 return SDValue(); 12357 12358 // Try to replace VecIn1 with two extract_subvectors 12359 // No need to update the masks, they should still be correct. 12360 VecIn2 = DAG.getNode( 12361 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12362 DAG.getConstant(VT.getVectorNumElements(), dl, 12363 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12364 VecIn1 = DAG.getNode( 12365 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12366 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12367 } else 12368 return SDValue(); 12369 } 12370 12371 if (UsesZeroVector) 12372 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12373 DAG.getConstantFP(0.0, dl, VT); 12374 else 12375 // If VecIn2 is unused then change it to undef. 12376 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12377 12378 // Check that we were able to transform all incoming values to the same 12379 // type. 12380 if (VecIn2.getValueType() != VecIn1.getValueType() || 12381 VecIn1.getValueType() != VT) 12382 return SDValue(); 12383 12384 // Return the new VECTOR_SHUFFLE node. 12385 SDValue Ops[2]; 12386 Ops[0] = VecIn1; 12387 Ops[1] = VecIn2; 12388 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12389 } 12390 12391 return SDValue(); 12392 } 12393 12394 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12395 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12396 EVT OpVT = N->getOperand(0).getValueType(); 12397 12398 // If the operands are legal vectors, leave them alone. 12399 if (TLI.isTypeLegal(OpVT)) 12400 return SDValue(); 12401 12402 SDLoc DL(N); 12403 EVT VT = N->getValueType(0); 12404 SmallVector<SDValue, 8> Ops; 12405 12406 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12407 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12408 12409 // Keep track of what we encounter. 12410 bool AnyInteger = false; 12411 bool AnyFP = false; 12412 for (const SDValue &Op : N->ops()) { 12413 if (ISD::BITCAST == Op.getOpcode() && 12414 !Op.getOperand(0).getValueType().isVector()) 12415 Ops.push_back(Op.getOperand(0)); 12416 else if (ISD::UNDEF == Op.getOpcode()) 12417 Ops.push_back(ScalarUndef); 12418 else 12419 return SDValue(); 12420 12421 // Note whether we encounter an integer or floating point scalar. 12422 // If it's neither, bail out, it could be something weird like x86mmx. 12423 EVT LastOpVT = Ops.back().getValueType(); 12424 if (LastOpVT.isFloatingPoint()) 12425 AnyFP = true; 12426 else if (LastOpVT.isInteger()) 12427 AnyInteger = true; 12428 else 12429 return SDValue(); 12430 } 12431 12432 // If any of the operands is a floating point scalar bitcast to a vector, 12433 // use floating point types throughout, and bitcast everything. 12434 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12435 if (AnyFP) { 12436 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12437 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12438 if (AnyInteger) { 12439 for (SDValue &Op : Ops) { 12440 if (Op.getValueType() == SVT) 12441 continue; 12442 if (Op.getOpcode() == ISD::UNDEF) 12443 Op = ScalarUndef; 12444 else 12445 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12446 } 12447 } 12448 } 12449 12450 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12451 VT.getSizeInBits() / SVT.getSizeInBits()); 12452 return DAG.getNode(ISD::BITCAST, DL, VT, 12453 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 12454 } 12455 12456 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12457 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12458 // most two distinct vectors the same size as the result, attempt to turn this 12459 // into a legal shuffle. 12460 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12461 EVT VT = N->getValueType(0); 12462 EVT OpVT = N->getOperand(0).getValueType(); 12463 int NumElts = VT.getVectorNumElements(); 12464 int NumOpElts = OpVT.getVectorNumElements(); 12465 12466 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12467 SmallVector<int, 8> Mask; 12468 12469 for (SDValue Op : N->ops()) { 12470 // Peek through any bitcast. 12471 while (Op.getOpcode() == ISD::BITCAST) 12472 Op = Op.getOperand(0); 12473 12474 // UNDEF nodes convert to UNDEF shuffle mask values. 12475 if (Op.getOpcode() == ISD::UNDEF) { 12476 Mask.append((unsigned)NumOpElts, -1); 12477 continue; 12478 } 12479 12480 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12481 return SDValue(); 12482 12483 // What vector are we extracting the subvector from and at what index? 12484 SDValue ExtVec = Op.getOperand(0); 12485 12486 // We want the EVT of the original extraction to correctly scale the 12487 // extraction index. 12488 EVT ExtVT = ExtVec.getValueType(); 12489 12490 // Peek through any bitcast. 12491 while (ExtVec.getOpcode() == ISD::BITCAST) 12492 ExtVec = ExtVec.getOperand(0); 12493 12494 // UNDEF nodes convert to UNDEF shuffle mask values. 12495 if (ExtVec.getOpcode() == ISD::UNDEF) { 12496 Mask.append((unsigned)NumOpElts, -1); 12497 continue; 12498 } 12499 12500 if (!isa<ConstantSDNode>(Op.getOperand(1))) 12501 return SDValue(); 12502 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 12503 12504 // Ensure that we are extracting a subvector from a vector the same 12505 // size as the result. 12506 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 12507 return SDValue(); 12508 12509 // Scale the subvector index to account for any bitcast. 12510 int NumExtElts = ExtVT.getVectorNumElements(); 12511 if (0 == (NumExtElts % NumElts)) 12512 ExtIdx /= (NumExtElts / NumElts); 12513 else if (0 == (NumElts % NumExtElts)) 12514 ExtIdx *= (NumElts / NumExtElts); 12515 else 12516 return SDValue(); 12517 12518 // At most we can reference 2 inputs in the final shuffle. 12519 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) { 12520 SV0 = ExtVec; 12521 for (int i = 0; i != NumOpElts; ++i) 12522 Mask.push_back(i + ExtIdx); 12523 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) { 12524 SV1 = ExtVec; 12525 for (int i = 0; i != NumOpElts; ++i) 12526 Mask.push_back(i + ExtIdx + NumElts); 12527 } else { 12528 return SDValue(); 12529 } 12530 } 12531 12532 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 12533 return SDValue(); 12534 12535 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 12536 DAG.getBitcast(VT, SV1), Mask); 12537 } 12538 12539 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12540 // If we only have one input vector, we don't need to do any concatenation. 12541 if (N->getNumOperands() == 1) 12542 return N->getOperand(0); 12543 12544 // Check if all of the operands are undefs. 12545 EVT VT = N->getValueType(0); 12546 if (ISD::allOperandsUndef(N)) 12547 return DAG.getUNDEF(VT); 12548 12549 // Optimize concat_vectors where all but the first of the vectors are undef. 12550 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 12551 return Op.getOpcode() == ISD::UNDEF; 12552 })) { 12553 SDValue In = N->getOperand(0); 12554 assert(In.getValueType().isVector() && "Must concat vectors"); 12555 12556 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 12557 if (In->getOpcode() == ISD::BITCAST && 12558 !In->getOperand(0)->getValueType(0).isVector()) { 12559 SDValue Scalar = In->getOperand(0); 12560 12561 // If the bitcast type isn't legal, it might be a trunc of a legal type; 12562 // look through the trunc so we can still do the transform: 12563 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 12564 if (Scalar->getOpcode() == ISD::TRUNCATE && 12565 !TLI.isTypeLegal(Scalar.getValueType()) && 12566 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 12567 Scalar = Scalar->getOperand(0); 12568 12569 EVT SclTy = Scalar->getValueType(0); 12570 12571 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 12572 return SDValue(); 12573 12574 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 12575 VT.getSizeInBits() / SclTy.getSizeInBits()); 12576 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 12577 return SDValue(); 12578 12579 SDLoc dl = SDLoc(N); 12580 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 12581 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 12582 } 12583 } 12584 12585 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 12586 // We have already tested above for an UNDEF only concatenation. 12587 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 12588 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 12589 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 12590 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 12591 }; 12592 bool AllBuildVectorsOrUndefs = 12593 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 12594 if (AllBuildVectorsOrUndefs) { 12595 SmallVector<SDValue, 8> Opnds; 12596 EVT SVT = VT.getScalarType(); 12597 12598 EVT MinVT = SVT; 12599 if (!SVT.isFloatingPoint()) { 12600 // If BUILD_VECTOR are from built from integer, they may have different 12601 // operand types. Get the smallest type and truncate all operands to it. 12602 bool FoundMinVT = false; 12603 for (const SDValue &Op : N->ops()) 12604 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12605 EVT OpSVT = Op.getOperand(0)->getValueType(0); 12606 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 12607 FoundMinVT = true; 12608 } 12609 assert(FoundMinVT && "Concat vector type mismatch"); 12610 } 12611 12612 for (const SDValue &Op : N->ops()) { 12613 EVT OpVT = Op.getValueType(); 12614 unsigned NumElts = OpVT.getVectorNumElements(); 12615 12616 if (ISD::UNDEF == Op.getOpcode()) 12617 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 12618 12619 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12620 if (SVT.isFloatingPoint()) { 12621 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 12622 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 12623 } else { 12624 for (unsigned i = 0; i != NumElts; ++i) 12625 Opnds.push_back( 12626 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 12627 } 12628 } 12629 } 12630 12631 assert(VT.getVectorNumElements() == Opnds.size() && 12632 "Concat vector type mismatch"); 12633 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 12634 } 12635 12636 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 12637 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 12638 return V; 12639 12640 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 12641 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 12642 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 12643 return V; 12644 12645 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 12646 // nodes often generate nop CONCAT_VECTOR nodes. 12647 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 12648 // place the incoming vectors at the exact same location. 12649 SDValue SingleSource = SDValue(); 12650 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 12651 12652 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12653 SDValue Op = N->getOperand(i); 12654 12655 if (Op.getOpcode() == ISD::UNDEF) 12656 continue; 12657 12658 // Check if this is the identity extract: 12659 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12660 return SDValue(); 12661 12662 // Find the single incoming vector for the extract_subvector. 12663 if (SingleSource.getNode()) { 12664 if (Op.getOperand(0) != SingleSource) 12665 return SDValue(); 12666 } else { 12667 SingleSource = Op.getOperand(0); 12668 12669 // Check the source type is the same as the type of the result. 12670 // If not, this concat may extend the vector, so we can not 12671 // optimize it away. 12672 if (SingleSource.getValueType() != N->getValueType(0)) 12673 return SDValue(); 12674 } 12675 12676 unsigned IdentityIndex = i * PartNumElem; 12677 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 12678 // The extract index must be constant. 12679 if (!CS) 12680 return SDValue(); 12681 12682 // Check that we are reading from the identity index. 12683 if (CS->getZExtValue() != IdentityIndex) 12684 return SDValue(); 12685 } 12686 12687 if (SingleSource.getNode()) 12688 return SingleSource; 12689 12690 return SDValue(); 12691 } 12692 12693 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 12694 EVT NVT = N->getValueType(0); 12695 SDValue V = N->getOperand(0); 12696 12697 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 12698 // Combine: 12699 // (extract_subvec (concat V1, V2, ...), i) 12700 // Into: 12701 // Vi if possible 12702 // Only operand 0 is checked as 'concat' assumes all inputs of the same 12703 // type. 12704 if (V->getOperand(0).getValueType() != NVT) 12705 return SDValue(); 12706 unsigned Idx = N->getConstantOperandVal(1); 12707 unsigned NumElems = NVT.getVectorNumElements(); 12708 assert((Idx % NumElems) == 0 && 12709 "IDX in concat is not a multiple of the result vector length."); 12710 return V->getOperand(Idx / NumElems); 12711 } 12712 12713 // Skip bitcasting 12714 if (V->getOpcode() == ISD::BITCAST) 12715 V = V.getOperand(0); 12716 12717 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 12718 SDLoc dl(N); 12719 // Handle only simple case where vector being inserted and vector 12720 // being extracted are of same type, and are half size of larger vectors. 12721 EVT BigVT = V->getOperand(0).getValueType(); 12722 EVT SmallVT = V->getOperand(1).getValueType(); 12723 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 12724 return SDValue(); 12725 12726 // Only handle cases where both indexes are constants with the same type. 12727 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12728 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12729 12730 if (InsIdx && ExtIdx && 12731 InsIdx->getValueType(0).getSizeInBits() <= 64 && 12732 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 12733 // Combine: 12734 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 12735 // Into: 12736 // indices are equal or bit offsets are equal => V1 12737 // otherwise => (extract_subvec V1, ExtIdx) 12738 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 12739 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 12740 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 12741 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 12742 DAG.getNode(ISD::BITCAST, dl, 12743 N->getOperand(0).getValueType(), 12744 V->getOperand(0)), N->getOperand(1)); 12745 } 12746 } 12747 12748 return SDValue(); 12749 } 12750 12751 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 12752 SDValue V, SelectionDAG &DAG) { 12753 SDLoc DL(V); 12754 EVT VT = V.getValueType(); 12755 12756 switch (V.getOpcode()) { 12757 default: 12758 return V; 12759 12760 case ISD::CONCAT_VECTORS: { 12761 EVT OpVT = V->getOperand(0).getValueType(); 12762 int OpSize = OpVT.getVectorNumElements(); 12763 SmallBitVector OpUsedElements(OpSize, false); 12764 bool FoundSimplification = false; 12765 SmallVector<SDValue, 4> NewOps; 12766 NewOps.reserve(V->getNumOperands()); 12767 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 12768 SDValue Op = V->getOperand(i); 12769 bool OpUsed = false; 12770 for (int j = 0; j < OpSize; ++j) 12771 if (UsedElements[i * OpSize + j]) { 12772 OpUsedElements[j] = true; 12773 OpUsed = true; 12774 } 12775 NewOps.push_back( 12776 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 12777 : DAG.getUNDEF(OpVT)); 12778 FoundSimplification |= Op == NewOps.back(); 12779 OpUsedElements.reset(); 12780 } 12781 if (FoundSimplification) 12782 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 12783 return V; 12784 } 12785 12786 case ISD::INSERT_SUBVECTOR: { 12787 SDValue BaseV = V->getOperand(0); 12788 SDValue SubV = V->getOperand(1); 12789 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12790 if (!IdxN) 12791 return V; 12792 12793 int SubSize = SubV.getValueType().getVectorNumElements(); 12794 int Idx = IdxN->getZExtValue(); 12795 bool SubVectorUsed = false; 12796 SmallBitVector SubUsedElements(SubSize, false); 12797 for (int i = 0; i < SubSize; ++i) 12798 if (UsedElements[i + Idx]) { 12799 SubVectorUsed = true; 12800 SubUsedElements[i] = true; 12801 UsedElements[i + Idx] = false; 12802 } 12803 12804 // Now recurse on both the base and sub vectors. 12805 SDValue SimplifiedSubV = 12806 SubVectorUsed 12807 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 12808 : DAG.getUNDEF(SubV.getValueType()); 12809 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 12810 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 12811 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 12812 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 12813 return V; 12814 } 12815 } 12816 } 12817 12818 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 12819 SDValue N1, SelectionDAG &DAG) { 12820 EVT VT = SVN->getValueType(0); 12821 int NumElts = VT.getVectorNumElements(); 12822 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 12823 for (int M : SVN->getMask()) 12824 if (M >= 0 && M < NumElts) 12825 N0UsedElements[M] = true; 12826 else if (M >= NumElts) 12827 N1UsedElements[M - NumElts] = true; 12828 12829 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 12830 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 12831 if (S0 == N0 && S1 == N1) 12832 return SDValue(); 12833 12834 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 12835 } 12836 12837 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 12838 // or turn a shuffle of a single concat into simpler shuffle then concat. 12839 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 12840 EVT VT = N->getValueType(0); 12841 unsigned NumElts = VT.getVectorNumElements(); 12842 12843 SDValue N0 = N->getOperand(0); 12844 SDValue N1 = N->getOperand(1); 12845 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12846 12847 SmallVector<SDValue, 4> Ops; 12848 EVT ConcatVT = N0.getOperand(0).getValueType(); 12849 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 12850 unsigned NumConcats = NumElts / NumElemsPerConcat; 12851 12852 // Special case: shuffle(concat(A,B)) can be more efficiently represented 12853 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 12854 // half vector elements. 12855 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 12856 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 12857 SVN->getMask().end(), [](int i) { return i == -1; })) { 12858 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 12859 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 12860 N1 = DAG.getUNDEF(ConcatVT); 12861 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 12862 } 12863 12864 // Look at every vector that's inserted. We're looking for exact 12865 // subvector-sized copies from a concatenated vector 12866 for (unsigned I = 0; I != NumConcats; ++I) { 12867 // Make sure we're dealing with a copy. 12868 unsigned Begin = I * NumElemsPerConcat; 12869 bool AllUndef = true, NoUndef = true; 12870 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 12871 if (SVN->getMaskElt(J) >= 0) 12872 AllUndef = false; 12873 else 12874 NoUndef = false; 12875 } 12876 12877 if (NoUndef) { 12878 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 12879 return SDValue(); 12880 12881 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 12882 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 12883 return SDValue(); 12884 12885 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 12886 if (FirstElt < N0.getNumOperands()) 12887 Ops.push_back(N0.getOperand(FirstElt)); 12888 else 12889 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 12890 12891 } else if (AllUndef) { 12892 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 12893 } else { // Mixed with general masks and undefs, can't do optimization. 12894 return SDValue(); 12895 } 12896 } 12897 12898 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 12899 } 12900 12901 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 12902 EVT VT = N->getValueType(0); 12903 unsigned NumElts = VT.getVectorNumElements(); 12904 12905 SDValue N0 = N->getOperand(0); 12906 SDValue N1 = N->getOperand(1); 12907 12908 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 12909 12910 // Canonicalize shuffle undef, undef -> undef 12911 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 12912 return DAG.getUNDEF(VT); 12913 12914 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12915 12916 // Canonicalize shuffle v, v -> v, undef 12917 if (N0 == N1) { 12918 SmallVector<int, 8> NewMask; 12919 for (unsigned i = 0; i != NumElts; ++i) { 12920 int Idx = SVN->getMaskElt(i); 12921 if (Idx >= (int)NumElts) Idx -= NumElts; 12922 NewMask.push_back(Idx); 12923 } 12924 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 12925 &NewMask[0]); 12926 } 12927 12928 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 12929 if (N0.getOpcode() == ISD::UNDEF) { 12930 SmallVector<int, 8> NewMask; 12931 for (unsigned i = 0; i != NumElts; ++i) { 12932 int Idx = SVN->getMaskElt(i); 12933 if (Idx >= 0) { 12934 if (Idx >= (int)NumElts) 12935 Idx -= NumElts; 12936 else 12937 Idx = -1; // remove reference to lhs 12938 } 12939 NewMask.push_back(Idx); 12940 } 12941 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 12942 &NewMask[0]); 12943 } 12944 12945 // Remove references to rhs if it is undef 12946 if (N1.getOpcode() == ISD::UNDEF) { 12947 bool Changed = false; 12948 SmallVector<int, 8> NewMask; 12949 for (unsigned i = 0; i != NumElts; ++i) { 12950 int Idx = SVN->getMaskElt(i); 12951 if (Idx >= (int)NumElts) { 12952 Idx = -1; 12953 Changed = true; 12954 } 12955 NewMask.push_back(Idx); 12956 } 12957 if (Changed) 12958 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 12959 } 12960 12961 // If it is a splat, check if the argument vector is another splat or a 12962 // build_vector. 12963 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 12964 SDNode *V = N0.getNode(); 12965 12966 // If this is a bit convert that changes the element type of the vector but 12967 // not the number of vector elements, look through it. Be careful not to 12968 // look though conversions that change things like v4f32 to v2f64. 12969 if (V->getOpcode() == ISD::BITCAST) { 12970 SDValue ConvInput = V->getOperand(0); 12971 if (ConvInput.getValueType().isVector() && 12972 ConvInput.getValueType().getVectorNumElements() == NumElts) 12973 V = ConvInput.getNode(); 12974 } 12975 12976 if (V->getOpcode() == ISD::BUILD_VECTOR) { 12977 assert(V->getNumOperands() == NumElts && 12978 "BUILD_VECTOR has wrong number of operands"); 12979 SDValue Base; 12980 bool AllSame = true; 12981 for (unsigned i = 0; i != NumElts; ++i) { 12982 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 12983 Base = V->getOperand(i); 12984 break; 12985 } 12986 } 12987 // Splat of <u, u, u, u>, return <u, u, u, u> 12988 if (!Base.getNode()) 12989 return N0; 12990 for (unsigned i = 0; i != NumElts; ++i) { 12991 if (V->getOperand(i) != Base) { 12992 AllSame = false; 12993 break; 12994 } 12995 } 12996 // Splat of <x, x, x, x>, return <x, x, x, x> 12997 if (AllSame) 12998 return N0; 12999 13000 // Canonicalize any other splat as a build_vector. 13001 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13002 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13003 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 13004 V->getValueType(0), Ops); 13005 13006 // We may have jumped through bitcasts, so the type of the 13007 // BUILD_VECTOR may not match the type of the shuffle. 13008 if (V->getValueType(0) != VT) 13009 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 13010 return NewBV; 13011 } 13012 } 13013 13014 // There are various patterns used to build up a vector from smaller vectors, 13015 // subvectors, or elements. Scan chains of these and replace unused insertions 13016 // or components with undef. 13017 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13018 return S; 13019 13020 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13021 Level < AfterLegalizeVectorOps && 13022 (N1.getOpcode() == ISD::UNDEF || 13023 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13024 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13025 SDValue V = partitionShuffleOfConcats(N, DAG); 13026 13027 if (V.getNode()) 13028 return V; 13029 } 13030 13031 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13032 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13033 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13034 SmallVector<SDValue, 8> Ops; 13035 for (int M : SVN->getMask()) { 13036 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13037 if (M >= 0) { 13038 int Idx = M % NumElts; 13039 SDValue &S = (M < (int)NumElts ? N0 : N1); 13040 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13041 Op = S.getOperand(Idx); 13042 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13043 if (Idx == 0) 13044 Op = S.getOperand(0); 13045 } else { 13046 // Operand can't be combined - bail out. 13047 break; 13048 } 13049 } 13050 Ops.push_back(Op); 13051 } 13052 if (Ops.size() == VT.getVectorNumElements()) { 13053 // BUILD_VECTOR requires all inputs to be of the same type, find the 13054 // maximum type and extend them all. 13055 EVT SVT = VT.getScalarType(); 13056 if (SVT.isInteger()) 13057 for (SDValue &Op : Ops) 13058 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13059 if (SVT != VT.getScalarType()) 13060 for (SDValue &Op : Ops) 13061 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13062 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13063 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13064 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 13065 } 13066 } 13067 13068 // If this shuffle only has a single input that is a bitcasted shuffle, 13069 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13070 // back to their original types. 13071 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13072 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 13073 TLI.isTypeLegal(VT)) { 13074 13075 // Peek through the bitcast only if there is one user. 13076 SDValue BC0 = N0; 13077 while (BC0.getOpcode() == ISD::BITCAST) { 13078 if (!BC0.hasOneUse()) 13079 break; 13080 BC0 = BC0.getOperand(0); 13081 } 13082 13083 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13084 if (Scale == 1) 13085 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13086 13087 SmallVector<int, 8> NewMask; 13088 for (int M : Mask) 13089 for (int s = 0; s != Scale; ++s) 13090 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13091 return NewMask; 13092 }; 13093 13094 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13095 EVT SVT = VT.getScalarType(); 13096 EVT InnerVT = BC0->getValueType(0); 13097 EVT InnerSVT = InnerVT.getScalarType(); 13098 13099 // Determine which shuffle works with the smaller scalar type. 13100 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13101 EVT ScaleSVT = ScaleVT.getScalarType(); 13102 13103 if (TLI.isTypeLegal(ScaleVT) && 13104 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13105 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13106 13107 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13108 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13109 13110 // Scale the shuffle masks to the smaller scalar type. 13111 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13112 SmallVector<int, 8> InnerMask = 13113 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13114 SmallVector<int, 8> OuterMask = 13115 ScaleShuffleMask(SVN->getMask(), OuterScale); 13116 13117 // Merge the shuffle masks. 13118 SmallVector<int, 8> NewMask; 13119 for (int M : OuterMask) 13120 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13121 13122 // Test for shuffle mask legality over both commutations. 13123 SDValue SV0 = BC0->getOperand(0); 13124 SDValue SV1 = BC0->getOperand(1); 13125 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13126 if (!LegalMask) { 13127 std::swap(SV0, SV1); 13128 ShuffleVectorSDNode::commuteMask(NewMask); 13129 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13130 } 13131 13132 if (LegalMask) { 13133 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 13134 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 13135 return DAG.getNode( 13136 ISD::BITCAST, SDLoc(N), VT, 13137 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13138 } 13139 } 13140 } 13141 } 13142 13143 // Canonicalize shuffles according to rules: 13144 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13145 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13146 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13147 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13148 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13149 TLI.isTypeLegal(VT)) { 13150 // The incoming shuffle must be of the same type as the result of the 13151 // current shuffle. 13152 assert(N1->getOperand(0).getValueType() == VT && 13153 "Shuffle types don't match"); 13154 13155 SDValue SV0 = N1->getOperand(0); 13156 SDValue SV1 = N1->getOperand(1); 13157 bool HasSameOp0 = N0 == SV0; 13158 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 13159 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13160 // Commute the operands of this shuffle so that next rule 13161 // will trigger. 13162 return DAG.getCommutedVectorShuffle(*SVN); 13163 } 13164 13165 // Try to fold according to rules: 13166 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13167 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13168 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13169 // Don't try to fold shuffles with illegal type. 13170 // Only fold if this shuffle is the only user of the other shuffle. 13171 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13172 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13173 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13174 13175 // The incoming shuffle must be of the same type as the result of the 13176 // current shuffle. 13177 assert(OtherSV->getOperand(0).getValueType() == VT && 13178 "Shuffle types don't match"); 13179 13180 SDValue SV0, SV1; 13181 SmallVector<int, 4> Mask; 13182 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13183 // operand, and SV1 as the second operand. 13184 for (unsigned i = 0; i != NumElts; ++i) { 13185 int Idx = SVN->getMaskElt(i); 13186 if (Idx < 0) { 13187 // Propagate Undef. 13188 Mask.push_back(Idx); 13189 continue; 13190 } 13191 13192 SDValue CurrentVec; 13193 if (Idx < (int)NumElts) { 13194 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13195 // shuffle mask to identify which vector is actually referenced. 13196 Idx = OtherSV->getMaskElt(Idx); 13197 if (Idx < 0) { 13198 // Propagate Undef. 13199 Mask.push_back(Idx); 13200 continue; 13201 } 13202 13203 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13204 : OtherSV->getOperand(1); 13205 } else { 13206 // This shuffle index references an element within N1. 13207 CurrentVec = N1; 13208 } 13209 13210 // Simple case where 'CurrentVec' is UNDEF. 13211 if (CurrentVec.getOpcode() == ISD::UNDEF) { 13212 Mask.push_back(-1); 13213 continue; 13214 } 13215 13216 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13217 // will be the first or second operand of the combined shuffle. 13218 Idx = Idx % NumElts; 13219 if (!SV0.getNode() || SV0 == CurrentVec) { 13220 // Ok. CurrentVec is the left hand side. 13221 // Update the mask accordingly. 13222 SV0 = CurrentVec; 13223 Mask.push_back(Idx); 13224 continue; 13225 } 13226 13227 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13228 if (SV1.getNode() && SV1 != CurrentVec) 13229 return SDValue(); 13230 13231 // Ok. CurrentVec is the right hand side. 13232 // Update the mask accordingly. 13233 SV1 = CurrentVec; 13234 Mask.push_back(Idx + NumElts); 13235 } 13236 13237 // Check if all indices in Mask are Undef. In case, propagate Undef. 13238 bool isUndefMask = true; 13239 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13240 isUndefMask &= Mask[i] < 0; 13241 13242 if (isUndefMask) 13243 return DAG.getUNDEF(VT); 13244 13245 if (!SV0.getNode()) 13246 SV0 = DAG.getUNDEF(VT); 13247 if (!SV1.getNode()) 13248 SV1 = DAG.getUNDEF(VT); 13249 13250 // Avoid introducing shuffles with illegal mask. 13251 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13252 ShuffleVectorSDNode::commuteMask(Mask); 13253 13254 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13255 return SDValue(); 13256 13257 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13258 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13259 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13260 std::swap(SV0, SV1); 13261 } 13262 13263 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13264 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13265 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13266 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 13267 } 13268 13269 return SDValue(); 13270 } 13271 13272 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13273 SDValue InVal = N->getOperand(0); 13274 EVT VT = N->getValueType(0); 13275 13276 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13277 // with a VECTOR_SHUFFLE. 13278 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13279 SDValue InVec = InVal->getOperand(0); 13280 SDValue EltNo = InVal->getOperand(1); 13281 13282 // FIXME: We could support implicit truncation if the shuffle can be 13283 // scaled to a smaller vector scalar type. 13284 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13285 if (C0 && VT == InVec.getValueType() && 13286 VT.getScalarType() == InVal.getValueType()) { 13287 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13288 int Elt = C0->getZExtValue(); 13289 NewMask[0] = Elt; 13290 13291 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13292 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13293 NewMask); 13294 } 13295 } 13296 13297 return SDValue(); 13298 } 13299 13300 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13301 SDValue N0 = N->getOperand(0); 13302 SDValue N2 = N->getOperand(2); 13303 13304 // If the input vector is a concatenation, and the insert replaces 13305 // one of the halves, we can optimize into a single concat_vectors. 13306 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13307 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 13308 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13309 EVT VT = N->getValueType(0); 13310 13311 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13312 // (concat_vectors Z, Y) 13313 if (InsIdx == 0) 13314 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13315 N->getOperand(1), N0.getOperand(1)); 13316 13317 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13318 // (concat_vectors X, Z) 13319 if (InsIdx == VT.getVectorNumElements()/2) 13320 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13321 N0.getOperand(0), N->getOperand(1)); 13322 } 13323 13324 return SDValue(); 13325 } 13326 13327 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13328 SDValue N0 = N->getOperand(0); 13329 13330 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13331 if (N0->getOpcode() == ISD::FP16_TO_FP) 13332 return N0->getOperand(0); 13333 13334 return SDValue(); 13335 } 13336 13337 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13338 SDValue N0 = N->getOperand(0); 13339 13340 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13341 if (N0->getOpcode() == ISD::AND) { 13342 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13343 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13344 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13345 N0.getOperand(0)); 13346 } 13347 } 13348 13349 return SDValue(); 13350 } 13351 13352 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13353 /// with the destination vector and a zero vector. 13354 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13355 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13356 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13357 EVT VT = N->getValueType(0); 13358 SDValue LHS = N->getOperand(0); 13359 SDValue RHS = N->getOperand(1); 13360 SDLoc dl(N); 13361 13362 // Make sure we're not running after operation legalization where it 13363 // may have custom lowered the vector shuffles. 13364 if (LegalOperations) 13365 return SDValue(); 13366 13367 if (N->getOpcode() != ISD::AND) 13368 return SDValue(); 13369 13370 if (RHS.getOpcode() == ISD::BITCAST) 13371 RHS = RHS.getOperand(0); 13372 13373 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13374 return SDValue(); 13375 13376 EVT RVT = RHS.getValueType(); 13377 unsigned NumElts = RHS.getNumOperands(); 13378 13379 // Attempt to create a valid clear mask, splitting the mask into 13380 // sub elements and checking to see if each is 13381 // all zeros or all ones - suitable for shuffle masking. 13382 auto BuildClearMask = [&](int Split) { 13383 int NumSubElts = NumElts * Split; 13384 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13385 13386 SmallVector<int, 8> Indices; 13387 for (int i = 0; i != NumSubElts; ++i) { 13388 int EltIdx = i / Split; 13389 int SubIdx = i % Split; 13390 SDValue Elt = RHS.getOperand(EltIdx); 13391 if (Elt.getOpcode() == ISD::UNDEF) { 13392 Indices.push_back(-1); 13393 continue; 13394 } 13395 13396 APInt Bits; 13397 if (isa<ConstantSDNode>(Elt)) 13398 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13399 else if (isa<ConstantFPSDNode>(Elt)) 13400 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13401 else 13402 return SDValue(); 13403 13404 // Extract the sub element from the constant bit mask. 13405 if (DAG.getDataLayout().isBigEndian()) { 13406 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13407 } else { 13408 Bits = Bits.lshr(SubIdx * NumSubBits); 13409 } 13410 13411 if (Split > 1) 13412 Bits = Bits.trunc(NumSubBits); 13413 13414 if (Bits.isAllOnesValue()) 13415 Indices.push_back(i); 13416 else if (Bits == 0) 13417 Indices.push_back(i + NumSubElts); 13418 else 13419 return SDValue(); 13420 } 13421 13422 // Let's see if the target supports this vector_shuffle. 13423 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13424 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13425 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13426 return SDValue(); 13427 13428 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13429 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13430 DAG.getBitcast(ClearVT, LHS), 13431 Zero, &Indices[0])); 13432 }; 13433 13434 // Determine maximum split level (byte level masking). 13435 int MaxSplit = 1; 13436 if (RVT.getScalarSizeInBits() % 8 == 0) 13437 MaxSplit = RVT.getScalarSizeInBits() / 8; 13438 13439 for (int Split = 1; Split <= MaxSplit; ++Split) 13440 if (RVT.getScalarSizeInBits() % Split == 0) 13441 if (SDValue S = BuildClearMask(Split)) 13442 return S; 13443 13444 return SDValue(); 13445 } 13446 13447 /// Visit a binary vector operation, like ADD. 13448 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13449 assert(N->getValueType(0).isVector() && 13450 "SimplifyVBinOp only works on vectors!"); 13451 13452 SDValue LHS = N->getOperand(0); 13453 SDValue RHS = N->getOperand(1); 13454 13455 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 13456 // this operation. 13457 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 13458 RHS.getOpcode() == ISD::BUILD_VECTOR) { 13459 // Check if both vectors are constants. If not bail out. 13460 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 13461 cast<BuildVectorSDNode>(RHS)->isConstant())) 13462 return SDValue(); 13463 13464 SmallVector<SDValue, 8> Ops; 13465 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 13466 SDValue LHSOp = LHS.getOperand(i); 13467 SDValue RHSOp = RHS.getOperand(i); 13468 13469 // Can't fold divide by zero. 13470 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 13471 N->getOpcode() == ISD::FDIV) { 13472 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP && 13473 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero())) 13474 break; 13475 } 13476 13477 EVT VT = LHSOp.getValueType(); 13478 EVT RVT = RHSOp.getValueType(); 13479 EVT ST = VT; 13480 13481 if (RVT.getSizeInBits() < VT.getSizeInBits()) 13482 ST = RVT; 13483 13484 // Integer BUILD_VECTOR operands may have types larger than the element 13485 // size (e.g., when the element type is not legal). Prior to type 13486 // legalization, the types may not match between the two BUILD_VECTORS. 13487 // Truncate the operands to make them match. 13488 if (VT.getSizeInBits() != LHS.getValueType().getScalarSizeInBits()) { 13489 EVT ScalarT = LHS.getValueType().getScalarType(); 13490 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, LHSOp); 13491 VT = LHSOp.getValueType(); 13492 } 13493 if (RVT.getSizeInBits() != RHS.getValueType().getScalarSizeInBits()) { 13494 EVT ScalarT = RHS.getValueType().getScalarType(); 13495 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, RHSOp); 13496 RVT = RHSOp.getValueType(); 13497 } 13498 13499 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 13500 LHSOp, RHSOp, N->getFlags()); 13501 13502 // We need the resulting constant to be legal if we are in a phase after 13503 // legalization, so zero extend to the smallest operand type if required. 13504 if (ST != VT && Level != BeforeLegalizeTypes) 13505 FoldOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LHS), ST, FoldOp); 13506 13507 if (FoldOp.getOpcode() != ISD::UNDEF && 13508 FoldOp.getOpcode() != ISD::Constant && 13509 FoldOp.getOpcode() != ISD::ConstantFP) 13510 break; 13511 Ops.push_back(FoldOp); 13512 AddToWorklist(FoldOp.getNode()); 13513 } 13514 13515 if (Ops.size() == LHS.getNumOperands()) 13516 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 13517 } 13518 13519 // Try to convert a constant mask AND into a shuffle clear mask. 13520 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13521 return Shuffle; 13522 13523 // Type legalization might introduce new shuffles in the DAG. 13524 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13525 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13526 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13527 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13528 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 13529 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 13530 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13531 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13532 13533 if (SVN0->getMask().equals(SVN1->getMask())) { 13534 EVT VT = N->getValueType(0); 13535 SDValue UndefVector = LHS.getOperand(1); 13536 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13537 LHS.getOperand(0), RHS.getOperand(0), 13538 N->getFlags()); 13539 AddUsersToWorklist(N); 13540 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13541 &SVN0->getMask()[0]); 13542 } 13543 } 13544 13545 return SDValue(); 13546 } 13547 13548 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13549 SDValue N1, SDValue N2){ 13550 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13551 13552 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13553 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13554 13555 // If we got a simplified select_cc node back from SimplifySelectCC, then 13556 // break it down into a new SETCC node, and a new SELECT node, and then return 13557 // the SELECT node, since we were called with a SELECT node. 13558 if (SCC.getNode()) { 13559 // Check to see if we got a select_cc back (to turn into setcc/select). 13560 // Otherwise, just return whatever node we got back, like fabs. 13561 if (SCC.getOpcode() == ISD::SELECT_CC) { 13562 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13563 N0.getValueType(), 13564 SCC.getOperand(0), SCC.getOperand(1), 13565 SCC.getOperand(4)); 13566 AddToWorklist(SETCC.getNode()); 13567 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13568 SCC.getOperand(2), SCC.getOperand(3)); 13569 } 13570 13571 return SCC; 13572 } 13573 return SDValue(); 13574 } 13575 13576 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13577 /// being selected between, see if we can simplify the select. Callers of this 13578 /// should assume that TheSelect is deleted if this returns true. As such, they 13579 /// should return the appropriate thing (e.g. the node) back to the top-level of 13580 /// the DAG combiner loop to avoid it being looked at. 13581 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13582 SDValue RHS) { 13583 13584 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13585 // The select + setcc is redundant, because fsqrt returns NaN for X < -0. 13586 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13587 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13588 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13589 SDValue Sqrt = RHS; 13590 ISD::CondCode CC; 13591 SDValue CmpLHS; 13592 const ConstantFPSDNode *NegZero = nullptr; 13593 13594 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13595 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13596 CmpLHS = TheSelect->getOperand(0); 13597 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13598 } else { 13599 // SELECT or VSELECT 13600 SDValue Cmp = TheSelect->getOperand(0); 13601 if (Cmp.getOpcode() == ISD::SETCC) { 13602 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13603 CmpLHS = Cmp.getOperand(0); 13604 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13605 } 13606 } 13607 if (NegZero && NegZero->isNegative() && NegZero->isZero() && 13608 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13609 CC == ISD::SETULT || CC == ISD::SETLT)) { 13610 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13611 CombineTo(TheSelect, Sqrt); 13612 return true; 13613 } 13614 } 13615 } 13616 // Cannot simplify select with vector condition 13617 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 13618 13619 // If this is a select from two identical things, try to pull the operation 13620 // through the select. 13621 if (LHS.getOpcode() != RHS.getOpcode() || 13622 !LHS.hasOneUse() || !RHS.hasOneUse()) 13623 return false; 13624 13625 // If this is a load and the token chain is identical, replace the select 13626 // of two loads with a load through a select of the address to load from. 13627 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 13628 // constants have been dropped into the constant pool. 13629 if (LHS.getOpcode() == ISD::LOAD) { 13630 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 13631 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 13632 13633 // Token chains must be identical. 13634 if (LHS.getOperand(0) != RHS.getOperand(0) || 13635 // Do not let this transformation reduce the number of volatile loads. 13636 LLD->isVolatile() || RLD->isVolatile() || 13637 // FIXME: If either is a pre/post inc/dec load, 13638 // we'd need to split out the address adjustment. 13639 LLD->isIndexed() || RLD->isIndexed() || 13640 // If this is an EXTLOAD, the VT's must match. 13641 LLD->getMemoryVT() != RLD->getMemoryVT() || 13642 // If this is an EXTLOAD, the kind of extension must match. 13643 (LLD->getExtensionType() != RLD->getExtensionType() && 13644 // The only exception is if one of the extensions is anyext. 13645 LLD->getExtensionType() != ISD::EXTLOAD && 13646 RLD->getExtensionType() != ISD::EXTLOAD) || 13647 // FIXME: this discards src value information. This is 13648 // over-conservative. It would be beneficial to be able to remember 13649 // both potential memory locations. Since we are discarding 13650 // src value info, don't do the transformation if the memory 13651 // locations are not in the default address space. 13652 LLD->getPointerInfo().getAddrSpace() != 0 || 13653 RLD->getPointerInfo().getAddrSpace() != 0 || 13654 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 13655 LLD->getBasePtr().getValueType())) 13656 return false; 13657 13658 // Check that the select condition doesn't reach either load. If so, 13659 // folding this will induce a cycle into the DAG. If not, this is safe to 13660 // xform, so create a select of the addresses. 13661 SDValue Addr; 13662 if (TheSelect->getOpcode() == ISD::SELECT) { 13663 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 13664 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 13665 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 13666 return false; 13667 // The loads must not depend on one another. 13668 if (LLD->isPredecessorOf(RLD) || 13669 RLD->isPredecessorOf(LLD)) 13670 return false; 13671 Addr = DAG.getSelect(SDLoc(TheSelect), 13672 LLD->getBasePtr().getValueType(), 13673 TheSelect->getOperand(0), LLD->getBasePtr(), 13674 RLD->getBasePtr()); 13675 } else { // Otherwise SELECT_CC 13676 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 13677 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 13678 13679 if ((LLD->hasAnyUseOfValue(1) && 13680 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 13681 (RLD->hasAnyUseOfValue(1) && 13682 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 13683 return false; 13684 13685 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 13686 LLD->getBasePtr().getValueType(), 13687 TheSelect->getOperand(0), 13688 TheSelect->getOperand(1), 13689 LLD->getBasePtr(), RLD->getBasePtr(), 13690 TheSelect->getOperand(4)); 13691 } 13692 13693 SDValue Load; 13694 // It is safe to replace the two loads if they have different alignments, 13695 // but the new load must be the minimum (most restrictive) alignment of the 13696 // inputs. 13697 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 13698 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 13699 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 13700 Load = DAG.getLoad(TheSelect->getValueType(0), 13701 SDLoc(TheSelect), 13702 // FIXME: Discards pointer and AA info. 13703 LLD->getChain(), Addr, MachinePointerInfo(), 13704 LLD->isVolatile(), LLD->isNonTemporal(), 13705 isInvariant, Alignment); 13706 } else { 13707 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 13708 RLD->getExtensionType() : LLD->getExtensionType(), 13709 SDLoc(TheSelect), 13710 TheSelect->getValueType(0), 13711 // FIXME: Discards pointer and AA info. 13712 LLD->getChain(), Addr, MachinePointerInfo(), 13713 LLD->getMemoryVT(), LLD->isVolatile(), 13714 LLD->isNonTemporal(), isInvariant, Alignment); 13715 } 13716 13717 // Users of the select now use the result of the load. 13718 CombineTo(TheSelect, Load); 13719 13720 // Users of the old loads now use the new load's chain. We know the 13721 // old-load value is dead now. 13722 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 13723 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 13724 return true; 13725 } 13726 13727 return false; 13728 } 13729 13730 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 13731 /// where 'cond' is the comparison specified by CC. 13732 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 13733 SDValue N2, SDValue N3, 13734 ISD::CondCode CC, bool NotExtCompare) { 13735 // (x ? y : y) -> y. 13736 if (N2 == N3) return N2; 13737 13738 EVT VT = N2.getValueType(); 13739 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 13740 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 13741 13742 // Determine if the condition we're dealing with is constant 13743 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 13744 N0, N1, CC, DL, false); 13745 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 13746 13747 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 13748 // fold select_cc true, x, y -> x 13749 // fold select_cc false, x, y -> y 13750 return !SCCC->isNullValue() ? N2 : N3; 13751 } 13752 13753 // Check to see if we can simplify the select into an fabs node 13754 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 13755 // Allow either -0.0 or 0.0 13756 if (CFP->isZero()) { 13757 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 13758 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 13759 N0 == N2 && N3.getOpcode() == ISD::FNEG && 13760 N2 == N3.getOperand(0)) 13761 return DAG.getNode(ISD::FABS, DL, VT, N0); 13762 13763 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 13764 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 13765 N0 == N3 && N2.getOpcode() == ISD::FNEG && 13766 N2.getOperand(0) == N3) 13767 return DAG.getNode(ISD::FABS, DL, VT, N3); 13768 } 13769 } 13770 13771 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 13772 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 13773 // in it. This is a win when the constant is not otherwise available because 13774 // it replaces two constant pool loads with one. We only do this if the FP 13775 // type is known to be legal, because if it isn't, then we are before legalize 13776 // types an we want the other legalization to happen first (e.g. to avoid 13777 // messing with soft float) and if the ConstantFP is not legal, because if 13778 // it is legal, we may not need to store the FP constant in a constant pool. 13779 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 13780 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 13781 if (TLI.isTypeLegal(N2.getValueType()) && 13782 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 13783 TargetLowering::Legal && 13784 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 13785 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 13786 // If both constants have multiple uses, then we won't need to do an 13787 // extra load, they are likely around in registers for other users. 13788 (TV->hasOneUse() || FV->hasOneUse())) { 13789 Constant *Elts[] = { 13790 const_cast<ConstantFP*>(FV->getConstantFPValue()), 13791 const_cast<ConstantFP*>(TV->getConstantFPValue()) 13792 }; 13793 Type *FPTy = Elts[0]->getType(); 13794 const DataLayout &TD = DAG.getDataLayout(); 13795 13796 // Create a ConstantArray of the two constants. 13797 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 13798 SDValue CPIdx = 13799 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 13800 TD.getPrefTypeAlignment(FPTy)); 13801 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 13802 13803 // Get the offsets to the 0 and 1 element of the array so that we can 13804 // select between them. 13805 SDValue Zero = DAG.getIntPtrConstant(0, DL); 13806 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 13807 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 13808 13809 SDValue Cond = DAG.getSetCC(DL, 13810 getSetCCResultType(N0.getValueType()), 13811 N0, N1, CC); 13812 AddToWorklist(Cond.getNode()); 13813 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 13814 Cond, One, Zero); 13815 AddToWorklist(CstOffset.getNode()); 13816 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 13817 CstOffset); 13818 AddToWorklist(CPIdx.getNode()); 13819 return DAG.getLoad( 13820 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 13821 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 13822 false, false, false, Alignment); 13823 } 13824 } 13825 13826 // Check to see if we can perform the "gzip trick", transforming 13827 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 13828 if (isNullConstant(N3) && CC == ISD::SETLT && 13829 (isNullConstant(N1) || // (a < 0) ? b : 0 13830 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 13831 EVT XType = N0.getValueType(); 13832 EVT AType = N2.getValueType(); 13833 if (XType.bitsGE(AType)) { 13834 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 13835 // single-bit constant. 13836 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 13837 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 13838 ShCtV = XType.getSizeInBits() - ShCtV - 1; 13839 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 13840 getShiftAmountTy(N0.getValueType())); 13841 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 13842 XType, N0, ShCt); 13843 AddToWorklist(Shift.getNode()); 13844 13845 if (XType.bitsGT(AType)) { 13846 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13847 AddToWorklist(Shift.getNode()); 13848 } 13849 13850 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13851 } 13852 13853 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 13854 XType, N0, 13855 DAG.getConstant(XType.getSizeInBits() - 1, 13856 SDLoc(N0), 13857 getShiftAmountTy(N0.getValueType()))); 13858 AddToWorklist(Shift.getNode()); 13859 13860 if (XType.bitsGT(AType)) { 13861 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13862 AddToWorklist(Shift.getNode()); 13863 } 13864 13865 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13866 } 13867 } 13868 13869 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 13870 // where y is has a single bit set. 13871 // A plaintext description would be, we can turn the SELECT_CC into an AND 13872 // when the condition can be materialized as an all-ones register. Any 13873 // single bit-test can be materialized as an all-ones register with 13874 // shift-left and shift-right-arith. 13875 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 13876 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 13877 SDValue AndLHS = N0->getOperand(0); 13878 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13879 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 13880 // Shift the tested bit over the sign bit. 13881 APInt AndMask = ConstAndRHS->getAPIntValue(); 13882 SDValue ShlAmt = 13883 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 13884 getShiftAmountTy(AndLHS.getValueType())); 13885 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 13886 13887 // Now arithmetic right shift it all the way over, so the result is either 13888 // all-ones, or zero. 13889 SDValue ShrAmt = 13890 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 13891 getShiftAmountTy(Shl.getValueType())); 13892 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 13893 13894 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 13895 } 13896 } 13897 13898 // fold select C, 16, 0 -> shl C, 4 13899 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 13900 TLI.getBooleanContents(N0.getValueType()) == 13901 TargetLowering::ZeroOrOneBooleanContent) { 13902 13903 // If the caller doesn't want us to simplify this into a zext of a compare, 13904 // don't do it. 13905 if (NotExtCompare && N2C->isOne()) 13906 return SDValue(); 13907 13908 // Get a SetCC of the condition 13909 // NOTE: Don't create a SETCC if it's not legal on this target. 13910 if (!LegalOperations || 13911 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 13912 SDValue Temp, SCC; 13913 // cast from setcc result type to select result type 13914 if (LegalTypes) { 13915 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 13916 N0, N1, CC); 13917 if (N2.getValueType().bitsLT(SCC.getValueType())) 13918 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 13919 N2.getValueType()); 13920 else 13921 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13922 N2.getValueType(), SCC); 13923 } else { 13924 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 13925 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13926 N2.getValueType(), SCC); 13927 } 13928 13929 AddToWorklist(SCC.getNode()); 13930 AddToWorklist(Temp.getNode()); 13931 13932 if (N2C->isOne()) 13933 return Temp; 13934 13935 // shl setcc result by log2 n2c 13936 return DAG.getNode( 13937 ISD::SHL, DL, N2.getValueType(), Temp, 13938 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 13939 getShiftAmountTy(Temp.getValueType()))); 13940 } 13941 } 13942 13943 // Check to see if this is an integer abs. 13944 // select_cc setg[te] X, 0, X, -X -> 13945 // select_cc setgt X, -1, X, -X -> 13946 // select_cc setl[te] X, 0, -X, X -> 13947 // select_cc setlt X, 1, -X, X -> 13948 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 13949 if (N1C) { 13950 ConstantSDNode *SubC = nullptr; 13951 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 13952 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 13953 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 13954 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 13955 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 13956 (N1C->isOne() && CC == ISD::SETLT)) && 13957 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 13958 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 13959 13960 EVT XType = N0.getValueType(); 13961 if (SubC && SubC->isNullValue() && XType.isInteger()) { 13962 SDLoc DL(N0); 13963 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 13964 N0, 13965 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13966 getShiftAmountTy(N0.getValueType()))); 13967 SDValue Add = DAG.getNode(ISD::ADD, DL, 13968 XType, N0, Shift); 13969 AddToWorklist(Shift.getNode()); 13970 AddToWorklist(Add.getNode()); 13971 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 13972 } 13973 } 13974 13975 return SDValue(); 13976 } 13977 13978 /// This is a stub for TargetLowering::SimplifySetCC. 13979 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 13980 SDValue N1, ISD::CondCode Cond, 13981 SDLoc DL, bool foldBooleans) { 13982 TargetLowering::DAGCombinerInfo 13983 DagCombineInfo(DAG, Level, false, this); 13984 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 13985 } 13986 13987 /// Given an ISD::SDIV node expressing a divide by constant, return 13988 /// a DAG expression to select that will generate the same value by multiplying 13989 /// by a magic number. 13990 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 13991 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 13992 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13993 if (!C) 13994 return SDValue(); 13995 13996 // Avoid division by zero. 13997 if (C->isNullValue()) 13998 return SDValue(); 13999 14000 std::vector<SDNode*> Built; 14001 SDValue S = 14002 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14003 14004 for (SDNode *N : Built) 14005 AddToWorklist(N); 14006 return S; 14007 } 14008 14009 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14010 /// DAG expression that will generate the same value by right shifting. 14011 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14012 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14013 if (!C) 14014 return SDValue(); 14015 14016 // Avoid division by zero. 14017 if (C->isNullValue()) 14018 return SDValue(); 14019 14020 std::vector<SDNode *> Built; 14021 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14022 14023 for (SDNode *N : Built) 14024 AddToWorklist(N); 14025 return S; 14026 } 14027 14028 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14029 /// expression that will generate the same value by multiplying by a magic 14030 /// number. 14031 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14032 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14033 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14034 if (!C) 14035 return SDValue(); 14036 14037 // Avoid division by zero. 14038 if (C->isNullValue()) 14039 return SDValue(); 14040 14041 std::vector<SDNode*> Built; 14042 SDValue S = 14043 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14044 14045 for (SDNode *N : Built) 14046 AddToWorklist(N); 14047 return S; 14048 } 14049 14050 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14051 if (Level >= AfterLegalizeDAG) 14052 return SDValue(); 14053 14054 // Expose the DAG combiner to the target combiner implementations. 14055 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14056 14057 unsigned Iterations = 0; 14058 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14059 if (Iterations) { 14060 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14061 // For the reciprocal, we need to find the zero of the function: 14062 // F(X) = A X - 1 [which has a zero at X = 1/A] 14063 // => 14064 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14065 // does not require additional intermediate precision] 14066 EVT VT = Op.getValueType(); 14067 SDLoc DL(Op); 14068 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14069 14070 AddToWorklist(Est.getNode()); 14071 14072 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14073 for (unsigned i = 0; i < Iterations; ++i) { 14074 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14075 AddToWorklist(NewEst.getNode()); 14076 14077 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14078 AddToWorklist(NewEst.getNode()); 14079 14080 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14081 AddToWorklist(NewEst.getNode()); 14082 14083 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14084 AddToWorklist(Est.getNode()); 14085 } 14086 } 14087 return Est; 14088 } 14089 14090 return SDValue(); 14091 } 14092 14093 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14094 /// For the reciprocal sqrt, we need to find the zero of the function: 14095 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14096 /// => 14097 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14098 /// As a result, we precompute A/2 prior to the iteration loop. 14099 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 14100 unsigned Iterations, 14101 SDNodeFlags *Flags) { 14102 EVT VT = Arg.getValueType(); 14103 SDLoc DL(Arg); 14104 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14105 14106 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14107 // this entire sequence requires only one FP constant. 14108 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14109 AddToWorklist(HalfArg.getNode()); 14110 14111 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14112 AddToWorklist(HalfArg.getNode()); 14113 14114 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14115 for (unsigned i = 0; i < Iterations; ++i) { 14116 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14117 AddToWorklist(NewEst.getNode()); 14118 14119 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14120 AddToWorklist(NewEst.getNode()); 14121 14122 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14123 AddToWorklist(NewEst.getNode()); 14124 14125 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14126 AddToWorklist(Est.getNode()); 14127 } 14128 return Est; 14129 } 14130 14131 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14132 /// For the reciprocal sqrt, we need to find the zero of the function: 14133 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14134 /// => 14135 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14136 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 14137 unsigned Iterations, 14138 SDNodeFlags *Flags) { 14139 EVT VT = Arg.getValueType(); 14140 SDLoc DL(Arg); 14141 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14142 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14143 14144 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 14145 for (unsigned i = 0; i < Iterations; ++i) { 14146 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14147 AddToWorklist(HalfEst.getNode()); 14148 14149 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14150 AddToWorklist(Est.getNode()); 14151 14152 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14153 AddToWorklist(Est.getNode()); 14154 14155 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags); 14156 AddToWorklist(Est.getNode()); 14157 14158 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags); 14159 AddToWorklist(Est.getNode()); 14160 } 14161 return Est; 14162 } 14163 14164 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14165 if (Level >= AfterLegalizeDAG) 14166 return SDValue(); 14167 14168 // Expose the DAG combiner to the target combiner implementations. 14169 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14170 unsigned Iterations = 0; 14171 bool UseOneConstNR = false; 14172 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14173 AddToWorklist(Est.getNode()); 14174 if (Iterations) { 14175 Est = UseOneConstNR ? 14176 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) : 14177 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags); 14178 } 14179 return Est; 14180 } 14181 14182 return SDValue(); 14183 } 14184 14185 /// Return true if base is a frame index, which is known not to alias with 14186 /// anything but itself. Provides base object and offset as results. 14187 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14188 const GlobalValue *&GV, const void *&CV) { 14189 // Assume it is a primitive operation. 14190 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14191 14192 // If it's an adding a simple constant then integrate the offset. 14193 if (Base.getOpcode() == ISD::ADD) { 14194 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14195 Base = Base.getOperand(0); 14196 Offset += C->getZExtValue(); 14197 } 14198 } 14199 14200 // Return the underlying GlobalValue, and update the Offset. Return false 14201 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14202 // by multiple nodes with different offsets. 14203 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14204 GV = G->getGlobal(); 14205 Offset += G->getOffset(); 14206 return false; 14207 } 14208 14209 // Return the underlying Constant value, and update the Offset. Return false 14210 // for ConstantSDNodes since the same constant pool entry may be represented 14211 // by multiple nodes with different offsets. 14212 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14213 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14214 : (const void *)C->getConstVal(); 14215 Offset += C->getOffset(); 14216 return false; 14217 } 14218 // If it's any of the following then it can't alias with anything but itself. 14219 return isa<FrameIndexSDNode>(Base); 14220 } 14221 14222 /// Return true if there is any possibility that the two addresses overlap. 14223 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14224 // If they are the same then they must be aliases. 14225 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14226 14227 // If they are both volatile then they cannot be reordered. 14228 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14229 14230 // If one operation reads from invariant memory, and the other may store, they 14231 // cannot alias. These should really be checking the equivalent of mayWrite, 14232 // but it only matters for memory nodes other than load /store. 14233 if (Op0->isInvariant() && Op1->writeMem()) 14234 return false; 14235 14236 if (Op1->isInvariant() && Op0->writeMem()) 14237 return false; 14238 14239 // Gather base node and offset information. 14240 SDValue Base1, Base2; 14241 int64_t Offset1, Offset2; 14242 const GlobalValue *GV1, *GV2; 14243 const void *CV1, *CV2; 14244 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14245 Base1, Offset1, GV1, CV1); 14246 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14247 Base2, Offset2, GV2, CV2); 14248 14249 // If they have a same base address then check to see if they overlap. 14250 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14251 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14252 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14253 14254 // It is possible for different frame indices to alias each other, mostly 14255 // when tail call optimization reuses return address slots for arguments. 14256 // To catch this case, look up the actual index of frame indices to compute 14257 // the real alias relationship. 14258 if (isFrameIndex1 && isFrameIndex2) { 14259 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 14260 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14261 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14262 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14263 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14264 } 14265 14266 // Otherwise, if we know what the bases are, and they aren't identical, then 14267 // we know they cannot alias. 14268 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14269 return false; 14270 14271 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14272 // compared to the size and offset of the access, we may be able to prove they 14273 // do not alias. This check is conservative for now to catch cases created by 14274 // splitting vector types. 14275 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14276 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14277 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14278 Op1->getMemoryVT().getSizeInBits() >> 3) && 14279 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 14280 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14281 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14282 14283 // There is no overlap between these relatively aligned accesses of similar 14284 // size, return no alias. 14285 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14286 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14287 return false; 14288 } 14289 14290 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14291 ? CombinerGlobalAA 14292 : DAG.getSubtarget().useAA(); 14293 #ifndef NDEBUG 14294 if (CombinerAAOnlyFunc.getNumOccurrences() && 14295 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14296 UseAA = false; 14297 #endif 14298 if (UseAA && 14299 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14300 // Use alias analysis information. 14301 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14302 Op1->getSrcValueOffset()); 14303 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14304 Op0->getSrcValueOffset() - MinOffset; 14305 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14306 Op1->getSrcValueOffset() - MinOffset; 14307 AliasResult AAResult = 14308 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14309 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14310 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14311 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14312 if (AAResult == NoAlias) 14313 return false; 14314 } 14315 14316 // Otherwise we have to assume they alias. 14317 return true; 14318 } 14319 14320 /// Walk up chain skipping non-aliasing memory nodes, 14321 /// looking for aliasing nodes and adding them to the Aliases vector. 14322 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14323 SmallVectorImpl<SDValue> &Aliases) { 14324 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14325 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14326 14327 // Get alias information for node. 14328 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14329 14330 // Starting off. 14331 Chains.push_back(OriginalChain); 14332 unsigned Depth = 0; 14333 14334 // Look at each chain and determine if it is an alias. If so, add it to the 14335 // aliases list. If not, then continue up the chain looking for the next 14336 // candidate. 14337 while (!Chains.empty()) { 14338 SDValue Chain = Chains.pop_back_val(); 14339 14340 // For TokenFactor nodes, look at each operand and only continue up the 14341 // chain until we find two aliases. If we've seen two aliases, assume we'll 14342 // find more and revert to original chain since the xform is unlikely to be 14343 // profitable. 14344 // 14345 // FIXME: The depth check could be made to return the last non-aliasing 14346 // chain we found before we hit a tokenfactor rather than the original 14347 // chain. 14348 if (Depth > 6 || Aliases.size() == 2) { 14349 Aliases.clear(); 14350 Aliases.push_back(OriginalChain); 14351 return; 14352 } 14353 14354 // Don't bother if we've been before. 14355 if (!Visited.insert(Chain.getNode()).second) 14356 continue; 14357 14358 switch (Chain.getOpcode()) { 14359 case ISD::EntryToken: 14360 // Entry token is ideal chain operand, but handled in FindBetterChain. 14361 break; 14362 14363 case ISD::LOAD: 14364 case ISD::STORE: { 14365 // Get alias information for Chain. 14366 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14367 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14368 14369 // If chain is alias then stop here. 14370 if (!(IsLoad && IsOpLoad) && 14371 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14372 Aliases.push_back(Chain); 14373 } else { 14374 // Look further up the chain. 14375 Chains.push_back(Chain.getOperand(0)); 14376 ++Depth; 14377 } 14378 break; 14379 } 14380 14381 case ISD::TokenFactor: 14382 // We have to check each of the operands of the token factor for "small" 14383 // token factors, so we queue them up. Adding the operands to the queue 14384 // (stack) in reverse order maintains the original order and increases the 14385 // likelihood that getNode will find a matching token factor (CSE.) 14386 if (Chain.getNumOperands() > 16) { 14387 Aliases.push_back(Chain); 14388 break; 14389 } 14390 for (unsigned n = Chain.getNumOperands(); n;) 14391 Chains.push_back(Chain.getOperand(--n)); 14392 ++Depth; 14393 break; 14394 14395 default: 14396 // For all other instructions we will just have to take what we can get. 14397 Aliases.push_back(Chain); 14398 break; 14399 } 14400 } 14401 14402 // We need to be careful here to also search for aliases through the 14403 // value operand of a store, etc. Consider the following situation: 14404 // Token1 = ... 14405 // L1 = load Token1, %52 14406 // S1 = store Token1, L1, %51 14407 // L2 = load Token1, %52+8 14408 // S2 = store Token1, L2, %51+8 14409 // Token2 = Token(S1, S2) 14410 // L3 = load Token2, %53 14411 // S3 = store Token2, L3, %52 14412 // L4 = load Token2, %53+8 14413 // S4 = store Token2, L4, %52+8 14414 // If we search for aliases of S3 (which loads address %52), and we look 14415 // only through the chain, then we'll miss the trivial dependence on L1 14416 // (which also loads from %52). We then might change all loads and 14417 // stores to use Token1 as their chain operand, which could result in 14418 // copying %53 into %52 before copying %52 into %51 (which should 14419 // happen first). 14420 // 14421 // The problem is, however, that searching for such data dependencies 14422 // can become expensive, and the cost is not directly related to the 14423 // chain depth. Instead, we'll rule out such configurations here by 14424 // insisting that we've visited all chain users (except for users 14425 // of the original chain, which is not necessary). When doing this, 14426 // we need to look through nodes we don't care about (otherwise, things 14427 // like register copies will interfere with trivial cases). 14428 14429 SmallVector<const SDNode *, 16> Worklist; 14430 for (const SDNode *N : Visited) 14431 if (N != OriginalChain.getNode()) 14432 Worklist.push_back(N); 14433 14434 while (!Worklist.empty()) { 14435 const SDNode *M = Worklist.pop_back_val(); 14436 14437 // We have already visited M, and want to make sure we've visited any uses 14438 // of M that we care about. For uses that we've not visisted, and don't 14439 // care about, queue them to the worklist. 14440 14441 for (SDNode::use_iterator UI = M->use_begin(), 14442 UIE = M->use_end(); UI != UIE; ++UI) 14443 if (UI.getUse().getValueType() == MVT::Other && 14444 Visited.insert(*UI).second) { 14445 if (isa<MemSDNode>(*UI)) { 14446 // We've not visited this use, and we care about it (it could have an 14447 // ordering dependency with the original node). 14448 Aliases.clear(); 14449 Aliases.push_back(OriginalChain); 14450 return; 14451 } 14452 14453 // We've not visited this use, but we don't care about it. Mark it as 14454 // visited and enqueue it to the worklist. 14455 Worklist.push_back(*UI); 14456 } 14457 } 14458 } 14459 14460 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14461 /// (aliasing node.) 14462 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14463 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14464 14465 // Accumulate all the aliases to this node. 14466 GatherAllAliases(N, OldChain, Aliases); 14467 14468 // If no operands then chain to entry token. 14469 if (Aliases.size() == 0) 14470 return DAG.getEntryNode(); 14471 14472 // If a single operand then chain to it. We don't need to revisit it. 14473 if (Aliases.size() == 1) 14474 return Aliases[0]; 14475 14476 // Construct a custom tailored token factor. 14477 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14478 } 14479 14480 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) { 14481 // This holds the base pointer, index, and the offset in bytes from the base 14482 // pointer. 14483 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 14484 14485 // We must have a base and an offset. 14486 if (!BasePtr.Base.getNode()) 14487 return false; 14488 14489 // Do not handle stores to undef base pointers. 14490 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 14491 return false; 14492 14493 SmallVector<StoreSDNode *, 8> ChainedStores; 14494 ChainedStores.push_back(St); 14495 14496 // Walk up the chain and look for nodes with offsets from the same 14497 // base pointer. Stop when reaching an instruction with a different kind 14498 // or instruction which has a different base pointer. 14499 StoreSDNode *Index = St; 14500 while (Index) { 14501 // If the chain has more than one use, then we can't reorder the mem ops. 14502 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14503 break; 14504 14505 if (Index->isVolatile() || Index->isIndexed()) 14506 break; 14507 14508 // Find the base pointer and offset for this memory node. 14509 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 14510 14511 // Check that the base pointer is the same as the original one. 14512 if (!Ptr.equalBaseIndex(BasePtr)) 14513 break; 14514 14515 // Find the next memory operand in the chain. If the next operand in the 14516 // chain is a store then move up and continue the scan with the next 14517 // memory operand. If the next operand is a load save it and use alias 14518 // information to check if it interferes with anything. 14519 SDNode *NextInChain = Index->getChain().getNode(); 14520 while (true) { 14521 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14522 // We found a store node. Use it for the next iteration. 14523 ChainedStores.push_back(STn); 14524 Index = STn; 14525 break; 14526 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14527 NextInChain = Ldn->getChain().getNode(); 14528 continue; 14529 } else { 14530 Index = nullptr; 14531 break; 14532 } 14533 } 14534 } 14535 14536 bool MadeChange = false; 14537 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 14538 14539 for (StoreSDNode *ChainedStore : ChainedStores) { 14540 SDValue Chain = ChainedStore->getChain(); 14541 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 14542 14543 if (Chain != BetterChain) { 14544 MadeChange = true; 14545 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 14546 } 14547 } 14548 14549 // Do all replacements after finding the replacements to make to avoid making 14550 // the chains more complicated by introducing new TokenFactors. 14551 for (auto Replacement : BetterChains) 14552 replaceStoreChain(Replacement.first, Replacement.second); 14553 14554 return MadeChange; 14555 } 14556 14557 /// This is the entry point for the file. 14558 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 14559 CodeGenOpt::Level OptLevel) { 14560 /// This is the main entry point to this class. 14561 DAGCombiner(*this, AA, OptLevel).Run(Level); 14562 } 14563