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 EVT Ty) const; 411 412 /// This is a helper function for MergeConsecutiveStores. When the source 413 /// elements of the consecutive stores are all constants or all extracted 414 /// vector elements, try to merge them into one larger store. 415 /// \return True if a merged store was created. 416 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 417 EVT MemVT, unsigned NumStores, 418 bool IsConstantSrc, bool UseVector); 419 420 /// This is a helper function for MergeConsecutiveStores. 421 /// Stores that may be merged are placed in StoreNodes. 422 /// Loads that may alias with those stores are placed in AliasLoadNodes. 423 void getStoreMergeAndAliasCandidates( 424 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 425 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 426 427 /// Merge consecutive store operations into a wide store. 428 /// This optimization uses wide integers or vectors when possible. 429 /// \return True if some memory operations were changed. 430 bool MergeConsecutiveStores(StoreSDNode *N); 431 432 /// \brief Try to transform a truncation where C is a constant: 433 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 434 /// 435 /// \p N needs to be a truncation and its first operand an AND. Other 436 /// requirements are checked by the function (e.g. that trunc is 437 /// single-use) and if missed an empty SDValue is returned. 438 SDValue distributeTruncateThroughAnd(SDNode *N); 439 440 public: 441 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 442 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 443 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 444 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 445 } 446 447 /// Runs the dag combiner on all nodes in the work list 448 void Run(CombineLevel AtLevel); 449 450 SelectionDAG &getDAG() const { return DAG; } 451 452 /// Returns a type large enough to hold any valid shift amount - before type 453 /// legalization these can be huge. 454 EVT getShiftAmountTy(EVT LHSTy) { 455 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 456 if (LHSTy.isVector()) 457 return LHSTy; 458 auto &DL = DAG.getDataLayout(); 459 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 460 : TLI.getPointerTy(DL); 461 } 462 463 /// This method returns true if we are running before type legalization or 464 /// if the specified VT is legal. 465 bool isTypeLegal(const EVT &VT) { 466 if (!LegalTypes) return true; 467 return TLI.isTypeLegal(VT); 468 } 469 470 /// Convenience wrapper around TargetLowering::getSetCCResultType 471 EVT getSetCCResultType(EVT VT) const { 472 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 473 } 474 }; 475 } 476 477 478 namespace { 479 /// This class is a DAGUpdateListener that removes any deleted 480 /// nodes from the worklist. 481 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 482 DAGCombiner &DC; 483 public: 484 explicit WorklistRemover(DAGCombiner &dc) 485 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 486 487 void NodeDeleted(SDNode *N, SDNode *E) override { 488 DC.removeFromWorklist(N); 489 } 490 }; 491 } 492 493 //===----------------------------------------------------------------------===// 494 // TargetLowering::DAGCombinerInfo implementation 495 //===----------------------------------------------------------------------===// 496 497 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 498 ((DAGCombiner*)DC)->AddToWorklist(N); 499 } 500 501 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 502 ((DAGCombiner*)DC)->removeFromWorklist(N); 503 } 504 505 SDValue TargetLowering::DAGCombinerInfo:: 506 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 507 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 508 } 509 510 SDValue TargetLowering::DAGCombinerInfo:: 511 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 512 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 513 } 514 515 516 SDValue TargetLowering::DAGCombinerInfo:: 517 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 518 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 519 } 520 521 void TargetLowering::DAGCombinerInfo:: 522 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 523 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 524 } 525 526 //===----------------------------------------------------------------------===// 527 // Helper Functions 528 //===----------------------------------------------------------------------===// 529 530 void DAGCombiner::deleteAndRecombine(SDNode *N) { 531 removeFromWorklist(N); 532 533 // If the operands of this node are only used by the node, they will now be 534 // dead. Make sure to re-visit them and recursively delete dead nodes. 535 for (const SDValue &Op : N->ops()) 536 // For an operand generating multiple values, one of the values may 537 // become dead allowing further simplification (e.g. split index 538 // arithmetic from an indexed load). 539 if (Op->hasOneUse() || Op->getNumValues() > 1) 540 AddToWorklist(Op.getNode()); 541 542 DAG.DeleteNode(N); 543 } 544 545 /// Return 1 if we can compute the negated form of the specified expression for 546 /// the same cost as the expression itself, or 2 if we can compute the negated 547 /// form more cheaply than the expression itself. 548 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 549 const TargetLowering &TLI, 550 const TargetOptions *Options, 551 unsigned Depth = 0) { 552 // fneg is removable even if it has multiple uses. 553 if (Op.getOpcode() == ISD::FNEG) return 2; 554 555 // Don't allow anything with multiple uses. 556 if (!Op.hasOneUse()) return 0; 557 558 // Don't recurse exponentially. 559 if (Depth > 6) return 0; 560 561 switch (Op.getOpcode()) { 562 default: return false; 563 case ISD::ConstantFP: 564 // Don't invert constant FP values after legalize. The negated constant 565 // isn't necessarily legal. 566 return LegalOperations ? 0 : 1; 567 case ISD::FADD: 568 // FIXME: determine better conditions for this xform. 569 if (!Options->UnsafeFPMath) return 0; 570 571 // After operation legalization, it might not be legal to create new FSUBs. 572 if (LegalOperations && 573 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 574 return 0; 575 576 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 577 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 578 Options, Depth + 1)) 579 return V; 580 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 581 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 582 Depth + 1); 583 case ISD::FSUB: 584 // We can't turn -(A-B) into B-A when we honor signed zeros. 585 if (!Options->UnsafeFPMath) return 0; 586 587 // fold (fneg (fsub A, B)) -> (fsub B, A) 588 return 1; 589 590 case ISD::FMUL: 591 case ISD::FDIV: 592 if (Options->HonorSignDependentRoundingFPMath()) return 0; 593 594 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 595 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 596 Options, Depth + 1)) 597 return V; 598 599 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 600 Depth + 1); 601 602 case ISD::FP_EXTEND: 603 case ISD::FP_ROUND: 604 case ISD::FSIN: 605 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 606 Depth + 1); 607 } 608 } 609 610 /// If isNegatibleForFree returns true, return the newly negated expression. 611 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 612 bool LegalOperations, unsigned Depth = 0) { 613 const TargetOptions &Options = DAG.getTarget().Options; 614 // fneg is removable even if it has multiple uses. 615 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 616 617 // Don't allow anything with multiple uses. 618 assert(Op.hasOneUse() && "Unknown reuse!"); 619 620 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 621 622 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 623 624 switch (Op.getOpcode()) { 625 default: llvm_unreachable("Unknown code"); 626 case ISD::ConstantFP: { 627 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 628 V.changeSign(); 629 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 630 } 631 case ISD::FADD: 632 // FIXME: determine better conditions for this xform. 633 assert(Options.UnsafeFPMath); 634 635 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 636 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 637 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 638 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 639 GetNegatedExpression(Op.getOperand(0), DAG, 640 LegalOperations, Depth+1), 641 Op.getOperand(1), Flags); 642 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 643 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 644 GetNegatedExpression(Op.getOperand(1), DAG, 645 LegalOperations, Depth+1), 646 Op.getOperand(0), Flags); 647 case ISD::FSUB: 648 // We can't turn -(A-B) into B-A when we honor signed zeros. 649 assert(Options.UnsafeFPMath); 650 651 // fold (fneg (fsub 0, B)) -> B 652 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 653 if (N0CFP->isZero()) 654 return Op.getOperand(1); 655 656 // fold (fneg (fsub A, B)) -> (fsub B, A) 657 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 658 Op.getOperand(1), Op.getOperand(0), Flags); 659 660 case ISD::FMUL: 661 case ISD::FDIV: 662 assert(!Options.HonorSignDependentRoundingFPMath()); 663 664 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 665 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 666 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 667 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 668 GetNegatedExpression(Op.getOperand(0), DAG, 669 LegalOperations, Depth+1), 670 Op.getOperand(1), Flags); 671 672 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 673 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 674 Op.getOperand(0), 675 GetNegatedExpression(Op.getOperand(1), DAG, 676 LegalOperations, Depth+1), Flags); 677 678 case ISD::FP_EXTEND: 679 case ISD::FSIN: 680 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 681 GetNegatedExpression(Op.getOperand(0), DAG, 682 LegalOperations, Depth+1)); 683 case ISD::FP_ROUND: 684 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 685 GetNegatedExpression(Op.getOperand(0), DAG, 686 LegalOperations, Depth+1), 687 Op.getOperand(1)); 688 } 689 } 690 691 // Return true if this node is a setcc, or is a select_cc 692 // that selects between the target values used for true and false, making it 693 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 694 // the appropriate nodes based on the type of node we are checking. This 695 // simplifies life a bit for the callers. 696 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 697 SDValue &CC) const { 698 if (N.getOpcode() == ISD::SETCC) { 699 LHS = N.getOperand(0); 700 RHS = N.getOperand(1); 701 CC = N.getOperand(2); 702 return true; 703 } 704 705 if (N.getOpcode() != ISD::SELECT_CC || 706 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 707 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 708 return false; 709 710 if (TLI.getBooleanContents(N.getValueType()) == 711 TargetLowering::UndefinedBooleanContent) 712 return false; 713 714 LHS = N.getOperand(0); 715 RHS = N.getOperand(1); 716 CC = N.getOperand(4); 717 return true; 718 } 719 720 /// Return true if this is a SetCC-equivalent operation with only one use. 721 /// If this is true, it allows the users to invert the operation for free when 722 /// it is profitable to do so. 723 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 724 SDValue N0, N1, N2; 725 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 726 return true; 727 return false; 728 } 729 730 /// Returns true if N is a BUILD_VECTOR node whose 731 /// elements are all the same constant or undefined. 732 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 733 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 734 if (!C) 735 return false; 736 737 APInt SplatUndef; 738 unsigned SplatBitSize; 739 bool HasAnyUndefs; 740 EVT EltVT = N->getValueType(0).getVectorElementType(); 741 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 742 HasAnyUndefs) && 743 EltVT.getSizeInBits() >= SplatBitSize); 744 } 745 746 // \brief Returns the SDNode if it is a constant integer BuildVector 747 // or constant integer. 748 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) { 749 if (isa<ConstantSDNode>(N)) 750 return N.getNode(); 751 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 752 return N.getNode(); 753 return nullptr; 754 } 755 756 // \brief Returns the SDNode if it is a constant float BuildVector 757 // or constant float. 758 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 759 if (isa<ConstantFPSDNode>(N)) 760 return N.getNode(); 761 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 762 return N.getNode(); 763 return nullptr; 764 } 765 766 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 767 // int. 768 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 769 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 770 return CN; 771 772 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 773 BitVector UndefElements; 774 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 775 776 // BuildVectors can truncate their operands. Ignore that case here. 777 // FIXME: We blindly ignore splats which include undef which is overly 778 // pessimistic. 779 if (CN && UndefElements.none() && 780 CN->getValueType(0) == N.getValueType().getScalarType()) 781 return CN; 782 } 783 784 return nullptr; 785 } 786 787 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 788 // float. 789 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 790 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 791 return CN; 792 793 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 794 BitVector UndefElements; 795 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 796 797 if (CN && UndefElements.none()) 798 return CN; 799 } 800 801 return nullptr; 802 } 803 804 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 805 SDValue N0, SDValue N1) { 806 EVT VT = N0.getValueType(); 807 if (N0.getOpcode() == Opc) { 808 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 809 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) { 810 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 811 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 812 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 813 return SDValue(); 814 } 815 if (N0.hasOneUse()) { 816 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 817 // use 818 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 819 if (!OpNode.getNode()) 820 return SDValue(); 821 AddToWorklist(OpNode.getNode()); 822 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 823 } 824 } 825 } 826 827 if (N1.getOpcode() == Opc) { 828 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 829 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) { 830 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 831 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 832 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 833 return SDValue(); 834 } 835 if (N1.hasOneUse()) { 836 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 837 // use 838 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 839 if (!OpNode.getNode()) 840 return SDValue(); 841 AddToWorklist(OpNode.getNode()); 842 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 843 } 844 } 845 } 846 847 return SDValue(); 848 } 849 850 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 851 bool AddTo) { 852 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 853 ++NodesCombined; 854 DEBUG(dbgs() << "\nReplacing.1 "; 855 N->dump(&DAG); 856 dbgs() << "\nWith: "; 857 To[0].getNode()->dump(&DAG); 858 dbgs() << " and " << NumTo-1 << " other values\n"); 859 for (unsigned i = 0, e = NumTo; i != e; ++i) 860 assert((!To[i].getNode() || 861 N->getValueType(i) == To[i].getValueType()) && 862 "Cannot combine value to value of different type!"); 863 864 WorklistRemover DeadNodes(*this); 865 DAG.ReplaceAllUsesWith(N, To); 866 if (AddTo) { 867 // Push the new nodes and any users onto the worklist 868 for (unsigned i = 0, e = NumTo; i != e; ++i) { 869 if (To[i].getNode()) { 870 AddToWorklist(To[i].getNode()); 871 AddUsersToWorklist(To[i].getNode()); 872 } 873 } 874 } 875 876 // Finally, if the node is now dead, remove it from the graph. The node 877 // may not be dead if the replacement process recursively simplified to 878 // something else needing this node. 879 if (N->use_empty()) 880 deleteAndRecombine(N); 881 return SDValue(N, 0); 882 } 883 884 void DAGCombiner:: 885 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 886 // Replace all uses. If any nodes become isomorphic to other nodes and 887 // are deleted, make sure to remove them from our worklist. 888 WorklistRemover DeadNodes(*this); 889 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 890 891 // Push the new node and any (possibly new) users onto the worklist. 892 AddToWorklist(TLO.New.getNode()); 893 AddUsersToWorklist(TLO.New.getNode()); 894 895 // Finally, if the node is now dead, remove it from the graph. The node 896 // may not be dead if the replacement process recursively simplified to 897 // something else needing this node. 898 if (TLO.Old.getNode()->use_empty()) 899 deleteAndRecombine(TLO.Old.getNode()); 900 } 901 902 /// Check the specified integer node value to see if it can be simplified or if 903 /// things it uses can be simplified by bit propagation. If so, return true. 904 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 905 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 906 APInt KnownZero, KnownOne; 907 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 908 return false; 909 910 // Revisit the node. 911 AddToWorklist(Op.getNode()); 912 913 // Replace the old value with the new one. 914 ++NodesCombined; 915 DEBUG(dbgs() << "\nReplacing.2 "; 916 TLO.Old.getNode()->dump(&DAG); 917 dbgs() << "\nWith: "; 918 TLO.New.getNode()->dump(&DAG); 919 dbgs() << '\n'); 920 921 CommitTargetLoweringOpt(TLO); 922 return true; 923 } 924 925 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 926 SDLoc dl(Load); 927 EVT VT = Load->getValueType(0); 928 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 929 930 DEBUG(dbgs() << "\nReplacing.9 "; 931 Load->dump(&DAG); 932 dbgs() << "\nWith: "; 933 Trunc.getNode()->dump(&DAG); 934 dbgs() << '\n'); 935 WorklistRemover DeadNodes(*this); 936 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 937 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 938 deleteAndRecombine(Load); 939 AddToWorklist(Trunc.getNode()); 940 } 941 942 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 943 Replace = false; 944 SDLoc dl(Op); 945 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 946 EVT MemVT = LD->getMemoryVT(); 947 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 948 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 949 : ISD::EXTLOAD) 950 : LD->getExtensionType(); 951 Replace = true; 952 return DAG.getExtLoad(ExtType, dl, PVT, 953 LD->getChain(), LD->getBasePtr(), 954 MemVT, LD->getMemOperand()); 955 } 956 957 unsigned Opc = Op.getOpcode(); 958 switch (Opc) { 959 default: break; 960 case ISD::AssertSext: 961 return DAG.getNode(ISD::AssertSext, dl, PVT, 962 SExtPromoteOperand(Op.getOperand(0), PVT), 963 Op.getOperand(1)); 964 case ISD::AssertZext: 965 return DAG.getNode(ISD::AssertZext, dl, PVT, 966 ZExtPromoteOperand(Op.getOperand(0), PVT), 967 Op.getOperand(1)); 968 case ISD::Constant: { 969 unsigned ExtOpc = 970 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 971 return DAG.getNode(ExtOpc, dl, PVT, Op); 972 } 973 } 974 975 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 976 return SDValue(); 977 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 978 } 979 980 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 981 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 982 return SDValue(); 983 EVT OldVT = Op.getValueType(); 984 SDLoc dl(Op); 985 bool Replace = false; 986 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 987 if (!NewOp.getNode()) 988 return SDValue(); 989 AddToWorklist(NewOp.getNode()); 990 991 if (Replace) 992 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 993 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 994 DAG.getValueType(OldVT)); 995 } 996 997 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 998 EVT OldVT = Op.getValueType(); 999 SDLoc dl(Op); 1000 bool Replace = false; 1001 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1002 if (!NewOp.getNode()) 1003 return SDValue(); 1004 AddToWorklist(NewOp.getNode()); 1005 1006 if (Replace) 1007 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1008 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1009 } 1010 1011 /// Promote the specified integer binary operation if the target indicates it is 1012 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1013 /// i32 since i16 instructions are longer. 1014 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1015 if (!LegalOperations) 1016 return SDValue(); 1017 1018 EVT VT = Op.getValueType(); 1019 if (VT.isVector() || !VT.isInteger()) 1020 return SDValue(); 1021 1022 // If operation type is 'undesirable', e.g. i16 on x86, consider 1023 // promoting it. 1024 unsigned Opc = Op.getOpcode(); 1025 if (TLI.isTypeDesirableForOp(Opc, VT)) 1026 return SDValue(); 1027 1028 EVT PVT = VT; 1029 // Consult target whether it is a good idea to promote this operation and 1030 // what's the right type to promote it to. 1031 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1032 assert(PVT != VT && "Don't know what type to promote to!"); 1033 1034 bool Replace0 = false; 1035 SDValue N0 = Op.getOperand(0); 1036 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1037 if (!NN0.getNode()) 1038 return SDValue(); 1039 1040 bool Replace1 = false; 1041 SDValue N1 = Op.getOperand(1); 1042 SDValue NN1; 1043 if (N0 == N1) 1044 NN1 = NN0; 1045 else { 1046 NN1 = PromoteOperand(N1, PVT, Replace1); 1047 if (!NN1.getNode()) 1048 return SDValue(); 1049 } 1050 1051 AddToWorklist(NN0.getNode()); 1052 if (NN1.getNode()) 1053 AddToWorklist(NN1.getNode()); 1054 1055 if (Replace0) 1056 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1057 if (Replace1) 1058 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1059 1060 DEBUG(dbgs() << "\nPromoting "; 1061 Op.getNode()->dump(&DAG)); 1062 SDLoc dl(Op); 1063 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1064 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1065 } 1066 return SDValue(); 1067 } 1068 1069 /// Promote the specified integer shift operation if the target indicates it is 1070 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1071 /// i32 since i16 instructions are longer. 1072 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1073 if (!LegalOperations) 1074 return SDValue(); 1075 1076 EVT VT = Op.getValueType(); 1077 if (VT.isVector() || !VT.isInteger()) 1078 return SDValue(); 1079 1080 // If operation type is 'undesirable', e.g. i16 on x86, consider 1081 // promoting it. 1082 unsigned Opc = Op.getOpcode(); 1083 if (TLI.isTypeDesirableForOp(Opc, VT)) 1084 return SDValue(); 1085 1086 EVT PVT = VT; 1087 // Consult target whether it is a good idea to promote this operation and 1088 // what's the right type to promote it to. 1089 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1090 assert(PVT != VT && "Don't know what type to promote to!"); 1091 1092 bool Replace = false; 1093 SDValue N0 = Op.getOperand(0); 1094 if (Opc == ISD::SRA) 1095 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1096 else if (Opc == ISD::SRL) 1097 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1098 else 1099 N0 = PromoteOperand(N0, PVT, Replace); 1100 if (!N0.getNode()) 1101 return SDValue(); 1102 1103 AddToWorklist(N0.getNode()); 1104 if (Replace) 1105 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1106 1107 DEBUG(dbgs() << "\nPromoting "; 1108 Op.getNode()->dump(&DAG)); 1109 SDLoc dl(Op); 1110 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1111 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1112 } 1113 return SDValue(); 1114 } 1115 1116 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1117 if (!LegalOperations) 1118 return SDValue(); 1119 1120 EVT VT = Op.getValueType(); 1121 if (VT.isVector() || !VT.isInteger()) 1122 return SDValue(); 1123 1124 // If operation type is 'undesirable', e.g. i16 on x86, consider 1125 // promoting it. 1126 unsigned Opc = Op.getOpcode(); 1127 if (TLI.isTypeDesirableForOp(Opc, VT)) 1128 return SDValue(); 1129 1130 EVT PVT = VT; 1131 // Consult target whether it is a good idea to promote this operation and 1132 // what's the right type to promote it to. 1133 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1134 assert(PVT != VT && "Don't know what type to promote to!"); 1135 // fold (aext (aext x)) -> (aext x) 1136 // fold (aext (zext x)) -> (zext x) 1137 // fold (aext (sext x)) -> (sext x) 1138 DEBUG(dbgs() << "\nPromoting "; 1139 Op.getNode()->dump(&DAG)); 1140 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1141 } 1142 return SDValue(); 1143 } 1144 1145 bool DAGCombiner::PromoteLoad(SDValue Op) { 1146 if (!LegalOperations) 1147 return false; 1148 1149 EVT VT = Op.getValueType(); 1150 if (VT.isVector() || !VT.isInteger()) 1151 return false; 1152 1153 // If operation type is 'undesirable', e.g. i16 on x86, consider 1154 // promoting it. 1155 unsigned Opc = Op.getOpcode(); 1156 if (TLI.isTypeDesirableForOp(Opc, VT)) 1157 return false; 1158 1159 EVT PVT = VT; 1160 // Consult target whether it is a good idea to promote this operation and 1161 // what's the right type to promote it to. 1162 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1163 assert(PVT != VT && "Don't know what type to promote to!"); 1164 1165 SDLoc dl(Op); 1166 SDNode *N = Op.getNode(); 1167 LoadSDNode *LD = cast<LoadSDNode>(N); 1168 EVT MemVT = LD->getMemoryVT(); 1169 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1170 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1171 : ISD::EXTLOAD) 1172 : LD->getExtensionType(); 1173 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1174 LD->getChain(), LD->getBasePtr(), 1175 MemVT, LD->getMemOperand()); 1176 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1177 1178 DEBUG(dbgs() << "\nPromoting "; 1179 N->dump(&DAG); 1180 dbgs() << "\nTo: "; 1181 Result.getNode()->dump(&DAG); 1182 dbgs() << '\n'); 1183 WorklistRemover DeadNodes(*this); 1184 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1185 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1186 deleteAndRecombine(N); 1187 AddToWorklist(Result.getNode()); 1188 return true; 1189 } 1190 return false; 1191 } 1192 1193 /// \brief Recursively delete a node which has no uses and any operands for 1194 /// which it is the only use. 1195 /// 1196 /// Note that this both deletes the nodes and removes them from the worklist. 1197 /// It also adds any nodes who have had a user deleted to the worklist as they 1198 /// may now have only one use and subject to other combines. 1199 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1200 if (!N->use_empty()) 1201 return false; 1202 1203 SmallSetVector<SDNode *, 16> Nodes; 1204 Nodes.insert(N); 1205 do { 1206 N = Nodes.pop_back_val(); 1207 if (!N) 1208 continue; 1209 1210 if (N->use_empty()) { 1211 for (const SDValue &ChildN : N->op_values()) 1212 Nodes.insert(ChildN.getNode()); 1213 1214 removeFromWorklist(N); 1215 DAG.DeleteNode(N); 1216 } else { 1217 AddToWorklist(N); 1218 } 1219 } while (!Nodes.empty()); 1220 return true; 1221 } 1222 1223 //===----------------------------------------------------------------------===// 1224 // Main DAG Combiner implementation 1225 //===----------------------------------------------------------------------===// 1226 1227 void DAGCombiner::Run(CombineLevel AtLevel) { 1228 // set the instance variables, so that the various visit routines may use it. 1229 Level = AtLevel; 1230 LegalOperations = Level >= AfterLegalizeVectorOps; 1231 LegalTypes = Level >= AfterLegalizeTypes; 1232 1233 // Add all the dag nodes to the worklist. 1234 for (SDNode &Node : DAG.allnodes()) 1235 AddToWorklist(&Node); 1236 1237 // Create a dummy node (which is not added to allnodes), that adds a reference 1238 // to the root node, preventing it from being deleted, and tracking any 1239 // changes of the root. 1240 HandleSDNode Dummy(DAG.getRoot()); 1241 1242 // while the worklist isn't empty, find a node and 1243 // try and combine it. 1244 while (!WorklistMap.empty()) { 1245 SDNode *N; 1246 // The Worklist holds the SDNodes in order, but it may contain null entries. 1247 do { 1248 N = Worklist.pop_back_val(); 1249 } while (!N); 1250 1251 bool GoodWorklistEntry = WorklistMap.erase(N); 1252 (void)GoodWorklistEntry; 1253 assert(GoodWorklistEntry && 1254 "Found a worklist entry without a corresponding map entry!"); 1255 1256 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1257 // N is deleted from the DAG, since they too may now be dead or may have a 1258 // reduced number of uses, allowing other xforms. 1259 if (recursivelyDeleteUnusedNodes(N)) 1260 continue; 1261 1262 WorklistRemover DeadNodes(*this); 1263 1264 // If this combine is running after legalizing the DAG, re-legalize any 1265 // nodes pulled off the worklist. 1266 if (Level == AfterLegalizeDAG) { 1267 SmallSetVector<SDNode *, 16> UpdatedNodes; 1268 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1269 1270 for (SDNode *LN : UpdatedNodes) { 1271 AddToWorklist(LN); 1272 AddUsersToWorklist(LN); 1273 } 1274 if (!NIsValid) 1275 continue; 1276 } 1277 1278 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1279 1280 // Add any operands of the new node which have not yet been combined to the 1281 // worklist as well. Because the worklist uniques things already, this 1282 // won't repeatedly process the same operand. 1283 CombinedNodes.insert(N); 1284 for (const SDValue &ChildN : N->op_values()) 1285 if (!CombinedNodes.count(ChildN.getNode())) 1286 AddToWorklist(ChildN.getNode()); 1287 1288 SDValue RV = combine(N); 1289 1290 if (!RV.getNode()) 1291 continue; 1292 1293 ++NodesCombined; 1294 1295 // If we get back the same node we passed in, rather than a new node or 1296 // zero, we know that the node must have defined multiple values and 1297 // CombineTo was used. Since CombineTo takes care of the worklist 1298 // mechanics for us, we have no work to do in this case. 1299 if (RV.getNode() == N) 1300 continue; 1301 1302 assert(N->getOpcode() != ISD::DELETED_NODE && 1303 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1304 "Node was deleted but visit returned new node!"); 1305 1306 DEBUG(dbgs() << " ... into: "; 1307 RV.getNode()->dump(&DAG)); 1308 1309 // Transfer debug value. 1310 DAG.TransferDbgValues(SDValue(N, 0), RV); 1311 if (N->getNumValues() == RV.getNode()->getNumValues()) 1312 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1313 else { 1314 assert(N->getValueType(0) == RV.getValueType() && 1315 N->getNumValues() == 1 && "Type mismatch"); 1316 SDValue OpV = RV; 1317 DAG.ReplaceAllUsesWith(N, &OpV); 1318 } 1319 1320 // Push the new node and any users onto the worklist 1321 AddToWorklist(RV.getNode()); 1322 AddUsersToWorklist(RV.getNode()); 1323 1324 // Finally, if the node is now dead, remove it from the graph. The node 1325 // may not be dead if the replacement process recursively simplified to 1326 // something else needing this node. This will also take care of adding any 1327 // operands which have lost a user to the worklist. 1328 recursivelyDeleteUnusedNodes(N); 1329 } 1330 1331 // If the root changed (e.g. it was a dead load, update the root). 1332 DAG.setRoot(Dummy.getValue()); 1333 DAG.RemoveDeadNodes(); 1334 } 1335 1336 SDValue DAGCombiner::visit(SDNode *N) { 1337 switch (N->getOpcode()) { 1338 default: break; 1339 case ISD::TokenFactor: return visitTokenFactor(N); 1340 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1341 case ISD::ADD: return visitADD(N); 1342 case ISD::SUB: return visitSUB(N); 1343 case ISD::ADDC: return visitADDC(N); 1344 case ISD::SUBC: return visitSUBC(N); 1345 case ISD::ADDE: return visitADDE(N); 1346 case ISD::SUBE: return visitSUBE(N); 1347 case ISD::MUL: return visitMUL(N); 1348 case ISD::SDIV: return visitSDIV(N); 1349 case ISD::UDIV: return visitUDIV(N); 1350 case ISD::SREM: return visitSREM(N); 1351 case ISD::UREM: return visitUREM(N); 1352 case ISD::MULHU: return visitMULHU(N); 1353 case ISD::MULHS: return visitMULHS(N); 1354 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1355 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1356 case ISD::SMULO: return visitSMULO(N); 1357 case ISD::UMULO: return visitUMULO(N); 1358 case ISD::SDIVREM: return visitSDIVREM(N); 1359 case ISD::UDIVREM: return visitUDIVREM(N); 1360 case ISD::SMIN: 1361 case ISD::SMAX: 1362 case ISD::UMIN: 1363 case ISD::UMAX: return visitIMINMAX(N); 1364 case ISD::AND: return visitAND(N); 1365 case ISD::OR: return visitOR(N); 1366 case ISD::XOR: return visitXOR(N); 1367 case ISD::SHL: return visitSHL(N); 1368 case ISD::SRA: return visitSRA(N); 1369 case ISD::SRL: return visitSRL(N); 1370 case ISD::ROTR: 1371 case ISD::ROTL: return visitRotate(N); 1372 case ISD::BSWAP: return visitBSWAP(N); 1373 case ISD::CTLZ: return visitCTLZ(N); 1374 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1375 case ISD::CTTZ: return visitCTTZ(N); 1376 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1377 case ISD::CTPOP: return visitCTPOP(N); 1378 case ISD::SELECT: return visitSELECT(N); 1379 case ISD::VSELECT: return visitVSELECT(N); 1380 case ISD::SELECT_CC: return visitSELECT_CC(N); 1381 case ISD::SETCC: return visitSETCC(N); 1382 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1383 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1384 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1385 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1386 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1387 case ISD::TRUNCATE: return visitTRUNCATE(N); 1388 case ISD::BITCAST: return visitBITCAST(N); 1389 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1390 case ISD::FADD: return visitFADD(N); 1391 case ISD::FSUB: return visitFSUB(N); 1392 case ISD::FMUL: return visitFMUL(N); 1393 case ISD::FMA: return visitFMA(N); 1394 case ISD::FDIV: return visitFDIV(N); 1395 case ISD::FREM: return visitFREM(N); 1396 case ISD::FSQRT: return visitFSQRT(N); 1397 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1398 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1399 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1400 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1401 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1402 case ISD::FP_ROUND: return visitFP_ROUND(N); 1403 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1404 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1405 case ISD::FNEG: return visitFNEG(N); 1406 case ISD::FABS: return visitFABS(N); 1407 case ISD::FFLOOR: return visitFFLOOR(N); 1408 case ISD::FMINNUM: return visitFMINNUM(N); 1409 case ISD::FMAXNUM: return visitFMAXNUM(N); 1410 case ISD::FCEIL: return visitFCEIL(N); 1411 case ISD::FTRUNC: return visitFTRUNC(N); 1412 case ISD::BRCOND: return visitBRCOND(N); 1413 case ISD::BR_CC: return visitBR_CC(N); 1414 case ISD::LOAD: return visitLOAD(N); 1415 case ISD::STORE: return visitSTORE(N); 1416 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1417 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1418 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1419 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1420 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1421 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1422 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1423 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1424 case ISD::MGATHER: return visitMGATHER(N); 1425 case ISD::MLOAD: return visitMLOAD(N); 1426 case ISD::MSCATTER: return visitMSCATTER(N); 1427 case ISD::MSTORE: return visitMSTORE(N); 1428 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1429 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1430 } 1431 return SDValue(); 1432 } 1433 1434 SDValue DAGCombiner::combine(SDNode *N) { 1435 SDValue RV = visit(N); 1436 1437 // If nothing happened, try a target-specific DAG combine. 1438 if (!RV.getNode()) { 1439 assert(N->getOpcode() != ISD::DELETED_NODE && 1440 "Node was deleted but visit returned NULL!"); 1441 1442 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1443 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1444 1445 // Expose the DAG combiner to the target combiner impls. 1446 TargetLowering::DAGCombinerInfo 1447 DagCombineInfo(DAG, Level, false, this); 1448 1449 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1450 } 1451 } 1452 1453 // If nothing happened still, try promoting the operation. 1454 if (!RV.getNode()) { 1455 switch (N->getOpcode()) { 1456 default: break; 1457 case ISD::ADD: 1458 case ISD::SUB: 1459 case ISD::MUL: 1460 case ISD::AND: 1461 case ISD::OR: 1462 case ISD::XOR: 1463 RV = PromoteIntBinOp(SDValue(N, 0)); 1464 break; 1465 case ISD::SHL: 1466 case ISD::SRA: 1467 case ISD::SRL: 1468 RV = PromoteIntShiftOp(SDValue(N, 0)); 1469 break; 1470 case ISD::SIGN_EXTEND: 1471 case ISD::ZERO_EXTEND: 1472 case ISD::ANY_EXTEND: 1473 RV = PromoteExtend(SDValue(N, 0)); 1474 break; 1475 case ISD::LOAD: 1476 if (PromoteLoad(SDValue(N, 0))) 1477 RV = SDValue(N, 0); 1478 break; 1479 } 1480 } 1481 1482 // If N is a commutative binary node, try commuting it to enable more 1483 // sdisel CSE. 1484 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1485 N->getNumValues() == 1) { 1486 SDValue N0 = N->getOperand(0); 1487 SDValue N1 = N->getOperand(1); 1488 1489 // Constant operands are canonicalized to RHS. 1490 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1491 SDValue Ops[] = {N1, N0}; 1492 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1493 N->getFlags()); 1494 if (CSENode) 1495 return SDValue(CSENode, 0); 1496 } 1497 } 1498 1499 return RV; 1500 } 1501 1502 /// Given a node, return its input chain if it has one, otherwise return a null 1503 /// sd operand. 1504 static SDValue getInputChainForNode(SDNode *N) { 1505 if (unsigned NumOps = N->getNumOperands()) { 1506 if (N->getOperand(0).getValueType() == MVT::Other) 1507 return N->getOperand(0); 1508 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1509 return N->getOperand(NumOps-1); 1510 for (unsigned i = 1; i < NumOps-1; ++i) 1511 if (N->getOperand(i).getValueType() == MVT::Other) 1512 return N->getOperand(i); 1513 } 1514 return SDValue(); 1515 } 1516 1517 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1518 // If N has two operands, where one has an input chain equal to the other, 1519 // the 'other' chain is redundant. 1520 if (N->getNumOperands() == 2) { 1521 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1522 return N->getOperand(0); 1523 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1524 return N->getOperand(1); 1525 } 1526 1527 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1528 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1529 SmallPtrSet<SDNode*, 16> SeenOps; 1530 bool Changed = false; // If we should replace this token factor. 1531 1532 // Start out with this token factor. 1533 TFs.push_back(N); 1534 1535 // Iterate through token factors. The TFs grows when new token factors are 1536 // encountered. 1537 for (unsigned i = 0; i < TFs.size(); ++i) { 1538 SDNode *TF = TFs[i]; 1539 1540 // Check each of the operands. 1541 for (const SDValue &Op : TF->op_values()) { 1542 1543 switch (Op.getOpcode()) { 1544 case ISD::EntryToken: 1545 // Entry tokens don't need to be added to the list. They are 1546 // redundant. 1547 Changed = true; 1548 break; 1549 1550 case ISD::TokenFactor: 1551 if (Op.hasOneUse() && 1552 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1553 // Queue up for processing. 1554 TFs.push_back(Op.getNode()); 1555 // Clean up in case the token factor is removed. 1556 AddToWorklist(Op.getNode()); 1557 Changed = true; 1558 break; 1559 } 1560 // Fall thru 1561 1562 default: 1563 // Only add if it isn't already in the list. 1564 if (SeenOps.insert(Op.getNode()).second) 1565 Ops.push_back(Op); 1566 else 1567 Changed = true; 1568 break; 1569 } 1570 } 1571 } 1572 1573 SDValue Result; 1574 1575 // If we've changed things around then replace token factor. 1576 if (Changed) { 1577 if (Ops.empty()) { 1578 // The entry token is the only possible outcome. 1579 Result = DAG.getEntryNode(); 1580 } else { 1581 // New and improved token factor. 1582 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1583 } 1584 1585 // Add users to worklist if AA is enabled, since it may introduce 1586 // a lot of new chained token factors while removing memory deps. 1587 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1588 : DAG.getSubtarget().useAA(); 1589 return CombineTo(N, Result, UseAA /*add to worklist*/); 1590 } 1591 1592 return Result; 1593 } 1594 1595 /// MERGE_VALUES can always be eliminated. 1596 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1597 WorklistRemover DeadNodes(*this); 1598 // Replacing results may cause a different MERGE_VALUES to suddenly 1599 // be CSE'd with N, and carry its uses with it. Iterate until no 1600 // uses remain, to ensure that the node can be safely deleted. 1601 // First add the users of this node to the work list so that they 1602 // can be tried again once they have new operands. 1603 AddUsersToWorklist(N); 1604 do { 1605 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1606 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1607 } while (!N->use_empty()); 1608 deleteAndRecombine(N); 1609 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1610 } 1611 1612 static bool isNullConstant(SDValue V) { 1613 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1614 return Const != nullptr && Const->isNullValue(); 1615 } 1616 1617 static bool isNullFPConstant(SDValue V) { 1618 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 1619 return Const != nullptr && Const->isZero() && !Const->isNegative(); 1620 } 1621 1622 static bool isAllOnesConstant(SDValue V) { 1623 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1624 return Const != nullptr && Const->isAllOnesValue(); 1625 } 1626 1627 static bool isOneConstant(SDValue V) { 1628 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1629 return Const != nullptr && Const->isOne(); 1630 } 1631 1632 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a 1633 /// ContantSDNode pointer else nullptr. 1634 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1635 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1636 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1637 } 1638 1639 SDValue DAGCombiner::visitADD(SDNode *N) { 1640 SDValue N0 = N->getOperand(0); 1641 SDValue N1 = N->getOperand(1); 1642 EVT VT = N0.getValueType(); 1643 1644 // fold vector ops 1645 if (VT.isVector()) { 1646 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1647 return FoldedVOp; 1648 1649 // fold (add x, 0) -> x, vector edition 1650 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1651 return N0; 1652 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1653 return N1; 1654 } 1655 1656 // fold (add x, undef) -> undef 1657 if (N0.getOpcode() == ISD::UNDEF) 1658 return N0; 1659 if (N1.getOpcode() == ISD::UNDEF) 1660 return N1; 1661 // fold (add c1, c2) -> c1+c2 1662 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1663 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1664 if (N0C && N1C) 1665 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C); 1666 // canonicalize constant to RHS 1667 if (isConstantIntBuildVectorOrConstantInt(N0) && 1668 !isConstantIntBuildVectorOrConstantInt(N1)) 1669 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1670 // fold (add x, 0) -> x 1671 if (isNullConstant(N1)) 1672 return N0; 1673 // fold (add Sym, c) -> Sym+c 1674 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1675 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1676 GA->getOpcode() == ISD::GlobalAddress) 1677 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1678 GA->getOffset() + 1679 (uint64_t)N1C->getSExtValue()); 1680 // fold ((c1-A)+c2) -> (c1+c2)-A 1681 if (N1C && N0.getOpcode() == ISD::SUB) 1682 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1683 SDLoc DL(N); 1684 return DAG.getNode(ISD::SUB, DL, VT, 1685 DAG.getConstant(N1C->getAPIntValue()+ 1686 N0C->getAPIntValue(), DL, VT), 1687 N0.getOperand(1)); 1688 } 1689 // reassociate add 1690 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1691 return RADD; 1692 // fold ((0-A) + B) -> B-A 1693 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1694 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1695 // fold (A + (0-B)) -> A-B 1696 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1697 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1698 // fold (A+(B-A)) -> B 1699 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1700 return N1.getOperand(0); 1701 // fold ((B-A)+A) -> B 1702 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1703 return N0.getOperand(0); 1704 // fold (A+(B-(A+C))) to (B-C) 1705 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1706 N0 == N1.getOperand(1).getOperand(0)) 1707 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1708 N1.getOperand(1).getOperand(1)); 1709 // fold (A+(B-(C+A))) to (B-C) 1710 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1711 N0 == N1.getOperand(1).getOperand(1)) 1712 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1713 N1.getOperand(1).getOperand(0)); 1714 // fold (A+((B-A)+or-C)) to (B+or-C) 1715 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1716 N1.getOperand(0).getOpcode() == ISD::SUB && 1717 N0 == N1.getOperand(0).getOperand(1)) 1718 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1719 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1720 1721 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1722 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1723 SDValue N00 = N0.getOperand(0); 1724 SDValue N01 = N0.getOperand(1); 1725 SDValue N10 = N1.getOperand(0); 1726 SDValue N11 = N1.getOperand(1); 1727 1728 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1729 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1730 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1731 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1732 } 1733 1734 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1735 return SDValue(N, 0); 1736 1737 // fold (a+b) -> (a|b) iff a and b share no bits. 1738 if (VT.isInteger() && !VT.isVector()) { 1739 APInt LHSZero, LHSOne; 1740 APInt RHSZero, RHSOne; 1741 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1742 1743 if (LHSZero.getBoolValue()) { 1744 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1745 1746 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1747 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1748 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1749 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1750 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1751 } 1752 } 1753 } 1754 1755 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1756 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1757 isNullConstant(N1.getOperand(0).getOperand(0))) 1758 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1759 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1760 N1.getOperand(0).getOperand(1), 1761 N1.getOperand(1))); 1762 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1763 isNullConstant(N0.getOperand(0).getOperand(0))) 1764 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1765 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1766 N0.getOperand(0).getOperand(1), 1767 N0.getOperand(1))); 1768 1769 if (N1.getOpcode() == ISD::AND) { 1770 SDValue AndOp0 = N1.getOperand(0); 1771 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1772 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1773 1774 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1775 // and similar xforms where the inner op is either ~0 or 0. 1776 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1777 SDLoc DL(N); 1778 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1779 } 1780 } 1781 1782 // add (sext i1), X -> sub X, (zext i1) 1783 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1784 N0.getOperand(0).getValueType() == MVT::i1 && 1785 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1786 SDLoc DL(N); 1787 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1788 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1789 } 1790 1791 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1792 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1793 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1794 if (TN->getVT() == MVT::i1) { 1795 SDLoc DL(N); 1796 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1797 DAG.getConstant(1, DL, VT)); 1798 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1799 } 1800 } 1801 1802 return SDValue(); 1803 } 1804 1805 SDValue DAGCombiner::visitADDC(SDNode *N) { 1806 SDValue N0 = N->getOperand(0); 1807 SDValue N1 = N->getOperand(1); 1808 EVT VT = N0.getValueType(); 1809 1810 // If the flag result is dead, turn this into an ADD. 1811 if (!N->hasAnyUseOfValue(1)) 1812 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1813 DAG.getNode(ISD::CARRY_FALSE, 1814 SDLoc(N), MVT::Glue)); 1815 1816 // canonicalize constant to RHS. 1817 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1818 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1819 if (N0C && !N1C) 1820 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1821 1822 // fold (addc x, 0) -> x + no carry out 1823 if (isNullConstant(N1)) 1824 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1825 SDLoc(N), MVT::Glue)); 1826 1827 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1828 APInt LHSZero, LHSOne; 1829 APInt RHSZero, RHSOne; 1830 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1831 1832 if (LHSZero.getBoolValue()) { 1833 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1834 1835 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1836 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1837 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1838 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1839 DAG.getNode(ISD::CARRY_FALSE, 1840 SDLoc(N), MVT::Glue)); 1841 } 1842 1843 return SDValue(); 1844 } 1845 1846 SDValue DAGCombiner::visitADDE(SDNode *N) { 1847 SDValue N0 = N->getOperand(0); 1848 SDValue N1 = N->getOperand(1); 1849 SDValue CarryIn = N->getOperand(2); 1850 1851 // canonicalize constant to RHS 1852 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1853 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1854 if (N0C && !N1C) 1855 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1856 N1, N0, CarryIn); 1857 1858 // fold (adde x, y, false) -> (addc x, y) 1859 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1860 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1861 1862 return SDValue(); 1863 } 1864 1865 // Since it may not be valid to emit a fold to zero for vector initializers 1866 // check if we can before folding. 1867 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1868 SelectionDAG &DAG, 1869 bool LegalOperations, bool LegalTypes) { 1870 if (!VT.isVector()) 1871 return DAG.getConstant(0, DL, VT); 1872 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1873 return DAG.getConstant(0, DL, VT); 1874 return SDValue(); 1875 } 1876 1877 SDValue DAGCombiner::visitSUB(SDNode *N) { 1878 SDValue N0 = N->getOperand(0); 1879 SDValue N1 = N->getOperand(1); 1880 EVT VT = N0.getValueType(); 1881 1882 // fold vector ops 1883 if (VT.isVector()) { 1884 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1885 return FoldedVOp; 1886 1887 // fold (sub x, 0) -> x, vector edition 1888 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1889 return N0; 1890 } 1891 1892 // fold (sub x, x) -> 0 1893 // FIXME: Refactor this and xor and other similar operations together. 1894 if (N0 == N1) 1895 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1896 // fold (sub c1, c2) -> c1-c2 1897 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1898 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1899 if (N0C && N1C) 1900 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C); 1901 // fold (sub x, c) -> (add x, -c) 1902 if (N1C) { 1903 SDLoc DL(N); 1904 return DAG.getNode(ISD::ADD, DL, VT, N0, 1905 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1906 } 1907 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1908 if (isAllOnesConstant(N0)) 1909 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1910 // fold A-(A-B) -> B 1911 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1912 return N1.getOperand(1); 1913 // fold (A+B)-A -> B 1914 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1915 return N0.getOperand(1); 1916 // fold (A+B)-B -> A 1917 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1918 return N0.getOperand(0); 1919 // fold C2-(A+C1) -> (C2-C1)-A 1920 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1921 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1922 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1923 SDLoc DL(N); 1924 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1925 DL, VT); 1926 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1927 N1.getOperand(0)); 1928 } 1929 // fold ((A+(B+or-C))-B) -> A+or-C 1930 if (N0.getOpcode() == ISD::ADD && 1931 (N0.getOperand(1).getOpcode() == ISD::SUB || 1932 N0.getOperand(1).getOpcode() == ISD::ADD) && 1933 N0.getOperand(1).getOperand(0) == N1) 1934 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1935 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1936 // fold ((A+(C+B))-B) -> A+C 1937 if (N0.getOpcode() == ISD::ADD && 1938 N0.getOperand(1).getOpcode() == ISD::ADD && 1939 N0.getOperand(1).getOperand(1) == N1) 1940 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1941 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1942 // fold ((A-(B-C))-C) -> A-B 1943 if (N0.getOpcode() == ISD::SUB && 1944 N0.getOperand(1).getOpcode() == ISD::SUB && 1945 N0.getOperand(1).getOperand(1) == N1) 1946 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1947 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1948 1949 // If either operand of a sub is undef, the result is undef 1950 if (N0.getOpcode() == ISD::UNDEF) 1951 return N0; 1952 if (N1.getOpcode() == ISD::UNDEF) 1953 return N1; 1954 1955 // If the relocation model supports it, consider symbol offsets. 1956 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1957 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1958 // fold (sub Sym, c) -> Sym-c 1959 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1960 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1961 GA->getOffset() - 1962 (uint64_t)N1C->getSExtValue()); 1963 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1964 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1965 if (GA->getGlobal() == GB->getGlobal()) 1966 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1967 SDLoc(N), VT); 1968 } 1969 1970 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1971 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1972 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1973 if (TN->getVT() == MVT::i1) { 1974 SDLoc DL(N); 1975 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1976 DAG.getConstant(1, DL, VT)); 1977 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1978 } 1979 } 1980 1981 return SDValue(); 1982 } 1983 1984 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1985 SDValue N0 = N->getOperand(0); 1986 SDValue N1 = N->getOperand(1); 1987 EVT VT = N0.getValueType(); 1988 1989 // If the flag result is dead, turn this into an SUB. 1990 if (!N->hasAnyUseOfValue(1)) 1991 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1992 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1993 MVT::Glue)); 1994 1995 // fold (subc x, x) -> 0 + no borrow 1996 if (N0 == N1) { 1997 SDLoc DL(N); 1998 return CombineTo(N, DAG.getConstant(0, DL, VT), 1999 DAG.getNode(ISD::CARRY_FALSE, DL, 2000 MVT::Glue)); 2001 } 2002 2003 // fold (subc x, 0) -> x + no borrow 2004 if (isNullConstant(N1)) 2005 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 2006 MVT::Glue)); 2007 2008 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2009 if (isAllOnesConstant(N0)) 2010 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 2011 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 2012 MVT::Glue)); 2013 2014 return SDValue(); 2015 } 2016 2017 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2018 SDValue N0 = N->getOperand(0); 2019 SDValue N1 = N->getOperand(1); 2020 SDValue CarryIn = N->getOperand(2); 2021 2022 // fold (sube x, y, false) -> (subc x, y) 2023 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2024 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2025 2026 return SDValue(); 2027 } 2028 2029 SDValue DAGCombiner::visitMUL(SDNode *N) { 2030 SDValue N0 = N->getOperand(0); 2031 SDValue N1 = N->getOperand(1); 2032 EVT VT = N0.getValueType(); 2033 2034 // fold (mul x, undef) -> 0 2035 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2036 return DAG.getConstant(0, SDLoc(N), VT); 2037 2038 bool N0IsConst = false; 2039 bool N1IsConst = false; 2040 bool N1IsOpaqueConst = false; 2041 bool N0IsOpaqueConst = false; 2042 APInt ConstValue0, ConstValue1; 2043 // fold vector ops 2044 if (VT.isVector()) { 2045 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2046 return FoldedVOp; 2047 2048 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2049 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2050 } else { 2051 N0IsConst = isa<ConstantSDNode>(N0); 2052 if (N0IsConst) { 2053 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2054 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2055 } 2056 N1IsConst = isa<ConstantSDNode>(N1); 2057 if (N1IsConst) { 2058 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2059 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2060 } 2061 } 2062 2063 // fold (mul c1, c2) -> c1*c2 2064 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2065 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2066 N0.getNode(), N1.getNode()); 2067 2068 // canonicalize constant to RHS (vector doesn't have to splat) 2069 if (isConstantIntBuildVectorOrConstantInt(N0) && 2070 !isConstantIntBuildVectorOrConstantInt(N1)) 2071 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2072 // fold (mul x, 0) -> 0 2073 if (N1IsConst && ConstValue1 == 0) 2074 return N1; 2075 // We require a splat of the entire scalar bit width for non-contiguous 2076 // bit patterns. 2077 bool IsFullSplat = 2078 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2079 // fold (mul x, 1) -> x 2080 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2081 return N0; 2082 // fold (mul x, -1) -> 0-x 2083 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2084 SDLoc DL(N); 2085 return DAG.getNode(ISD::SUB, DL, VT, 2086 DAG.getConstant(0, DL, VT), N0); 2087 } 2088 // fold (mul x, (1 << c)) -> x << c 2089 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2090 IsFullSplat) { 2091 SDLoc DL(N); 2092 return DAG.getNode(ISD::SHL, DL, VT, N0, 2093 DAG.getConstant(ConstValue1.logBase2(), DL, 2094 getShiftAmountTy(N0.getValueType()))); 2095 } 2096 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2097 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2098 IsFullSplat) { 2099 unsigned Log2Val = (-ConstValue1).logBase2(); 2100 SDLoc DL(N); 2101 // FIXME: If the input is something that is easily negated (e.g. a 2102 // single-use add), we should put the negate there. 2103 return DAG.getNode(ISD::SUB, DL, VT, 2104 DAG.getConstant(0, DL, VT), 2105 DAG.getNode(ISD::SHL, DL, VT, N0, 2106 DAG.getConstant(Log2Val, DL, 2107 getShiftAmountTy(N0.getValueType())))); 2108 } 2109 2110 APInt Val; 2111 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2112 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2113 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2114 isa<ConstantSDNode>(N0.getOperand(1)))) { 2115 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2116 N1, N0.getOperand(1)); 2117 AddToWorklist(C3.getNode()); 2118 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2119 N0.getOperand(0), C3); 2120 } 2121 2122 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2123 // use. 2124 { 2125 SDValue Sh(nullptr,0), Y(nullptr,0); 2126 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2127 if (N0.getOpcode() == ISD::SHL && 2128 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2129 isa<ConstantSDNode>(N0.getOperand(1))) && 2130 N0.getNode()->hasOneUse()) { 2131 Sh = N0; Y = N1; 2132 } else if (N1.getOpcode() == ISD::SHL && 2133 isa<ConstantSDNode>(N1.getOperand(1)) && 2134 N1.getNode()->hasOneUse()) { 2135 Sh = N1; Y = N0; 2136 } 2137 2138 if (Sh.getNode()) { 2139 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2140 Sh.getOperand(0), Y); 2141 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2142 Mul, Sh.getOperand(1)); 2143 } 2144 } 2145 2146 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2147 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 2148 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2149 isa<ConstantSDNode>(N0.getOperand(1)))) 2150 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2151 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2152 N0.getOperand(0), N1), 2153 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2154 N0.getOperand(1), N1)); 2155 2156 // reassociate mul 2157 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2158 return RMUL; 2159 2160 return SDValue(); 2161 } 2162 2163 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2164 SDValue N0 = N->getOperand(0); 2165 SDValue N1 = N->getOperand(1); 2166 EVT VT = N->getValueType(0); 2167 2168 // fold vector ops 2169 if (VT.isVector()) 2170 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2171 return FoldedVOp; 2172 2173 // fold (sdiv c1, c2) -> c1/c2 2174 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2175 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2176 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2177 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C); 2178 // fold (sdiv X, 1) -> X 2179 if (N1C && N1C->isOne()) 2180 return N0; 2181 // fold (sdiv X, -1) -> 0-X 2182 if (N1C && N1C->isAllOnesValue()) { 2183 SDLoc DL(N); 2184 return DAG.getNode(ISD::SUB, DL, VT, 2185 DAG.getConstant(0, DL, VT), N0); 2186 } 2187 // If we know the sign bits of both operands are zero, strength reduce to a 2188 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2189 if (!VT.isVector()) { 2190 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2191 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2192 N0, N1); 2193 } 2194 2195 // fold (sdiv X, pow2) -> simple ops after legalize 2196 // FIXME: We check for the exact bit here because the generic lowering gives 2197 // better results in that case. The target-specific lowering should learn how 2198 // to handle exact sdivs efficiently. 2199 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2200 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2201 (N1C->getAPIntValue().isPowerOf2() || 2202 (-N1C->getAPIntValue()).isPowerOf2())) { 2203 // Target-specific implementation of sdiv x, pow2. 2204 if (SDValue Res = BuildSDIVPow2(N)) 2205 return Res; 2206 2207 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2208 SDLoc DL(N); 2209 2210 // Splat the sign bit into the register 2211 SDValue SGN = 2212 DAG.getNode(ISD::SRA, DL, VT, N0, 2213 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2214 getShiftAmountTy(N0.getValueType()))); 2215 AddToWorklist(SGN.getNode()); 2216 2217 // Add (N0 < 0) ? abs2 - 1 : 0; 2218 SDValue SRL = 2219 DAG.getNode(ISD::SRL, DL, VT, SGN, 2220 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2221 getShiftAmountTy(SGN.getValueType()))); 2222 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2223 AddToWorklist(SRL.getNode()); 2224 AddToWorklist(ADD.getNode()); // Divide by pow2 2225 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2226 DAG.getConstant(lg2, DL, 2227 getShiftAmountTy(ADD.getValueType()))); 2228 2229 // If we're dividing by a positive value, we're done. Otherwise, we must 2230 // negate the result. 2231 if (N1C->getAPIntValue().isNonNegative()) 2232 return SRA; 2233 2234 AddToWorklist(SRA.getNode()); 2235 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2236 } 2237 2238 // If integer divide is expensive and we satisfy the requirements, emit an 2239 // alternate sequence. Targets may check function attributes for size/speed 2240 // trade-offs. 2241 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2242 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2243 if (SDValue Op = BuildSDIV(N)) 2244 return Op; 2245 2246 // undef / X -> 0 2247 if (N0.getOpcode() == ISD::UNDEF) 2248 return DAG.getConstant(0, SDLoc(N), VT); 2249 // X / undef -> undef 2250 if (N1.getOpcode() == ISD::UNDEF) 2251 return N1; 2252 2253 return SDValue(); 2254 } 2255 2256 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2257 SDValue N0 = N->getOperand(0); 2258 SDValue N1 = N->getOperand(1); 2259 EVT VT = N->getValueType(0); 2260 2261 // fold vector ops 2262 if (VT.isVector()) 2263 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2264 return FoldedVOp; 2265 2266 // fold (udiv c1, c2) -> c1/c2 2267 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2268 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2269 if (N0C && N1C) 2270 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, 2271 N0C, N1C)) 2272 return Folded; 2273 // fold (udiv x, (1 << c)) -> x >>u c 2274 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) { 2275 SDLoc DL(N); 2276 return DAG.getNode(ISD::SRL, DL, VT, N0, 2277 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2278 getShiftAmountTy(N0.getValueType()))); 2279 } 2280 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2281 if (N1.getOpcode() == ISD::SHL) { 2282 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2283 if (SHC->getAPIntValue().isPowerOf2()) { 2284 EVT ADDVT = N1.getOperand(1).getValueType(); 2285 SDLoc DL(N); 2286 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2287 N1.getOperand(1), 2288 DAG.getConstant(SHC->getAPIntValue() 2289 .logBase2(), 2290 DL, ADDVT)); 2291 AddToWorklist(Add.getNode()); 2292 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2293 } 2294 } 2295 } 2296 2297 // fold (udiv x, c) -> alternate 2298 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2299 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2300 if (SDValue Op = BuildUDIV(N)) 2301 return Op; 2302 2303 // undef / X -> 0 2304 if (N0.getOpcode() == ISD::UNDEF) 2305 return DAG.getConstant(0, SDLoc(N), VT); 2306 // X / undef -> undef 2307 if (N1.getOpcode() == ISD::UNDEF) 2308 return N1; 2309 2310 return SDValue(); 2311 } 2312 2313 SDValue DAGCombiner::visitSREM(SDNode *N) { 2314 SDValue N0 = N->getOperand(0); 2315 SDValue N1 = N->getOperand(1); 2316 EVT VT = N->getValueType(0); 2317 2318 // fold (srem c1, c2) -> c1%c2 2319 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2320 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2321 if (N0C && N1C) 2322 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, 2323 N0C, N1C)) 2324 return Folded; 2325 // If we know the sign bits of both operands are zero, strength reduce to a 2326 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2327 if (!VT.isVector()) { 2328 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2329 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2330 } 2331 2332 // If X/C can be simplified by the division-by-constant logic, lower 2333 // X%C to the equivalent of X-X/C*C. 2334 if (N1C && !N1C->isNullValue()) { 2335 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2336 AddToWorklist(Div.getNode()); 2337 SDValue OptimizedDiv = combine(Div.getNode()); 2338 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2339 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2340 OptimizedDiv, N1); 2341 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2342 AddToWorklist(Mul.getNode()); 2343 return Sub; 2344 } 2345 } 2346 2347 // undef % X -> 0 2348 if (N0.getOpcode() == ISD::UNDEF) 2349 return DAG.getConstant(0, SDLoc(N), VT); 2350 // X % undef -> undef 2351 if (N1.getOpcode() == ISD::UNDEF) 2352 return N1; 2353 2354 return SDValue(); 2355 } 2356 2357 SDValue DAGCombiner::visitUREM(SDNode *N) { 2358 SDValue N0 = N->getOperand(0); 2359 SDValue N1 = N->getOperand(1); 2360 EVT VT = N->getValueType(0); 2361 2362 // fold (urem c1, c2) -> c1%c2 2363 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2364 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2365 if (N0C && N1C) 2366 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, 2367 N0C, N1C)) 2368 return Folded; 2369 // fold (urem x, pow2) -> (and x, pow2-1) 2370 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2371 N1C->getAPIntValue().isPowerOf2()) { 2372 SDLoc DL(N); 2373 return DAG.getNode(ISD::AND, DL, VT, N0, 2374 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2375 } 2376 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2377 if (N1.getOpcode() == ISD::SHL) { 2378 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2379 if (SHC->getAPIntValue().isPowerOf2()) { 2380 SDLoc DL(N); 2381 SDValue Add = 2382 DAG.getNode(ISD::ADD, DL, VT, N1, 2383 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2384 VT)); 2385 AddToWorklist(Add.getNode()); 2386 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2387 } 2388 } 2389 } 2390 2391 // If X/C can be simplified by the division-by-constant logic, lower 2392 // X%C to the equivalent of X-X/C*C. 2393 if (N1C && !N1C->isNullValue()) { 2394 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2395 AddToWorklist(Div.getNode()); 2396 SDValue OptimizedDiv = combine(Div.getNode()); 2397 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2398 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2399 OptimizedDiv, N1); 2400 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2401 AddToWorklist(Mul.getNode()); 2402 return Sub; 2403 } 2404 } 2405 2406 // undef % X -> 0 2407 if (N0.getOpcode() == ISD::UNDEF) 2408 return DAG.getConstant(0, SDLoc(N), VT); 2409 // X % undef -> undef 2410 if (N1.getOpcode() == ISD::UNDEF) 2411 return N1; 2412 2413 return SDValue(); 2414 } 2415 2416 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2417 SDValue N0 = N->getOperand(0); 2418 SDValue N1 = N->getOperand(1); 2419 EVT VT = N->getValueType(0); 2420 SDLoc DL(N); 2421 2422 // fold (mulhs x, 0) -> 0 2423 if (isNullConstant(N1)) 2424 return N1; 2425 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2426 if (isOneConstant(N1)) { 2427 SDLoc DL(N); 2428 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2429 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2430 DL, 2431 getShiftAmountTy(N0.getValueType()))); 2432 } 2433 // fold (mulhs x, undef) -> 0 2434 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2435 return DAG.getConstant(0, SDLoc(N), VT); 2436 2437 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2438 // plus a shift. 2439 if (VT.isSimple() && !VT.isVector()) { 2440 MVT Simple = VT.getSimpleVT(); 2441 unsigned SimpleSize = Simple.getSizeInBits(); 2442 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2443 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2444 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2445 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2446 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2447 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2448 DAG.getConstant(SimpleSize, DL, 2449 getShiftAmountTy(N1.getValueType()))); 2450 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2451 } 2452 } 2453 2454 return SDValue(); 2455 } 2456 2457 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2458 SDValue N0 = N->getOperand(0); 2459 SDValue N1 = N->getOperand(1); 2460 EVT VT = N->getValueType(0); 2461 SDLoc DL(N); 2462 2463 // fold (mulhu x, 0) -> 0 2464 if (isNullConstant(N1)) 2465 return N1; 2466 // fold (mulhu x, 1) -> 0 2467 if (isOneConstant(N1)) 2468 return DAG.getConstant(0, DL, N0.getValueType()); 2469 // fold (mulhu x, undef) -> 0 2470 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2471 return DAG.getConstant(0, DL, VT); 2472 2473 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2474 // plus a shift. 2475 if (VT.isSimple() && !VT.isVector()) { 2476 MVT Simple = VT.getSimpleVT(); 2477 unsigned SimpleSize = Simple.getSizeInBits(); 2478 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2479 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2480 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2481 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2482 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2483 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2484 DAG.getConstant(SimpleSize, DL, 2485 getShiftAmountTy(N1.getValueType()))); 2486 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2487 } 2488 } 2489 2490 return SDValue(); 2491 } 2492 2493 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2494 /// give the opcodes for the two computations that are being performed. Return 2495 /// true if a simplification was made. 2496 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2497 unsigned HiOp) { 2498 // If the high half is not needed, just compute the low half. 2499 bool HiExists = N->hasAnyUseOfValue(1); 2500 if (!HiExists && 2501 (!LegalOperations || 2502 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2503 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2504 return CombineTo(N, Res, Res); 2505 } 2506 2507 // If the low half is not needed, just compute the high half. 2508 bool LoExists = N->hasAnyUseOfValue(0); 2509 if (!LoExists && 2510 (!LegalOperations || 2511 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2512 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2513 return CombineTo(N, Res, Res); 2514 } 2515 2516 // If both halves are used, return as it is. 2517 if (LoExists && HiExists) 2518 return SDValue(); 2519 2520 // If the two computed results can be simplified separately, separate them. 2521 if (LoExists) { 2522 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2523 AddToWorklist(Lo.getNode()); 2524 SDValue LoOpt = combine(Lo.getNode()); 2525 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2526 (!LegalOperations || 2527 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2528 return CombineTo(N, LoOpt, LoOpt); 2529 } 2530 2531 if (HiExists) { 2532 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2533 AddToWorklist(Hi.getNode()); 2534 SDValue HiOpt = combine(Hi.getNode()); 2535 if (HiOpt.getNode() && HiOpt != Hi && 2536 (!LegalOperations || 2537 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2538 return CombineTo(N, HiOpt, HiOpt); 2539 } 2540 2541 return SDValue(); 2542 } 2543 2544 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2545 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2546 return Res; 2547 2548 EVT VT = N->getValueType(0); 2549 SDLoc DL(N); 2550 2551 // If the type is twice as wide is legal, transform the mulhu to a wider 2552 // multiply plus a shift. 2553 if (VT.isSimple() && !VT.isVector()) { 2554 MVT Simple = VT.getSimpleVT(); 2555 unsigned SimpleSize = Simple.getSizeInBits(); 2556 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2557 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2558 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2559 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2560 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2561 // Compute the high part as N1. 2562 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2563 DAG.getConstant(SimpleSize, DL, 2564 getShiftAmountTy(Lo.getValueType()))); 2565 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2566 // Compute the low part as N0. 2567 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2568 return CombineTo(N, Lo, Hi); 2569 } 2570 } 2571 2572 return SDValue(); 2573 } 2574 2575 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2576 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2577 return Res; 2578 2579 EVT VT = N->getValueType(0); 2580 SDLoc DL(N); 2581 2582 // If the type is twice as wide is legal, transform the mulhu to a wider 2583 // multiply plus a shift. 2584 if (VT.isSimple() && !VT.isVector()) { 2585 MVT Simple = VT.getSimpleVT(); 2586 unsigned SimpleSize = Simple.getSizeInBits(); 2587 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2588 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2589 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2590 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2591 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2592 // Compute the high part as N1. 2593 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2594 DAG.getConstant(SimpleSize, DL, 2595 getShiftAmountTy(Lo.getValueType()))); 2596 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2597 // Compute the low part as N0. 2598 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2599 return CombineTo(N, Lo, Hi); 2600 } 2601 } 2602 2603 return SDValue(); 2604 } 2605 2606 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2607 // (smulo x, 2) -> (saddo x, x) 2608 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2609 if (C2->getAPIntValue() == 2) 2610 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2611 N->getOperand(0), N->getOperand(0)); 2612 2613 return SDValue(); 2614 } 2615 2616 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2617 // (umulo x, 2) -> (uaddo x, x) 2618 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2619 if (C2->getAPIntValue() == 2) 2620 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2621 N->getOperand(0), N->getOperand(0)); 2622 2623 return SDValue(); 2624 } 2625 2626 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2627 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM)) 2628 return Res; 2629 2630 return SDValue(); 2631 } 2632 2633 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2634 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM)) 2635 return Res; 2636 2637 return SDValue(); 2638 } 2639 2640 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2641 SDValue N0 = N->getOperand(0); 2642 SDValue N1 = N->getOperand(1); 2643 EVT VT = N0.getValueType(); 2644 2645 // fold vector ops 2646 if (VT.isVector()) 2647 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2648 return FoldedVOp; 2649 2650 // fold (add c1, c2) -> c1+c2 2651 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2652 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2653 if (N0C && N1C) 2654 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2655 2656 // canonicalize constant to RHS 2657 if (isConstantIntBuildVectorOrConstantInt(N0) && 2658 !isConstantIntBuildVectorOrConstantInt(N1)) 2659 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2660 2661 return SDValue(); 2662 } 2663 2664 /// If this is a binary operator with two operands of the same opcode, try to 2665 /// simplify it. 2666 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2667 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2668 EVT VT = N0.getValueType(); 2669 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2670 2671 // Bail early if none of these transforms apply. 2672 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2673 2674 // For each of OP in AND/OR/XOR: 2675 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2676 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2677 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2678 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2679 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2680 // 2681 // do not sink logical op inside of a vector extend, since it may combine 2682 // into a vsetcc. 2683 EVT Op0VT = N0.getOperand(0).getValueType(); 2684 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2685 N0.getOpcode() == ISD::SIGN_EXTEND || 2686 N0.getOpcode() == ISD::BSWAP || 2687 // Avoid infinite looping with PromoteIntBinOp. 2688 (N0.getOpcode() == ISD::ANY_EXTEND && 2689 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2690 (N0.getOpcode() == ISD::TRUNCATE && 2691 (!TLI.isZExtFree(VT, Op0VT) || 2692 !TLI.isTruncateFree(Op0VT, VT)) && 2693 TLI.isTypeLegal(Op0VT))) && 2694 !VT.isVector() && 2695 Op0VT == N1.getOperand(0).getValueType() && 2696 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2697 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2698 N0.getOperand(0).getValueType(), 2699 N0.getOperand(0), N1.getOperand(0)); 2700 AddToWorklist(ORNode.getNode()); 2701 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2702 } 2703 2704 // For each of OP in SHL/SRL/SRA/AND... 2705 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2706 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2707 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2708 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2709 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2710 N0.getOperand(1) == N1.getOperand(1)) { 2711 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2712 N0.getOperand(0).getValueType(), 2713 N0.getOperand(0), N1.getOperand(0)); 2714 AddToWorklist(ORNode.getNode()); 2715 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2716 ORNode, N0.getOperand(1)); 2717 } 2718 2719 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2720 // Only perform this optimization after type legalization and before 2721 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2722 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2723 // we don't want to undo this promotion. 2724 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2725 // on scalars. 2726 if ((N0.getOpcode() == ISD::BITCAST || 2727 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2728 Level == AfterLegalizeTypes) { 2729 SDValue In0 = N0.getOperand(0); 2730 SDValue In1 = N1.getOperand(0); 2731 EVT In0Ty = In0.getValueType(); 2732 EVT In1Ty = In1.getValueType(); 2733 SDLoc DL(N); 2734 // If both incoming values are integers, and the original types are the 2735 // same. 2736 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2737 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2738 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2739 AddToWorklist(Op.getNode()); 2740 return BC; 2741 } 2742 } 2743 2744 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2745 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2746 // If both shuffles use the same mask, and both shuffle within a single 2747 // vector, then it is worthwhile to move the swizzle after the operation. 2748 // The type-legalizer generates this pattern when loading illegal 2749 // vector types from memory. In many cases this allows additional shuffle 2750 // optimizations. 2751 // There are other cases where moving the shuffle after the xor/and/or 2752 // is profitable even if shuffles don't perform a swizzle. 2753 // If both shuffles use the same mask, and both shuffles have the same first 2754 // or second operand, then it might still be profitable to move the shuffle 2755 // after the xor/and/or operation. 2756 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2757 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2758 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2759 2760 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2761 "Inputs to shuffles are not the same type"); 2762 2763 // Check that both shuffles use the same mask. The masks are known to be of 2764 // the same length because the result vector type is the same. 2765 // Check also that shuffles have only one use to avoid introducing extra 2766 // instructions. 2767 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2768 SVN0->getMask().equals(SVN1->getMask())) { 2769 SDValue ShOp = N0->getOperand(1); 2770 2771 // Don't try to fold this node if it requires introducing a 2772 // build vector of all zeros that might be illegal at this stage. 2773 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2774 if (!LegalTypes) 2775 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2776 else 2777 ShOp = SDValue(); 2778 } 2779 2780 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2781 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2782 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2783 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2784 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2785 N0->getOperand(0), N1->getOperand(0)); 2786 AddToWorklist(NewNode.getNode()); 2787 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2788 &SVN0->getMask()[0]); 2789 } 2790 2791 // Don't try to fold this node if it requires introducing a 2792 // build vector of all zeros that might be illegal at this stage. 2793 ShOp = N0->getOperand(0); 2794 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2795 if (!LegalTypes) 2796 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2797 else 2798 ShOp = SDValue(); 2799 } 2800 2801 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2802 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2803 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2804 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2805 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2806 N0->getOperand(1), N1->getOperand(1)); 2807 AddToWorklist(NewNode.getNode()); 2808 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2809 &SVN0->getMask()[0]); 2810 } 2811 } 2812 } 2813 2814 return SDValue(); 2815 } 2816 2817 /// This contains all DAGCombine rules which reduce two values combined by 2818 /// an And operation to a single value. This makes them reusable in the context 2819 /// of visitSELECT(). Rules involving constants are not included as 2820 /// visitSELECT() already handles those cases. 2821 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2822 SDNode *LocReference) { 2823 EVT VT = N1.getValueType(); 2824 2825 // fold (and x, undef) -> 0 2826 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2827 return DAG.getConstant(0, SDLoc(LocReference), VT); 2828 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2829 SDValue LL, LR, RL, RR, CC0, CC1; 2830 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2831 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2832 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2833 2834 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2835 LL.getValueType().isInteger()) { 2836 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2837 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2838 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2839 LR.getValueType(), LL, RL); 2840 AddToWorklist(ORNode.getNode()); 2841 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2842 } 2843 if (isAllOnesConstant(LR)) { 2844 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2845 if (Op1 == ISD::SETEQ) { 2846 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2847 LR.getValueType(), LL, RL); 2848 AddToWorklist(ANDNode.getNode()); 2849 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2850 } 2851 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2852 if (Op1 == ISD::SETGT) { 2853 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2854 LR.getValueType(), LL, RL); 2855 AddToWorklist(ORNode.getNode()); 2856 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2857 } 2858 } 2859 } 2860 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2861 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2862 Op0 == Op1 && LL.getValueType().isInteger() && 2863 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2864 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2865 SDLoc DL(N0); 2866 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2867 LL, DAG.getConstant(1, DL, 2868 LL.getValueType())); 2869 AddToWorklist(ADDNode.getNode()); 2870 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2871 DAG.getConstant(2, DL, LL.getValueType()), 2872 ISD::SETUGE); 2873 } 2874 // canonicalize equivalent to ll == rl 2875 if (LL == RR && LR == RL) { 2876 Op1 = ISD::getSetCCSwappedOperands(Op1); 2877 std::swap(RL, RR); 2878 } 2879 if (LL == RL && LR == RR) { 2880 bool isInteger = LL.getValueType().isInteger(); 2881 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2882 if (Result != ISD::SETCC_INVALID && 2883 (!LegalOperations || 2884 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2885 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2886 EVT CCVT = getSetCCResultType(LL.getValueType()); 2887 if (N0.getValueType() == CCVT || 2888 (!LegalOperations && N0.getValueType() == MVT::i1)) 2889 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2890 LL, LR, Result); 2891 } 2892 } 2893 } 2894 2895 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2896 VT.getSizeInBits() <= 64) { 2897 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2898 APInt ADDC = ADDI->getAPIntValue(); 2899 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2900 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2901 // immediate for an add, but it is legal if its top c2 bits are set, 2902 // transform the ADD so the immediate doesn't need to be materialized 2903 // in a register. 2904 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2905 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2906 SRLI->getZExtValue()); 2907 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2908 ADDC |= Mask; 2909 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2910 SDLoc DL(N0); 2911 SDValue NewAdd = 2912 DAG.getNode(ISD::ADD, DL, VT, 2913 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2914 CombineTo(N0.getNode(), NewAdd); 2915 // Return N so it doesn't get rechecked! 2916 return SDValue(LocReference, 0); 2917 } 2918 } 2919 } 2920 } 2921 } 2922 } 2923 2924 return SDValue(); 2925 } 2926 2927 SDValue DAGCombiner::visitAND(SDNode *N) { 2928 SDValue N0 = N->getOperand(0); 2929 SDValue N1 = N->getOperand(1); 2930 EVT VT = N1.getValueType(); 2931 2932 // fold vector ops 2933 if (VT.isVector()) { 2934 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2935 return FoldedVOp; 2936 2937 // fold (and x, 0) -> 0, vector edition 2938 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2939 // do not return N0, because undef node may exist in N0 2940 return DAG.getConstant( 2941 APInt::getNullValue( 2942 N0.getValueType().getScalarType().getSizeInBits()), 2943 SDLoc(N), N0.getValueType()); 2944 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2945 // do not return N1, because undef node may exist in N1 2946 return DAG.getConstant( 2947 APInt::getNullValue( 2948 N1.getValueType().getScalarType().getSizeInBits()), 2949 SDLoc(N), N1.getValueType()); 2950 2951 // fold (and x, -1) -> x, vector edition 2952 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2953 return N1; 2954 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2955 return N0; 2956 } 2957 2958 // fold (and c1, c2) -> c1&c2 2959 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2960 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2961 if (N0C && N1C && !N1C->isOpaque()) 2962 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 2963 // canonicalize constant to RHS 2964 if (isConstantIntBuildVectorOrConstantInt(N0) && 2965 !isConstantIntBuildVectorOrConstantInt(N1)) 2966 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2967 // fold (and x, -1) -> x 2968 if (isAllOnesConstant(N1)) 2969 return N0; 2970 // if (and x, c) is known to be zero, return 0 2971 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2972 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2973 APInt::getAllOnesValue(BitWidth))) 2974 return DAG.getConstant(0, SDLoc(N), VT); 2975 // reassociate and 2976 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 2977 return RAND; 2978 // fold (and (or x, C), D) -> D if (C & D) == D 2979 if (N1C && N0.getOpcode() == ISD::OR) 2980 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2981 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2982 return N1; 2983 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2984 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2985 SDValue N0Op0 = N0.getOperand(0); 2986 APInt Mask = ~N1C->getAPIntValue(); 2987 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2988 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2989 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2990 N0.getValueType(), N0Op0); 2991 2992 // Replace uses of the AND with uses of the Zero extend node. 2993 CombineTo(N, Zext); 2994 2995 // We actually want to replace all uses of the any_extend with the 2996 // zero_extend, to avoid duplicating things. This will later cause this 2997 // AND to be folded. 2998 CombineTo(N0.getNode(), Zext); 2999 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3000 } 3001 } 3002 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3003 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3004 // already be zero by virtue of the width of the base type of the load. 3005 // 3006 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3007 // more cases. 3008 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3009 N0.getOperand(0).getOpcode() == ISD::LOAD) || 3010 N0.getOpcode() == ISD::LOAD) { 3011 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3012 N0 : N0.getOperand(0) ); 3013 3014 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3015 // This can be a pure constant or a vector splat, in which case we treat the 3016 // vector as a scalar and use the splat value. 3017 APInt Constant = APInt::getNullValue(1); 3018 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3019 Constant = C->getAPIntValue(); 3020 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3021 APInt SplatValue, SplatUndef; 3022 unsigned SplatBitSize; 3023 bool HasAnyUndefs; 3024 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3025 SplatBitSize, HasAnyUndefs); 3026 if (IsSplat) { 3027 // Undef bits can contribute to a possible optimisation if set, so 3028 // set them. 3029 SplatValue |= SplatUndef; 3030 3031 // The splat value may be something like "0x00FFFFFF", which means 0 for 3032 // the first vector value and FF for the rest, repeating. We need a mask 3033 // that will apply equally to all members of the vector, so AND all the 3034 // lanes of the constant together. 3035 EVT VT = Vector->getValueType(0); 3036 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3037 3038 // If the splat value has been compressed to a bitlength lower 3039 // than the size of the vector lane, we need to re-expand it to 3040 // the lane size. 3041 if (BitWidth > SplatBitSize) 3042 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3043 SplatBitSize < BitWidth; 3044 SplatBitSize = SplatBitSize * 2) 3045 SplatValue |= SplatValue.shl(SplatBitSize); 3046 3047 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3048 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3049 if (SplatBitSize % BitWidth == 0) { 3050 Constant = APInt::getAllOnesValue(BitWidth); 3051 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3052 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3053 } 3054 } 3055 } 3056 3057 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3058 // actually legal and isn't going to get expanded, else this is a false 3059 // optimisation. 3060 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3061 Load->getValueType(0), 3062 Load->getMemoryVT()); 3063 3064 // Resize the constant to the same size as the original memory access before 3065 // extension. If it is still the AllOnesValue then this AND is completely 3066 // unneeded. 3067 Constant = 3068 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3069 3070 bool B; 3071 switch (Load->getExtensionType()) { 3072 default: B = false; break; 3073 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3074 case ISD::ZEXTLOAD: 3075 case ISD::NON_EXTLOAD: B = true; break; 3076 } 3077 3078 if (B && Constant.isAllOnesValue()) { 3079 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3080 // preserve semantics once we get rid of the AND. 3081 SDValue NewLoad(Load, 0); 3082 if (Load->getExtensionType() == ISD::EXTLOAD) { 3083 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3084 Load->getValueType(0), SDLoc(Load), 3085 Load->getChain(), Load->getBasePtr(), 3086 Load->getOffset(), Load->getMemoryVT(), 3087 Load->getMemOperand()); 3088 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3089 if (Load->getNumValues() == 3) { 3090 // PRE/POST_INC loads have 3 values. 3091 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3092 NewLoad.getValue(2) }; 3093 CombineTo(Load, To, 3, true); 3094 } else { 3095 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3096 } 3097 } 3098 3099 // Fold the AND away, taking care not to fold to the old load node if we 3100 // replaced it. 3101 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3102 3103 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3104 } 3105 } 3106 3107 // fold (and (load x), 255) -> (zextload x, i8) 3108 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3109 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3110 if (N1C && (N0.getOpcode() == ISD::LOAD || 3111 (N0.getOpcode() == ISD::ANY_EXTEND && 3112 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3113 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3114 LoadSDNode *LN0 = HasAnyExt 3115 ? cast<LoadSDNode>(N0.getOperand(0)) 3116 : cast<LoadSDNode>(N0); 3117 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3118 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3119 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 3120 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 3121 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3122 EVT LoadedVT = LN0->getMemoryVT(); 3123 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3124 3125 if (ExtVT == LoadedVT && 3126 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3127 ExtVT))) { 3128 3129 SDValue NewLoad = 3130 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3131 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3132 LN0->getMemOperand()); 3133 AddToWorklist(N); 3134 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3135 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3136 } 3137 3138 // Do not change the width of a volatile load. 3139 // Do not generate loads of non-round integer types since these can 3140 // be expensive (and would be wrong if the type is not byte sized). 3141 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 3142 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3143 ExtVT))) { 3144 EVT PtrType = LN0->getOperand(1).getValueType(); 3145 3146 unsigned Alignment = LN0->getAlignment(); 3147 SDValue NewPtr = LN0->getBasePtr(); 3148 3149 // For big endian targets, we need to add an offset to the pointer 3150 // to load the correct bytes. For little endian systems, we merely 3151 // need to read fewer bytes from the same pointer. 3152 if (DAG.getDataLayout().isBigEndian()) { 3153 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3154 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3155 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3156 SDLoc DL(LN0); 3157 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3158 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3159 Alignment = MinAlign(Alignment, PtrOff); 3160 } 3161 3162 AddToWorklist(NewPtr.getNode()); 3163 3164 SDValue Load = 3165 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3166 LN0->getChain(), NewPtr, 3167 LN0->getPointerInfo(), 3168 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3169 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3170 AddToWorklist(N); 3171 CombineTo(LN0, Load, Load.getValue(1)); 3172 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3173 } 3174 } 3175 } 3176 } 3177 3178 if (SDValue Combined = visitANDLike(N0, N1, N)) 3179 return Combined; 3180 3181 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3182 if (N0.getOpcode() == N1.getOpcode()) 3183 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3184 return Tmp; 3185 3186 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3187 // fold (and (sra)) -> (and (srl)) when possible. 3188 if (!VT.isVector() && 3189 SimplifyDemandedBits(SDValue(N, 0))) 3190 return SDValue(N, 0); 3191 3192 // fold (zext_inreg (extload x)) -> (zextload x) 3193 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3194 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3195 EVT MemVT = LN0->getMemoryVT(); 3196 // If we zero all the possible extended bits, then we can turn this into 3197 // a zextload if we are running before legalize or the operation is legal. 3198 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3199 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3200 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3201 ((!LegalOperations && !LN0->isVolatile()) || 3202 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3203 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3204 LN0->getChain(), LN0->getBasePtr(), 3205 MemVT, LN0->getMemOperand()); 3206 AddToWorklist(N); 3207 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3208 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3209 } 3210 } 3211 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3212 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3213 N0.hasOneUse()) { 3214 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3215 EVT MemVT = LN0->getMemoryVT(); 3216 // If we zero all the possible extended bits, then we can turn this into 3217 // a zextload if we are running before legalize or the operation is legal. 3218 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3219 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3220 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3221 ((!LegalOperations && !LN0->isVolatile()) || 3222 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3223 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3224 LN0->getChain(), LN0->getBasePtr(), 3225 MemVT, LN0->getMemOperand()); 3226 AddToWorklist(N); 3227 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3228 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3229 } 3230 } 3231 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3232 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3233 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3234 N0.getOperand(1), false); 3235 if (BSwap.getNode()) 3236 return BSwap; 3237 } 3238 3239 return SDValue(); 3240 } 3241 3242 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3243 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3244 bool DemandHighBits) { 3245 if (!LegalOperations) 3246 return SDValue(); 3247 3248 EVT VT = N->getValueType(0); 3249 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3250 return SDValue(); 3251 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3252 return SDValue(); 3253 3254 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3255 bool LookPassAnd0 = false; 3256 bool LookPassAnd1 = false; 3257 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3258 std::swap(N0, N1); 3259 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3260 std::swap(N0, N1); 3261 if (N0.getOpcode() == ISD::AND) { 3262 if (!N0.getNode()->hasOneUse()) 3263 return SDValue(); 3264 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3265 if (!N01C || N01C->getZExtValue() != 0xFF00) 3266 return SDValue(); 3267 N0 = N0.getOperand(0); 3268 LookPassAnd0 = true; 3269 } 3270 3271 if (N1.getOpcode() == ISD::AND) { 3272 if (!N1.getNode()->hasOneUse()) 3273 return SDValue(); 3274 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3275 if (!N11C || N11C->getZExtValue() != 0xFF) 3276 return SDValue(); 3277 N1 = N1.getOperand(0); 3278 LookPassAnd1 = true; 3279 } 3280 3281 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3282 std::swap(N0, N1); 3283 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3284 return SDValue(); 3285 if (!N0.getNode()->hasOneUse() || 3286 !N1.getNode()->hasOneUse()) 3287 return SDValue(); 3288 3289 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3290 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3291 if (!N01C || !N11C) 3292 return SDValue(); 3293 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3294 return SDValue(); 3295 3296 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3297 SDValue N00 = N0->getOperand(0); 3298 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3299 if (!N00.getNode()->hasOneUse()) 3300 return SDValue(); 3301 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3302 if (!N001C || N001C->getZExtValue() != 0xFF) 3303 return SDValue(); 3304 N00 = N00.getOperand(0); 3305 LookPassAnd0 = true; 3306 } 3307 3308 SDValue N10 = N1->getOperand(0); 3309 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3310 if (!N10.getNode()->hasOneUse()) 3311 return SDValue(); 3312 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3313 if (!N101C || N101C->getZExtValue() != 0xFF00) 3314 return SDValue(); 3315 N10 = N10.getOperand(0); 3316 LookPassAnd1 = true; 3317 } 3318 3319 if (N00 != N10) 3320 return SDValue(); 3321 3322 // Make sure everything beyond the low halfword gets set to zero since the SRL 3323 // 16 will clear the top bits. 3324 unsigned OpSizeInBits = VT.getSizeInBits(); 3325 if (DemandHighBits && OpSizeInBits > 16) { 3326 // If the left-shift isn't masked out then the only way this is a bswap is 3327 // if all bits beyond the low 8 are 0. In that case the entire pattern 3328 // reduces to a left shift anyway: leave it for other parts of the combiner. 3329 if (!LookPassAnd0) 3330 return SDValue(); 3331 3332 // However, if the right shift isn't masked out then it might be because 3333 // it's not needed. See if we can spot that too. 3334 if (!LookPassAnd1 && 3335 !DAG.MaskedValueIsZero( 3336 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3337 return SDValue(); 3338 } 3339 3340 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3341 if (OpSizeInBits > 16) { 3342 SDLoc DL(N); 3343 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3344 DAG.getConstant(OpSizeInBits - 16, DL, 3345 getShiftAmountTy(VT))); 3346 } 3347 return Res; 3348 } 3349 3350 /// Return true if the specified node is an element that makes up a 32-bit 3351 /// packed halfword byteswap. 3352 /// ((x & 0x000000ff) << 8) | 3353 /// ((x & 0x0000ff00) >> 8) | 3354 /// ((x & 0x00ff0000) << 8) | 3355 /// ((x & 0xff000000) >> 8) 3356 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3357 if (!N.getNode()->hasOneUse()) 3358 return false; 3359 3360 unsigned Opc = N.getOpcode(); 3361 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3362 return false; 3363 3364 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3365 if (!N1C) 3366 return false; 3367 3368 unsigned Num; 3369 switch (N1C->getZExtValue()) { 3370 default: 3371 return false; 3372 case 0xFF: Num = 0; break; 3373 case 0xFF00: Num = 1; break; 3374 case 0xFF0000: Num = 2; break; 3375 case 0xFF000000: Num = 3; break; 3376 } 3377 3378 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3379 SDValue N0 = N.getOperand(0); 3380 if (Opc == ISD::AND) { 3381 if (Num == 0 || Num == 2) { 3382 // (x >> 8) & 0xff 3383 // (x >> 8) & 0xff0000 3384 if (N0.getOpcode() != ISD::SRL) 3385 return false; 3386 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3387 if (!C || C->getZExtValue() != 8) 3388 return false; 3389 } else { 3390 // (x << 8) & 0xff00 3391 // (x << 8) & 0xff000000 3392 if (N0.getOpcode() != ISD::SHL) 3393 return false; 3394 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3395 if (!C || C->getZExtValue() != 8) 3396 return false; 3397 } 3398 } else if (Opc == ISD::SHL) { 3399 // (x & 0xff) << 8 3400 // (x & 0xff0000) << 8 3401 if (Num != 0 && Num != 2) 3402 return false; 3403 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3404 if (!C || C->getZExtValue() != 8) 3405 return false; 3406 } else { // Opc == ISD::SRL 3407 // (x & 0xff00) >> 8 3408 // (x & 0xff000000) >> 8 3409 if (Num != 1 && Num != 3) 3410 return false; 3411 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3412 if (!C || C->getZExtValue() != 8) 3413 return false; 3414 } 3415 3416 if (Parts[Num]) 3417 return false; 3418 3419 Parts[Num] = N0.getOperand(0).getNode(); 3420 return true; 3421 } 3422 3423 /// Match a 32-bit packed halfword bswap. That is 3424 /// ((x & 0x000000ff) << 8) | 3425 /// ((x & 0x0000ff00) >> 8) | 3426 /// ((x & 0x00ff0000) << 8) | 3427 /// ((x & 0xff000000) >> 8) 3428 /// => (rotl (bswap x), 16) 3429 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3430 if (!LegalOperations) 3431 return SDValue(); 3432 3433 EVT VT = N->getValueType(0); 3434 if (VT != MVT::i32) 3435 return SDValue(); 3436 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3437 return SDValue(); 3438 3439 // Look for either 3440 // (or (or (and), (and)), (or (and), (and))) 3441 // (or (or (or (and), (and)), (and)), (and)) 3442 if (N0.getOpcode() != ISD::OR) 3443 return SDValue(); 3444 SDValue N00 = N0.getOperand(0); 3445 SDValue N01 = N0.getOperand(1); 3446 SDNode *Parts[4] = {}; 3447 3448 if (N1.getOpcode() == ISD::OR && 3449 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3450 // (or (or (and), (and)), (or (and), (and))) 3451 SDValue N000 = N00.getOperand(0); 3452 if (!isBSwapHWordElement(N000, Parts)) 3453 return SDValue(); 3454 3455 SDValue N001 = N00.getOperand(1); 3456 if (!isBSwapHWordElement(N001, Parts)) 3457 return SDValue(); 3458 SDValue N010 = N01.getOperand(0); 3459 if (!isBSwapHWordElement(N010, Parts)) 3460 return SDValue(); 3461 SDValue N011 = N01.getOperand(1); 3462 if (!isBSwapHWordElement(N011, Parts)) 3463 return SDValue(); 3464 } else { 3465 // (or (or (or (and), (and)), (and)), (and)) 3466 if (!isBSwapHWordElement(N1, Parts)) 3467 return SDValue(); 3468 if (!isBSwapHWordElement(N01, Parts)) 3469 return SDValue(); 3470 if (N00.getOpcode() != ISD::OR) 3471 return SDValue(); 3472 SDValue N000 = N00.getOperand(0); 3473 if (!isBSwapHWordElement(N000, Parts)) 3474 return SDValue(); 3475 SDValue N001 = N00.getOperand(1); 3476 if (!isBSwapHWordElement(N001, Parts)) 3477 return SDValue(); 3478 } 3479 3480 // Make sure the parts are all coming from the same node. 3481 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3482 return SDValue(); 3483 3484 SDLoc DL(N); 3485 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3486 SDValue(Parts[0], 0)); 3487 3488 // Result of the bswap should be rotated by 16. If it's not legal, then 3489 // do (x << 16) | (x >> 16). 3490 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3491 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3492 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3493 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3494 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3495 return DAG.getNode(ISD::OR, DL, VT, 3496 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3497 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3498 } 3499 3500 /// This contains all DAGCombine rules which reduce two values combined by 3501 /// an Or operation to a single value \see visitANDLike(). 3502 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3503 EVT VT = N1.getValueType(); 3504 // fold (or x, undef) -> -1 3505 if (!LegalOperations && 3506 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3507 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3508 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3509 SDLoc(LocReference), VT); 3510 } 3511 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3512 SDValue LL, LR, RL, RR, CC0, CC1; 3513 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3514 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3515 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3516 3517 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3518 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3519 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3520 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3521 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3522 LR.getValueType(), LL, RL); 3523 AddToWorklist(ORNode.getNode()); 3524 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3525 } 3526 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3527 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3528 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3529 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3530 LR.getValueType(), LL, RL); 3531 AddToWorklist(ANDNode.getNode()); 3532 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3533 } 3534 } 3535 // canonicalize equivalent to ll == rl 3536 if (LL == RR && LR == RL) { 3537 Op1 = ISD::getSetCCSwappedOperands(Op1); 3538 std::swap(RL, RR); 3539 } 3540 if (LL == RL && LR == RR) { 3541 bool isInteger = LL.getValueType().isInteger(); 3542 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3543 if (Result != ISD::SETCC_INVALID && 3544 (!LegalOperations || 3545 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3546 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3547 EVT CCVT = getSetCCResultType(LL.getValueType()); 3548 if (N0.getValueType() == CCVT || 3549 (!LegalOperations && N0.getValueType() == MVT::i1)) 3550 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3551 LL, LR, Result); 3552 } 3553 } 3554 } 3555 3556 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3557 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3558 // Don't increase # computations. 3559 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3560 // We can only do this xform if we know that bits from X that are set in C2 3561 // but not in C1 are already zero. Likewise for Y. 3562 if (const ConstantSDNode *N0O1C = 3563 getAsNonOpaqueConstant(N0.getOperand(1))) { 3564 if (const ConstantSDNode *N1O1C = 3565 getAsNonOpaqueConstant(N1.getOperand(1))) { 3566 // We can only do this xform if we know that bits from X that are set in 3567 // C2 but not in C1 are already zero. Likewise for Y. 3568 const APInt &LHSMask = N0O1C->getAPIntValue(); 3569 const APInt &RHSMask = N1O1C->getAPIntValue(); 3570 3571 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3572 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3573 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3574 N0.getOperand(0), N1.getOperand(0)); 3575 SDLoc DL(LocReference); 3576 return DAG.getNode(ISD::AND, DL, VT, X, 3577 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3578 } 3579 } 3580 } 3581 } 3582 3583 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3584 if (N0.getOpcode() == ISD::AND && 3585 N1.getOpcode() == ISD::AND && 3586 N0.getOperand(0) == N1.getOperand(0) && 3587 // Don't increase # computations. 3588 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3589 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3590 N0.getOperand(1), N1.getOperand(1)); 3591 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3592 } 3593 3594 return SDValue(); 3595 } 3596 3597 SDValue DAGCombiner::visitOR(SDNode *N) { 3598 SDValue N0 = N->getOperand(0); 3599 SDValue N1 = N->getOperand(1); 3600 EVT VT = N1.getValueType(); 3601 3602 // fold vector ops 3603 if (VT.isVector()) { 3604 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3605 return FoldedVOp; 3606 3607 // fold (or x, 0) -> x, vector edition 3608 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3609 return N1; 3610 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3611 return N0; 3612 3613 // fold (or x, -1) -> -1, vector edition 3614 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3615 // do not return N0, because undef node may exist in N0 3616 return DAG.getConstant( 3617 APInt::getAllOnesValue( 3618 N0.getValueType().getScalarType().getSizeInBits()), 3619 SDLoc(N), N0.getValueType()); 3620 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3621 // do not return N1, because undef node may exist in N1 3622 return DAG.getConstant( 3623 APInt::getAllOnesValue( 3624 N1.getValueType().getScalarType().getSizeInBits()), 3625 SDLoc(N), N1.getValueType()); 3626 3627 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3628 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3629 // Do this only if the resulting shuffle is legal. 3630 if (isa<ShuffleVectorSDNode>(N0) && 3631 isa<ShuffleVectorSDNode>(N1) && 3632 // Avoid folding a node with illegal type. 3633 TLI.isTypeLegal(VT) && 3634 N0->getOperand(1) == N1->getOperand(1) && 3635 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3636 bool CanFold = true; 3637 unsigned NumElts = VT.getVectorNumElements(); 3638 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3639 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3640 // We construct two shuffle masks: 3641 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3642 // and N1 as the second operand. 3643 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3644 // and N0 as the second operand. 3645 // We do this because OR is commutable and therefore there might be 3646 // two ways to fold this node into a shuffle. 3647 SmallVector<int,4> Mask1; 3648 SmallVector<int,4> Mask2; 3649 3650 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3651 int M0 = SV0->getMaskElt(i); 3652 int M1 = SV1->getMaskElt(i); 3653 3654 // Both shuffle indexes are undef. Propagate Undef. 3655 if (M0 < 0 && M1 < 0) { 3656 Mask1.push_back(M0); 3657 Mask2.push_back(M0); 3658 continue; 3659 } 3660 3661 if (M0 < 0 || M1 < 0 || 3662 (M0 < (int)NumElts && M1 < (int)NumElts) || 3663 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3664 CanFold = false; 3665 break; 3666 } 3667 3668 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3669 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3670 } 3671 3672 if (CanFold) { 3673 // Fold this sequence only if the resulting shuffle is 'legal'. 3674 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3675 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3676 N1->getOperand(0), &Mask1[0]); 3677 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3678 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3679 N0->getOperand(0), &Mask2[0]); 3680 } 3681 } 3682 } 3683 3684 // fold (or c1, c2) -> c1|c2 3685 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3686 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3687 if (N0C && N1C && !N1C->isOpaque()) 3688 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3689 // canonicalize constant to RHS 3690 if (isConstantIntBuildVectorOrConstantInt(N0) && 3691 !isConstantIntBuildVectorOrConstantInt(N1)) 3692 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3693 // fold (or x, 0) -> x 3694 if (isNullConstant(N1)) 3695 return N0; 3696 // fold (or x, -1) -> -1 3697 if (isAllOnesConstant(N1)) 3698 return N1; 3699 // fold (or x, c) -> c iff (x & ~c) == 0 3700 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3701 return N1; 3702 3703 if (SDValue Combined = visitORLike(N0, N1, N)) 3704 return Combined; 3705 3706 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3707 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3708 return BSwap; 3709 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3710 return BSwap; 3711 3712 // reassociate or 3713 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3714 return ROR; 3715 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3716 // iff (c1 & c2) == 0. 3717 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3718 isa<ConstantSDNode>(N0.getOperand(1))) { 3719 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3720 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3721 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3722 N1C, C1)) 3723 return DAG.getNode( 3724 ISD::AND, SDLoc(N), VT, 3725 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3726 return SDValue(); 3727 } 3728 } 3729 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3730 if (N0.getOpcode() == N1.getOpcode()) 3731 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3732 return Tmp; 3733 3734 // See if this is some rotate idiom. 3735 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3736 return SDValue(Rot, 0); 3737 3738 // Simplify the operands using demanded-bits information. 3739 if (!VT.isVector() && 3740 SimplifyDemandedBits(SDValue(N, 0))) 3741 return SDValue(N, 0); 3742 3743 return SDValue(); 3744 } 3745 3746 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3747 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3748 if (Op.getOpcode() == ISD::AND) { 3749 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3750 Mask = Op.getOperand(1); 3751 Op = Op.getOperand(0); 3752 } else { 3753 return false; 3754 } 3755 } 3756 3757 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3758 Shift = Op; 3759 return true; 3760 } 3761 3762 return false; 3763 } 3764 3765 // Return true if we can prove that, whenever Neg and Pos are both in the 3766 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3767 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3768 // 3769 // (or (shift1 X, Neg), (shift2 X, Pos)) 3770 // 3771 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3772 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3773 // to consider shift amounts with defined behavior. 3774 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3775 // If OpSize is a power of 2 then: 3776 // 3777 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3778 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3779 // 3780 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3781 // for the stronger condition: 3782 // 3783 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3784 // 3785 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3786 // we can just replace Neg with Neg' for the rest of the function. 3787 // 3788 // In other cases we check for the even stronger condition: 3789 // 3790 // Neg == OpSize - Pos [B] 3791 // 3792 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3793 // behavior if Pos == 0 (and consequently Neg == OpSize). 3794 // 3795 // We could actually use [A] whenever OpSize is a power of 2, but the 3796 // only extra cases that it would match are those uninteresting ones 3797 // where Neg and Pos are never in range at the same time. E.g. for 3798 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3799 // as well as (sub 32, Pos), but: 3800 // 3801 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3802 // 3803 // always invokes undefined behavior for 32-bit X. 3804 // 3805 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3806 unsigned MaskLoBits = 0; 3807 if (Neg.getOpcode() == ISD::AND && 3808 isPowerOf2_64(OpSize) && 3809 Neg.getOperand(1).getOpcode() == ISD::Constant && 3810 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3811 Neg = Neg.getOperand(0); 3812 MaskLoBits = Log2_64(OpSize); 3813 } 3814 3815 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3816 if (Neg.getOpcode() != ISD::SUB) 3817 return 0; 3818 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3819 if (!NegC) 3820 return 0; 3821 SDValue NegOp1 = Neg.getOperand(1); 3822 3823 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3824 // Pos'. The truncation is redundant for the purpose of the equality. 3825 if (MaskLoBits && 3826 Pos.getOpcode() == ISD::AND && 3827 Pos.getOperand(1).getOpcode() == ISD::Constant && 3828 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3829 Pos = Pos.getOperand(0); 3830 3831 // The condition we need is now: 3832 // 3833 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3834 // 3835 // If NegOp1 == Pos then we need: 3836 // 3837 // OpSize & Mask == NegC & Mask 3838 // 3839 // (because "x & Mask" is a truncation and distributes through subtraction). 3840 APInt Width; 3841 if (Pos == NegOp1) 3842 Width = NegC->getAPIntValue(); 3843 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3844 // Then the condition we want to prove becomes: 3845 // 3846 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3847 // 3848 // which, again because "x & Mask" is a truncation, becomes: 3849 // 3850 // NegC & Mask == (OpSize - PosC) & Mask 3851 // OpSize & Mask == (NegC + PosC) & Mask 3852 else if (Pos.getOpcode() == ISD::ADD && 3853 Pos.getOperand(0) == NegOp1 && 3854 Pos.getOperand(1).getOpcode() == ISD::Constant) 3855 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3856 NegC->getAPIntValue()); 3857 else 3858 return false; 3859 3860 // Now we just need to check that OpSize & Mask == Width & Mask. 3861 if (MaskLoBits) 3862 // Opsize & Mask is 0 since Mask is Opsize - 1. 3863 return Width.getLoBits(MaskLoBits) == 0; 3864 return Width == OpSize; 3865 } 3866 3867 // A subroutine of MatchRotate used once we have found an OR of two opposite 3868 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3869 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3870 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3871 // Neg with outer conversions stripped away. 3872 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3873 SDValue Neg, SDValue InnerPos, 3874 SDValue InnerNeg, unsigned PosOpcode, 3875 unsigned NegOpcode, SDLoc DL) { 3876 // fold (or (shl x, (*ext y)), 3877 // (srl x, (*ext (sub 32, y)))) -> 3878 // (rotl x, y) or (rotr x, (sub 32, y)) 3879 // 3880 // fold (or (shl x, (*ext (sub 32, y))), 3881 // (srl x, (*ext y))) -> 3882 // (rotr x, y) or (rotl x, (sub 32, y)) 3883 EVT VT = Shifted.getValueType(); 3884 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3885 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3886 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3887 HasPos ? Pos : Neg).getNode(); 3888 } 3889 3890 return nullptr; 3891 } 3892 3893 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3894 // idioms for rotate, and if the target supports rotation instructions, generate 3895 // a rot[lr]. 3896 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3897 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3898 EVT VT = LHS.getValueType(); 3899 if (!TLI.isTypeLegal(VT)) return nullptr; 3900 3901 // The target must have at least one rotate flavor. 3902 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3903 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3904 if (!HasROTL && !HasROTR) return nullptr; 3905 3906 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3907 SDValue LHSShift; // The shift. 3908 SDValue LHSMask; // AND value if any. 3909 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3910 return nullptr; // Not part of a rotate. 3911 3912 SDValue RHSShift; // The shift. 3913 SDValue RHSMask; // AND value if any. 3914 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3915 return nullptr; // Not part of a rotate. 3916 3917 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3918 return nullptr; // Not shifting the same value. 3919 3920 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3921 return nullptr; // Shifts must disagree. 3922 3923 // Canonicalize shl to left side in a shl/srl pair. 3924 if (RHSShift.getOpcode() == ISD::SHL) { 3925 std::swap(LHS, RHS); 3926 std::swap(LHSShift, RHSShift); 3927 std::swap(LHSMask , RHSMask ); 3928 } 3929 3930 unsigned OpSizeInBits = VT.getSizeInBits(); 3931 SDValue LHSShiftArg = LHSShift.getOperand(0); 3932 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3933 SDValue RHSShiftArg = RHSShift.getOperand(0); 3934 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3935 3936 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3937 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3938 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3939 RHSShiftAmt.getOpcode() == ISD::Constant) { 3940 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3941 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3942 if ((LShVal + RShVal) != OpSizeInBits) 3943 return nullptr; 3944 3945 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3946 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3947 3948 // If there is an AND of either shifted operand, apply it to the result. 3949 if (LHSMask.getNode() || RHSMask.getNode()) { 3950 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3951 3952 if (LHSMask.getNode()) { 3953 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3954 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3955 } 3956 if (RHSMask.getNode()) { 3957 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3958 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3959 } 3960 3961 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT)); 3962 } 3963 3964 return Rot.getNode(); 3965 } 3966 3967 // If there is a mask here, and we have a variable shift, we can't be sure 3968 // that we're masking out the right stuff. 3969 if (LHSMask.getNode() || RHSMask.getNode()) 3970 return nullptr; 3971 3972 // If the shift amount is sign/zext/any-extended just peel it off. 3973 SDValue LExtOp0 = LHSShiftAmt; 3974 SDValue RExtOp0 = RHSShiftAmt; 3975 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3976 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3977 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3978 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3979 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3980 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3981 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3982 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3983 LExtOp0 = LHSShiftAmt.getOperand(0); 3984 RExtOp0 = RHSShiftAmt.getOperand(0); 3985 } 3986 3987 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3988 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3989 if (TryL) 3990 return TryL; 3991 3992 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3993 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3994 if (TryR) 3995 return TryR; 3996 3997 return nullptr; 3998 } 3999 4000 SDValue DAGCombiner::visitXOR(SDNode *N) { 4001 SDValue N0 = N->getOperand(0); 4002 SDValue N1 = N->getOperand(1); 4003 EVT VT = N0.getValueType(); 4004 4005 // fold vector ops 4006 if (VT.isVector()) { 4007 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4008 return FoldedVOp; 4009 4010 // fold (xor x, 0) -> x, vector edition 4011 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4012 return N1; 4013 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4014 return N0; 4015 } 4016 4017 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4018 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 4019 return DAG.getConstant(0, SDLoc(N), VT); 4020 // fold (xor x, undef) -> undef 4021 if (N0.getOpcode() == ISD::UNDEF) 4022 return N0; 4023 if (N1.getOpcode() == ISD::UNDEF) 4024 return N1; 4025 // fold (xor c1, c2) -> c1^c2 4026 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4027 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4028 if (N0C && N1C) 4029 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4030 // canonicalize constant to RHS 4031 if (isConstantIntBuildVectorOrConstantInt(N0) && 4032 !isConstantIntBuildVectorOrConstantInt(N1)) 4033 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4034 // fold (xor x, 0) -> x 4035 if (isNullConstant(N1)) 4036 return N0; 4037 // reassociate xor 4038 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4039 return RXOR; 4040 4041 // fold !(x cc y) -> (x !cc y) 4042 SDValue LHS, RHS, CC; 4043 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4044 bool isInt = LHS.getValueType().isInteger(); 4045 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4046 isInt); 4047 4048 if (!LegalOperations || 4049 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4050 switch (N0.getOpcode()) { 4051 default: 4052 llvm_unreachable("Unhandled SetCC Equivalent!"); 4053 case ISD::SETCC: 4054 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4055 case ISD::SELECT_CC: 4056 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4057 N0.getOperand(3), NotCC); 4058 } 4059 } 4060 } 4061 4062 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4063 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4064 N0.getNode()->hasOneUse() && 4065 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4066 SDValue V = N0.getOperand(0); 4067 SDLoc DL(N0); 4068 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4069 DAG.getConstant(1, DL, V.getValueType())); 4070 AddToWorklist(V.getNode()); 4071 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4072 } 4073 4074 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4075 if (isOneConstant(N1) && VT == MVT::i1 && 4076 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4077 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4078 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4079 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4080 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4081 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4082 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4083 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4084 } 4085 } 4086 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4087 if (isAllOnesConstant(N1) && 4088 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4089 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4090 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4091 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4092 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4093 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4094 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4095 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4096 } 4097 } 4098 // fold (xor (and x, y), y) -> (and (not x), y) 4099 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4100 N0->getOperand(1) == N1) { 4101 SDValue X = N0->getOperand(0); 4102 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4103 AddToWorklist(NotX.getNode()); 4104 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4105 } 4106 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4107 if (N1C && N0.getOpcode() == ISD::XOR) { 4108 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4109 SDLoc DL(N); 4110 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4111 DAG.getConstant(N1C->getAPIntValue() ^ 4112 N00C->getAPIntValue(), DL, VT)); 4113 } 4114 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4115 SDLoc DL(N); 4116 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4117 DAG.getConstant(N1C->getAPIntValue() ^ 4118 N01C->getAPIntValue(), DL, VT)); 4119 } 4120 } 4121 // fold (xor x, x) -> 0 4122 if (N0 == N1) 4123 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4124 4125 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4126 // Here is a concrete example of this equivalence: 4127 // i16 x == 14 4128 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4129 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4130 // 4131 // => 4132 // 4133 // i16 ~1 == 0b1111111111111110 4134 // i16 rol(~1, 14) == 0b1011111111111111 4135 // 4136 // Some additional tips to help conceptualize this transform: 4137 // - Try to see the operation as placing a single zero in a value of all ones. 4138 // - There exists no value for x which would allow the result to contain zero. 4139 // - Values of x larger than the bitwidth are undefined and do not require a 4140 // consistent result. 4141 // - Pushing the zero left requires shifting one bits in from the right. 4142 // A rotate left of ~1 is a nice way of achieving the desired result. 4143 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4144 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4145 SDLoc DL(N); 4146 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4147 N0.getOperand(1)); 4148 } 4149 4150 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4151 if (N0.getOpcode() == N1.getOpcode()) 4152 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4153 return Tmp; 4154 4155 // Simplify the expression using non-local knowledge. 4156 if (!VT.isVector() && 4157 SimplifyDemandedBits(SDValue(N, 0))) 4158 return SDValue(N, 0); 4159 4160 return SDValue(); 4161 } 4162 4163 /// Handle transforms common to the three shifts, when the shift amount is a 4164 /// constant. 4165 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4166 SDNode *LHS = N->getOperand(0).getNode(); 4167 if (!LHS->hasOneUse()) return SDValue(); 4168 4169 // We want to pull some binops through shifts, so that we have (and (shift)) 4170 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4171 // thing happens with address calculations, so it's important to canonicalize 4172 // it. 4173 bool HighBitSet = false; // Can we transform this if the high bit is set? 4174 4175 switch (LHS->getOpcode()) { 4176 default: return SDValue(); 4177 case ISD::OR: 4178 case ISD::XOR: 4179 HighBitSet = false; // We can only transform sra if the high bit is clear. 4180 break; 4181 case ISD::AND: 4182 HighBitSet = true; // We can only transform sra if the high bit is set. 4183 break; 4184 case ISD::ADD: 4185 if (N->getOpcode() != ISD::SHL) 4186 return SDValue(); // only shl(add) not sr[al](add). 4187 HighBitSet = false; // We can only transform sra if the high bit is clear. 4188 break; 4189 } 4190 4191 // We require the RHS of the binop to be a constant and not opaque as well. 4192 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4193 if (!BinOpCst) return SDValue(); 4194 4195 // FIXME: disable this unless the input to the binop is a shift by a constant. 4196 // If it is not a shift, it pessimizes some common cases like: 4197 // 4198 // void foo(int *X, int i) { X[i & 1235] = 1; } 4199 // int bar(int *X, int i) { return X[i & 255]; } 4200 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4201 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4202 BinOpLHSVal->getOpcode() != ISD::SRA && 4203 BinOpLHSVal->getOpcode() != ISD::SRL) || 4204 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4205 return SDValue(); 4206 4207 EVT VT = N->getValueType(0); 4208 4209 // If this is a signed shift right, and the high bit is modified by the 4210 // logical operation, do not perform the transformation. The highBitSet 4211 // boolean indicates the value of the high bit of the constant which would 4212 // cause it to be modified for this operation. 4213 if (N->getOpcode() == ISD::SRA) { 4214 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4215 if (BinOpRHSSignSet != HighBitSet) 4216 return SDValue(); 4217 } 4218 4219 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4220 return SDValue(); 4221 4222 // Fold the constants, shifting the binop RHS by the shift amount. 4223 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4224 N->getValueType(0), 4225 LHS->getOperand(1), N->getOperand(1)); 4226 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4227 4228 // Create the new shift. 4229 SDValue NewShift = DAG.getNode(N->getOpcode(), 4230 SDLoc(LHS->getOperand(0)), 4231 VT, LHS->getOperand(0), N->getOperand(1)); 4232 4233 // Create the new binop. 4234 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4235 } 4236 4237 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4238 assert(N->getOpcode() == ISD::TRUNCATE); 4239 assert(N->getOperand(0).getOpcode() == ISD::AND); 4240 4241 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4242 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4243 SDValue N01 = N->getOperand(0).getOperand(1); 4244 4245 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4246 if (!N01C->isOpaque()) { 4247 EVT TruncVT = N->getValueType(0); 4248 SDValue N00 = N->getOperand(0).getOperand(0); 4249 APInt TruncC = N01C->getAPIntValue(); 4250 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4251 SDLoc DL(N); 4252 4253 return DAG.getNode(ISD::AND, DL, TruncVT, 4254 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4255 DAG.getConstant(TruncC, DL, TruncVT)); 4256 } 4257 } 4258 } 4259 4260 return SDValue(); 4261 } 4262 4263 SDValue DAGCombiner::visitRotate(SDNode *N) { 4264 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4265 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4266 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4267 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4268 if (NewOp1.getNode()) 4269 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4270 N->getOperand(0), NewOp1); 4271 } 4272 return SDValue(); 4273 } 4274 4275 SDValue DAGCombiner::visitSHL(SDNode *N) { 4276 SDValue N0 = N->getOperand(0); 4277 SDValue N1 = N->getOperand(1); 4278 EVT VT = N0.getValueType(); 4279 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4280 4281 // fold vector ops 4282 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4283 if (VT.isVector()) { 4284 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4285 return FoldedVOp; 4286 4287 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4288 // If setcc produces all-one true value then: 4289 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4290 if (N1CV && N1CV->isConstant()) { 4291 if (N0.getOpcode() == ISD::AND) { 4292 SDValue N00 = N0->getOperand(0); 4293 SDValue N01 = N0->getOperand(1); 4294 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4295 4296 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4297 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4298 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4299 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4300 N01CV, N1CV)) 4301 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4302 } 4303 } else { 4304 N1C = isConstOrConstSplat(N1); 4305 } 4306 } 4307 } 4308 4309 // fold (shl c1, c2) -> c1<<c2 4310 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4311 if (N0C && N1C && !N1C->isOpaque()) 4312 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4313 // fold (shl 0, x) -> 0 4314 if (isNullConstant(N0)) 4315 return N0; 4316 // fold (shl x, c >= size(x)) -> undef 4317 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4318 return DAG.getUNDEF(VT); 4319 // fold (shl x, 0) -> x 4320 if (N1C && N1C->isNullValue()) 4321 return N0; 4322 // fold (shl undef, x) -> 0 4323 if (N0.getOpcode() == ISD::UNDEF) 4324 return DAG.getConstant(0, SDLoc(N), VT); 4325 // if (shl x, c) is known to be zero, return 0 4326 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4327 APInt::getAllOnesValue(OpSizeInBits))) 4328 return DAG.getConstant(0, SDLoc(N), VT); 4329 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4330 if (N1.getOpcode() == ISD::TRUNCATE && 4331 N1.getOperand(0).getOpcode() == ISD::AND) { 4332 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4333 if (NewOp1.getNode()) 4334 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4335 } 4336 4337 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4338 return SDValue(N, 0); 4339 4340 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4341 if (N1C && N0.getOpcode() == ISD::SHL) { 4342 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4343 uint64_t c1 = N0C1->getZExtValue(); 4344 uint64_t c2 = N1C->getZExtValue(); 4345 SDLoc DL(N); 4346 if (c1 + c2 >= OpSizeInBits) 4347 return DAG.getConstant(0, DL, VT); 4348 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4349 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4350 } 4351 } 4352 4353 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4354 // For this to be valid, the second form must not preserve any of the bits 4355 // that are shifted out by the inner shift in the first form. This means 4356 // the outer shift size must be >= the number of bits added by the ext. 4357 // As a corollary, we don't care what kind of ext it is. 4358 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4359 N0.getOpcode() == ISD::ANY_EXTEND || 4360 N0.getOpcode() == ISD::SIGN_EXTEND) && 4361 N0.getOperand(0).getOpcode() == ISD::SHL) { 4362 SDValue N0Op0 = N0.getOperand(0); 4363 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4364 uint64_t c1 = N0Op0C1->getZExtValue(); 4365 uint64_t c2 = N1C->getZExtValue(); 4366 EVT InnerShiftVT = N0Op0.getValueType(); 4367 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4368 if (c2 >= OpSizeInBits - InnerShiftSize) { 4369 SDLoc DL(N0); 4370 if (c1 + c2 >= OpSizeInBits) 4371 return DAG.getConstant(0, DL, VT); 4372 return DAG.getNode(ISD::SHL, DL, VT, 4373 DAG.getNode(N0.getOpcode(), DL, VT, 4374 N0Op0->getOperand(0)), 4375 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4376 } 4377 } 4378 } 4379 4380 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4381 // Only fold this if the inner zext has no other uses to avoid increasing 4382 // the total number of instructions. 4383 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4384 N0.getOperand(0).getOpcode() == ISD::SRL) { 4385 SDValue N0Op0 = N0.getOperand(0); 4386 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4387 uint64_t c1 = N0Op0C1->getZExtValue(); 4388 if (c1 < VT.getScalarSizeInBits()) { 4389 uint64_t c2 = N1C->getZExtValue(); 4390 if (c1 == c2) { 4391 SDValue NewOp0 = N0.getOperand(0); 4392 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4393 SDLoc DL(N); 4394 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4395 NewOp0, 4396 DAG.getConstant(c2, DL, CountVT)); 4397 AddToWorklist(NewSHL.getNode()); 4398 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4399 } 4400 } 4401 } 4402 } 4403 4404 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4405 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4406 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4407 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4408 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4409 uint64_t C1 = N0C1->getZExtValue(); 4410 uint64_t C2 = N1C->getZExtValue(); 4411 SDLoc DL(N); 4412 if (C1 <= C2) 4413 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4414 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4415 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4416 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4417 } 4418 } 4419 4420 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4421 // (and (srl x, (sub c1, c2), MASK) 4422 // Only fold this if the inner shift has no other uses -- if it does, folding 4423 // this will increase the total number of instructions. 4424 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4425 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4426 uint64_t c1 = N0C1->getZExtValue(); 4427 if (c1 < OpSizeInBits) { 4428 uint64_t c2 = N1C->getZExtValue(); 4429 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4430 SDValue Shift; 4431 if (c2 > c1) { 4432 Mask = Mask.shl(c2 - c1); 4433 SDLoc DL(N); 4434 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4435 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4436 } else { 4437 Mask = Mask.lshr(c1 - c2); 4438 SDLoc DL(N); 4439 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4440 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4441 } 4442 SDLoc DL(N0); 4443 return DAG.getNode(ISD::AND, DL, VT, Shift, 4444 DAG.getConstant(Mask, DL, VT)); 4445 } 4446 } 4447 } 4448 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4449 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4450 unsigned BitSize = VT.getScalarSizeInBits(); 4451 SDLoc DL(N); 4452 SDValue HiBitsMask = 4453 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4454 BitSize - N1C->getZExtValue()), 4455 DL, VT); 4456 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4457 HiBitsMask); 4458 } 4459 4460 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4461 // Variant of version done on multiply, except mul by a power of 2 is turned 4462 // into a shift. 4463 APInt Val; 4464 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4465 (isa<ConstantSDNode>(N0.getOperand(1)) || 4466 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4467 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4468 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4469 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4470 } 4471 4472 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4473 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4474 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4475 if (SDValue Folded = 4476 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4477 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4478 } 4479 } 4480 4481 if (N1C && !N1C->isOpaque()) 4482 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4483 return NewSHL; 4484 4485 return SDValue(); 4486 } 4487 4488 SDValue DAGCombiner::visitSRA(SDNode *N) { 4489 SDValue N0 = N->getOperand(0); 4490 SDValue N1 = N->getOperand(1); 4491 EVT VT = N0.getValueType(); 4492 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4493 4494 // fold vector ops 4495 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4496 if (VT.isVector()) { 4497 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4498 return FoldedVOp; 4499 4500 N1C = isConstOrConstSplat(N1); 4501 } 4502 4503 // fold (sra c1, c2) -> (sra c1, c2) 4504 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4505 if (N0C && N1C && !N1C->isOpaque()) 4506 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4507 // fold (sra 0, x) -> 0 4508 if (isNullConstant(N0)) 4509 return N0; 4510 // fold (sra -1, x) -> -1 4511 if (isAllOnesConstant(N0)) 4512 return N0; 4513 // fold (sra x, (setge c, size(x))) -> undef 4514 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4515 return DAG.getUNDEF(VT); 4516 // fold (sra x, 0) -> x 4517 if (N1C && N1C->isNullValue()) 4518 return N0; 4519 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4520 // sext_inreg. 4521 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4522 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4523 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4524 if (VT.isVector()) 4525 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4526 ExtVT, VT.getVectorNumElements()); 4527 if ((!LegalOperations || 4528 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4529 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4530 N0.getOperand(0), DAG.getValueType(ExtVT)); 4531 } 4532 4533 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4534 if (N1C && N0.getOpcode() == ISD::SRA) { 4535 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4536 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4537 if (Sum >= OpSizeInBits) 4538 Sum = OpSizeInBits - 1; 4539 SDLoc DL(N); 4540 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4541 DAG.getConstant(Sum, DL, N1.getValueType())); 4542 } 4543 } 4544 4545 // fold (sra (shl X, m), (sub result_size, n)) 4546 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4547 // result_size - n != m. 4548 // If truncate is free for the target sext(shl) is likely to result in better 4549 // code. 4550 if (N0.getOpcode() == ISD::SHL && N1C) { 4551 // Get the two constanst of the shifts, CN0 = m, CN = n. 4552 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4553 if (N01C) { 4554 LLVMContext &Ctx = *DAG.getContext(); 4555 // Determine what the truncate's result bitsize and type would be. 4556 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4557 4558 if (VT.isVector()) 4559 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4560 4561 // Determine the residual right-shift amount. 4562 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4563 4564 // If the shift is not a no-op (in which case this should be just a sign 4565 // extend already), the truncated to type is legal, sign_extend is legal 4566 // on that type, and the truncate to that type is both legal and free, 4567 // perform the transform. 4568 if ((ShiftAmt > 0) && 4569 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4570 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4571 TLI.isTruncateFree(VT, TruncVT)) { 4572 4573 SDLoc DL(N); 4574 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4575 getShiftAmountTy(N0.getOperand(0).getValueType())); 4576 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4577 N0.getOperand(0), Amt); 4578 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4579 Shift); 4580 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4581 N->getValueType(0), Trunc); 4582 } 4583 } 4584 } 4585 4586 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4587 if (N1.getOpcode() == ISD::TRUNCATE && 4588 N1.getOperand(0).getOpcode() == ISD::AND) { 4589 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4590 if (NewOp1.getNode()) 4591 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4592 } 4593 4594 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4595 // if c1 is equal to the number of bits the trunc removes 4596 if (N0.getOpcode() == ISD::TRUNCATE && 4597 (N0.getOperand(0).getOpcode() == ISD::SRL || 4598 N0.getOperand(0).getOpcode() == ISD::SRA) && 4599 N0.getOperand(0).hasOneUse() && 4600 N0.getOperand(0).getOperand(1).hasOneUse() && 4601 N1C) { 4602 SDValue N0Op0 = N0.getOperand(0); 4603 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4604 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4605 EVT LargeVT = N0Op0.getValueType(); 4606 4607 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4608 SDLoc DL(N); 4609 SDValue Amt = 4610 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4611 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4612 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4613 N0Op0.getOperand(0), Amt); 4614 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4615 } 4616 } 4617 } 4618 4619 // Simplify, based on bits shifted out of the LHS. 4620 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4621 return SDValue(N, 0); 4622 4623 4624 // If the sign bit is known to be zero, switch this to a SRL. 4625 if (DAG.SignBitIsZero(N0)) 4626 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4627 4628 if (N1C && !N1C->isOpaque()) 4629 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4630 return NewSRA; 4631 4632 return SDValue(); 4633 } 4634 4635 SDValue DAGCombiner::visitSRL(SDNode *N) { 4636 SDValue N0 = N->getOperand(0); 4637 SDValue N1 = N->getOperand(1); 4638 EVT VT = N0.getValueType(); 4639 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4640 4641 // fold vector ops 4642 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4643 if (VT.isVector()) { 4644 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4645 return FoldedVOp; 4646 4647 N1C = isConstOrConstSplat(N1); 4648 } 4649 4650 // fold (srl c1, c2) -> c1 >>u c2 4651 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4652 if (N0C && N1C && !N1C->isOpaque()) 4653 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4654 // fold (srl 0, x) -> 0 4655 if (isNullConstant(N0)) 4656 return N0; 4657 // fold (srl x, c >= size(x)) -> undef 4658 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4659 return DAG.getUNDEF(VT); 4660 // fold (srl x, 0) -> x 4661 if (N1C && N1C->isNullValue()) 4662 return N0; 4663 // if (srl x, c) is known to be zero, return 0 4664 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4665 APInt::getAllOnesValue(OpSizeInBits))) 4666 return DAG.getConstant(0, SDLoc(N), VT); 4667 4668 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4669 if (N1C && N0.getOpcode() == ISD::SRL) { 4670 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4671 uint64_t c1 = N01C->getZExtValue(); 4672 uint64_t c2 = N1C->getZExtValue(); 4673 SDLoc DL(N); 4674 if (c1 + c2 >= OpSizeInBits) 4675 return DAG.getConstant(0, DL, VT); 4676 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4677 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4678 } 4679 } 4680 4681 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4682 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4683 N0.getOperand(0).getOpcode() == ISD::SRL && 4684 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4685 uint64_t c1 = 4686 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4687 uint64_t c2 = N1C->getZExtValue(); 4688 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4689 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4690 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4691 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4692 if (c1 + OpSizeInBits == InnerShiftSize) { 4693 SDLoc DL(N0); 4694 if (c1 + c2 >= InnerShiftSize) 4695 return DAG.getConstant(0, DL, VT); 4696 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4697 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4698 N0.getOperand(0)->getOperand(0), 4699 DAG.getConstant(c1 + c2, DL, 4700 ShiftCountVT))); 4701 } 4702 } 4703 4704 // fold (srl (shl x, c), c) -> (and x, cst2) 4705 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4706 unsigned BitSize = N0.getScalarValueSizeInBits(); 4707 if (BitSize <= 64) { 4708 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4709 SDLoc DL(N); 4710 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4711 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4712 } 4713 } 4714 4715 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4716 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4717 // Shifting in all undef bits? 4718 EVT SmallVT = N0.getOperand(0).getValueType(); 4719 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4720 if (N1C->getZExtValue() >= BitSize) 4721 return DAG.getUNDEF(VT); 4722 4723 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4724 uint64_t ShiftAmt = N1C->getZExtValue(); 4725 SDLoc DL0(N0); 4726 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4727 N0.getOperand(0), 4728 DAG.getConstant(ShiftAmt, DL0, 4729 getShiftAmountTy(SmallVT))); 4730 AddToWorklist(SmallShift.getNode()); 4731 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4732 SDLoc DL(N); 4733 return DAG.getNode(ISD::AND, DL, VT, 4734 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4735 DAG.getConstant(Mask, DL, VT)); 4736 } 4737 } 4738 4739 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4740 // bit, which is unmodified by sra. 4741 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4742 if (N0.getOpcode() == ISD::SRA) 4743 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4744 } 4745 4746 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4747 if (N1C && N0.getOpcode() == ISD::CTLZ && 4748 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4749 APInt KnownZero, KnownOne; 4750 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4751 4752 // If any of the input bits are KnownOne, then the input couldn't be all 4753 // zeros, thus the result of the srl will always be zero. 4754 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4755 4756 // If all of the bits input the to ctlz node are known to be zero, then 4757 // the result of the ctlz is "32" and the result of the shift is one. 4758 APInt UnknownBits = ~KnownZero; 4759 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4760 4761 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4762 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4763 // Okay, we know that only that the single bit specified by UnknownBits 4764 // could be set on input to the CTLZ node. If this bit is set, the SRL 4765 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4766 // to an SRL/XOR pair, which is likely to simplify more. 4767 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4768 SDValue Op = N0.getOperand(0); 4769 4770 if (ShAmt) { 4771 SDLoc DL(N0); 4772 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4773 DAG.getConstant(ShAmt, DL, 4774 getShiftAmountTy(Op.getValueType()))); 4775 AddToWorklist(Op.getNode()); 4776 } 4777 4778 SDLoc DL(N); 4779 return DAG.getNode(ISD::XOR, DL, VT, 4780 Op, DAG.getConstant(1, DL, VT)); 4781 } 4782 } 4783 4784 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4785 if (N1.getOpcode() == ISD::TRUNCATE && 4786 N1.getOperand(0).getOpcode() == ISD::AND) { 4787 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4788 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4789 } 4790 4791 // fold operands of srl based on knowledge that the low bits are not 4792 // demanded. 4793 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4794 return SDValue(N, 0); 4795 4796 if (N1C && !N1C->isOpaque()) 4797 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4798 return NewSRL; 4799 4800 // Attempt to convert a srl of a load into a narrower zero-extending load. 4801 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4802 return NarrowLoad; 4803 4804 // Here is a common situation. We want to optimize: 4805 // 4806 // %a = ... 4807 // %b = and i32 %a, 2 4808 // %c = srl i32 %b, 1 4809 // brcond i32 %c ... 4810 // 4811 // into 4812 // 4813 // %a = ... 4814 // %b = and %a, 2 4815 // %c = setcc eq %b, 0 4816 // brcond %c ... 4817 // 4818 // However when after the source operand of SRL is optimized into AND, the SRL 4819 // itself may not be optimized further. Look for it and add the BRCOND into 4820 // the worklist. 4821 if (N->hasOneUse()) { 4822 SDNode *Use = *N->use_begin(); 4823 if (Use->getOpcode() == ISD::BRCOND) 4824 AddToWorklist(Use); 4825 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4826 // Also look pass the truncate. 4827 Use = *Use->use_begin(); 4828 if (Use->getOpcode() == ISD::BRCOND) 4829 AddToWorklist(Use); 4830 } 4831 } 4832 4833 return SDValue(); 4834 } 4835 4836 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4837 SDValue N0 = N->getOperand(0); 4838 EVT VT = N->getValueType(0); 4839 4840 // fold (bswap c1) -> c2 4841 if (isConstantIntBuildVectorOrConstantInt(N0)) 4842 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4843 // fold (bswap (bswap x)) -> x 4844 if (N0.getOpcode() == ISD::BSWAP) 4845 return N0->getOperand(0); 4846 return SDValue(); 4847 } 4848 4849 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4850 SDValue N0 = N->getOperand(0); 4851 EVT VT = N->getValueType(0); 4852 4853 // fold (ctlz c1) -> c2 4854 if (isConstantIntBuildVectorOrConstantInt(N0)) 4855 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4856 return SDValue(); 4857 } 4858 4859 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4860 SDValue N0 = N->getOperand(0); 4861 EVT VT = N->getValueType(0); 4862 4863 // fold (ctlz_zero_undef c1) -> c2 4864 if (isConstantIntBuildVectorOrConstantInt(N0)) 4865 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4866 return SDValue(); 4867 } 4868 4869 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4870 SDValue N0 = N->getOperand(0); 4871 EVT VT = N->getValueType(0); 4872 4873 // fold (cttz c1) -> c2 4874 if (isConstantIntBuildVectorOrConstantInt(N0)) 4875 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4876 return SDValue(); 4877 } 4878 4879 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4880 SDValue N0 = N->getOperand(0); 4881 EVT VT = N->getValueType(0); 4882 4883 // fold (cttz_zero_undef c1) -> c2 4884 if (isConstantIntBuildVectorOrConstantInt(N0)) 4885 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4886 return SDValue(); 4887 } 4888 4889 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4890 SDValue N0 = N->getOperand(0); 4891 EVT VT = N->getValueType(0); 4892 4893 // fold (ctpop c1) -> c2 4894 if (isConstantIntBuildVectorOrConstantInt(N0)) 4895 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4896 return SDValue(); 4897 } 4898 4899 4900 /// \brief Generate Min/Max node 4901 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4902 SDValue True, SDValue False, 4903 ISD::CondCode CC, const TargetLowering &TLI, 4904 SelectionDAG &DAG) { 4905 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4906 return SDValue(); 4907 4908 switch (CC) { 4909 case ISD::SETOLT: 4910 case ISD::SETOLE: 4911 case ISD::SETLT: 4912 case ISD::SETLE: 4913 case ISD::SETULT: 4914 case ISD::SETULE: { 4915 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4916 if (TLI.isOperationLegal(Opcode, VT)) 4917 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4918 return SDValue(); 4919 } 4920 case ISD::SETOGT: 4921 case ISD::SETOGE: 4922 case ISD::SETGT: 4923 case ISD::SETGE: 4924 case ISD::SETUGT: 4925 case ISD::SETUGE: { 4926 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4927 if (TLI.isOperationLegal(Opcode, VT)) 4928 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4929 return SDValue(); 4930 } 4931 default: 4932 return SDValue(); 4933 } 4934 } 4935 4936 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4937 SDValue N0 = N->getOperand(0); 4938 SDValue N1 = N->getOperand(1); 4939 SDValue N2 = N->getOperand(2); 4940 EVT VT = N->getValueType(0); 4941 EVT VT0 = N0.getValueType(); 4942 4943 // fold (select C, X, X) -> X 4944 if (N1 == N2) 4945 return N1; 4946 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 4947 // fold (select true, X, Y) -> X 4948 // fold (select false, X, Y) -> Y 4949 return !N0C->isNullValue() ? N1 : N2; 4950 } 4951 // fold (select C, 1, X) -> (or C, X) 4952 if (VT == MVT::i1 && isOneConstant(N1)) 4953 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4954 // fold (select C, 0, 1) -> (xor C, 1) 4955 // We can't do this reliably if integer based booleans have different contents 4956 // to floating point based booleans. This is because we can't tell whether we 4957 // have an integer-based boolean or a floating-point-based boolean unless we 4958 // can find the SETCC that produced it and inspect its operands. This is 4959 // fairly easy if C is the SETCC node, but it can potentially be 4960 // undiscoverable (or not reasonably discoverable). For example, it could be 4961 // in another basic block or it could require searching a complicated 4962 // expression. 4963 if (VT.isInteger() && 4964 (VT0 == MVT::i1 || (VT0.isInteger() && 4965 TLI.getBooleanContents(false, false) == 4966 TLI.getBooleanContents(false, true) && 4967 TLI.getBooleanContents(false, false) == 4968 TargetLowering::ZeroOrOneBooleanContent)) && 4969 isNullConstant(N1) && isOneConstant(N2)) { 4970 SDValue XORNode; 4971 if (VT == VT0) { 4972 SDLoc DL(N); 4973 return DAG.getNode(ISD::XOR, DL, VT0, 4974 N0, DAG.getConstant(1, DL, VT0)); 4975 } 4976 SDLoc DL0(N0); 4977 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 4978 N0, DAG.getConstant(1, DL0, VT0)); 4979 AddToWorklist(XORNode.getNode()); 4980 if (VT.bitsGT(VT0)) 4981 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4982 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4983 } 4984 // fold (select C, 0, X) -> (and (not C), X) 4985 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 4986 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4987 AddToWorklist(NOTNode.getNode()); 4988 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4989 } 4990 // fold (select C, X, 1) -> (or (not C), X) 4991 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 4992 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4993 AddToWorklist(NOTNode.getNode()); 4994 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4995 } 4996 // fold (select C, X, 0) -> (and C, X) 4997 if (VT == MVT::i1 && isNullConstant(N2)) 4998 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4999 // fold (select X, X, Y) -> (or X, Y) 5000 // fold (select X, 1, Y) -> (or X, Y) 5001 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5002 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5003 // fold (select X, Y, X) -> (and X, Y) 5004 // fold (select X, Y, 0) -> (and X, Y) 5005 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5006 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5007 5008 // If we can fold this based on the true/false value, do so. 5009 if (SimplifySelectOps(N, N1, N2)) 5010 return SDValue(N, 0); // Don't revisit N. 5011 5012 if (VT0 == MVT::i1) { 5013 // The code in this block deals with the following 2 equivalences: 5014 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5015 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5016 // The target can specify its prefered form with the 5017 // shouldNormalizeToSelectSequence() callback. However we always transform 5018 // to the right anyway if we find the inner select exists in the DAG anyway 5019 // and we always transform to the left side if we know that we can further 5020 // optimize the combination of the conditions. 5021 bool normalizeToSequence 5022 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5023 // select (and Cond0, Cond1), X, Y 5024 // -> select Cond0, (select Cond1, X, Y), Y 5025 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5026 SDValue Cond0 = N0->getOperand(0); 5027 SDValue Cond1 = N0->getOperand(1); 5028 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5029 N1.getValueType(), Cond1, N1, N2); 5030 if (normalizeToSequence || !InnerSelect.use_empty()) 5031 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5032 InnerSelect, N2); 5033 } 5034 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5035 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5036 SDValue Cond0 = N0->getOperand(0); 5037 SDValue Cond1 = N0->getOperand(1); 5038 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5039 N1.getValueType(), Cond1, N1, N2); 5040 if (normalizeToSequence || !InnerSelect.use_empty()) 5041 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5042 InnerSelect); 5043 } 5044 5045 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5046 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5047 SDValue N1_0 = N1->getOperand(0); 5048 SDValue N1_1 = N1->getOperand(1); 5049 SDValue N1_2 = N1->getOperand(2); 5050 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5051 // Create the actual and node if we can generate good code for it. 5052 if (!normalizeToSequence) { 5053 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5054 N0, N1_0); 5055 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5056 N1_1, N2); 5057 } 5058 // Otherwise see if we can optimize the "and" to a better pattern. 5059 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5060 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5061 N1_1, N2); 5062 } 5063 } 5064 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5065 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5066 SDValue N2_0 = N2->getOperand(0); 5067 SDValue N2_1 = N2->getOperand(1); 5068 SDValue N2_2 = N2->getOperand(2); 5069 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5070 // Create the actual or node if we can generate good code for it. 5071 if (!normalizeToSequence) { 5072 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5073 N0, N2_0); 5074 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5075 N1, N2_2); 5076 } 5077 // Otherwise see if we can optimize to a better pattern. 5078 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5079 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5080 N1, N2_2); 5081 } 5082 } 5083 } 5084 5085 // fold selects based on a setcc into other things, such as min/max/abs 5086 if (N0.getOpcode() == ISD::SETCC) { 5087 // select x, y (fcmp lt x, y) -> fminnum x, y 5088 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5089 // 5090 // This is OK if we don't care about what happens if either operand is a 5091 // NaN. 5092 // 5093 5094 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5095 // no signed zeros as well as no nans. 5096 const TargetOptions &Options = DAG.getTarget().Options; 5097 if (Options.UnsafeFPMath && 5098 VT.isFloatingPoint() && N0.hasOneUse() && 5099 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5100 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5101 5102 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5103 N0.getOperand(1), N1, N2, CC, 5104 TLI, DAG)) 5105 return FMinMax; 5106 } 5107 5108 if ((!LegalOperations && 5109 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5110 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5111 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5112 N0.getOperand(0), N0.getOperand(1), 5113 N1, N2, N0.getOperand(2)); 5114 return SimplifySelect(SDLoc(N), N0, N1, N2); 5115 } 5116 5117 return SDValue(); 5118 } 5119 5120 static 5121 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5122 SDLoc DL(N); 5123 EVT LoVT, HiVT; 5124 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5125 5126 // Split the inputs. 5127 SDValue Lo, Hi, LL, LH, RL, RH; 5128 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5129 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5130 5131 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5132 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5133 5134 return std::make_pair(Lo, Hi); 5135 } 5136 5137 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5138 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5139 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5140 SDLoc dl(N); 5141 SDValue Cond = N->getOperand(0); 5142 SDValue LHS = N->getOperand(1); 5143 SDValue RHS = N->getOperand(2); 5144 EVT VT = N->getValueType(0); 5145 int NumElems = VT.getVectorNumElements(); 5146 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5147 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5148 Cond.getOpcode() == ISD::BUILD_VECTOR); 5149 5150 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5151 // binary ones here. 5152 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5153 return SDValue(); 5154 5155 // We're sure we have an even number of elements due to the 5156 // concat_vectors we have as arguments to vselect. 5157 // Skip BV elements until we find one that's not an UNDEF 5158 // After we find an UNDEF element, keep looping until we get to half the 5159 // length of the BV and see if all the non-undef nodes are the same. 5160 ConstantSDNode *BottomHalf = nullptr; 5161 for (int i = 0; i < NumElems / 2; ++i) { 5162 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5163 continue; 5164 5165 if (BottomHalf == nullptr) 5166 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5167 else if (Cond->getOperand(i).getNode() != BottomHalf) 5168 return SDValue(); 5169 } 5170 5171 // Do the same for the second half of the BuildVector 5172 ConstantSDNode *TopHalf = nullptr; 5173 for (int i = NumElems / 2; i < NumElems; ++i) { 5174 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5175 continue; 5176 5177 if (TopHalf == nullptr) 5178 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5179 else if (Cond->getOperand(i).getNode() != TopHalf) 5180 return SDValue(); 5181 } 5182 5183 assert(TopHalf && BottomHalf && 5184 "One half of the selector was all UNDEFs and the other was all the " 5185 "same value. This should have been addressed before this function."); 5186 return DAG.getNode( 5187 ISD::CONCAT_VECTORS, dl, VT, 5188 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5189 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5190 } 5191 5192 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5193 5194 if (Level >= AfterLegalizeTypes) 5195 return SDValue(); 5196 5197 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5198 SDValue Mask = MSC->getMask(); 5199 SDValue Data = MSC->getValue(); 5200 SDLoc DL(N); 5201 5202 // If the MSCATTER data type requires splitting and the mask is provided by a 5203 // SETCC, then split both nodes and its operands before legalization. This 5204 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5205 // and enables future optimizations (e.g. min/max pattern matching on X86). 5206 if (Mask.getOpcode() != ISD::SETCC) 5207 return SDValue(); 5208 5209 // Check if any splitting is required. 5210 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5211 TargetLowering::TypeSplitVector) 5212 return SDValue(); 5213 SDValue MaskLo, MaskHi, Lo, Hi; 5214 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5215 5216 EVT LoVT, HiVT; 5217 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5218 5219 SDValue Chain = MSC->getChain(); 5220 5221 EVT MemoryVT = MSC->getMemoryVT(); 5222 unsigned Alignment = MSC->getOriginalAlignment(); 5223 5224 EVT LoMemVT, HiMemVT; 5225 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5226 5227 SDValue DataLo, DataHi; 5228 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5229 5230 SDValue BasePtr = MSC->getBasePtr(); 5231 SDValue IndexLo, IndexHi; 5232 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5233 5234 MachineMemOperand *MMO = DAG.getMachineFunction(). 5235 getMachineMemOperand(MSC->getPointerInfo(), 5236 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5237 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5238 5239 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5240 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5241 DL, OpsLo, MMO); 5242 5243 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5244 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5245 DL, OpsHi, MMO); 5246 5247 AddToWorklist(Lo.getNode()); 5248 AddToWorklist(Hi.getNode()); 5249 5250 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5251 } 5252 5253 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5254 5255 if (Level >= AfterLegalizeTypes) 5256 return SDValue(); 5257 5258 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5259 SDValue Mask = MST->getMask(); 5260 SDValue Data = MST->getValue(); 5261 SDLoc DL(N); 5262 5263 // If the MSTORE data type requires splitting and the mask is provided by a 5264 // SETCC, then split both nodes and its operands before legalization. This 5265 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5266 // and enables future optimizations (e.g. min/max pattern matching on X86). 5267 if (Mask.getOpcode() == ISD::SETCC) { 5268 5269 // Check if any splitting is required. 5270 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5271 TargetLowering::TypeSplitVector) 5272 return SDValue(); 5273 5274 SDValue MaskLo, MaskHi, Lo, Hi; 5275 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5276 5277 EVT LoVT, HiVT; 5278 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5279 5280 SDValue Chain = MST->getChain(); 5281 SDValue Ptr = MST->getBasePtr(); 5282 5283 EVT MemoryVT = MST->getMemoryVT(); 5284 unsigned Alignment = MST->getOriginalAlignment(); 5285 5286 // if Alignment is equal to the vector size, 5287 // take the half of it for the second part 5288 unsigned SecondHalfAlignment = 5289 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5290 Alignment/2 : Alignment; 5291 5292 EVT LoMemVT, HiMemVT; 5293 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5294 5295 SDValue DataLo, DataHi; 5296 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5297 5298 MachineMemOperand *MMO = DAG.getMachineFunction(). 5299 getMachineMemOperand(MST->getPointerInfo(), 5300 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5301 Alignment, MST->getAAInfo(), MST->getRanges()); 5302 5303 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5304 MST->isTruncatingStore()); 5305 5306 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5307 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5308 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5309 5310 MMO = DAG.getMachineFunction(). 5311 getMachineMemOperand(MST->getPointerInfo(), 5312 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5313 SecondHalfAlignment, MST->getAAInfo(), 5314 MST->getRanges()); 5315 5316 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5317 MST->isTruncatingStore()); 5318 5319 AddToWorklist(Lo.getNode()); 5320 AddToWorklist(Hi.getNode()); 5321 5322 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5323 } 5324 return SDValue(); 5325 } 5326 5327 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5328 5329 if (Level >= AfterLegalizeTypes) 5330 return SDValue(); 5331 5332 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5333 SDValue Mask = MGT->getMask(); 5334 SDLoc DL(N); 5335 5336 // If the MGATHER result requires splitting and the mask is provided by a 5337 // SETCC, then split both nodes and its operands before legalization. This 5338 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5339 // and enables future optimizations (e.g. min/max pattern matching on X86). 5340 5341 if (Mask.getOpcode() != ISD::SETCC) 5342 return SDValue(); 5343 5344 EVT VT = N->getValueType(0); 5345 5346 // Check if any splitting is required. 5347 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5348 TargetLowering::TypeSplitVector) 5349 return SDValue(); 5350 5351 SDValue MaskLo, MaskHi, Lo, Hi; 5352 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5353 5354 SDValue Src0 = MGT->getValue(); 5355 SDValue Src0Lo, Src0Hi; 5356 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5357 5358 EVT LoVT, HiVT; 5359 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5360 5361 SDValue Chain = MGT->getChain(); 5362 EVT MemoryVT = MGT->getMemoryVT(); 5363 unsigned Alignment = MGT->getOriginalAlignment(); 5364 5365 EVT LoMemVT, HiMemVT; 5366 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5367 5368 SDValue BasePtr = MGT->getBasePtr(); 5369 SDValue Index = MGT->getIndex(); 5370 SDValue IndexLo, IndexHi; 5371 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5372 5373 MachineMemOperand *MMO = DAG.getMachineFunction(). 5374 getMachineMemOperand(MGT->getPointerInfo(), 5375 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5376 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5377 5378 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5379 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5380 MMO); 5381 5382 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5383 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5384 MMO); 5385 5386 AddToWorklist(Lo.getNode()); 5387 AddToWorklist(Hi.getNode()); 5388 5389 // Build a factor node to remember that this load is independent of the 5390 // other one. 5391 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5392 Hi.getValue(1)); 5393 5394 // Legalized the chain result - switch anything that used the old chain to 5395 // use the new one. 5396 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5397 5398 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5399 5400 SDValue RetOps[] = { GatherRes, Chain }; 5401 return DAG.getMergeValues(RetOps, DL); 5402 } 5403 5404 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5405 5406 if (Level >= AfterLegalizeTypes) 5407 return SDValue(); 5408 5409 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5410 SDValue Mask = MLD->getMask(); 5411 SDLoc DL(N); 5412 5413 // If the MLOAD result requires splitting and the mask is provided by a 5414 // SETCC, then split both nodes and its operands before legalization. This 5415 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5416 // and enables future optimizations (e.g. min/max pattern matching on X86). 5417 5418 if (Mask.getOpcode() == ISD::SETCC) { 5419 EVT VT = N->getValueType(0); 5420 5421 // Check if any splitting is required. 5422 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5423 TargetLowering::TypeSplitVector) 5424 return SDValue(); 5425 5426 SDValue MaskLo, MaskHi, Lo, Hi; 5427 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5428 5429 SDValue Src0 = MLD->getSrc0(); 5430 SDValue Src0Lo, Src0Hi; 5431 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5432 5433 EVT LoVT, HiVT; 5434 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5435 5436 SDValue Chain = MLD->getChain(); 5437 SDValue Ptr = MLD->getBasePtr(); 5438 EVT MemoryVT = MLD->getMemoryVT(); 5439 unsigned Alignment = MLD->getOriginalAlignment(); 5440 5441 // if Alignment is equal to the vector size, 5442 // take the half of it for the second part 5443 unsigned SecondHalfAlignment = 5444 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5445 Alignment/2 : Alignment; 5446 5447 EVT LoMemVT, HiMemVT; 5448 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5449 5450 MachineMemOperand *MMO = DAG.getMachineFunction(). 5451 getMachineMemOperand(MLD->getPointerInfo(), 5452 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5453 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5454 5455 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5456 ISD::NON_EXTLOAD); 5457 5458 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5459 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5460 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5461 5462 MMO = DAG.getMachineFunction(). 5463 getMachineMemOperand(MLD->getPointerInfo(), 5464 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5465 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5466 5467 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5468 ISD::NON_EXTLOAD); 5469 5470 AddToWorklist(Lo.getNode()); 5471 AddToWorklist(Hi.getNode()); 5472 5473 // Build a factor node to remember that this load is independent of the 5474 // other one. 5475 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5476 Hi.getValue(1)); 5477 5478 // Legalized the chain result - switch anything that used the old chain to 5479 // use the new one. 5480 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5481 5482 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5483 5484 SDValue RetOps[] = { LoadRes, Chain }; 5485 return DAG.getMergeValues(RetOps, DL); 5486 } 5487 return SDValue(); 5488 } 5489 5490 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5491 SDValue N0 = N->getOperand(0); 5492 SDValue N1 = N->getOperand(1); 5493 SDValue N2 = N->getOperand(2); 5494 SDLoc DL(N); 5495 5496 // Canonicalize integer abs. 5497 // vselect (setg[te] X, 0), X, -X -> 5498 // vselect (setgt X, -1), X, -X -> 5499 // vselect (setl[te] X, 0), -X, X -> 5500 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5501 if (N0.getOpcode() == ISD::SETCC) { 5502 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5503 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5504 bool isAbs = false; 5505 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5506 5507 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5508 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5509 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5510 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5511 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5512 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5513 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5514 5515 if (isAbs) { 5516 EVT VT = LHS.getValueType(); 5517 SDValue Shift = DAG.getNode( 5518 ISD::SRA, DL, VT, LHS, 5519 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5520 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5521 AddToWorklist(Shift.getNode()); 5522 AddToWorklist(Add.getNode()); 5523 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5524 } 5525 } 5526 5527 if (SimplifySelectOps(N, N1, N2)) 5528 return SDValue(N, 0); // Don't revisit N. 5529 5530 // If the VSELECT result requires splitting and the mask is provided by a 5531 // SETCC, then split both nodes and its operands before legalization. This 5532 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5533 // and enables future optimizations (e.g. min/max pattern matching on X86). 5534 if (N0.getOpcode() == ISD::SETCC) { 5535 EVT VT = N->getValueType(0); 5536 5537 // Check if any splitting is required. 5538 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5539 TargetLowering::TypeSplitVector) 5540 return SDValue(); 5541 5542 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5543 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5544 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5545 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5546 5547 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5548 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5549 5550 // Add the new VSELECT nodes to the work list in case they need to be split 5551 // again. 5552 AddToWorklist(Lo.getNode()); 5553 AddToWorklist(Hi.getNode()); 5554 5555 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5556 } 5557 5558 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5559 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5560 return N1; 5561 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5562 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5563 return N2; 5564 5565 // The ConvertSelectToConcatVector function is assuming both the above 5566 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5567 // and addressed. 5568 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5569 N2.getOpcode() == ISD::CONCAT_VECTORS && 5570 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5571 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5572 return CV; 5573 } 5574 5575 return SDValue(); 5576 } 5577 5578 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5579 SDValue N0 = N->getOperand(0); 5580 SDValue N1 = N->getOperand(1); 5581 SDValue N2 = N->getOperand(2); 5582 SDValue N3 = N->getOperand(3); 5583 SDValue N4 = N->getOperand(4); 5584 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5585 5586 // fold select_cc lhs, rhs, x, x, cc -> x 5587 if (N2 == N3) 5588 return N2; 5589 5590 // Determine if the condition we're dealing with is constant 5591 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5592 N0, N1, CC, SDLoc(N), false); 5593 if (SCC.getNode()) { 5594 AddToWorklist(SCC.getNode()); 5595 5596 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5597 if (!SCCC->isNullValue()) 5598 return N2; // cond always true -> true val 5599 else 5600 return N3; // cond always false -> false val 5601 } else if (SCC->getOpcode() == ISD::UNDEF) { 5602 // When the condition is UNDEF, just return the first operand. This is 5603 // coherent the DAG creation, no setcc node is created in this case 5604 return N2; 5605 } else if (SCC.getOpcode() == ISD::SETCC) { 5606 // Fold to a simpler select_cc 5607 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5608 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5609 SCC.getOperand(2)); 5610 } 5611 } 5612 5613 // If we can fold this based on the true/false value, do so. 5614 if (SimplifySelectOps(N, N2, N3)) 5615 return SDValue(N, 0); // Don't revisit N. 5616 5617 // fold select_cc into other things, such as min/max/abs 5618 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5619 } 5620 5621 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5622 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5623 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5624 SDLoc(N)); 5625 } 5626 5627 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5628 /// a build_vector of constants. 5629 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5630 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5631 /// Vector extends are not folded if operations are legal; this is to 5632 /// avoid introducing illegal build_vector dag nodes. 5633 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5634 SelectionDAG &DAG, bool LegalTypes, 5635 bool LegalOperations) { 5636 unsigned Opcode = N->getOpcode(); 5637 SDValue N0 = N->getOperand(0); 5638 EVT VT = N->getValueType(0); 5639 5640 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5641 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5642 && "Expected EXTEND dag node in input!"); 5643 5644 // fold (sext c1) -> c1 5645 // fold (zext c1) -> c1 5646 // fold (aext c1) -> c1 5647 if (isa<ConstantSDNode>(N0)) 5648 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5649 5650 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5651 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5652 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5653 EVT SVT = VT.getScalarType(); 5654 if (!(VT.isVector() && 5655 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5656 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5657 return nullptr; 5658 5659 // We can fold this node into a build_vector. 5660 unsigned VTBits = SVT.getSizeInBits(); 5661 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5662 SmallVector<SDValue, 8> Elts; 5663 unsigned NumElts = VT.getVectorNumElements(); 5664 SDLoc DL(N); 5665 5666 for (unsigned i=0; i != NumElts; ++i) { 5667 SDValue Op = N0->getOperand(i); 5668 if (Op->getOpcode() == ISD::UNDEF) { 5669 Elts.push_back(DAG.getUNDEF(SVT)); 5670 continue; 5671 } 5672 5673 SDLoc DL(Op); 5674 // Get the constant value and if needed trunc it to the size of the type. 5675 // Nodes like build_vector might have constants wider than the scalar type. 5676 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5677 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5678 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5679 else 5680 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5681 } 5682 5683 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5684 } 5685 5686 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5687 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5688 // transformation. Returns true if extension are possible and the above 5689 // mentioned transformation is profitable. 5690 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5691 unsigned ExtOpc, 5692 SmallVectorImpl<SDNode *> &ExtendNodes, 5693 const TargetLowering &TLI) { 5694 bool HasCopyToRegUses = false; 5695 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5696 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5697 UE = N0.getNode()->use_end(); 5698 UI != UE; ++UI) { 5699 SDNode *User = *UI; 5700 if (User == N) 5701 continue; 5702 if (UI.getUse().getResNo() != N0.getResNo()) 5703 continue; 5704 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5705 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5706 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5707 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5708 // Sign bits will be lost after a zext. 5709 return false; 5710 bool Add = false; 5711 for (unsigned i = 0; i != 2; ++i) { 5712 SDValue UseOp = User->getOperand(i); 5713 if (UseOp == N0) 5714 continue; 5715 if (!isa<ConstantSDNode>(UseOp)) 5716 return false; 5717 Add = true; 5718 } 5719 if (Add) 5720 ExtendNodes.push_back(User); 5721 continue; 5722 } 5723 // If truncates aren't free and there are users we can't 5724 // extend, it isn't worthwhile. 5725 if (!isTruncFree) 5726 return false; 5727 // Remember if this value is live-out. 5728 if (User->getOpcode() == ISD::CopyToReg) 5729 HasCopyToRegUses = true; 5730 } 5731 5732 if (HasCopyToRegUses) { 5733 bool BothLiveOut = false; 5734 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5735 UI != UE; ++UI) { 5736 SDUse &Use = UI.getUse(); 5737 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5738 BothLiveOut = true; 5739 break; 5740 } 5741 } 5742 if (BothLiveOut) 5743 // Both unextended and extended values are live out. There had better be 5744 // a good reason for the transformation. 5745 return ExtendNodes.size(); 5746 } 5747 return true; 5748 } 5749 5750 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5751 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5752 ISD::NodeType ExtType) { 5753 // Extend SetCC uses if necessary. 5754 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5755 SDNode *SetCC = SetCCs[i]; 5756 SmallVector<SDValue, 4> Ops; 5757 5758 for (unsigned j = 0; j != 2; ++j) { 5759 SDValue SOp = SetCC->getOperand(j); 5760 if (SOp == Trunc) 5761 Ops.push_back(ExtLoad); 5762 else 5763 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5764 } 5765 5766 Ops.push_back(SetCC->getOperand(2)); 5767 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5768 } 5769 } 5770 5771 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5772 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5773 SDValue N0 = N->getOperand(0); 5774 EVT DstVT = N->getValueType(0); 5775 EVT SrcVT = N0.getValueType(); 5776 5777 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5778 N->getOpcode() == ISD::ZERO_EXTEND) && 5779 "Unexpected node type (not an extend)!"); 5780 5781 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5782 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5783 // (v8i32 (sext (v8i16 (load x)))) 5784 // into: 5785 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5786 // (v4i32 (sextload (x + 16))))) 5787 // Where uses of the original load, i.e.: 5788 // (v8i16 (load x)) 5789 // are replaced with: 5790 // (v8i16 (truncate 5791 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5792 // (v4i32 (sextload (x + 16))))))) 5793 // 5794 // This combine is only applicable to illegal, but splittable, vectors. 5795 // All legal types, and illegal non-vector types, are handled elsewhere. 5796 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5797 // 5798 if (N0->getOpcode() != ISD::LOAD) 5799 return SDValue(); 5800 5801 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5802 5803 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5804 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5805 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5806 return SDValue(); 5807 5808 SmallVector<SDNode *, 4> SetCCs; 5809 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5810 return SDValue(); 5811 5812 ISD::LoadExtType ExtType = 5813 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5814 5815 // Try to split the vector types to get down to legal types. 5816 EVT SplitSrcVT = SrcVT; 5817 EVT SplitDstVT = DstVT; 5818 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5819 SplitSrcVT.getVectorNumElements() > 1) { 5820 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5821 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5822 } 5823 5824 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5825 return SDValue(); 5826 5827 SDLoc DL(N); 5828 const unsigned NumSplits = 5829 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5830 const unsigned Stride = SplitSrcVT.getStoreSize(); 5831 SmallVector<SDValue, 4> Loads; 5832 SmallVector<SDValue, 4> Chains; 5833 5834 SDValue BasePtr = LN0->getBasePtr(); 5835 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5836 const unsigned Offset = Idx * Stride; 5837 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5838 5839 SDValue SplitLoad = DAG.getExtLoad( 5840 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5841 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5842 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5843 Align, LN0->getAAInfo()); 5844 5845 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5846 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5847 5848 Loads.push_back(SplitLoad.getValue(0)); 5849 Chains.push_back(SplitLoad.getValue(1)); 5850 } 5851 5852 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5853 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5854 5855 CombineTo(N, NewValue); 5856 5857 // Replace uses of the original load (before extension) 5858 // with a truncate of the concatenated sextloaded vectors. 5859 SDValue Trunc = 5860 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5861 CombineTo(N0.getNode(), Trunc, NewChain); 5862 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5863 (ISD::NodeType)N->getOpcode()); 5864 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5865 } 5866 5867 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5868 SDValue N0 = N->getOperand(0); 5869 EVT VT = N->getValueType(0); 5870 5871 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5872 LegalOperations)) 5873 return SDValue(Res, 0); 5874 5875 // fold (sext (sext x)) -> (sext x) 5876 // fold (sext (aext x)) -> (sext x) 5877 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5878 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5879 N0.getOperand(0)); 5880 5881 if (N0.getOpcode() == ISD::TRUNCATE) { 5882 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5883 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5884 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 5885 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5886 if (NarrowLoad.getNode() != N0.getNode()) { 5887 CombineTo(N0.getNode(), NarrowLoad); 5888 // CombineTo deleted the truncate, if needed, but not what's under it. 5889 AddToWorklist(oye); 5890 } 5891 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5892 } 5893 5894 // See if the value being truncated is already sign extended. If so, just 5895 // eliminate the trunc/sext pair. 5896 SDValue Op = N0.getOperand(0); 5897 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5898 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5899 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5900 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5901 5902 if (OpBits == DestBits) { 5903 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5904 // bits, it is already ready. 5905 if (NumSignBits > DestBits-MidBits) 5906 return Op; 5907 } else if (OpBits < DestBits) { 5908 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5909 // bits, just sext from i32. 5910 if (NumSignBits > OpBits-MidBits) 5911 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5912 } else { 5913 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5914 // bits, just truncate to i32. 5915 if (NumSignBits > OpBits-MidBits) 5916 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5917 } 5918 5919 // fold (sext (truncate x)) -> (sextinreg x). 5920 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5921 N0.getValueType())) { 5922 if (OpBits < DestBits) 5923 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5924 else if (OpBits > DestBits) 5925 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5926 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5927 DAG.getValueType(N0.getValueType())); 5928 } 5929 } 5930 5931 // fold (sext (load x)) -> (sext (truncate (sextload x))) 5932 // Only generate vector extloads when 1) they're legal, and 2) they are 5933 // deemed desirable by the target. 5934 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5935 ((!LegalOperations && !VT.isVector() && 5936 !cast<LoadSDNode>(N0)->isVolatile()) || 5937 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 5938 bool DoXform = true; 5939 SmallVector<SDNode*, 4> SetCCs; 5940 if (!N0.hasOneUse()) 5941 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5942 if (VT.isVector()) 5943 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5944 if (DoXform) { 5945 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5946 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5947 LN0->getChain(), 5948 LN0->getBasePtr(), N0.getValueType(), 5949 LN0->getMemOperand()); 5950 CombineTo(N, ExtLoad); 5951 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5952 N0.getValueType(), ExtLoad); 5953 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5954 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5955 ISD::SIGN_EXTEND); 5956 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5957 } 5958 } 5959 5960 // fold (sext (load x)) to multiple smaller sextloads. 5961 // Only on illegal but splittable vectors. 5962 if (SDValue ExtLoad = CombineExtLoad(N)) 5963 return ExtLoad; 5964 5965 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5966 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5967 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5968 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5969 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5970 EVT MemVT = LN0->getMemoryVT(); 5971 if ((!LegalOperations && !LN0->isVolatile()) || 5972 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 5973 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5974 LN0->getChain(), 5975 LN0->getBasePtr(), MemVT, 5976 LN0->getMemOperand()); 5977 CombineTo(N, ExtLoad); 5978 CombineTo(N0.getNode(), 5979 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5980 N0.getValueType(), ExtLoad), 5981 ExtLoad.getValue(1)); 5982 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5983 } 5984 } 5985 5986 // fold (sext (and/or/xor (load x), cst)) -> 5987 // (and/or/xor (sextload x), (sext cst)) 5988 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5989 N0.getOpcode() == ISD::XOR) && 5990 isa<LoadSDNode>(N0.getOperand(0)) && 5991 N0.getOperand(1).getOpcode() == ISD::Constant && 5992 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 5993 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5994 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5995 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5996 bool DoXform = true; 5997 SmallVector<SDNode*, 4> SetCCs; 5998 if (!N0.hasOneUse()) 5999 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6000 SetCCs, TLI); 6001 if (DoXform) { 6002 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6003 LN0->getChain(), LN0->getBasePtr(), 6004 LN0->getMemoryVT(), 6005 LN0->getMemOperand()); 6006 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6007 Mask = Mask.sext(VT.getSizeInBits()); 6008 SDLoc DL(N); 6009 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6010 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6011 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6012 SDLoc(N0.getOperand(0)), 6013 N0.getOperand(0).getValueType(), ExtLoad); 6014 CombineTo(N, And); 6015 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6016 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6017 ISD::SIGN_EXTEND); 6018 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6019 } 6020 } 6021 } 6022 6023 if (N0.getOpcode() == ISD::SETCC) { 6024 EVT N0VT = N0.getOperand(0).getValueType(); 6025 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6026 // Only do this before legalize for now. 6027 if (VT.isVector() && !LegalOperations && 6028 TLI.getBooleanContents(N0VT) == 6029 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6030 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6031 // of the same size as the compared operands. Only optimize sext(setcc()) 6032 // if this is the case. 6033 EVT SVT = getSetCCResultType(N0VT); 6034 6035 // We know that the # elements of the results is the same as the 6036 // # elements of the compare (and the # elements of the compare result 6037 // for that matter). Check to see that they are the same size. If so, 6038 // we know that the element size of the sext'd result matches the 6039 // element size of the compare operands. 6040 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6041 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6042 N0.getOperand(1), 6043 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6044 6045 // If the desired elements are smaller or larger than the source 6046 // elements we can use a matching integer vector type and then 6047 // truncate/sign extend 6048 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6049 if (SVT == MatchingVectorType) { 6050 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6051 N0.getOperand(0), N0.getOperand(1), 6052 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6053 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6054 } 6055 } 6056 6057 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6058 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6059 SDLoc DL(N); 6060 SDValue NegOne = 6061 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6062 SDValue SCC = 6063 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6064 NegOne, DAG.getConstant(0, DL, VT), 6065 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6066 if (SCC.getNode()) return SCC; 6067 6068 if (!VT.isVector()) { 6069 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6070 if (!LegalOperations || 6071 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6072 SDLoc DL(N); 6073 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6074 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6075 N0.getOperand(0), N0.getOperand(1), CC); 6076 return DAG.getSelect(DL, VT, SetCC, 6077 NegOne, DAG.getConstant(0, DL, VT)); 6078 } 6079 } 6080 } 6081 6082 // fold (sext x) -> (zext x) if the sign bit is known zero. 6083 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6084 DAG.SignBitIsZero(N0)) 6085 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6086 6087 return SDValue(); 6088 } 6089 6090 // isTruncateOf - If N is a truncate of some other value, return true, record 6091 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6092 // This function computes KnownZero to avoid a duplicated call to 6093 // computeKnownBits in the caller. 6094 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6095 APInt &KnownZero) { 6096 APInt KnownOne; 6097 if (N->getOpcode() == ISD::TRUNCATE) { 6098 Op = N->getOperand(0); 6099 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6100 return true; 6101 } 6102 6103 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6104 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6105 return false; 6106 6107 SDValue Op0 = N->getOperand(0); 6108 SDValue Op1 = N->getOperand(1); 6109 assert(Op0.getValueType() == Op1.getValueType()); 6110 6111 if (isNullConstant(Op0)) 6112 Op = Op1; 6113 else if (isNullConstant(Op1)) 6114 Op = Op0; 6115 else 6116 return false; 6117 6118 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6119 6120 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6121 return false; 6122 6123 return true; 6124 } 6125 6126 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6127 SDValue N0 = N->getOperand(0); 6128 EVT VT = N->getValueType(0); 6129 6130 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6131 LegalOperations)) 6132 return SDValue(Res, 0); 6133 6134 // fold (zext (zext x)) -> (zext x) 6135 // fold (zext (aext x)) -> (zext x) 6136 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6137 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6138 N0.getOperand(0)); 6139 6140 // fold (zext (truncate x)) -> (zext x) or 6141 // (zext (truncate x)) -> (truncate x) 6142 // This is valid when the truncated bits of x are already zero. 6143 // FIXME: We should extend this to work for vectors too. 6144 SDValue Op; 6145 APInt KnownZero; 6146 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6147 APInt TruncatedBits = 6148 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6149 APInt(Op.getValueSizeInBits(), 0) : 6150 APInt::getBitsSet(Op.getValueSizeInBits(), 6151 N0.getValueSizeInBits(), 6152 std::min(Op.getValueSizeInBits(), 6153 VT.getSizeInBits())); 6154 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6155 if (VT.bitsGT(Op.getValueType())) 6156 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6157 if (VT.bitsLT(Op.getValueType())) 6158 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6159 6160 return Op; 6161 } 6162 } 6163 6164 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6165 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6166 if (N0.getOpcode() == ISD::TRUNCATE) { 6167 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6168 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6169 if (NarrowLoad.getNode() != N0.getNode()) { 6170 CombineTo(N0.getNode(), NarrowLoad); 6171 // CombineTo deleted the truncate, if needed, but not what's under it. 6172 AddToWorklist(oye); 6173 } 6174 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6175 } 6176 } 6177 6178 // fold (zext (truncate x)) -> (and x, mask) 6179 if (N0.getOpcode() == ISD::TRUNCATE) { 6180 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6181 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6182 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6183 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6184 if (NarrowLoad.getNode() != N0.getNode()) { 6185 CombineTo(N0.getNode(), NarrowLoad); 6186 // CombineTo deleted the truncate, if needed, but not what's under it. 6187 AddToWorklist(oye); 6188 } 6189 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6190 } 6191 6192 EVT SrcVT = N0.getOperand(0).getValueType(); 6193 EVT MinVT = N0.getValueType(); 6194 6195 // Try to mask before the extension to avoid having to generate a larger mask, 6196 // possibly over several sub-vectors. 6197 if (SrcVT.bitsLT(VT)) { 6198 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6199 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6200 SDValue Op = N0.getOperand(0); 6201 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6202 AddToWorklist(Op.getNode()); 6203 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6204 } 6205 } 6206 6207 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6208 SDValue Op = N0.getOperand(0); 6209 if (SrcVT.bitsLT(VT)) { 6210 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6211 AddToWorklist(Op.getNode()); 6212 } else if (SrcVT.bitsGT(VT)) { 6213 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6214 AddToWorklist(Op.getNode()); 6215 } 6216 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6217 } 6218 } 6219 6220 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6221 // if either of the casts is not free. 6222 if (N0.getOpcode() == ISD::AND && 6223 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6224 N0.getOperand(1).getOpcode() == ISD::Constant && 6225 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6226 N0.getValueType()) || 6227 !TLI.isZExtFree(N0.getValueType(), VT))) { 6228 SDValue X = N0.getOperand(0).getOperand(0); 6229 if (X.getValueType().bitsLT(VT)) { 6230 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6231 } else if (X.getValueType().bitsGT(VT)) { 6232 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6233 } 6234 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6235 Mask = Mask.zext(VT.getSizeInBits()); 6236 SDLoc DL(N); 6237 return DAG.getNode(ISD::AND, DL, VT, 6238 X, DAG.getConstant(Mask, DL, VT)); 6239 } 6240 6241 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6242 // Only generate vector extloads when 1) they're legal, and 2) they are 6243 // deemed desirable by the target. 6244 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6245 ((!LegalOperations && !VT.isVector() && 6246 !cast<LoadSDNode>(N0)->isVolatile()) || 6247 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6248 bool DoXform = true; 6249 SmallVector<SDNode*, 4> SetCCs; 6250 if (!N0.hasOneUse()) 6251 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6252 if (VT.isVector()) 6253 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6254 if (DoXform) { 6255 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6256 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6257 LN0->getChain(), 6258 LN0->getBasePtr(), N0.getValueType(), 6259 LN0->getMemOperand()); 6260 CombineTo(N, ExtLoad); 6261 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6262 N0.getValueType(), ExtLoad); 6263 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6264 6265 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6266 ISD::ZERO_EXTEND); 6267 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6268 } 6269 } 6270 6271 // fold (zext (load x)) to multiple smaller zextloads. 6272 // Only on illegal but splittable vectors. 6273 if (SDValue ExtLoad = CombineExtLoad(N)) 6274 return ExtLoad; 6275 6276 // fold (zext (and/or/xor (load x), cst)) -> 6277 // (and/or/xor (zextload x), (zext cst)) 6278 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6279 N0.getOpcode() == ISD::XOR) && 6280 isa<LoadSDNode>(N0.getOperand(0)) && 6281 N0.getOperand(1).getOpcode() == ISD::Constant && 6282 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6283 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6284 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6285 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6286 bool DoXform = true; 6287 SmallVector<SDNode*, 4> SetCCs; 6288 if (!N0.hasOneUse()) 6289 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 6290 SetCCs, TLI); 6291 if (DoXform) { 6292 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6293 LN0->getChain(), LN0->getBasePtr(), 6294 LN0->getMemoryVT(), 6295 LN0->getMemOperand()); 6296 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6297 Mask = Mask.zext(VT.getSizeInBits()); 6298 SDLoc DL(N); 6299 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6300 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6301 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6302 SDLoc(N0.getOperand(0)), 6303 N0.getOperand(0).getValueType(), ExtLoad); 6304 CombineTo(N, And); 6305 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6306 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6307 ISD::ZERO_EXTEND); 6308 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6309 } 6310 } 6311 } 6312 6313 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6314 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6315 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6316 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6317 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6318 EVT MemVT = LN0->getMemoryVT(); 6319 if ((!LegalOperations && !LN0->isVolatile()) || 6320 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6321 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6322 LN0->getChain(), 6323 LN0->getBasePtr(), MemVT, 6324 LN0->getMemOperand()); 6325 CombineTo(N, ExtLoad); 6326 CombineTo(N0.getNode(), 6327 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6328 ExtLoad), 6329 ExtLoad.getValue(1)); 6330 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6331 } 6332 } 6333 6334 if (N0.getOpcode() == ISD::SETCC) { 6335 if (!LegalOperations && VT.isVector() && 6336 N0.getValueType().getVectorElementType() == MVT::i1) { 6337 EVT N0VT = N0.getOperand(0).getValueType(); 6338 if (getSetCCResultType(N0VT) == N0.getValueType()) 6339 return SDValue(); 6340 6341 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6342 // Only do this before legalize for now. 6343 EVT EltVT = VT.getVectorElementType(); 6344 SDLoc DL(N); 6345 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 6346 DAG.getConstant(1, DL, EltVT)); 6347 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6348 // We know that the # elements of the results is the same as the 6349 // # elements of the compare (and the # elements of the compare result 6350 // for that matter). Check to see that they are the same size. If so, 6351 // we know that the element size of the sext'd result matches the 6352 // element size of the compare operands. 6353 return DAG.getNode(ISD::AND, DL, VT, 6354 DAG.getSetCC(DL, VT, N0.getOperand(0), 6355 N0.getOperand(1), 6356 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6357 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 6358 OneOps)); 6359 6360 // If the desired elements are smaller or larger than the source 6361 // elements we can use a matching integer vector type and then 6362 // truncate/sign extend 6363 EVT MatchingElementType = 6364 EVT::getIntegerVT(*DAG.getContext(), 6365 N0VT.getScalarType().getSizeInBits()); 6366 EVT MatchingVectorType = 6367 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6368 N0VT.getVectorNumElements()); 6369 SDValue VsetCC = 6370 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6371 N0.getOperand(1), 6372 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6373 return DAG.getNode(ISD::AND, DL, VT, 6374 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6375 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps)); 6376 } 6377 6378 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6379 SDLoc DL(N); 6380 SDValue SCC = 6381 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6382 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6383 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6384 if (SCC.getNode()) return SCC; 6385 } 6386 6387 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6388 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6389 isa<ConstantSDNode>(N0.getOperand(1)) && 6390 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6391 N0.hasOneUse()) { 6392 SDValue ShAmt = N0.getOperand(1); 6393 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6394 if (N0.getOpcode() == ISD::SHL) { 6395 SDValue InnerZExt = N0.getOperand(0); 6396 // If the original shl may be shifting out bits, do not perform this 6397 // transformation. 6398 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6399 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6400 if (ShAmtVal > KnownZeroBits) 6401 return SDValue(); 6402 } 6403 6404 SDLoc DL(N); 6405 6406 // Ensure that the shift amount is wide enough for the shifted value. 6407 if (VT.getSizeInBits() >= 256) 6408 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6409 6410 return DAG.getNode(N0.getOpcode(), DL, VT, 6411 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6412 ShAmt); 6413 } 6414 6415 return SDValue(); 6416 } 6417 6418 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6419 SDValue N0 = N->getOperand(0); 6420 EVT VT = N->getValueType(0); 6421 6422 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6423 LegalOperations)) 6424 return SDValue(Res, 0); 6425 6426 // fold (aext (aext x)) -> (aext x) 6427 // fold (aext (zext x)) -> (zext x) 6428 // fold (aext (sext x)) -> (sext x) 6429 if (N0.getOpcode() == ISD::ANY_EXTEND || 6430 N0.getOpcode() == ISD::ZERO_EXTEND || 6431 N0.getOpcode() == ISD::SIGN_EXTEND) 6432 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6433 6434 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6435 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6436 if (N0.getOpcode() == ISD::TRUNCATE) { 6437 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6438 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6439 if (NarrowLoad.getNode() != N0.getNode()) { 6440 CombineTo(N0.getNode(), NarrowLoad); 6441 // CombineTo deleted the truncate, if needed, but not what's under it. 6442 AddToWorklist(oye); 6443 } 6444 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6445 } 6446 } 6447 6448 // fold (aext (truncate x)) 6449 if (N0.getOpcode() == ISD::TRUNCATE) { 6450 SDValue TruncOp = N0.getOperand(0); 6451 if (TruncOp.getValueType() == VT) 6452 return TruncOp; // x iff x size == zext size. 6453 if (TruncOp.getValueType().bitsGT(VT)) 6454 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6455 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6456 } 6457 6458 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6459 // if the trunc is not free. 6460 if (N0.getOpcode() == ISD::AND && 6461 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6462 N0.getOperand(1).getOpcode() == ISD::Constant && 6463 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6464 N0.getValueType())) { 6465 SDValue X = N0.getOperand(0).getOperand(0); 6466 if (X.getValueType().bitsLT(VT)) { 6467 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6468 } else if (X.getValueType().bitsGT(VT)) { 6469 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6470 } 6471 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6472 Mask = Mask.zext(VT.getSizeInBits()); 6473 SDLoc DL(N); 6474 return DAG.getNode(ISD::AND, DL, VT, 6475 X, DAG.getConstant(Mask, DL, VT)); 6476 } 6477 6478 // fold (aext (load x)) -> (aext (truncate (extload x))) 6479 // None of the supported targets knows how to perform load and any_ext 6480 // on vectors in one instruction. We only perform this transformation on 6481 // scalars. 6482 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6483 ISD::isUNINDEXEDLoad(N0.getNode()) && 6484 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6485 bool DoXform = true; 6486 SmallVector<SDNode*, 4> SetCCs; 6487 if (!N0.hasOneUse()) 6488 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6489 if (DoXform) { 6490 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6491 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6492 LN0->getChain(), 6493 LN0->getBasePtr(), N0.getValueType(), 6494 LN0->getMemOperand()); 6495 CombineTo(N, ExtLoad); 6496 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6497 N0.getValueType(), ExtLoad); 6498 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6499 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6500 ISD::ANY_EXTEND); 6501 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6502 } 6503 } 6504 6505 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6506 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6507 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6508 if (N0.getOpcode() == ISD::LOAD && 6509 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6510 N0.hasOneUse()) { 6511 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6512 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6513 EVT MemVT = LN0->getMemoryVT(); 6514 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6515 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6516 VT, LN0->getChain(), LN0->getBasePtr(), 6517 MemVT, LN0->getMemOperand()); 6518 CombineTo(N, ExtLoad); 6519 CombineTo(N0.getNode(), 6520 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6521 N0.getValueType(), ExtLoad), 6522 ExtLoad.getValue(1)); 6523 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6524 } 6525 } 6526 6527 if (N0.getOpcode() == ISD::SETCC) { 6528 // For vectors: 6529 // aext(setcc) -> vsetcc 6530 // aext(setcc) -> truncate(vsetcc) 6531 // aext(setcc) -> aext(vsetcc) 6532 // Only do this before legalize for now. 6533 if (VT.isVector() && !LegalOperations) { 6534 EVT N0VT = N0.getOperand(0).getValueType(); 6535 // We know that the # elements of the results is the same as the 6536 // # elements of the compare (and the # elements of the compare result 6537 // for that matter). Check to see that they are the same size. If so, 6538 // we know that the element size of the sext'd result matches the 6539 // element size of the compare operands. 6540 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6541 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6542 N0.getOperand(1), 6543 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6544 // If the desired elements are smaller or larger than the source 6545 // elements we can use a matching integer vector type and then 6546 // truncate/any extend 6547 else { 6548 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6549 SDValue VsetCC = 6550 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6551 N0.getOperand(1), 6552 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6553 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6554 } 6555 } 6556 6557 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6558 SDLoc DL(N); 6559 SDValue SCC = 6560 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6561 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6562 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6563 if (SCC.getNode()) 6564 return SCC; 6565 } 6566 6567 return SDValue(); 6568 } 6569 6570 /// See if the specified operand can be simplified with the knowledge that only 6571 /// the bits specified by Mask are used. If so, return the simpler operand, 6572 /// otherwise return a null SDValue. 6573 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6574 switch (V.getOpcode()) { 6575 default: break; 6576 case ISD::Constant: { 6577 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6578 assert(CV && "Const value should be ConstSDNode."); 6579 const APInt &CVal = CV->getAPIntValue(); 6580 APInt NewVal = CVal & Mask; 6581 if (NewVal != CVal) 6582 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6583 break; 6584 } 6585 case ISD::OR: 6586 case ISD::XOR: 6587 // If the LHS or RHS don't contribute bits to the or, drop them. 6588 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6589 return V.getOperand(1); 6590 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6591 return V.getOperand(0); 6592 break; 6593 case ISD::SRL: 6594 // Only look at single-use SRLs. 6595 if (!V.getNode()->hasOneUse()) 6596 break; 6597 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6598 // See if we can recursively simplify the LHS. 6599 unsigned Amt = RHSC->getZExtValue(); 6600 6601 // Watch out for shift count overflow though. 6602 if (Amt >= Mask.getBitWidth()) break; 6603 APInt NewMask = Mask << Amt; 6604 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6605 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6606 SimplifyLHS, V.getOperand(1)); 6607 } 6608 } 6609 return SDValue(); 6610 } 6611 6612 /// If the result of a wider load is shifted to right of N bits and then 6613 /// truncated to a narrower type and where N is a multiple of number of bits of 6614 /// the narrower type, transform it to a narrower load from address + N / num of 6615 /// bits of new type. If the result is to be extended, also fold the extension 6616 /// to form a extending load. 6617 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6618 unsigned Opc = N->getOpcode(); 6619 6620 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6621 SDValue N0 = N->getOperand(0); 6622 EVT VT = N->getValueType(0); 6623 EVT ExtVT = VT; 6624 6625 // This transformation isn't valid for vector loads. 6626 if (VT.isVector()) 6627 return SDValue(); 6628 6629 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6630 // extended to VT. 6631 if (Opc == ISD::SIGN_EXTEND_INREG) { 6632 ExtType = ISD::SEXTLOAD; 6633 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6634 } else if (Opc == ISD::SRL) { 6635 // Another special-case: SRL is basically zero-extending a narrower value. 6636 ExtType = ISD::ZEXTLOAD; 6637 N0 = SDValue(N, 0); 6638 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6639 if (!N01) return SDValue(); 6640 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6641 VT.getSizeInBits() - N01->getZExtValue()); 6642 } 6643 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6644 return SDValue(); 6645 6646 unsigned EVTBits = ExtVT.getSizeInBits(); 6647 6648 // Do not generate loads of non-round integer types since these can 6649 // be expensive (and would be wrong if the type is not byte sized). 6650 if (!ExtVT.isRound()) 6651 return SDValue(); 6652 6653 unsigned ShAmt = 0; 6654 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6655 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6656 ShAmt = N01->getZExtValue(); 6657 // Is the shift amount a multiple of size of VT? 6658 if ((ShAmt & (EVTBits-1)) == 0) { 6659 N0 = N0.getOperand(0); 6660 // Is the load width a multiple of size of VT? 6661 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6662 return SDValue(); 6663 } 6664 6665 // At this point, we must have a load or else we can't do the transform. 6666 if (!isa<LoadSDNode>(N0)) return SDValue(); 6667 6668 // Because a SRL must be assumed to *need* to zero-extend the high bits 6669 // (as opposed to anyext the high bits), we can't combine the zextload 6670 // lowering of SRL and an sextload. 6671 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6672 return SDValue(); 6673 6674 // If the shift amount is larger than the input type then we're not 6675 // accessing any of the loaded bytes. If the load was a zextload/extload 6676 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6677 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6678 return SDValue(); 6679 } 6680 } 6681 6682 // If the load is shifted left (and the result isn't shifted back right), 6683 // we can fold the truncate through the shift. 6684 unsigned ShLeftAmt = 0; 6685 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6686 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6687 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6688 ShLeftAmt = N01->getZExtValue(); 6689 N0 = N0.getOperand(0); 6690 } 6691 } 6692 6693 // If we haven't found a load, we can't narrow it. Don't transform one with 6694 // multiple uses, this would require adding a new load. 6695 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6696 return SDValue(); 6697 6698 // Don't change the width of a volatile load. 6699 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6700 if (LN0->isVolatile()) 6701 return SDValue(); 6702 6703 // Verify that we are actually reducing a load width here. 6704 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6705 return SDValue(); 6706 6707 // For the transform to be legal, the load must produce only two values 6708 // (the value loaded and the chain). Don't transform a pre-increment 6709 // load, for example, which produces an extra value. Otherwise the 6710 // transformation is not equivalent, and the downstream logic to replace 6711 // uses gets things wrong. 6712 if (LN0->getNumValues() > 2) 6713 return SDValue(); 6714 6715 // If the load that we're shrinking is an extload and we're not just 6716 // discarding the extension we can't simply shrink the load. Bail. 6717 // TODO: It would be possible to merge the extensions in some cases. 6718 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6719 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6720 return SDValue(); 6721 6722 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6723 return SDValue(); 6724 6725 EVT PtrType = N0.getOperand(1).getValueType(); 6726 6727 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6728 // It's not possible to generate a constant of extended or untyped type. 6729 return SDValue(); 6730 6731 // For big endian targets, we need to adjust the offset to the pointer to 6732 // load the correct bytes. 6733 if (DAG.getDataLayout().isBigEndian()) { 6734 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6735 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6736 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6737 } 6738 6739 uint64_t PtrOff = ShAmt / 8; 6740 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6741 SDLoc DL(LN0); 6742 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6743 PtrType, LN0->getBasePtr(), 6744 DAG.getConstant(PtrOff, DL, PtrType)); 6745 AddToWorklist(NewPtr.getNode()); 6746 6747 SDValue Load; 6748 if (ExtType == ISD::NON_EXTLOAD) 6749 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6750 LN0->getPointerInfo().getWithOffset(PtrOff), 6751 LN0->isVolatile(), LN0->isNonTemporal(), 6752 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6753 else 6754 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6755 LN0->getPointerInfo().getWithOffset(PtrOff), 6756 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6757 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6758 6759 // Replace the old load's chain with the new load's chain. 6760 WorklistRemover DeadNodes(*this); 6761 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6762 6763 // Shift the result left, if we've swallowed a left shift. 6764 SDValue Result = Load; 6765 if (ShLeftAmt != 0) { 6766 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6767 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6768 ShImmTy = VT; 6769 // If the shift amount is as large as the result size (but, presumably, 6770 // no larger than the source) then the useful bits of the result are 6771 // zero; we can't simply return the shortened shift, because the result 6772 // of that operation is undefined. 6773 SDLoc DL(N0); 6774 if (ShLeftAmt >= VT.getSizeInBits()) 6775 Result = DAG.getConstant(0, DL, VT); 6776 else 6777 Result = DAG.getNode(ISD::SHL, DL, VT, 6778 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6779 } 6780 6781 // Return the new loaded value. 6782 return Result; 6783 } 6784 6785 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6786 SDValue N0 = N->getOperand(0); 6787 SDValue N1 = N->getOperand(1); 6788 EVT VT = N->getValueType(0); 6789 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6790 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6791 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6792 6793 // fold (sext_in_reg c1) -> c1 6794 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 6795 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6796 6797 // If the input is already sign extended, just drop the extension. 6798 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6799 return N0; 6800 6801 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6802 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6803 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6804 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6805 N0.getOperand(0), N1); 6806 6807 // fold (sext_in_reg (sext x)) -> (sext x) 6808 // fold (sext_in_reg (aext x)) -> (sext x) 6809 // if x is small enough. 6810 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6811 SDValue N00 = N0.getOperand(0); 6812 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6813 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6814 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6815 } 6816 6817 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6818 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6819 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6820 6821 // fold operands of sext_in_reg based on knowledge that the top bits are not 6822 // demanded. 6823 if (SimplifyDemandedBits(SDValue(N, 0))) 6824 return SDValue(N, 0); 6825 6826 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6827 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6828 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6829 return NarrowLoad; 6830 6831 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6832 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6833 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6834 if (N0.getOpcode() == ISD::SRL) { 6835 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6836 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6837 // We can turn this into an SRA iff the input to the SRL is already sign 6838 // extended enough. 6839 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6840 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6841 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6842 N0.getOperand(0), N0.getOperand(1)); 6843 } 6844 } 6845 6846 // fold (sext_inreg (extload x)) -> (sextload x) 6847 if (ISD::isEXTLoad(N0.getNode()) && 6848 ISD::isUNINDEXEDLoad(N0.getNode()) && 6849 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6850 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6851 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6852 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6853 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6854 LN0->getChain(), 6855 LN0->getBasePtr(), EVT, 6856 LN0->getMemOperand()); 6857 CombineTo(N, ExtLoad); 6858 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6859 AddToWorklist(ExtLoad.getNode()); 6860 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6861 } 6862 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6863 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6864 N0.hasOneUse() && 6865 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6866 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6867 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6868 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6869 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6870 LN0->getChain(), 6871 LN0->getBasePtr(), EVT, 6872 LN0->getMemOperand()); 6873 CombineTo(N, ExtLoad); 6874 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6875 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6876 } 6877 6878 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6879 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6880 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6881 N0.getOperand(1), false); 6882 if (BSwap.getNode()) 6883 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6884 BSwap, N1); 6885 } 6886 6887 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 6888 // into a build_vector. 6889 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6890 SmallVector<SDValue, 8> Elts; 6891 unsigned NumElts = N0->getNumOperands(); 6892 unsigned ShAmt = VTBits - EVTBits; 6893 6894 for (unsigned i = 0; i != NumElts; ++i) { 6895 SDValue Op = N0->getOperand(i); 6896 if (Op->getOpcode() == ISD::UNDEF) { 6897 Elts.push_back(Op); 6898 continue; 6899 } 6900 6901 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 6902 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 6903 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 6904 SDLoc(Op), Op.getValueType())); 6905 } 6906 6907 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts); 6908 } 6909 6910 return SDValue(); 6911 } 6912 6913 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 6914 SDValue N0 = N->getOperand(0); 6915 EVT VT = N->getValueType(0); 6916 6917 if (N0.getOpcode() == ISD::UNDEF) 6918 return DAG.getUNDEF(VT); 6919 6920 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6921 LegalOperations)) 6922 return SDValue(Res, 0); 6923 6924 return SDValue(); 6925 } 6926 6927 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6928 SDValue N0 = N->getOperand(0); 6929 EVT VT = N->getValueType(0); 6930 bool isLE = DAG.getDataLayout().isLittleEndian(); 6931 6932 // noop truncate 6933 if (N0.getValueType() == N->getValueType(0)) 6934 return N0; 6935 // fold (truncate c1) -> c1 6936 if (isConstantIntBuildVectorOrConstantInt(N0)) 6937 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6938 // fold (truncate (truncate x)) -> (truncate x) 6939 if (N0.getOpcode() == ISD::TRUNCATE) 6940 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6941 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6942 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6943 N0.getOpcode() == ISD::SIGN_EXTEND || 6944 N0.getOpcode() == ISD::ANY_EXTEND) { 6945 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6946 // if the source is smaller than the dest, we still need an extend 6947 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6948 N0.getOperand(0)); 6949 if (N0.getOperand(0).getValueType().bitsGT(VT)) 6950 // if the source is larger than the dest, than we just need the truncate 6951 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6952 // if the source and dest are the same type, we can drop both the extend 6953 // and the truncate. 6954 return N0.getOperand(0); 6955 } 6956 6957 // Fold extract-and-trunc into a narrow extract. For example: 6958 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 6959 // i32 y = TRUNCATE(i64 x) 6960 // -- becomes -- 6961 // v16i8 b = BITCAST (v2i64 val) 6962 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 6963 // 6964 // Note: We only run this optimization after type legalization (which often 6965 // creates this pattern) and before operation legalization after which 6966 // we need to be more careful about the vector instructions that we generate. 6967 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6968 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 6969 6970 EVT VecTy = N0.getOperand(0).getValueType(); 6971 EVT ExTy = N0.getValueType(); 6972 EVT TrTy = N->getValueType(0); 6973 6974 unsigned NumElem = VecTy.getVectorNumElements(); 6975 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 6976 6977 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 6978 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 6979 6980 SDValue EltNo = N0->getOperand(1); 6981 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 6982 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6983 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 6984 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6985 6986 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6987 NVT, N0.getOperand(0)); 6988 6989 SDLoc DL(N); 6990 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6991 DL, TrTy, V, 6992 DAG.getConstant(Index, DL, IndexTy)); 6993 } 6994 } 6995 6996 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 6997 if (N0.getOpcode() == ISD::SELECT) { 6998 EVT SrcVT = N0.getValueType(); 6999 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7000 TLI.isTruncateFree(SrcVT, VT)) { 7001 SDLoc SL(N0); 7002 SDValue Cond = N0.getOperand(0); 7003 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7004 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7005 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7006 } 7007 } 7008 7009 // Fold a series of buildvector, bitcast, and truncate if possible. 7010 // For example fold 7011 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7012 // (2xi32 (buildvector x, y)). 7013 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7014 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7015 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7016 N0.getOperand(0).hasOneUse()) { 7017 7018 SDValue BuildVect = N0.getOperand(0); 7019 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7020 EVT TruncVecEltTy = VT.getVectorElementType(); 7021 7022 // Check that the element types match. 7023 if (BuildVectEltTy == TruncVecEltTy) { 7024 // Now we only need to compute the offset of the truncated elements. 7025 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7026 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7027 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7028 7029 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7030 "Invalid number of elements"); 7031 7032 SmallVector<SDValue, 8> Opnds; 7033 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7034 Opnds.push_back(BuildVect.getOperand(i)); 7035 7036 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 7037 } 7038 } 7039 7040 // See if we can simplify the input to this truncate through knowledge that 7041 // only the low bits are being used. 7042 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7043 // Currently we only perform this optimization on scalars because vectors 7044 // may have different active low bits. 7045 if (!VT.isVector()) { 7046 SDValue Shorter = 7047 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7048 VT.getSizeInBits())); 7049 if (Shorter.getNode()) 7050 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7051 } 7052 // fold (truncate (load x)) -> (smaller load x) 7053 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7054 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7055 if (SDValue Reduced = ReduceLoadWidth(N)) 7056 return Reduced; 7057 7058 // Handle the case where the load remains an extending load even 7059 // after truncation. 7060 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7061 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7062 if (!LN0->isVolatile() && 7063 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7064 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7065 VT, LN0->getChain(), LN0->getBasePtr(), 7066 LN0->getMemoryVT(), 7067 LN0->getMemOperand()); 7068 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7069 return NewLoad; 7070 } 7071 } 7072 } 7073 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7074 // where ... are all 'undef'. 7075 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7076 SmallVector<EVT, 8> VTs; 7077 SDValue V; 7078 unsigned Idx = 0; 7079 unsigned NumDefs = 0; 7080 7081 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7082 SDValue X = N0.getOperand(i); 7083 if (X.getOpcode() != ISD::UNDEF) { 7084 V = X; 7085 Idx = i; 7086 NumDefs++; 7087 } 7088 // Stop if more than one members are non-undef. 7089 if (NumDefs > 1) 7090 break; 7091 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7092 VT.getVectorElementType(), 7093 X.getValueType().getVectorNumElements())); 7094 } 7095 7096 if (NumDefs == 0) 7097 return DAG.getUNDEF(VT); 7098 7099 if (NumDefs == 1) { 7100 assert(V.getNode() && "The single defined operand is empty!"); 7101 SmallVector<SDValue, 8> Opnds; 7102 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7103 if (i != Idx) { 7104 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7105 continue; 7106 } 7107 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7108 AddToWorklist(NV.getNode()); 7109 Opnds.push_back(NV); 7110 } 7111 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7112 } 7113 } 7114 7115 // Simplify the operands using demanded-bits information. 7116 if (!VT.isVector() && 7117 SimplifyDemandedBits(SDValue(N, 0))) 7118 return SDValue(N, 0); 7119 7120 return SDValue(); 7121 } 7122 7123 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7124 SDValue Elt = N->getOperand(i); 7125 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7126 return Elt.getNode(); 7127 return Elt.getOperand(Elt.getResNo()).getNode(); 7128 } 7129 7130 /// build_pair (load, load) -> load 7131 /// if load locations are consecutive. 7132 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7133 assert(N->getOpcode() == ISD::BUILD_PAIR); 7134 7135 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7136 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7137 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7138 LD1->getAddressSpace() != LD2->getAddressSpace()) 7139 return SDValue(); 7140 EVT LD1VT = LD1->getValueType(0); 7141 7142 if (ISD::isNON_EXTLoad(LD2) && 7143 LD2->hasOneUse() && 7144 // If both are volatile this would reduce the number of volatile loads. 7145 // If one is volatile it might be ok, but play conservative and bail out. 7146 !LD1->isVolatile() && 7147 !LD2->isVolatile() && 7148 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 7149 unsigned Align = LD1->getAlignment(); 7150 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7151 VT.getTypeForEVT(*DAG.getContext())); 7152 7153 if (NewAlign <= Align && 7154 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7155 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7156 LD1->getBasePtr(), LD1->getPointerInfo(), 7157 false, false, false, Align); 7158 } 7159 7160 return SDValue(); 7161 } 7162 7163 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7164 SDValue N0 = N->getOperand(0); 7165 EVT VT = N->getValueType(0); 7166 7167 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7168 // Only do this before legalize, since afterward the target may be depending 7169 // on the bitconvert. 7170 // First check to see if this is all constant. 7171 if (!LegalTypes && 7172 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7173 VT.isVector()) { 7174 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7175 7176 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7177 assert(!DestEltVT.isVector() && 7178 "Element type of vector ValueType must not be vector!"); 7179 if (isSimple) 7180 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7181 } 7182 7183 // If the input is a constant, let getNode fold it. 7184 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7185 // If we can't allow illegal operations, we need to check that this is just 7186 // a fp -> int or int -> conversion and that the resulting operation will 7187 // be legal. 7188 if (!LegalOperations || 7189 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7190 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7191 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7192 TLI.isOperationLegal(ISD::Constant, VT))) 7193 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7194 } 7195 7196 // (conv (conv x, t1), t2) -> (conv x, t2) 7197 if (N0.getOpcode() == ISD::BITCAST) 7198 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7199 N0.getOperand(0)); 7200 7201 // fold (conv (load x)) -> (load (conv*)x) 7202 // If the resultant load doesn't need a higher alignment than the original! 7203 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7204 // Do not change the width of a volatile load. 7205 !cast<LoadSDNode>(N0)->isVolatile() && 7206 // Do not remove the cast if the types differ in endian layout. 7207 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7208 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7209 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7210 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7211 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7212 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 7213 VT.getTypeForEVT(*DAG.getContext())); 7214 unsigned OrigAlign = LN0->getAlignment(); 7215 7216 if (Align <= OrigAlign) { 7217 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7218 LN0->getBasePtr(), LN0->getPointerInfo(), 7219 LN0->isVolatile(), LN0->isNonTemporal(), 7220 LN0->isInvariant(), OrigAlign, 7221 LN0->getAAInfo()); 7222 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7223 return Load; 7224 } 7225 } 7226 7227 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7228 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7229 // This often reduces constant pool loads. 7230 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7231 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7232 N0.getNode()->hasOneUse() && VT.isInteger() && 7233 !VT.isVector() && !N0.getValueType().isVector()) { 7234 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7235 N0.getOperand(0)); 7236 AddToWorklist(NewConv.getNode()); 7237 7238 SDLoc DL(N); 7239 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7240 if (N0.getOpcode() == ISD::FNEG) 7241 return DAG.getNode(ISD::XOR, DL, VT, 7242 NewConv, DAG.getConstant(SignBit, DL, VT)); 7243 assert(N0.getOpcode() == ISD::FABS); 7244 return DAG.getNode(ISD::AND, DL, VT, 7245 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7246 } 7247 7248 // fold (bitconvert (fcopysign cst, x)) -> 7249 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7250 // Note that we don't handle (copysign x, cst) because this can always be 7251 // folded to an fneg or fabs. 7252 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7253 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7254 VT.isInteger() && !VT.isVector()) { 7255 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7256 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7257 if (isTypeLegal(IntXVT)) { 7258 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7259 IntXVT, N0.getOperand(1)); 7260 AddToWorklist(X.getNode()); 7261 7262 // If X has a different width than the result/lhs, sext it or truncate it. 7263 unsigned VTWidth = VT.getSizeInBits(); 7264 if (OrigXWidth < VTWidth) { 7265 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7266 AddToWorklist(X.getNode()); 7267 } else if (OrigXWidth > VTWidth) { 7268 // To get the sign bit in the right place, we have to shift it right 7269 // before truncating. 7270 SDLoc DL(X); 7271 X = DAG.getNode(ISD::SRL, DL, 7272 X.getValueType(), X, 7273 DAG.getConstant(OrigXWidth-VTWidth, DL, 7274 X.getValueType())); 7275 AddToWorklist(X.getNode()); 7276 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7277 AddToWorklist(X.getNode()); 7278 } 7279 7280 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7281 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7282 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7283 AddToWorklist(X.getNode()); 7284 7285 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7286 VT, N0.getOperand(0)); 7287 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7288 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7289 AddToWorklist(Cst.getNode()); 7290 7291 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7292 } 7293 } 7294 7295 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7296 if (N0.getOpcode() == ISD::BUILD_PAIR) 7297 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7298 return CombineLD; 7299 7300 // Remove double bitcasts from shuffles - this is often a legacy of 7301 // XformToShuffleWithZero being used to combine bitmaskings (of 7302 // float vectors bitcast to integer vectors) into shuffles. 7303 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7304 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7305 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7306 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7307 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7308 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7309 7310 // If operands are a bitcast, peek through if it casts the original VT. 7311 // If operands are a constant, just bitcast back to original VT. 7312 auto PeekThroughBitcast = [&](SDValue Op) { 7313 if (Op.getOpcode() == ISD::BITCAST && 7314 Op.getOperand(0).getValueType() == VT) 7315 return SDValue(Op.getOperand(0)); 7316 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7317 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7318 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7319 return SDValue(); 7320 }; 7321 7322 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7323 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7324 if (!(SV0 && SV1)) 7325 return SDValue(); 7326 7327 int MaskScale = 7328 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7329 SmallVector<int, 8> NewMask; 7330 for (int M : SVN->getMask()) 7331 for (int i = 0; i != MaskScale; ++i) 7332 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7333 7334 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7335 if (!LegalMask) { 7336 std::swap(SV0, SV1); 7337 ShuffleVectorSDNode::commuteMask(NewMask); 7338 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7339 } 7340 7341 if (LegalMask) 7342 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7343 } 7344 7345 return SDValue(); 7346 } 7347 7348 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7349 EVT VT = N->getValueType(0); 7350 return CombineConsecutiveLoads(N, VT); 7351 } 7352 7353 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7354 /// operands. DstEltVT indicates the destination element value type. 7355 SDValue DAGCombiner:: 7356 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7357 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7358 7359 // If this is already the right type, we're done. 7360 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7361 7362 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7363 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7364 7365 // If this is a conversion of N elements of one type to N elements of another 7366 // type, convert each element. This handles FP<->INT cases. 7367 if (SrcBitSize == DstBitSize) { 7368 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7369 BV->getValueType(0).getVectorNumElements()); 7370 7371 // Due to the FP element handling below calling this routine recursively, 7372 // we can end up with a scalar-to-vector node here. 7373 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7374 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7375 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7376 DstEltVT, BV->getOperand(0))); 7377 7378 SmallVector<SDValue, 8> Ops; 7379 for (SDValue Op : BV->op_values()) { 7380 // If the vector element type is not legal, the BUILD_VECTOR operands 7381 // are promoted and implicitly truncated. Make that explicit here. 7382 if (Op.getValueType() != SrcEltVT) 7383 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7384 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7385 DstEltVT, Op)); 7386 AddToWorklist(Ops.back().getNode()); 7387 } 7388 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7389 } 7390 7391 // Otherwise, we're growing or shrinking the elements. To avoid having to 7392 // handle annoying details of growing/shrinking FP values, we convert them to 7393 // int first. 7394 if (SrcEltVT.isFloatingPoint()) { 7395 // Convert the input float vector to a int vector where the elements are the 7396 // same sizes. 7397 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7398 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7399 SrcEltVT = IntVT; 7400 } 7401 7402 // Now we know the input is an integer vector. If the output is a FP type, 7403 // convert to integer first, then to FP of the right size. 7404 if (DstEltVT.isFloatingPoint()) { 7405 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7406 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7407 7408 // Next, convert to FP elements of the same size. 7409 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7410 } 7411 7412 SDLoc DL(BV); 7413 7414 // Okay, we know the src/dst types are both integers of differing types. 7415 // Handling growing first. 7416 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7417 if (SrcBitSize < DstBitSize) { 7418 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7419 7420 SmallVector<SDValue, 8> Ops; 7421 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7422 i += NumInputsPerOutput) { 7423 bool isLE = DAG.getDataLayout().isLittleEndian(); 7424 APInt NewBits = APInt(DstBitSize, 0); 7425 bool EltIsUndef = true; 7426 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7427 // Shift the previously computed bits over. 7428 NewBits <<= SrcBitSize; 7429 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7430 if (Op.getOpcode() == ISD::UNDEF) continue; 7431 EltIsUndef = false; 7432 7433 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7434 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7435 } 7436 7437 if (EltIsUndef) 7438 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7439 else 7440 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7441 } 7442 7443 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7444 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7445 } 7446 7447 // Finally, this must be the case where we are shrinking elements: each input 7448 // turns into multiple outputs. 7449 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7450 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7451 NumOutputsPerInput*BV->getNumOperands()); 7452 SmallVector<SDValue, 8> Ops; 7453 7454 for (const SDValue &Op : BV->op_values()) { 7455 if (Op.getOpcode() == ISD::UNDEF) { 7456 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7457 continue; 7458 } 7459 7460 APInt OpVal = cast<ConstantSDNode>(Op)-> 7461 getAPIntValue().zextOrTrunc(SrcBitSize); 7462 7463 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7464 APInt ThisVal = OpVal.trunc(DstBitSize); 7465 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7466 OpVal = OpVal.lshr(DstBitSize); 7467 } 7468 7469 // For big endian targets, swap the order of the pieces of each element. 7470 if (DAG.getDataLayout().isBigEndian()) 7471 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7472 } 7473 7474 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7475 } 7476 7477 /// Try to perform FMA combining on a given FADD node. 7478 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7479 SDValue N0 = N->getOperand(0); 7480 SDValue N1 = N->getOperand(1); 7481 EVT VT = N->getValueType(0); 7482 SDLoc SL(N); 7483 7484 const TargetOptions &Options = DAG.getTarget().Options; 7485 bool AllowFusion = 7486 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7487 7488 // Floating-point multiply-add with intermediate rounding. 7489 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7490 7491 // Floating-point multiply-add without intermediate rounding. 7492 bool HasFMA = 7493 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7494 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7495 7496 // No valid opcode, do not combine. 7497 if (!HasFMAD && !HasFMA) 7498 return SDValue(); 7499 7500 // Always prefer FMAD to FMA for precision. 7501 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7502 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7503 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7504 7505 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7506 // prefer to fold the multiply with fewer uses. 7507 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7508 N1.getOpcode() == ISD::FMUL) { 7509 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7510 std::swap(N0, N1); 7511 } 7512 7513 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7514 if (N0.getOpcode() == ISD::FMUL && 7515 (Aggressive || N0->hasOneUse())) { 7516 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7517 N0.getOperand(0), N0.getOperand(1), N1); 7518 } 7519 7520 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7521 // Note: Commutes FADD operands. 7522 if (N1.getOpcode() == ISD::FMUL && 7523 (Aggressive || N1->hasOneUse())) { 7524 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7525 N1.getOperand(0), N1.getOperand(1), N0); 7526 } 7527 7528 // Look through FP_EXTEND nodes to do more combining. 7529 if (AllowFusion && LookThroughFPExt) { 7530 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7531 if (N0.getOpcode() == ISD::FP_EXTEND) { 7532 SDValue N00 = N0.getOperand(0); 7533 if (N00.getOpcode() == ISD::FMUL) 7534 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7535 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7536 N00.getOperand(0)), 7537 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7538 N00.getOperand(1)), N1); 7539 } 7540 7541 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7542 // Note: Commutes FADD operands. 7543 if (N1.getOpcode() == ISD::FP_EXTEND) { 7544 SDValue N10 = N1.getOperand(0); 7545 if (N10.getOpcode() == ISD::FMUL) 7546 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7547 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7548 N10.getOperand(0)), 7549 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7550 N10.getOperand(1)), N0); 7551 } 7552 } 7553 7554 // More folding opportunities when target permits. 7555 if ((AllowFusion || HasFMAD) && Aggressive) { 7556 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7557 if (N0.getOpcode() == PreferredFusedOpcode && 7558 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7559 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7560 N0.getOperand(0), N0.getOperand(1), 7561 DAG.getNode(PreferredFusedOpcode, SL, VT, 7562 N0.getOperand(2).getOperand(0), 7563 N0.getOperand(2).getOperand(1), 7564 N1)); 7565 } 7566 7567 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7568 if (N1->getOpcode() == PreferredFusedOpcode && 7569 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7570 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7571 N1.getOperand(0), N1.getOperand(1), 7572 DAG.getNode(PreferredFusedOpcode, SL, VT, 7573 N1.getOperand(2).getOperand(0), 7574 N1.getOperand(2).getOperand(1), 7575 N0)); 7576 } 7577 7578 if (AllowFusion && LookThroughFPExt) { 7579 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7580 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7581 auto FoldFAddFMAFPExtFMul = [&] ( 7582 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7583 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7584 DAG.getNode(PreferredFusedOpcode, SL, VT, 7585 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7586 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7587 Z)); 7588 }; 7589 if (N0.getOpcode() == PreferredFusedOpcode) { 7590 SDValue N02 = N0.getOperand(2); 7591 if (N02.getOpcode() == ISD::FP_EXTEND) { 7592 SDValue N020 = N02.getOperand(0); 7593 if (N020.getOpcode() == ISD::FMUL) 7594 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7595 N020.getOperand(0), N020.getOperand(1), 7596 N1); 7597 } 7598 } 7599 7600 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7601 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7602 // FIXME: This turns two single-precision and one double-precision 7603 // operation into two double-precision operations, which might not be 7604 // interesting for all targets, especially GPUs. 7605 auto FoldFAddFPExtFMAFMul = [&] ( 7606 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7607 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7608 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7609 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7610 DAG.getNode(PreferredFusedOpcode, SL, VT, 7611 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7612 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7613 Z)); 7614 }; 7615 if (N0.getOpcode() == ISD::FP_EXTEND) { 7616 SDValue N00 = N0.getOperand(0); 7617 if (N00.getOpcode() == PreferredFusedOpcode) { 7618 SDValue N002 = N00.getOperand(2); 7619 if (N002.getOpcode() == ISD::FMUL) 7620 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7621 N002.getOperand(0), N002.getOperand(1), 7622 N1); 7623 } 7624 } 7625 7626 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7627 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7628 if (N1.getOpcode() == PreferredFusedOpcode) { 7629 SDValue N12 = N1.getOperand(2); 7630 if (N12.getOpcode() == ISD::FP_EXTEND) { 7631 SDValue N120 = N12.getOperand(0); 7632 if (N120.getOpcode() == ISD::FMUL) 7633 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7634 N120.getOperand(0), N120.getOperand(1), 7635 N0); 7636 } 7637 } 7638 7639 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7640 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7641 // FIXME: This turns two single-precision and one double-precision 7642 // operation into two double-precision operations, which might not be 7643 // interesting for all targets, especially GPUs. 7644 if (N1.getOpcode() == ISD::FP_EXTEND) { 7645 SDValue N10 = N1.getOperand(0); 7646 if (N10.getOpcode() == PreferredFusedOpcode) { 7647 SDValue N102 = N10.getOperand(2); 7648 if (N102.getOpcode() == ISD::FMUL) 7649 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7650 N102.getOperand(0), N102.getOperand(1), 7651 N0); 7652 } 7653 } 7654 } 7655 } 7656 7657 return SDValue(); 7658 } 7659 7660 /// Try to perform FMA combining on a given FSUB node. 7661 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7662 SDValue N0 = N->getOperand(0); 7663 SDValue N1 = N->getOperand(1); 7664 EVT VT = N->getValueType(0); 7665 SDLoc SL(N); 7666 7667 const TargetOptions &Options = DAG.getTarget().Options; 7668 bool AllowFusion = 7669 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7670 7671 // Floating-point multiply-add with intermediate rounding. 7672 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7673 7674 // Floating-point multiply-add without intermediate rounding. 7675 bool HasFMA = 7676 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7677 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7678 7679 // No valid opcode, do not combine. 7680 if (!HasFMAD && !HasFMA) 7681 return SDValue(); 7682 7683 // Always prefer FMAD to FMA for precision. 7684 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7685 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7686 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7687 7688 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7689 if (N0.getOpcode() == ISD::FMUL && 7690 (Aggressive || N0->hasOneUse())) { 7691 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7692 N0.getOperand(0), N0.getOperand(1), 7693 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7694 } 7695 7696 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7697 // Note: Commutes FSUB operands. 7698 if (N1.getOpcode() == ISD::FMUL && 7699 (Aggressive || N1->hasOneUse())) 7700 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7701 DAG.getNode(ISD::FNEG, SL, VT, 7702 N1.getOperand(0)), 7703 N1.getOperand(1), N0); 7704 7705 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7706 if (N0.getOpcode() == ISD::FNEG && 7707 N0.getOperand(0).getOpcode() == ISD::FMUL && 7708 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7709 SDValue N00 = N0.getOperand(0).getOperand(0); 7710 SDValue N01 = N0.getOperand(0).getOperand(1); 7711 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7712 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7713 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7714 } 7715 7716 // Look through FP_EXTEND nodes to do more combining. 7717 if (AllowFusion && LookThroughFPExt) { 7718 // fold (fsub (fpext (fmul x, y)), z) 7719 // -> (fma (fpext x), (fpext y), (fneg z)) 7720 if (N0.getOpcode() == ISD::FP_EXTEND) { 7721 SDValue N00 = N0.getOperand(0); 7722 if (N00.getOpcode() == ISD::FMUL) 7723 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7724 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7725 N00.getOperand(0)), 7726 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7727 N00.getOperand(1)), 7728 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7729 } 7730 7731 // fold (fsub x, (fpext (fmul y, z))) 7732 // -> (fma (fneg (fpext y)), (fpext z), x) 7733 // Note: Commutes FSUB operands. 7734 if (N1.getOpcode() == ISD::FP_EXTEND) { 7735 SDValue N10 = N1.getOperand(0); 7736 if (N10.getOpcode() == ISD::FMUL) 7737 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7738 DAG.getNode(ISD::FNEG, SL, VT, 7739 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7740 N10.getOperand(0))), 7741 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7742 N10.getOperand(1)), 7743 N0); 7744 } 7745 7746 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7747 // -> (fneg (fma (fpext x), (fpext y), z)) 7748 // Note: This could be removed with appropriate canonicalization of the 7749 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7750 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7751 // from implementing the canonicalization in visitFSUB. 7752 if (N0.getOpcode() == ISD::FP_EXTEND) { 7753 SDValue N00 = N0.getOperand(0); 7754 if (N00.getOpcode() == ISD::FNEG) { 7755 SDValue N000 = N00.getOperand(0); 7756 if (N000.getOpcode() == ISD::FMUL) { 7757 return DAG.getNode(ISD::FNEG, SL, VT, 7758 DAG.getNode(PreferredFusedOpcode, SL, VT, 7759 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7760 N000.getOperand(0)), 7761 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7762 N000.getOperand(1)), 7763 N1)); 7764 } 7765 } 7766 } 7767 7768 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7769 // -> (fneg (fma (fpext x)), (fpext y), z) 7770 // Note: This could be removed with appropriate canonicalization of the 7771 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7772 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7773 // from implementing the canonicalization in visitFSUB. 7774 if (N0.getOpcode() == ISD::FNEG) { 7775 SDValue N00 = N0.getOperand(0); 7776 if (N00.getOpcode() == ISD::FP_EXTEND) { 7777 SDValue N000 = N00.getOperand(0); 7778 if (N000.getOpcode() == ISD::FMUL) { 7779 return DAG.getNode(ISD::FNEG, SL, VT, 7780 DAG.getNode(PreferredFusedOpcode, SL, VT, 7781 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7782 N000.getOperand(0)), 7783 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7784 N000.getOperand(1)), 7785 N1)); 7786 } 7787 } 7788 } 7789 7790 } 7791 7792 // More folding opportunities when target permits. 7793 if ((AllowFusion || HasFMAD) && Aggressive) { 7794 // fold (fsub (fma x, y, (fmul u, v)), z) 7795 // -> (fma x, y (fma u, v, (fneg z))) 7796 if (N0.getOpcode() == PreferredFusedOpcode && 7797 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7798 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7799 N0.getOperand(0), N0.getOperand(1), 7800 DAG.getNode(PreferredFusedOpcode, SL, VT, 7801 N0.getOperand(2).getOperand(0), 7802 N0.getOperand(2).getOperand(1), 7803 DAG.getNode(ISD::FNEG, SL, VT, 7804 N1))); 7805 } 7806 7807 // fold (fsub x, (fma y, z, (fmul u, v))) 7808 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7809 if (N1.getOpcode() == PreferredFusedOpcode && 7810 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7811 SDValue N20 = N1.getOperand(2).getOperand(0); 7812 SDValue N21 = N1.getOperand(2).getOperand(1); 7813 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7814 DAG.getNode(ISD::FNEG, SL, VT, 7815 N1.getOperand(0)), 7816 N1.getOperand(1), 7817 DAG.getNode(PreferredFusedOpcode, SL, VT, 7818 DAG.getNode(ISD::FNEG, SL, VT, N20), 7819 7820 N21, N0)); 7821 } 7822 7823 if (AllowFusion && LookThroughFPExt) { 7824 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7825 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 7826 if (N0.getOpcode() == PreferredFusedOpcode) { 7827 SDValue N02 = N0.getOperand(2); 7828 if (N02.getOpcode() == ISD::FP_EXTEND) { 7829 SDValue N020 = N02.getOperand(0); 7830 if (N020.getOpcode() == ISD::FMUL) 7831 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7832 N0.getOperand(0), N0.getOperand(1), 7833 DAG.getNode(PreferredFusedOpcode, SL, VT, 7834 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7835 N020.getOperand(0)), 7836 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7837 N020.getOperand(1)), 7838 DAG.getNode(ISD::FNEG, SL, VT, 7839 N1))); 7840 } 7841 } 7842 7843 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 7844 // -> (fma (fpext x), (fpext y), 7845 // (fma (fpext u), (fpext v), (fneg z))) 7846 // FIXME: This turns two single-precision and one double-precision 7847 // operation into two double-precision operations, which might not be 7848 // interesting for all targets, especially GPUs. 7849 if (N0.getOpcode() == ISD::FP_EXTEND) { 7850 SDValue N00 = N0.getOperand(0); 7851 if (N00.getOpcode() == PreferredFusedOpcode) { 7852 SDValue N002 = N00.getOperand(2); 7853 if (N002.getOpcode() == ISD::FMUL) 7854 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7855 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7856 N00.getOperand(0)), 7857 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7858 N00.getOperand(1)), 7859 DAG.getNode(PreferredFusedOpcode, SL, VT, 7860 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7861 N002.getOperand(0)), 7862 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7863 N002.getOperand(1)), 7864 DAG.getNode(ISD::FNEG, SL, VT, 7865 N1))); 7866 } 7867 } 7868 7869 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 7870 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 7871 if (N1.getOpcode() == PreferredFusedOpcode && 7872 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 7873 SDValue N120 = N1.getOperand(2).getOperand(0); 7874 if (N120.getOpcode() == ISD::FMUL) { 7875 SDValue N1200 = N120.getOperand(0); 7876 SDValue N1201 = N120.getOperand(1); 7877 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7878 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 7879 N1.getOperand(1), 7880 DAG.getNode(PreferredFusedOpcode, SL, VT, 7881 DAG.getNode(ISD::FNEG, SL, VT, 7882 DAG.getNode(ISD::FP_EXTEND, SL, 7883 VT, N1200)), 7884 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7885 N1201), 7886 N0)); 7887 } 7888 } 7889 7890 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 7891 // -> (fma (fneg (fpext y)), (fpext z), 7892 // (fma (fneg (fpext u)), (fpext v), x)) 7893 // FIXME: This turns two single-precision and one double-precision 7894 // operation into two double-precision operations, which might not be 7895 // interesting for all targets, especially GPUs. 7896 if (N1.getOpcode() == ISD::FP_EXTEND && 7897 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 7898 SDValue N100 = N1.getOperand(0).getOperand(0); 7899 SDValue N101 = N1.getOperand(0).getOperand(1); 7900 SDValue N102 = N1.getOperand(0).getOperand(2); 7901 if (N102.getOpcode() == ISD::FMUL) { 7902 SDValue N1020 = N102.getOperand(0); 7903 SDValue N1021 = N102.getOperand(1); 7904 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7905 DAG.getNode(ISD::FNEG, SL, VT, 7906 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7907 N100)), 7908 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 7909 DAG.getNode(PreferredFusedOpcode, SL, VT, 7910 DAG.getNode(ISD::FNEG, SL, VT, 7911 DAG.getNode(ISD::FP_EXTEND, SL, 7912 VT, N1020)), 7913 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7914 N1021), 7915 N0)); 7916 } 7917 } 7918 } 7919 } 7920 7921 return SDValue(); 7922 } 7923 7924 /// Try to perform FMA combining on a given FMUL node. 7925 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 7926 SDValue N0 = N->getOperand(0); 7927 SDValue N1 = N->getOperand(1); 7928 EVT VT = N->getValueType(0); 7929 SDLoc SL(N); 7930 7931 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 7932 7933 const TargetOptions &Options = DAG.getTarget().Options; 7934 bool AllowFusion = 7935 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7936 7937 // Floating-point multiply-add with intermediate rounding. 7938 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7939 7940 // Floating-point multiply-add without intermediate rounding. 7941 bool HasFMA = 7942 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7943 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7944 7945 // No valid opcode, do not combine. 7946 if (!HasFMAD && !HasFMA) 7947 return SDValue(); 7948 7949 // Always prefer FMAD to FMA for precision. 7950 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7951 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7952 7953 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 7954 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 7955 auto FuseFADD = [&](SDValue X, SDValue Y) { 7956 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 7957 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 7958 if (XC1 && XC1->isExactlyValue(+1.0)) 7959 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 7960 if (XC1 && XC1->isExactlyValue(-1.0)) 7961 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 7962 DAG.getNode(ISD::FNEG, SL, VT, Y)); 7963 } 7964 return SDValue(); 7965 }; 7966 7967 if (SDValue FMA = FuseFADD(N0, N1)) 7968 return FMA; 7969 if (SDValue FMA = FuseFADD(N1, N0)) 7970 return FMA; 7971 7972 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 7973 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 7974 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 7975 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 7976 auto FuseFSUB = [&](SDValue X, SDValue Y) { 7977 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 7978 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 7979 if (XC0 && XC0->isExactlyValue(+1.0)) 7980 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7981 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 7982 Y); 7983 if (XC0 && XC0->isExactlyValue(-1.0)) 7984 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7985 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 7986 DAG.getNode(ISD::FNEG, SL, VT, Y)); 7987 7988 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 7989 if (XC1 && XC1->isExactlyValue(+1.0)) 7990 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 7991 DAG.getNode(ISD::FNEG, SL, VT, Y)); 7992 if (XC1 && XC1->isExactlyValue(-1.0)) 7993 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 7994 } 7995 return SDValue(); 7996 }; 7997 7998 if (SDValue FMA = FuseFSUB(N0, N1)) 7999 return FMA; 8000 if (SDValue FMA = FuseFSUB(N1, N0)) 8001 return FMA; 8002 8003 return SDValue(); 8004 } 8005 8006 SDValue DAGCombiner::visitFADD(SDNode *N) { 8007 SDValue N0 = N->getOperand(0); 8008 SDValue N1 = N->getOperand(1); 8009 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8010 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8011 EVT VT = N->getValueType(0); 8012 SDLoc DL(N); 8013 const TargetOptions &Options = DAG.getTarget().Options; 8014 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8015 8016 // fold vector ops 8017 if (VT.isVector()) 8018 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8019 return FoldedVOp; 8020 8021 // fold (fadd c1, c2) -> c1 + c2 8022 if (N0CFP && N1CFP) 8023 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8024 8025 // canonicalize constant to RHS 8026 if (N0CFP && !N1CFP) 8027 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8028 8029 // fold (fadd A, (fneg B)) -> (fsub A, B) 8030 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8031 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8032 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8033 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8034 8035 // fold (fadd (fneg A), B) -> (fsub B, A) 8036 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8037 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8038 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8039 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8040 8041 // If 'unsafe math' is enabled, fold lots of things. 8042 if (Options.UnsafeFPMath) { 8043 // No FP constant should be created after legalization as Instruction 8044 // Selection pass has a hard time dealing with FP constants. 8045 bool AllowNewConst = (Level < AfterLegalizeDAG); 8046 8047 // fold (fadd A, 0) -> A 8048 if (N1CFP && N1CFP->isZero()) 8049 return N0; 8050 8051 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8052 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8053 isa<ConstantFPSDNode>(N0.getOperand(1))) 8054 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8055 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8056 Flags), 8057 Flags); 8058 8059 // If allowed, fold (fadd (fneg x), x) -> 0.0 8060 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8061 return DAG.getConstantFP(0.0, DL, VT); 8062 8063 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8064 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8065 return DAG.getConstantFP(0.0, DL, VT); 8066 8067 // We can fold chains of FADD's of the same value into multiplications. 8068 // This transform is not safe in general because we are reducing the number 8069 // of rounding steps. 8070 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8071 if (N0.getOpcode() == ISD::FMUL) { 8072 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 8073 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8074 8075 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8076 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8077 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0), 8078 DAG.getConstantFP(1.0, DL, VT), Flags); 8079 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8080 } 8081 8082 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8083 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8084 N1.getOperand(0) == N1.getOperand(1) && 8085 N0.getOperand(0) == N1.getOperand(0)) { 8086 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0), 8087 DAG.getConstantFP(2.0, DL, VT), Flags); 8088 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8089 } 8090 } 8091 8092 if (N1.getOpcode() == ISD::FMUL) { 8093 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 8094 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 8095 8096 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8097 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8098 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0), 8099 DAG.getConstantFP(1.0, DL, VT), Flags); 8100 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8101 } 8102 8103 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8104 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8105 N0.getOperand(0) == N0.getOperand(1) && 8106 N1.getOperand(0) == N0.getOperand(0)) { 8107 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0), 8108 DAG.getConstantFP(2.0, DL, VT), Flags); 8109 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8110 } 8111 } 8112 8113 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8114 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 8115 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8116 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 8117 (N0.getOperand(0) == N1)) { 8118 return DAG.getNode(ISD::FMUL, DL, VT, 8119 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8120 } 8121 } 8122 8123 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8124 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 8125 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8126 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8127 N1.getOperand(0) == N0) { 8128 return DAG.getNode(ISD::FMUL, DL, VT, 8129 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8130 } 8131 } 8132 8133 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8134 if (AllowNewConst && 8135 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8136 N0.getOperand(0) == N0.getOperand(1) && 8137 N1.getOperand(0) == N1.getOperand(1) && 8138 N0.getOperand(0) == N1.getOperand(0)) { 8139 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8140 DAG.getConstantFP(4.0, DL, VT), Flags); 8141 } 8142 } 8143 } // enable-unsafe-fp-math 8144 8145 // FADD -> FMA combines: 8146 if (SDValue Fused = visitFADDForFMACombine(N)) { 8147 AddToWorklist(Fused.getNode()); 8148 return Fused; 8149 } 8150 8151 return SDValue(); 8152 } 8153 8154 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8155 SDValue N0 = N->getOperand(0); 8156 SDValue N1 = N->getOperand(1); 8157 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8158 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8159 EVT VT = N->getValueType(0); 8160 SDLoc dl(N); 8161 const TargetOptions &Options = DAG.getTarget().Options; 8162 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8163 8164 // fold vector ops 8165 if (VT.isVector()) 8166 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8167 return FoldedVOp; 8168 8169 // fold (fsub c1, c2) -> c1-c2 8170 if (N0CFP && N1CFP) 8171 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8172 8173 // fold (fsub A, (fneg B)) -> (fadd A, B) 8174 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8175 return DAG.getNode(ISD::FADD, dl, VT, N0, 8176 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8177 8178 // If 'unsafe math' is enabled, fold lots of things. 8179 if (Options.UnsafeFPMath) { 8180 // (fsub A, 0) -> A 8181 if (N1CFP && N1CFP->isZero()) 8182 return N0; 8183 8184 // (fsub 0, B) -> -B 8185 if (N0CFP && N0CFP->isZero()) { 8186 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8187 return GetNegatedExpression(N1, DAG, LegalOperations); 8188 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8189 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8190 } 8191 8192 // (fsub x, x) -> 0.0 8193 if (N0 == N1) 8194 return DAG.getConstantFP(0.0f, dl, VT); 8195 8196 // (fsub x, (fadd x, y)) -> (fneg y) 8197 // (fsub x, (fadd y, x)) -> (fneg y) 8198 if (N1.getOpcode() == ISD::FADD) { 8199 SDValue N10 = N1->getOperand(0); 8200 SDValue N11 = N1->getOperand(1); 8201 8202 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8203 return GetNegatedExpression(N11, DAG, LegalOperations); 8204 8205 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8206 return GetNegatedExpression(N10, DAG, LegalOperations); 8207 } 8208 } 8209 8210 // FSUB -> FMA combines: 8211 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8212 AddToWorklist(Fused.getNode()); 8213 return Fused; 8214 } 8215 8216 return SDValue(); 8217 } 8218 8219 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8220 SDValue N0 = N->getOperand(0); 8221 SDValue N1 = N->getOperand(1); 8222 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8223 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8224 EVT VT = N->getValueType(0); 8225 SDLoc DL(N); 8226 const TargetOptions &Options = DAG.getTarget().Options; 8227 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8228 8229 // fold vector ops 8230 if (VT.isVector()) { 8231 // This just handles C1 * C2 for vectors. Other vector folds are below. 8232 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8233 return FoldedVOp; 8234 } 8235 8236 // fold (fmul c1, c2) -> c1*c2 8237 if (N0CFP && N1CFP) 8238 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8239 8240 // canonicalize constant to RHS 8241 if (isConstantFPBuildVectorOrConstantFP(N0) && 8242 !isConstantFPBuildVectorOrConstantFP(N1)) 8243 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8244 8245 // fold (fmul A, 1.0) -> A 8246 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8247 return N0; 8248 8249 if (Options.UnsafeFPMath) { 8250 // fold (fmul A, 0) -> 0 8251 if (N1CFP && N1CFP->isZero()) 8252 return N1; 8253 8254 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8255 if (N0.getOpcode() == ISD::FMUL) { 8256 // Fold scalars or any vector constants (not just splats). 8257 // This fold is done in general by InstCombine, but extra fmul insts 8258 // may have been generated during lowering. 8259 SDValue N00 = N0.getOperand(0); 8260 SDValue N01 = N0.getOperand(1); 8261 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8262 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8263 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8264 8265 // Check 1: Make sure that the first operand of the inner multiply is NOT 8266 // a constant. Otherwise, we may induce infinite looping. 8267 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8268 // Check 2: Make sure that the second operand of the inner multiply and 8269 // the second operand of the outer multiply are constants. 8270 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8271 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8272 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8273 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8274 } 8275 } 8276 } 8277 8278 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8279 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8280 // during an early run of DAGCombiner can prevent folding with fmuls 8281 // inserted during lowering. 8282 if (N0.getOpcode() == ISD::FADD && 8283 (N0.getOperand(0) == N0.getOperand(1)) && 8284 N0.hasOneUse()) { 8285 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8286 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8287 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8288 } 8289 } 8290 8291 // fold (fmul X, 2.0) -> (fadd X, X) 8292 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8293 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8294 8295 // fold (fmul X, -1.0) -> (fneg X) 8296 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8297 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8298 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8299 8300 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8301 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8302 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8303 // Both can be negated for free, check to see if at least one is cheaper 8304 // negated. 8305 if (LHSNeg == 2 || RHSNeg == 2) 8306 return DAG.getNode(ISD::FMUL, DL, VT, 8307 GetNegatedExpression(N0, DAG, LegalOperations), 8308 GetNegatedExpression(N1, DAG, LegalOperations), 8309 Flags); 8310 } 8311 } 8312 8313 // FMUL -> FMA combines: 8314 if (SDValue Fused = visitFMULForFMACombine(N)) { 8315 AddToWorklist(Fused.getNode()); 8316 return Fused; 8317 } 8318 8319 return SDValue(); 8320 } 8321 8322 SDValue DAGCombiner::visitFMA(SDNode *N) { 8323 SDValue N0 = N->getOperand(0); 8324 SDValue N1 = N->getOperand(1); 8325 SDValue N2 = N->getOperand(2); 8326 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8327 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8328 EVT VT = N->getValueType(0); 8329 SDLoc dl(N); 8330 const TargetOptions &Options = DAG.getTarget().Options; 8331 8332 // Constant fold FMA. 8333 if (isa<ConstantFPSDNode>(N0) && 8334 isa<ConstantFPSDNode>(N1) && 8335 isa<ConstantFPSDNode>(N2)) { 8336 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8337 } 8338 8339 if (Options.UnsafeFPMath) { 8340 if (N0CFP && N0CFP->isZero()) 8341 return N2; 8342 if (N1CFP && N1CFP->isZero()) 8343 return N2; 8344 } 8345 // TODO: The FMA node should have flags that propagate to these nodes. 8346 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8347 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8348 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8349 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8350 8351 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8352 if (N0CFP && !N1CFP) 8353 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8354 8355 // TODO: FMA nodes should have flags that propagate to the created nodes. 8356 // For now, create a Flags object for use with all unsafe math transforms. 8357 SDNodeFlags Flags; 8358 Flags.setUnsafeAlgebra(true); 8359 8360 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8361 if (Options.UnsafeFPMath && N1CFP && 8362 N2.getOpcode() == ISD::FMUL && 8363 N0 == N2.getOperand(0) && 8364 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 8365 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8366 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8367 &Flags), &Flags); 8368 } 8369 8370 8371 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8372 if (Options.UnsafeFPMath && 8373 N0.getOpcode() == ISD::FMUL && N1CFP && 8374 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 8375 return DAG.getNode(ISD::FMA, dl, VT, 8376 N0.getOperand(0), 8377 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8378 &Flags), 8379 N2); 8380 } 8381 8382 // (fma x, 1, y) -> (fadd x, y) 8383 // (fma x, -1, y) -> (fadd (fneg x), y) 8384 if (N1CFP) { 8385 if (N1CFP->isExactlyValue(1.0)) 8386 // TODO: The FMA node should have flags that propagate to this node. 8387 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8388 8389 if (N1CFP->isExactlyValue(-1.0) && 8390 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8391 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8392 AddToWorklist(RHSNeg.getNode()); 8393 // TODO: The FMA node should have flags that propagate to this node. 8394 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8395 } 8396 } 8397 8398 // (fma x, c, x) -> (fmul x, (c+1)) 8399 if (Options.UnsafeFPMath && N1CFP && N0 == N2) { 8400 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8401 DAG.getNode(ISD::FADD, dl, VT, 8402 N1, DAG.getConstantFP(1.0, dl, VT), 8403 &Flags), &Flags); 8404 } 8405 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8406 if (Options.UnsafeFPMath && N1CFP && 8407 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8408 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8409 DAG.getNode(ISD::FADD, dl, VT, 8410 N1, DAG.getConstantFP(-1.0, dl, VT), 8411 &Flags), &Flags); 8412 } 8413 8414 return SDValue(); 8415 } 8416 8417 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8418 // reciprocal. 8419 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8420 // Notice that this is not always beneficial. One reason is different target 8421 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8422 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8423 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8424 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8425 if (!DAG.getTarget().Options.UnsafeFPMath) 8426 return SDValue(); 8427 8428 // Skip if current node is a reciprocal. 8429 SDValue N0 = N->getOperand(0); 8430 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8431 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8432 return SDValue(); 8433 8434 // Exit early if the target does not want this transform or if there can't 8435 // possibly be enough uses of the divisor to make the transform worthwhile. 8436 SDValue N1 = N->getOperand(1); 8437 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8438 if (!MinUses || N1->use_size() < MinUses) 8439 return SDValue(); 8440 8441 // Find all FDIV users of the same divisor. 8442 // Use a set because duplicates may be present in the user list. 8443 SetVector<SDNode *> Users; 8444 for (auto *U : N1->uses()) 8445 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) 8446 Users.insert(U); 8447 8448 // Now that we have the actual number of divisor uses, make sure it meets 8449 // the minimum threshold specified by the target. 8450 if (Users.size() < MinUses) 8451 return SDValue(); 8452 8453 EVT VT = N->getValueType(0); 8454 SDLoc DL(N); 8455 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8456 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8457 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8458 8459 // Dividend / Divisor -> Dividend * Reciprocal 8460 for (auto *U : Users) { 8461 SDValue Dividend = U->getOperand(0); 8462 if (Dividend != FPOne) { 8463 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8464 Reciprocal, Flags); 8465 CombineTo(U, NewNode); 8466 } else if (U != Reciprocal.getNode()) { 8467 // In the absence of fast-math-flags, this user node is always the 8468 // same node as Reciprocal, but with FMF they may be different nodes. 8469 CombineTo(U, Reciprocal); 8470 } 8471 } 8472 return SDValue(N, 0); // N was replaced. 8473 } 8474 8475 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8476 SDValue N0 = N->getOperand(0); 8477 SDValue N1 = N->getOperand(1); 8478 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8479 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8480 EVT VT = N->getValueType(0); 8481 SDLoc DL(N); 8482 const TargetOptions &Options = DAG.getTarget().Options; 8483 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8484 8485 // fold vector ops 8486 if (VT.isVector()) 8487 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8488 return FoldedVOp; 8489 8490 // fold (fdiv c1, c2) -> c1/c2 8491 if (N0CFP && N1CFP) 8492 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8493 8494 if (Options.UnsafeFPMath) { 8495 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8496 if (N1CFP) { 8497 // Compute the reciprocal 1.0 / c2. 8498 APFloat N1APF = N1CFP->getValueAPF(); 8499 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8500 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8501 // Only do the transform if the reciprocal is a legal fp immediate that 8502 // isn't too nasty (eg NaN, denormal, ...). 8503 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8504 (!LegalOperations || 8505 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8506 // backend)... we should handle this gracefully after Legalize. 8507 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8508 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8509 TLI.isFPImmLegal(Recip, VT))) 8510 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8511 DAG.getConstantFP(Recip, DL, VT), Flags); 8512 } 8513 8514 // If this FDIV is part of a reciprocal square root, it may be folded 8515 // into a target-specific square root estimate instruction. 8516 if (N1.getOpcode() == ISD::FSQRT) { 8517 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) { 8518 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8519 } 8520 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8521 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8522 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8523 Flags)) { 8524 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8525 AddToWorklist(RV.getNode()); 8526 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8527 } 8528 } else if (N1.getOpcode() == ISD::FP_ROUND && 8529 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8530 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8531 Flags)) { 8532 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8533 AddToWorklist(RV.getNode()); 8534 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8535 } 8536 } else if (N1.getOpcode() == ISD::FMUL) { 8537 // Look through an FMUL. Even though this won't remove the FDIV directly, 8538 // it's still worthwhile to get rid of the FSQRT if possible. 8539 SDValue SqrtOp; 8540 SDValue OtherOp; 8541 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8542 SqrtOp = N1.getOperand(0); 8543 OtherOp = N1.getOperand(1); 8544 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8545 SqrtOp = N1.getOperand(1); 8546 OtherOp = N1.getOperand(0); 8547 } 8548 if (SqrtOp.getNode()) { 8549 // We found a FSQRT, so try to make this fold: 8550 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8551 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8552 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8553 AddToWorklist(RV.getNode()); 8554 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8555 } 8556 } 8557 } 8558 8559 // Fold into a reciprocal estimate and multiply instead of a real divide. 8560 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8561 AddToWorklist(RV.getNode()); 8562 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8563 } 8564 } 8565 8566 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8567 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8568 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8569 // Both can be negated for free, check to see if at least one is cheaper 8570 // negated. 8571 if (LHSNeg == 2 || RHSNeg == 2) 8572 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8573 GetNegatedExpression(N0, DAG, LegalOperations), 8574 GetNegatedExpression(N1, DAG, LegalOperations), 8575 Flags); 8576 } 8577 } 8578 8579 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8580 return CombineRepeatedDivisors; 8581 8582 return SDValue(); 8583 } 8584 8585 SDValue DAGCombiner::visitFREM(SDNode *N) { 8586 SDValue N0 = N->getOperand(0); 8587 SDValue N1 = N->getOperand(1); 8588 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8589 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8590 EVT VT = N->getValueType(0); 8591 8592 // fold (frem c1, c2) -> fmod(c1,c2) 8593 if (N0CFP && N1CFP) 8594 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8595 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8596 8597 return SDValue(); 8598 } 8599 8600 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8601 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8602 return SDValue(); 8603 8604 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8605 // For now, create a Flags object for use with all unsafe math transforms. 8606 SDNodeFlags Flags; 8607 Flags.setUnsafeAlgebra(true); 8608 8609 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8610 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags); 8611 if (!RV) 8612 return SDValue(); 8613 8614 EVT VT = RV.getValueType(); 8615 SDLoc DL(N); 8616 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags); 8617 AddToWorklist(RV.getNode()); 8618 8619 // Unfortunately, RV is now NaN if the input was exactly 0. 8620 // Select out this case and force the answer to 0. 8621 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8622 EVT CCVT = getSetCCResultType(VT); 8623 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ); 8624 AddToWorklist(ZeroCmp.getNode()); 8625 AddToWorklist(RV.getNode()); 8626 8627 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 8628 ZeroCmp, Zero, RV); 8629 } 8630 8631 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8632 SDValue N0 = N->getOperand(0); 8633 SDValue N1 = N->getOperand(1); 8634 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8635 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8636 EVT VT = N->getValueType(0); 8637 8638 if (N0CFP && N1CFP) // Constant fold 8639 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8640 8641 if (N1CFP) { 8642 const APFloat& V = N1CFP->getValueAPF(); 8643 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8644 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8645 if (!V.isNegative()) { 8646 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8647 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8648 } else { 8649 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8650 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8651 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8652 } 8653 } 8654 8655 // copysign(fabs(x), y) -> copysign(x, y) 8656 // copysign(fneg(x), y) -> copysign(x, y) 8657 // copysign(copysign(x,z), y) -> copysign(x, y) 8658 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8659 N0.getOpcode() == ISD::FCOPYSIGN) 8660 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8661 N0.getOperand(0), N1); 8662 8663 // copysign(x, abs(y)) -> abs(x) 8664 if (N1.getOpcode() == ISD::FABS) 8665 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8666 8667 // copysign(x, copysign(y,z)) -> copysign(x, z) 8668 if (N1.getOpcode() == ISD::FCOPYSIGN) 8669 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8670 N0, N1.getOperand(1)); 8671 8672 // copysign(x, fp_extend(y)) -> copysign(x, y) 8673 // copysign(x, fp_round(y)) -> copysign(x, y) 8674 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 8675 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8676 N0, N1.getOperand(0)); 8677 8678 return SDValue(); 8679 } 8680 8681 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8682 SDValue N0 = N->getOperand(0); 8683 EVT VT = N->getValueType(0); 8684 EVT OpVT = N0.getValueType(); 8685 8686 // fold (sint_to_fp c1) -> c1fp 8687 if (isConstantIntBuildVectorOrConstantInt(N0) && 8688 // ...but only if the target supports immediate floating-point values 8689 (!LegalOperations || 8690 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8691 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8692 8693 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8694 // but UINT_TO_FP is legal on this target, try to convert. 8695 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8696 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8697 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8698 if (DAG.SignBitIsZero(N0)) 8699 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8700 } 8701 8702 // The next optimizations are desirable only if SELECT_CC can be lowered. 8703 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8704 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8705 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8706 !VT.isVector() && 8707 (!LegalOperations || 8708 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8709 SDLoc DL(N); 8710 SDValue Ops[] = 8711 { N0.getOperand(0), N0.getOperand(1), 8712 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8713 N0.getOperand(2) }; 8714 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8715 } 8716 8717 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8718 // (select_cc x, y, 1.0, 0.0,, cc) 8719 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8720 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8721 (!LegalOperations || 8722 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8723 SDLoc DL(N); 8724 SDValue Ops[] = 8725 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8726 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8727 N0.getOperand(0).getOperand(2) }; 8728 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8729 } 8730 } 8731 8732 return SDValue(); 8733 } 8734 8735 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8736 SDValue N0 = N->getOperand(0); 8737 EVT VT = N->getValueType(0); 8738 EVT OpVT = N0.getValueType(); 8739 8740 // fold (uint_to_fp c1) -> c1fp 8741 if (isConstantIntBuildVectorOrConstantInt(N0) && 8742 // ...but only if the target supports immediate floating-point values 8743 (!LegalOperations || 8744 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8745 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8746 8747 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8748 // but SINT_TO_FP is legal on this target, try to convert. 8749 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8750 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8751 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8752 if (DAG.SignBitIsZero(N0)) 8753 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8754 } 8755 8756 // The next optimizations are desirable only if SELECT_CC can be lowered. 8757 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8758 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8759 8760 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8761 (!LegalOperations || 8762 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8763 SDLoc DL(N); 8764 SDValue Ops[] = 8765 { N0.getOperand(0), N0.getOperand(1), 8766 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8767 N0.getOperand(2) }; 8768 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8769 } 8770 } 8771 8772 return SDValue(); 8773 } 8774 8775 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8776 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8777 SDValue N0 = N->getOperand(0); 8778 EVT VT = N->getValueType(0); 8779 8780 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8781 return SDValue(); 8782 8783 SDValue Src = N0.getOperand(0); 8784 EVT SrcVT = Src.getValueType(); 8785 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8786 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8787 8788 // We can safely assume the conversion won't overflow the output range, 8789 // because (for example) (uint8_t)18293.f is undefined behavior. 8790 8791 // Since we can assume the conversion won't overflow, our decision as to 8792 // whether the input will fit in the float should depend on the minimum 8793 // of the input range and output range. 8794 8795 // This means this is also safe for a signed input and unsigned output, since 8796 // a negative input would lead to undefined behavior. 8797 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8798 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8799 unsigned ActualSize = std::min(InputSize, OutputSize); 8800 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8801 8802 // We can only fold away the float conversion if the input range can be 8803 // represented exactly in the float range. 8804 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8805 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8806 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8807 : ISD::ZERO_EXTEND; 8808 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8809 } 8810 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8811 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8812 if (SrcVT == VT) 8813 return Src; 8814 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 8815 } 8816 return SDValue(); 8817 } 8818 8819 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8820 SDValue N0 = N->getOperand(0); 8821 EVT VT = N->getValueType(0); 8822 8823 // fold (fp_to_sint c1fp) -> c1 8824 if (isConstantFPBuildVectorOrConstantFP(N0)) 8825 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8826 8827 return FoldIntToFPToInt(N, DAG); 8828 } 8829 8830 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 8831 SDValue N0 = N->getOperand(0); 8832 EVT VT = N->getValueType(0); 8833 8834 // fold (fp_to_uint c1fp) -> c1 8835 if (isConstantFPBuildVectorOrConstantFP(N0)) 8836 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 8837 8838 return FoldIntToFPToInt(N, DAG); 8839 } 8840 8841 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 8842 SDValue N0 = N->getOperand(0); 8843 SDValue N1 = N->getOperand(1); 8844 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8845 EVT VT = N->getValueType(0); 8846 8847 // fold (fp_round c1fp) -> c1fp 8848 if (N0CFP) 8849 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 8850 8851 // fold (fp_round (fp_extend x)) -> x 8852 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 8853 return N0.getOperand(0); 8854 8855 // fold (fp_round (fp_round x)) -> (fp_round x) 8856 if (N0.getOpcode() == ISD::FP_ROUND) { 8857 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 8858 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 8859 // If the first fp_round isn't a value preserving truncation, it might 8860 // introduce a tie in the second fp_round, that wouldn't occur in the 8861 // single-step fp_round we want to fold to. 8862 // In other words, double rounding isn't the same as rounding. 8863 // Also, this is a value preserving truncation iff both fp_round's are. 8864 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 8865 SDLoc DL(N); 8866 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 8867 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 8868 } 8869 } 8870 8871 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 8872 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 8873 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 8874 N0.getOperand(0), N1); 8875 AddToWorklist(Tmp.getNode()); 8876 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8877 Tmp, N0.getOperand(1)); 8878 } 8879 8880 return SDValue(); 8881 } 8882 8883 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 8884 SDValue N0 = N->getOperand(0); 8885 EVT VT = N->getValueType(0); 8886 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8887 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8888 8889 // fold (fp_round_inreg c1fp) -> c1fp 8890 if (N0CFP && isTypeLegal(EVT)) { 8891 SDLoc DL(N); 8892 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 8893 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 8894 } 8895 8896 return SDValue(); 8897 } 8898 8899 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 8900 SDValue N0 = N->getOperand(0); 8901 EVT VT = N->getValueType(0); 8902 8903 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 8904 if (N->hasOneUse() && 8905 N->use_begin()->getOpcode() == ISD::FP_ROUND) 8906 return SDValue(); 8907 8908 // fold (fp_extend c1fp) -> c1fp 8909 if (isConstantFPBuildVectorOrConstantFP(N0)) 8910 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 8911 8912 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 8913 if (N0.getOpcode() == ISD::FP16_TO_FP && 8914 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 8915 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 8916 8917 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 8918 // value of X. 8919 if (N0.getOpcode() == ISD::FP_ROUND 8920 && N0.getNode()->getConstantOperandVal(1) == 1) { 8921 SDValue In = N0.getOperand(0); 8922 if (In.getValueType() == VT) return In; 8923 if (VT.bitsLT(In.getValueType())) 8924 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 8925 In, N0.getOperand(1)); 8926 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 8927 } 8928 8929 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 8930 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8931 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8932 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8933 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8934 LN0->getChain(), 8935 LN0->getBasePtr(), N0.getValueType(), 8936 LN0->getMemOperand()); 8937 CombineTo(N, ExtLoad); 8938 CombineTo(N0.getNode(), 8939 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 8940 N0.getValueType(), ExtLoad, 8941 DAG.getIntPtrConstant(1, SDLoc(N0))), 8942 ExtLoad.getValue(1)); 8943 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8944 } 8945 8946 return SDValue(); 8947 } 8948 8949 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 8950 SDValue N0 = N->getOperand(0); 8951 EVT VT = N->getValueType(0); 8952 8953 // fold (fceil c1) -> fceil(c1) 8954 if (isConstantFPBuildVectorOrConstantFP(N0)) 8955 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 8956 8957 return SDValue(); 8958 } 8959 8960 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 8961 SDValue N0 = N->getOperand(0); 8962 EVT VT = N->getValueType(0); 8963 8964 // fold (ftrunc c1) -> ftrunc(c1) 8965 if (isConstantFPBuildVectorOrConstantFP(N0)) 8966 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 8967 8968 return SDValue(); 8969 } 8970 8971 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 8972 SDValue N0 = N->getOperand(0); 8973 EVT VT = N->getValueType(0); 8974 8975 // fold (ffloor c1) -> ffloor(c1) 8976 if (isConstantFPBuildVectorOrConstantFP(N0)) 8977 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 8978 8979 return SDValue(); 8980 } 8981 8982 // FIXME: FNEG and FABS have a lot in common; refactor. 8983 SDValue DAGCombiner::visitFNEG(SDNode *N) { 8984 SDValue N0 = N->getOperand(0); 8985 EVT VT = N->getValueType(0); 8986 8987 // Constant fold FNEG. 8988 if (isConstantFPBuildVectorOrConstantFP(N0)) 8989 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 8990 8991 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 8992 &DAG.getTarget().Options)) 8993 return GetNegatedExpression(N0, DAG, LegalOperations); 8994 8995 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 8996 // constant pool values. 8997 if (!TLI.isFNegFree(VT) && 8998 N0.getOpcode() == ISD::BITCAST && 8999 N0.getNode()->hasOneUse()) { 9000 SDValue Int = N0.getOperand(0); 9001 EVT IntVT = Int.getValueType(); 9002 if (IntVT.isInteger() && !IntVT.isVector()) { 9003 APInt SignMask; 9004 if (N0.getValueType().isVector()) { 9005 // For a vector, get a mask such as 0x80... per scalar element 9006 // and splat it. 9007 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9008 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9009 } else { 9010 // For a scalar, just generate 0x80... 9011 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9012 } 9013 SDLoc DL0(N0); 9014 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9015 DAG.getConstant(SignMask, DL0, IntVT)); 9016 AddToWorklist(Int.getNode()); 9017 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 9018 } 9019 } 9020 9021 // (fneg (fmul c, x)) -> (fmul -c, x) 9022 if (N0.getOpcode() == ISD::FMUL && 9023 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9024 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9025 if (CFP1) { 9026 APFloat CVal = CFP1->getValueAPF(); 9027 CVal.changeSign(); 9028 if (Level >= AfterLegalizeDAG && 9029 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 9030 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 9031 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9032 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9033 N0.getOperand(1)), 9034 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9035 } 9036 } 9037 9038 return SDValue(); 9039 } 9040 9041 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9042 SDValue N0 = N->getOperand(0); 9043 SDValue N1 = N->getOperand(1); 9044 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9045 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9046 9047 if (N0CFP && N1CFP) { 9048 const APFloat &C0 = N0CFP->getValueAPF(); 9049 const APFloat &C1 = N1CFP->getValueAPF(); 9050 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0)); 9051 } 9052 9053 if (N0CFP) { 9054 EVT VT = N->getValueType(0); 9055 // Canonicalize to constant on RHS. 9056 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9057 } 9058 9059 return SDValue(); 9060 } 9061 9062 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9063 SDValue N0 = N->getOperand(0); 9064 SDValue N1 = N->getOperand(1); 9065 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9066 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 9067 9068 if (N0CFP && N1CFP) { 9069 const APFloat &C0 = N0CFP->getValueAPF(); 9070 const APFloat &C1 = N1CFP->getValueAPF(); 9071 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0)); 9072 } 9073 9074 if (N0CFP) { 9075 EVT VT = N->getValueType(0); 9076 // Canonicalize to constant on RHS. 9077 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9078 } 9079 9080 return SDValue(); 9081 } 9082 9083 SDValue DAGCombiner::visitFABS(SDNode *N) { 9084 SDValue N0 = N->getOperand(0); 9085 EVT VT = N->getValueType(0); 9086 9087 // fold (fabs c1) -> fabs(c1) 9088 if (isConstantFPBuildVectorOrConstantFP(N0)) 9089 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9090 9091 // fold (fabs (fabs x)) -> (fabs x) 9092 if (N0.getOpcode() == ISD::FABS) 9093 return N->getOperand(0); 9094 9095 // fold (fabs (fneg x)) -> (fabs x) 9096 // fold (fabs (fcopysign x, y)) -> (fabs x) 9097 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9098 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9099 9100 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9101 // constant pool values. 9102 if (!TLI.isFAbsFree(VT) && 9103 N0.getOpcode() == ISD::BITCAST && 9104 N0.getNode()->hasOneUse()) { 9105 SDValue Int = N0.getOperand(0); 9106 EVT IntVT = Int.getValueType(); 9107 if (IntVT.isInteger() && !IntVT.isVector()) { 9108 APInt SignMask; 9109 if (N0.getValueType().isVector()) { 9110 // For a vector, get a mask such as 0x7f... per scalar element 9111 // and splat it. 9112 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9113 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9114 } else { 9115 // For a scalar, just generate 0x7f... 9116 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9117 } 9118 SDLoc DL(N0); 9119 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9120 DAG.getConstant(SignMask, DL, IntVT)); 9121 AddToWorklist(Int.getNode()); 9122 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 9123 } 9124 } 9125 9126 return SDValue(); 9127 } 9128 9129 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9130 SDValue Chain = N->getOperand(0); 9131 SDValue N1 = N->getOperand(1); 9132 SDValue N2 = N->getOperand(2); 9133 9134 // If N is a constant we could fold this into a fallthrough or unconditional 9135 // branch. However that doesn't happen very often in normal code, because 9136 // Instcombine/SimplifyCFG should have handled the available opportunities. 9137 // If we did this folding here, it would be necessary to update the 9138 // MachineBasicBlock CFG, which is awkward. 9139 9140 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9141 // on the target. 9142 if (N1.getOpcode() == ISD::SETCC && 9143 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9144 N1.getOperand(0).getValueType())) { 9145 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9146 Chain, N1.getOperand(2), 9147 N1.getOperand(0), N1.getOperand(1), N2); 9148 } 9149 9150 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9151 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9152 (N1.getOperand(0).hasOneUse() && 9153 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9154 SDNode *Trunc = nullptr; 9155 if (N1.getOpcode() == ISD::TRUNCATE) { 9156 // Look pass the truncate. 9157 Trunc = N1.getNode(); 9158 N1 = N1.getOperand(0); 9159 } 9160 9161 // Match this pattern so that we can generate simpler code: 9162 // 9163 // %a = ... 9164 // %b = and i32 %a, 2 9165 // %c = srl i32 %b, 1 9166 // brcond i32 %c ... 9167 // 9168 // into 9169 // 9170 // %a = ... 9171 // %b = and i32 %a, 2 9172 // %c = setcc eq %b, 0 9173 // brcond %c ... 9174 // 9175 // This applies only when the AND constant value has one bit set and the 9176 // SRL constant is equal to the log2 of the AND constant. The back-end is 9177 // smart enough to convert the result into a TEST/JMP sequence. 9178 SDValue Op0 = N1.getOperand(0); 9179 SDValue Op1 = N1.getOperand(1); 9180 9181 if (Op0.getOpcode() == ISD::AND && 9182 Op1.getOpcode() == ISD::Constant) { 9183 SDValue AndOp1 = Op0.getOperand(1); 9184 9185 if (AndOp1.getOpcode() == ISD::Constant) { 9186 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9187 9188 if (AndConst.isPowerOf2() && 9189 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9190 SDLoc DL(N); 9191 SDValue SetCC = 9192 DAG.getSetCC(DL, 9193 getSetCCResultType(Op0.getValueType()), 9194 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9195 ISD::SETNE); 9196 9197 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9198 MVT::Other, Chain, SetCC, N2); 9199 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9200 // will convert it back to (X & C1) >> C2. 9201 CombineTo(N, NewBRCond, false); 9202 // Truncate is dead. 9203 if (Trunc) 9204 deleteAndRecombine(Trunc); 9205 // Replace the uses of SRL with SETCC 9206 WorklistRemover DeadNodes(*this); 9207 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9208 deleteAndRecombine(N1.getNode()); 9209 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9210 } 9211 } 9212 } 9213 9214 if (Trunc) 9215 // Restore N1 if the above transformation doesn't match. 9216 N1 = N->getOperand(1); 9217 } 9218 9219 // Transform br(xor(x, y)) -> br(x != y) 9220 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9221 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9222 SDNode *TheXor = N1.getNode(); 9223 SDValue Op0 = TheXor->getOperand(0); 9224 SDValue Op1 = TheXor->getOperand(1); 9225 if (Op0.getOpcode() == Op1.getOpcode()) { 9226 // Avoid missing important xor optimizations. 9227 if (SDValue Tmp = visitXOR(TheXor)) { 9228 if (Tmp.getNode() != TheXor) { 9229 DEBUG(dbgs() << "\nReplacing.8 "; 9230 TheXor->dump(&DAG); 9231 dbgs() << "\nWith: "; 9232 Tmp.getNode()->dump(&DAG); 9233 dbgs() << '\n'); 9234 WorklistRemover DeadNodes(*this); 9235 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9236 deleteAndRecombine(TheXor); 9237 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9238 MVT::Other, Chain, Tmp, N2); 9239 } 9240 9241 // visitXOR has changed XOR's operands or replaced the XOR completely, 9242 // bail out. 9243 return SDValue(N, 0); 9244 } 9245 } 9246 9247 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9248 bool Equal = false; 9249 if (isOneConstant(Op0) && Op0.hasOneUse() && 9250 Op0.getOpcode() == ISD::XOR) { 9251 TheXor = Op0.getNode(); 9252 Equal = true; 9253 } 9254 9255 EVT SetCCVT = N1.getValueType(); 9256 if (LegalTypes) 9257 SetCCVT = getSetCCResultType(SetCCVT); 9258 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9259 SetCCVT, 9260 Op0, Op1, 9261 Equal ? ISD::SETEQ : ISD::SETNE); 9262 // Replace the uses of XOR with SETCC 9263 WorklistRemover DeadNodes(*this); 9264 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9265 deleteAndRecombine(N1.getNode()); 9266 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9267 MVT::Other, Chain, SetCC, N2); 9268 } 9269 } 9270 9271 return SDValue(); 9272 } 9273 9274 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9275 // 9276 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9277 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9278 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9279 9280 // If N is a constant we could fold this into a fallthrough or unconditional 9281 // branch. However that doesn't happen very often in normal code, because 9282 // Instcombine/SimplifyCFG should have handled the available opportunities. 9283 // If we did this folding here, it would be necessary to update the 9284 // MachineBasicBlock CFG, which is awkward. 9285 9286 // Use SimplifySetCC to simplify SETCC's. 9287 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9288 CondLHS, CondRHS, CC->get(), SDLoc(N), 9289 false); 9290 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9291 9292 // fold to a simpler setcc 9293 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9294 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9295 N->getOperand(0), Simp.getOperand(2), 9296 Simp.getOperand(0), Simp.getOperand(1), 9297 N->getOperand(4)); 9298 9299 return SDValue(); 9300 } 9301 9302 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9303 /// and that N may be folded in the load / store addressing mode. 9304 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9305 SelectionDAG &DAG, 9306 const TargetLowering &TLI) { 9307 EVT VT; 9308 unsigned AS; 9309 9310 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9311 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9312 return false; 9313 VT = LD->getMemoryVT(); 9314 AS = LD->getAddressSpace(); 9315 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9316 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9317 return false; 9318 VT = ST->getMemoryVT(); 9319 AS = ST->getAddressSpace(); 9320 } else 9321 return false; 9322 9323 TargetLowering::AddrMode AM; 9324 if (N->getOpcode() == ISD::ADD) { 9325 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9326 if (Offset) 9327 // [reg +/- imm] 9328 AM.BaseOffs = Offset->getSExtValue(); 9329 else 9330 // [reg +/- reg] 9331 AM.Scale = 1; 9332 } else if (N->getOpcode() == ISD::SUB) { 9333 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9334 if (Offset) 9335 // [reg +/- imm] 9336 AM.BaseOffs = -Offset->getSExtValue(); 9337 else 9338 // [reg +/- reg] 9339 AM.Scale = 1; 9340 } else 9341 return false; 9342 9343 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9344 VT.getTypeForEVT(*DAG.getContext()), AS); 9345 } 9346 9347 /// Try turning a load/store into a pre-indexed load/store when the base 9348 /// pointer is an add or subtract and it has other uses besides the load/store. 9349 /// After the transformation, the new indexed load/store has effectively folded 9350 /// the add/subtract in and all of its other uses are redirected to the 9351 /// new load/store. 9352 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9353 if (Level < AfterLegalizeDAG) 9354 return false; 9355 9356 bool isLoad = true; 9357 SDValue Ptr; 9358 EVT VT; 9359 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9360 if (LD->isIndexed()) 9361 return false; 9362 VT = LD->getMemoryVT(); 9363 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9364 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9365 return false; 9366 Ptr = LD->getBasePtr(); 9367 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9368 if (ST->isIndexed()) 9369 return false; 9370 VT = ST->getMemoryVT(); 9371 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9372 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9373 return false; 9374 Ptr = ST->getBasePtr(); 9375 isLoad = false; 9376 } else { 9377 return false; 9378 } 9379 9380 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9381 // out. There is no reason to make this a preinc/predec. 9382 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9383 Ptr.getNode()->hasOneUse()) 9384 return false; 9385 9386 // Ask the target to do addressing mode selection. 9387 SDValue BasePtr; 9388 SDValue Offset; 9389 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9390 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9391 return false; 9392 9393 // Backends without true r+i pre-indexed forms may need to pass a 9394 // constant base with a variable offset so that constant coercion 9395 // will work with the patterns in canonical form. 9396 bool Swapped = false; 9397 if (isa<ConstantSDNode>(BasePtr)) { 9398 std::swap(BasePtr, Offset); 9399 Swapped = true; 9400 } 9401 9402 // Don't create a indexed load / store with zero offset. 9403 if (isNullConstant(Offset)) 9404 return false; 9405 9406 // Try turning it into a pre-indexed load / store except when: 9407 // 1) The new base ptr is a frame index. 9408 // 2) If N is a store and the new base ptr is either the same as or is a 9409 // predecessor of the value being stored. 9410 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9411 // that would create a cycle. 9412 // 4) All uses are load / store ops that use it as old base ptr. 9413 9414 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9415 // (plus the implicit offset) to a register to preinc anyway. 9416 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9417 return false; 9418 9419 // Check #2. 9420 if (!isLoad) { 9421 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9422 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9423 return false; 9424 } 9425 9426 // If the offset is a constant, there may be other adds of constants that 9427 // can be folded with this one. We should do this to avoid having to keep 9428 // a copy of the original base pointer. 9429 SmallVector<SDNode *, 16> OtherUses; 9430 if (isa<ConstantSDNode>(Offset)) 9431 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9432 UE = BasePtr.getNode()->use_end(); 9433 UI != UE; ++UI) { 9434 SDUse &Use = UI.getUse(); 9435 // Skip the use that is Ptr and uses of other results from BasePtr's 9436 // node (important for nodes that return multiple results). 9437 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9438 continue; 9439 9440 if (Use.getUser()->isPredecessorOf(N)) 9441 continue; 9442 9443 if (Use.getUser()->getOpcode() != ISD::ADD && 9444 Use.getUser()->getOpcode() != ISD::SUB) { 9445 OtherUses.clear(); 9446 break; 9447 } 9448 9449 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9450 if (!isa<ConstantSDNode>(Op1)) { 9451 OtherUses.clear(); 9452 break; 9453 } 9454 9455 // FIXME: In some cases, we can be smarter about this. 9456 if (Op1.getValueType() != Offset.getValueType()) { 9457 OtherUses.clear(); 9458 break; 9459 } 9460 9461 OtherUses.push_back(Use.getUser()); 9462 } 9463 9464 if (Swapped) 9465 std::swap(BasePtr, Offset); 9466 9467 // Now check for #3 and #4. 9468 bool RealUse = false; 9469 9470 // Caches for hasPredecessorHelper 9471 SmallPtrSet<const SDNode *, 32> Visited; 9472 SmallVector<const SDNode *, 16> Worklist; 9473 9474 for (SDNode *Use : Ptr.getNode()->uses()) { 9475 if (Use == N) 9476 continue; 9477 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 9478 return false; 9479 9480 // If Ptr may be folded in addressing mode of other use, then it's 9481 // not profitable to do this transformation. 9482 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9483 RealUse = true; 9484 } 9485 9486 if (!RealUse) 9487 return false; 9488 9489 SDValue Result; 9490 if (isLoad) 9491 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9492 BasePtr, Offset, AM); 9493 else 9494 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9495 BasePtr, Offset, AM); 9496 ++PreIndexedNodes; 9497 ++NodesCombined; 9498 DEBUG(dbgs() << "\nReplacing.4 "; 9499 N->dump(&DAG); 9500 dbgs() << "\nWith: "; 9501 Result.getNode()->dump(&DAG); 9502 dbgs() << '\n'); 9503 WorklistRemover DeadNodes(*this); 9504 if (isLoad) { 9505 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9506 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9507 } else { 9508 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9509 } 9510 9511 // Finally, since the node is now dead, remove it from the graph. 9512 deleteAndRecombine(N); 9513 9514 if (Swapped) 9515 std::swap(BasePtr, Offset); 9516 9517 // Replace other uses of BasePtr that can be updated to use Ptr 9518 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9519 unsigned OffsetIdx = 1; 9520 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9521 OffsetIdx = 0; 9522 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9523 BasePtr.getNode() && "Expected BasePtr operand"); 9524 9525 // We need to replace ptr0 in the following expression: 9526 // x0 * offset0 + y0 * ptr0 = t0 9527 // knowing that 9528 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9529 // 9530 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9531 // indexed load/store and the expresion that needs to be re-written. 9532 // 9533 // Therefore, we have: 9534 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9535 9536 ConstantSDNode *CN = 9537 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9538 int X0, X1, Y0, Y1; 9539 APInt Offset0 = CN->getAPIntValue(); 9540 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9541 9542 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9543 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9544 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9545 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9546 9547 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9548 9549 APInt CNV = Offset0; 9550 if (X0 < 0) CNV = -CNV; 9551 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9552 else CNV = CNV - Offset1; 9553 9554 SDLoc DL(OtherUses[i]); 9555 9556 // We can now generate the new expression. 9557 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9558 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9559 9560 SDValue NewUse = DAG.getNode(Opcode, 9561 DL, 9562 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9563 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9564 deleteAndRecombine(OtherUses[i]); 9565 } 9566 9567 // Replace the uses of Ptr with uses of the updated base value. 9568 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9569 deleteAndRecombine(Ptr.getNode()); 9570 9571 return true; 9572 } 9573 9574 /// Try to combine a load/store with a add/sub of the base pointer node into a 9575 /// post-indexed load/store. The transformation folded the add/subtract into the 9576 /// new indexed load/store effectively and all of its uses are redirected to the 9577 /// new load/store. 9578 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9579 if (Level < AfterLegalizeDAG) 9580 return false; 9581 9582 bool isLoad = true; 9583 SDValue Ptr; 9584 EVT VT; 9585 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9586 if (LD->isIndexed()) 9587 return false; 9588 VT = LD->getMemoryVT(); 9589 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9590 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9591 return false; 9592 Ptr = LD->getBasePtr(); 9593 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9594 if (ST->isIndexed()) 9595 return false; 9596 VT = ST->getMemoryVT(); 9597 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9598 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9599 return false; 9600 Ptr = ST->getBasePtr(); 9601 isLoad = false; 9602 } else { 9603 return false; 9604 } 9605 9606 if (Ptr.getNode()->hasOneUse()) 9607 return false; 9608 9609 for (SDNode *Op : Ptr.getNode()->uses()) { 9610 if (Op == N || 9611 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9612 continue; 9613 9614 SDValue BasePtr; 9615 SDValue Offset; 9616 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9617 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9618 // Don't create a indexed load / store with zero offset. 9619 if (isNullConstant(Offset)) 9620 continue; 9621 9622 // Try turning it into a post-indexed load / store except when 9623 // 1) All uses are load / store ops that use it as base ptr (and 9624 // it may be folded as addressing mmode). 9625 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9626 // nor a successor of N. Otherwise, if Op is folded that would 9627 // create a cycle. 9628 9629 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9630 continue; 9631 9632 // Check for #1. 9633 bool TryNext = false; 9634 for (SDNode *Use : BasePtr.getNode()->uses()) { 9635 if (Use == Ptr.getNode()) 9636 continue; 9637 9638 // If all the uses are load / store addresses, then don't do the 9639 // transformation. 9640 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9641 bool RealUse = false; 9642 for (SDNode *UseUse : Use->uses()) { 9643 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9644 RealUse = true; 9645 } 9646 9647 if (!RealUse) { 9648 TryNext = true; 9649 break; 9650 } 9651 } 9652 } 9653 9654 if (TryNext) 9655 continue; 9656 9657 // Check for #2 9658 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9659 SDValue Result = isLoad 9660 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9661 BasePtr, Offset, AM) 9662 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9663 BasePtr, Offset, AM); 9664 ++PostIndexedNodes; 9665 ++NodesCombined; 9666 DEBUG(dbgs() << "\nReplacing.5 "; 9667 N->dump(&DAG); 9668 dbgs() << "\nWith: "; 9669 Result.getNode()->dump(&DAG); 9670 dbgs() << '\n'); 9671 WorklistRemover DeadNodes(*this); 9672 if (isLoad) { 9673 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9674 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9675 } else { 9676 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9677 } 9678 9679 // Finally, since the node is now dead, remove it from the graph. 9680 deleteAndRecombine(N); 9681 9682 // Replace the uses of Use with uses of the updated base value. 9683 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9684 Result.getValue(isLoad ? 1 : 0)); 9685 deleteAndRecombine(Op); 9686 return true; 9687 } 9688 } 9689 } 9690 9691 return false; 9692 } 9693 9694 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9695 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9696 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9697 assert(AM != ISD::UNINDEXED); 9698 SDValue BP = LD->getOperand(1); 9699 SDValue Inc = LD->getOperand(2); 9700 9701 // Some backends use TargetConstants for load offsets, but don't expect 9702 // TargetConstants in general ADD nodes. We can convert these constants into 9703 // regular Constants (if the constant is not opaque). 9704 assert((Inc.getOpcode() != ISD::TargetConstant || 9705 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9706 "Cannot split out indexing using opaque target constants"); 9707 if (Inc.getOpcode() == ISD::TargetConstant) { 9708 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9709 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9710 ConstInc->getValueType(0)); 9711 } 9712 9713 unsigned Opc = 9714 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9715 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9716 } 9717 9718 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9719 LoadSDNode *LD = cast<LoadSDNode>(N); 9720 SDValue Chain = LD->getChain(); 9721 SDValue Ptr = LD->getBasePtr(); 9722 9723 // If load is not volatile and there are no uses of the loaded value (and 9724 // the updated indexed value in case of indexed loads), change uses of the 9725 // chain value into uses of the chain input (i.e. delete the dead load). 9726 if (!LD->isVolatile()) { 9727 if (N->getValueType(1) == MVT::Other) { 9728 // Unindexed loads. 9729 if (!N->hasAnyUseOfValue(0)) { 9730 // It's not safe to use the two value CombineTo variant here. e.g. 9731 // v1, chain2 = load chain1, loc 9732 // v2, chain3 = load chain2, loc 9733 // v3 = add v2, c 9734 // Now we replace use of chain2 with chain1. This makes the second load 9735 // isomorphic to the one we are deleting, and thus makes this load live. 9736 DEBUG(dbgs() << "\nReplacing.6 "; 9737 N->dump(&DAG); 9738 dbgs() << "\nWith chain: "; 9739 Chain.getNode()->dump(&DAG); 9740 dbgs() << "\n"); 9741 WorklistRemover DeadNodes(*this); 9742 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9743 9744 if (N->use_empty()) 9745 deleteAndRecombine(N); 9746 9747 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9748 } 9749 } else { 9750 // Indexed loads. 9751 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9752 9753 // If this load has an opaque TargetConstant offset, then we cannot split 9754 // the indexing into an add/sub directly (that TargetConstant may not be 9755 // valid for a different type of node, and we cannot convert an opaque 9756 // target constant into a regular constant). 9757 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9758 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9759 9760 if (!N->hasAnyUseOfValue(0) && 9761 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9762 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9763 SDValue Index; 9764 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9765 Index = SplitIndexingFromLoad(LD); 9766 // Try to fold the base pointer arithmetic into subsequent loads and 9767 // stores. 9768 AddUsersToWorklist(N); 9769 } else 9770 Index = DAG.getUNDEF(N->getValueType(1)); 9771 DEBUG(dbgs() << "\nReplacing.7 "; 9772 N->dump(&DAG); 9773 dbgs() << "\nWith: "; 9774 Undef.getNode()->dump(&DAG); 9775 dbgs() << " and 2 other values\n"); 9776 WorklistRemover DeadNodes(*this); 9777 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9778 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9779 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9780 deleteAndRecombine(N); 9781 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9782 } 9783 } 9784 } 9785 9786 // If this load is directly stored, replace the load value with the stored 9787 // value. 9788 // TODO: Handle store large -> read small portion. 9789 // TODO: Handle TRUNCSTORE/LOADEXT 9790 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9791 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9792 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9793 if (PrevST->getBasePtr() == Ptr && 9794 PrevST->getValue().getValueType() == N->getValueType(0)) 9795 return CombineTo(N, Chain.getOperand(1), Chain); 9796 } 9797 } 9798 9799 // Try to infer better alignment information than the load already has. 9800 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9801 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9802 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9803 SDValue NewLoad = 9804 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9805 LD->getValueType(0), 9806 Chain, Ptr, LD->getPointerInfo(), 9807 LD->getMemoryVT(), 9808 LD->isVolatile(), LD->isNonTemporal(), 9809 LD->isInvariant(), Align, LD->getAAInfo()); 9810 if (NewLoad.getNode() != N) 9811 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9812 } 9813 } 9814 } 9815 9816 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 9817 : DAG.getSubtarget().useAA(); 9818 #ifndef NDEBUG 9819 if (CombinerAAOnlyFunc.getNumOccurrences() && 9820 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9821 UseAA = false; 9822 #endif 9823 if (UseAA && LD->isUnindexed()) { 9824 // Walk up chain skipping non-aliasing memory nodes. 9825 SDValue BetterChain = FindBetterChain(N, Chain); 9826 9827 // If there is a better chain. 9828 if (Chain != BetterChain) { 9829 SDValue ReplLoad; 9830 9831 // Replace the chain to void dependency. 9832 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 9833 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 9834 BetterChain, Ptr, LD->getMemOperand()); 9835 } else { 9836 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 9837 LD->getValueType(0), 9838 BetterChain, Ptr, LD->getMemoryVT(), 9839 LD->getMemOperand()); 9840 } 9841 9842 // Create token factor to keep old chain connected. 9843 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9844 MVT::Other, Chain, ReplLoad.getValue(1)); 9845 9846 // Make sure the new and old chains are cleaned up. 9847 AddToWorklist(Token.getNode()); 9848 9849 // Replace uses with load result and token factor. Don't add users 9850 // to work list. 9851 return CombineTo(N, ReplLoad.getValue(0), Token, false); 9852 } 9853 } 9854 9855 // Try transforming N to an indexed load. 9856 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9857 return SDValue(N, 0); 9858 9859 // Try to slice up N to more direct loads if the slices are mapped to 9860 // different register banks or pairing can take place. 9861 if (SliceUpLoad(N)) 9862 return SDValue(N, 0); 9863 9864 return SDValue(); 9865 } 9866 9867 namespace { 9868 /// \brief Helper structure used to slice a load in smaller loads. 9869 /// Basically a slice is obtained from the following sequence: 9870 /// Origin = load Ty1, Base 9871 /// Shift = srl Ty1 Origin, CstTy Amount 9872 /// Inst = trunc Shift to Ty2 9873 /// 9874 /// Then, it will be rewriten into: 9875 /// Slice = load SliceTy, Base + SliceOffset 9876 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 9877 /// 9878 /// SliceTy is deduced from the number of bits that are actually used to 9879 /// build Inst. 9880 struct LoadedSlice { 9881 /// \brief Helper structure used to compute the cost of a slice. 9882 struct Cost { 9883 /// Are we optimizing for code size. 9884 bool ForCodeSize; 9885 /// Various cost. 9886 unsigned Loads; 9887 unsigned Truncates; 9888 unsigned CrossRegisterBanksCopies; 9889 unsigned ZExts; 9890 unsigned Shift; 9891 9892 Cost(bool ForCodeSize = false) 9893 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 9894 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 9895 9896 /// \brief Get the cost of one isolated slice. 9897 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 9898 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 9899 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 9900 EVT TruncType = LS.Inst->getValueType(0); 9901 EVT LoadedType = LS.getLoadedType(); 9902 if (TruncType != LoadedType && 9903 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 9904 ZExts = 1; 9905 } 9906 9907 /// \brief Account for slicing gain in the current cost. 9908 /// Slicing provide a few gains like removing a shift or a 9909 /// truncate. This method allows to grow the cost of the original 9910 /// load with the gain from this slice. 9911 void addSliceGain(const LoadedSlice &LS) { 9912 // Each slice saves a truncate. 9913 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 9914 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 9915 LS.Inst->getValueType(0))) 9916 ++Truncates; 9917 // If there is a shift amount, this slice gets rid of it. 9918 if (LS.Shift) 9919 ++Shift; 9920 // If this slice can merge a cross register bank copy, account for it. 9921 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 9922 ++CrossRegisterBanksCopies; 9923 } 9924 9925 Cost &operator+=(const Cost &RHS) { 9926 Loads += RHS.Loads; 9927 Truncates += RHS.Truncates; 9928 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 9929 ZExts += RHS.ZExts; 9930 Shift += RHS.Shift; 9931 return *this; 9932 } 9933 9934 bool operator==(const Cost &RHS) const { 9935 return Loads == RHS.Loads && Truncates == RHS.Truncates && 9936 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 9937 ZExts == RHS.ZExts && Shift == RHS.Shift; 9938 } 9939 9940 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 9941 9942 bool operator<(const Cost &RHS) const { 9943 // Assume cross register banks copies are as expensive as loads. 9944 // FIXME: Do we want some more target hooks? 9945 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 9946 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 9947 // Unless we are optimizing for code size, consider the 9948 // expensive operation first. 9949 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 9950 return ExpensiveOpsLHS < ExpensiveOpsRHS; 9951 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 9952 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 9953 } 9954 9955 bool operator>(const Cost &RHS) const { return RHS < *this; } 9956 9957 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 9958 9959 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 9960 }; 9961 // The last instruction that represent the slice. This should be a 9962 // truncate instruction. 9963 SDNode *Inst; 9964 // The original load instruction. 9965 LoadSDNode *Origin; 9966 // The right shift amount in bits from the original load. 9967 unsigned Shift; 9968 // The DAG from which Origin came from. 9969 // This is used to get some contextual information about legal types, etc. 9970 SelectionDAG *DAG; 9971 9972 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 9973 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 9974 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 9975 9976 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 9977 /// \return Result is \p BitWidth and has used bits set to 1 and 9978 /// not used bits set to 0. 9979 APInt getUsedBits() const { 9980 // Reproduce the trunc(lshr) sequence: 9981 // - Start from the truncated value. 9982 // - Zero extend to the desired bit width. 9983 // - Shift left. 9984 assert(Origin && "No original load to compare against."); 9985 unsigned BitWidth = Origin->getValueSizeInBits(0); 9986 assert(Inst && "This slice is not bound to an instruction"); 9987 assert(Inst->getValueSizeInBits(0) <= BitWidth && 9988 "Extracted slice is bigger than the whole type!"); 9989 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 9990 UsedBits.setAllBits(); 9991 UsedBits = UsedBits.zext(BitWidth); 9992 UsedBits <<= Shift; 9993 return UsedBits; 9994 } 9995 9996 /// \brief Get the size of the slice to be loaded in bytes. 9997 unsigned getLoadedSize() const { 9998 unsigned SliceSize = getUsedBits().countPopulation(); 9999 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10000 return SliceSize / 8; 10001 } 10002 10003 /// \brief Get the type that will be loaded for this slice. 10004 /// Note: This may not be the final type for the slice. 10005 EVT getLoadedType() const { 10006 assert(DAG && "Missing context"); 10007 LLVMContext &Ctxt = *DAG->getContext(); 10008 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10009 } 10010 10011 /// \brief Get the alignment of the load used for this slice. 10012 unsigned getAlignment() const { 10013 unsigned Alignment = Origin->getAlignment(); 10014 unsigned Offset = getOffsetFromBase(); 10015 if (Offset != 0) 10016 Alignment = MinAlign(Alignment, Alignment + Offset); 10017 return Alignment; 10018 } 10019 10020 /// \brief Check if this slice can be rewritten with legal operations. 10021 bool isLegal() const { 10022 // An invalid slice is not legal. 10023 if (!Origin || !Inst || !DAG) 10024 return false; 10025 10026 // Offsets are for indexed load only, we do not handle that. 10027 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 10028 return false; 10029 10030 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10031 10032 // Check that the type is legal. 10033 EVT SliceType = getLoadedType(); 10034 if (!TLI.isTypeLegal(SliceType)) 10035 return false; 10036 10037 // Check that the load is legal for this type. 10038 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10039 return false; 10040 10041 // Check that the offset can be computed. 10042 // 1. Check its type. 10043 EVT PtrType = Origin->getBasePtr().getValueType(); 10044 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10045 return false; 10046 10047 // 2. Check that it fits in the immediate. 10048 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10049 return false; 10050 10051 // 3. Check that the computation is legal. 10052 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10053 return false; 10054 10055 // Check that the zext is legal if it needs one. 10056 EVT TruncateType = Inst->getValueType(0); 10057 if (TruncateType != SliceType && 10058 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10059 return false; 10060 10061 return true; 10062 } 10063 10064 /// \brief Get the offset in bytes of this slice in the original chunk of 10065 /// bits. 10066 /// \pre DAG != nullptr. 10067 uint64_t getOffsetFromBase() const { 10068 assert(DAG && "Missing context."); 10069 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10070 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10071 uint64_t Offset = Shift / 8; 10072 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10073 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10074 "The size of the original loaded type is not a multiple of a" 10075 " byte."); 10076 // If Offset is bigger than TySizeInBytes, it means we are loading all 10077 // zeros. This should have been optimized before in the process. 10078 assert(TySizeInBytes > Offset && 10079 "Invalid shift amount for given loaded size"); 10080 if (IsBigEndian) 10081 Offset = TySizeInBytes - Offset - getLoadedSize(); 10082 return Offset; 10083 } 10084 10085 /// \brief Generate the sequence of instructions to load the slice 10086 /// represented by this object and redirect the uses of this slice to 10087 /// this new sequence of instructions. 10088 /// \pre this->Inst && this->Origin are valid Instructions and this 10089 /// object passed the legal check: LoadedSlice::isLegal returned true. 10090 /// \return The last instruction of the sequence used to load the slice. 10091 SDValue loadSlice() const { 10092 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10093 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10094 SDValue BaseAddr = OldBaseAddr; 10095 // Get the offset in that chunk of bytes w.r.t. the endianess. 10096 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10097 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10098 if (Offset) { 10099 // BaseAddr = BaseAddr + Offset. 10100 EVT ArithType = BaseAddr.getValueType(); 10101 SDLoc DL(Origin); 10102 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10103 DAG->getConstant(Offset, DL, ArithType)); 10104 } 10105 10106 // Create the type of the loaded slice according to its size. 10107 EVT SliceType = getLoadedType(); 10108 10109 // Create the load for the slice. 10110 SDValue LastInst = DAG->getLoad( 10111 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10112 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 10113 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 10114 // If the final type is not the same as the loaded type, this means that 10115 // we have to pad with zero. Create a zero extend for that. 10116 EVT FinalType = Inst->getValueType(0); 10117 if (SliceType != FinalType) 10118 LastInst = 10119 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10120 return LastInst; 10121 } 10122 10123 /// \brief Check if this slice can be merged with an expensive cross register 10124 /// bank copy. E.g., 10125 /// i = load i32 10126 /// f = bitcast i32 i to float 10127 bool canMergeExpensiveCrossRegisterBankCopy() const { 10128 if (!Inst || !Inst->hasOneUse()) 10129 return false; 10130 SDNode *Use = *Inst->use_begin(); 10131 if (Use->getOpcode() != ISD::BITCAST) 10132 return false; 10133 assert(DAG && "Missing context"); 10134 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10135 EVT ResVT = Use->getValueType(0); 10136 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10137 const TargetRegisterClass *ArgRC = 10138 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10139 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10140 return false; 10141 10142 // At this point, we know that we perform a cross-register-bank copy. 10143 // Check if it is expensive. 10144 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10145 // Assume bitcasts are cheap, unless both register classes do not 10146 // explicitly share a common sub class. 10147 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10148 return false; 10149 10150 // Check if it will be merged with the load. 10151 // 1. Check the alignment constraint. 10152 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10153 ResVT.getTypeForEVT(*DAG->getContext())); 10154 10155 if (RequiredAlignment > getAlignment()) 10156 return false; 10157 10158 // 2. Check that the load is a legal operation for that type. 10159 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10160 return false; 10161 10162 // 3. Check that we do not have a zext in the way. 10163 if (Inst->getValueType(0) != getLoadedType()) 10164 return false; 10165 10166 return true; 10167 } 10168 }; 10169 } 10170 10171 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10172 /// \p UsedBits looks like 0..0 1..1 0..0. 10173 static bool areUsedBitsDense(const APInt &UsedBits) { 10174 // If all the bits are one, this is dense! 10175 if (UsedBits.isAllOnesValue()) 10176 return true; 10177 10178 // Get rid of the unused bits on the right. 10179 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10180 // Get rid of the unused bits on the left. 10181 if (NarrowedUsedBits.countLeadingZeros()) 10182 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10183 // Check that the chunk of bits is completely used. 10184 return NarrowedUsedBits.isAllOnesValue(); 10185 } 10186 10187 /// \brief Check whether or not \p First and \p Second are next to each other 10188 /// in memory. This means that there is no hole between the bits loaded 10189 /// by \p First and the bits loaded by \p Second. 10190 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10191 const LoadedSlice &Second) { 10192 assert(First.Origin == Second.Origin && First.Origin && 10193 "Unable to match different memory origins."); 10194 APInt UsedBits = First.getUsedBits(); 10195 assert((UsedBits & Second.getUsedBits()) == 0 && 10196 "Slices are not supposed to overlap."); 10197 UsedBits |= Second.getUsedBits(); 10198 return areUsedBitsDense(UsedBits); 10199 } 10200 10201 /// \brief Adjust the \p GlobalLSCost according to the target 10202 /// paring capabilities and the layout of the slices. 10203 /// \pre \p GlobalLSCost should account for at least as many loads as 10204 /// there is in the slices in \p LoadedSlices. 10205 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10206 LoadedSlice::Cost &GlobalLSCost) { 10207 unsigned NumberOfSlices = LoadedSlices.size(); 10208 // If there is less than 2 elements, no pairing is possible. 10209 if (NumberOfSlices < 2) 10210 return; 10211 10212 // Sort the slices so that elements that are likely to be next to each 10213 // other in memory are next to each other in the list. 10214 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10215 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10216 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10217 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10218 }); 10219 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10220 // First (resp. Second) is the first (resp. Second) potentially candidate 10221 // to be placed in a paired load. 10222 const LoadedSlice *First = nullptr; 10223 const LoadedSlice *Second = nullptr; 10224 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10225 // Set the beginning of the pair. 10226 First = Second) { 10227 10228 Second = &LoadedSlices[CurrSlice]; 10229 10230 // If First is NULL, it means we start a new pair. 10231 // Get to the next slice. 10232 if (!First) 10233 continue; 10234 10235 EVT LoadedType = First->getLoadedType(); 10236 10237 // If the types of the slices are different, we cannot pair them. 10238 if (LoadedType != Second->getLoadedType()) 10239 continue; 10240 10241 // Check if the target supplies paired loads for this type. 10242 unsigned RequiredAlignment = 0; 10243 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10244 // move to the next pair, this type is hopeless. 10245 Second = nullptr; 10246 continue; 10247 } 10248 // Check if we meet the alignment requirement. 10249 if (RequiredAlignment > First->getAlignment()) 10250 continue; 10251 10252 // Check that both loads are next to each other in memory. 10253 if (!areSlicesNextToEachOther(*First, *Second)) 10254 continue; 10255 10256 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10257 --GlobalLSCost.Loads; 10258 // Move to the next pair. 10259 Second = nullptr; 10260 } 10261 } 10262 10263 /// \brief Check the profitability of all involved LoadedSlice. 10264 /// Currently, it is considered profitable if there is exactly two 10265 /// involved slices (1) which are (2) next to each other in memory, and 10266 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10267 /// 10268 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10269 /// the elements themselves. 10270 /// 10271 /// FIXME: When the cost model will be mature enough, we can relax 10272 /// constraints (1) and (2). 10273 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10274 const APInt &UsedBits, bool ForCodeSize) { 10275 unsigned NumberOfSlices = LoadedSlices.size(); 10276 if (StressLoadSlicing) 10277 return NumberOfSlices > 1; 10278 10279 // Check (1). 10280 if (NumberOfSlices != 2) 10281 return false; 10282 10283 // Check (2). 10284 if (!areUsedBitsDense(UsedBits)) 10285 return false; 10286 10287 // Check (3). 10288 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10289 // The original code has one big load. 10290 OrigCost.Loads = 1; 10291 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10292 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10293 // Accumulate the cost of all the slices. 10294 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10295 GlobalSlicingCost += SliceCost; 10296 10297 // Account as cost in the original configuration the gain obtained 10298 // with the current slices. 10299 OrigCost.addSliceGain(LS); 10300 } 10301 10302 // If the target supports paired load, adjust the cost accordingly. 10303 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10304 return OrigCost > GlobalSlicingCost; 10305 } 10306 10307 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10308 /// operations, split it in the various pieces being extracted. 10309 /// 10310 /// This sort of thing is introduced by SROA. 10311 /// This slicing takes care not to insert overlapping loads. 10312 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10313 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10314 if (Level < AfterLegalizeDAG) 10315 return false; 10316 10317 LoadSDNode *LD = cast<LoadSDNode>(N); 10318 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10319 !LD->getValueType(0).isInteger()) 10320 return false; 10321 10322 // Keep track of already used bits to detect overlapping values. 10323 // In that case, we will just abort the transformation. 10324 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10325 10326 SmallVector<LoadedSlice, 4> LoadedSlices; 10327 10328 // Check if this load is used as several smaller chunks of bits. 10329 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10330 // of computation for each trunc. 10331 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10332 UI != UIEnd; ++UI) { 10333 // Skip the uses of the chain. 10334 if (UI.getUse().getResNo() != 0) 10335 continue; 10336 10337 SDNode *User = *UI; 10338 unsigned Shift = 0; 10339 10340 // Check if this is a trunc(lshr). 10341 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10342 isa<ConstantSDNode>(User->getOperand(1))) { 10343 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10344 User = *User->use_begin(); 10345 } 10346 10347 // At this point, User is a Truncate, iff we encountered, trunc or 10348 // trunc(lshr). 10349 if (User->getOpcode() != ISD::TRUNCATE) 10350 return false; 10351 10352 // The width of the type must be a power of 2 and greater than 8-bits. 10353 // Otherwise the load cannot be represented in LLVM IR. 10354 // Moreover, if we shifted with a non-8-bits multiple, the slice 10355 // will be across several bytes. We do not support that. 10356 unsigned Width = User->getValueSizeInBits(0); 10357 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10358 return 0; 10359 10360 // Build the slice for this chain of computations. 10361 LoadedSlice LS(User, LD, Shift, &DAG); 10362 APInt CurrentUsedBits = LS.getUsedBits(); 10363 10364 // Check if this slice overlaps with another. 10365 if ((CurrentUsedBits & UsedBits) != 0) 10366 return false; 10367 // Update the bits used globally. 10368 UsedBits |= CurrentUsedBits; 10369 10370 // Check if the new slice would be legal. 10371 if (!LS.isLegal()) 10372 return false; 10373 10374 // Record the slice. 10375 LoadedSlices.push_back(LS); 10376 } 10377 10378 // Abort slicing if it does not seem to be profitable. 10379 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10380 return false; 10381 10382 ++SlicedLoads; 10383 10384 // Rewrite each chain to use an independent load. 10385 // By construction, each chain can be represented by a unique load. 10386 10387 // Prepare the argument for the new token factor for all the slices. 10388 SmallVector<SDValue, 8> ArgChains; 10389 for (SmallVectorImpl<LoadedSlice>::const_iterator 10390 LSIt = LoadedSlices.begin(), 10391 LSItEnd = LoadedSlices.end(); 10392 LSIt != LSItEnd; ++LSIt) { 10393 SDValue SliceInst = LSIt->loadSlice(); 10394 CombineTo(LSIt->Inst, SliceInst, true); 10395 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10396 SliceInst = SliceInst.getOperand(0); 10397 assert(SliceInst->getOpcode() == ISD::LOAD && 10398 "It takes more than a zext to get to the loaded slice!!"); 10399 ArgChains.push_back(SliceInst.getValue(1)); 10400 } 10401 10402 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10403 ArgChains); 10404 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10405 return true; 10406 } 10407 10408 /// Check to see if V is (and load (ptr), imm), where the load is having 10409 /// specific bytes cleared out. If so, return the byte size being masked out 10410 /// and the shift amount. 10411 static std::pair<unsigned, unsigned> 10412 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10413 std::pair<unsigned, unsigned> Result(0, 0); 10414 10415 // Check for the structure we're looking for. 10416 if (V->getOpcode() != ISD::AND || 10417 !isa<ConstantSDNode>(V->getOperand(1)) || 10418 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10419 return Result; 10420 10421 // Check the chain and pointer. 10422 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10423 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10424 10425 // The store should be chained directly to the load or be an operand of a 10426 // tokenfactor. 10427 if (LD == Chain.getNode()) 10428 ; // ok. 10429 else if (Chain->getOpcode() != ISD::TokenFactor) 10430 return Result; // Fail. 10431 else { 10432 bool isOk = false; 10433 for (const SDValue &ChainOp : Chain->op_values()) 10434 if (ChainOp.getNode() == LD) { 10435 isOk = true; 10436 break; 10437 } 10438 if (!isOk) return Result; 10439 } 10440 10441 // This only handles simple types. 10442 if (V.getValueType() != MVT::i16 && 10443 V.getValueType() != MVT::i32 && 10444 V.getValueType() != MVT::i64) 10445 return Result; 10446 10447 // Check the constant mask. Invert it so that the bits being masked out are 10448 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10449 // follow the sign bit for uniformity. 10450 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10451 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10452 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10453 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10454 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10455 if (NotMaskLZ == 64) return Result; // All zero mask. 10456 10457 // See if we have a continuous run of bits. If so, we have 0*1+0* 10458 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10459 return Result; 10460 10461 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10462 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10463 NotMaskLZ -= 64-V.getValueSizeInBits(); 10464 10465 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10466 switch (MaskedBytes) { 10467 case 1: 10468 case 2: 10469 case 4: break; 10470 default: return Result; // All one mask, or 5-byte mask. 10471 } 10472 10473 // Verify that the first bit starts at a multiple of mask so that the access 10474 // is aligned the same as the access width. 10475 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10476 10477 Result.first = MaskedBytes; 10478 Result.second = NotMaskTZ/8; 10479 return Result; 10480 } 10481 10482 10483 /// Check to see if IVal is something that provides a value as specified by 10484 /// MaskInfo. If so, replace the specified store with a narrower store of 10485 /// truncated IVal. 10486 static SDNode * 10487 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10488 SDValue IVal, StoreSDNode *St, 10489 DAGCombiner *DC) { 10490 unsigned NumBytes = MaskInfo.first; 10491 unsigned ByteShift = MaskInfo.second; 10492 SelectionDAG &DAG = DC->getDAG(); 10493 10494 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10495 // that uses this. If not, this is not a replacement. 10496 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10497 ByteShift*8, (ByteShift+NumBytes)*8); 10498 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10499 10500 // Check that it is legal on the target to do this. It is legal if the new 10501 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10502 // legalization. 10503 MVT VT = MVT::getIntegerVT(NumBytes*8); 10504 if (!DC->isTypeLegal(VT)) 10505 return nullptr; 10506 10507 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10508 // shifted by ByteShift and truncated down to NumBytes. 10509 if (ByteShift) { 10510 SDLoc DL(IVal); 10511 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10512 DAG.getConstant(ByteShift*8, DL, 10513 DC->getShiftAmountTy(IVal.getValueType()))); 10514 } 10515 10516 // Figure out the offset for the store and the alignment of the access. 10517 unsigned StOffset; 10518 unsigned NewAlign = St->getAlignment(); 10519 10520 if (DAG.getDataLayout().isLittleEndian()) 10521 StOffset = ByteShift; 10522 else 10523 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10524 10525 SDValue Ptr = St->getBasePtr(); 10526 if (StOffset) { 10527 SDLoc DL(IVal); 10528 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10529 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10530 NewAlign = MinAlign(NewAlign, StOffset); 10531 } 10532 10533 // Truncate down to the new size. 10534 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10535 10536 ++OpsNarrowed; 10537 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10538 St->getPointerInfo().getWithOffset(StOffset), 10539 false, false, NewAlign).getNode(); 10540 } 10541 10542 10543 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10544 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10545 /// narrowing the load and store if it would end up being a win for performance 10546 /// or code size. 10547 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10548 StoreSDNode *ST = cast<StoreSDNode>(N); 10549 if (ST->isVolatile()) 10550 return SDValue(); 10551 10552 SDValue Chain = ST->getChain(); 10553 SDValue Value = ST->getValue(); 10554 SDValue Ptr = ST->getBasePtr(); 10555 EVT VT = Value.getValueType(); 10556 10557 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10558 return SDValue(); 10559 10560 unsigned Opc = Value.getOpcode(); 10561 10562 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10563 // is a byte mask indicating a consecutive number of bytes, check to see if 10564 // Y is known to provide just those bytes. If so, we try to replace the 10565 // load + replace + store sequence with a single (narrower) store, which makes 10566 // the load dead. 10567 if (Opc == ISD::OR) { 10568 std::pair<unsigned, unsigned> MaskedLoad; 10569 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10570 if (MaskedLoad.first) 10571 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10572 Value.getOperand(1), ST,this)) 10573 return SDValue(NewST, 0); 10574 10575 // Or is commutative, so try swapping X and Y. 10576 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10577 if (MaskedLoad.first) 10578 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10579 Value.getOperand(0), ST,this)) 10580 return SDValue(NewST, 0); 10581 } 10582 10583 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10584 Value.getOperand(1).getOpcode() != ISD::Constant) 10585 return SDValue(); 10586 10587 SDValue N0 = Value.getOperand(0); 10588 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10589 Chain == SDValue(N0.getNode(), 1)) { 10590 LoadSDNode *LD = cast<LoadSDNode>(N0); 10591 if (LD->getBasePtr() != Ptr || 10592 LD->getPointerInfo().getAddrSpace() != 10593 ST->getPointerInfo().getAddrSpace()) 10594 return SDValue(); 10595 10596 // Find the type to narrow it the load / op / store to. 10597 SDValue N1 = Value.getOperand(1); 10598 unsigned BitWidth = N1.getValueSizeInBits(); 10599 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10600 if (Opc == ISD::AND) 10601 Imm ^= APInt::getAllOnesValue(BitWidth); 10602 if (Imm == 0 || Imm.isAllOnesValue()) 10603 return SDValue(); 10604 unsigned ShAmt = Imm.countTrailingZeros(); 10605 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10606 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10607 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10608 // The narrowing should be profitable, the load/store operation should be 10609 // legal (or custom) and the store size should be equal to the NewVT width. 10610 while (NewBW < BitWidth && 10611 (NewVT.getStoreSizeInBits() != NewBW || 10612 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10613 !TLI.isNarrowingProfitable(VT, NewVT))) { 10614 NewBW = NextPowerOf2(NewBW); 10615 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10616 } 10617 if (NewBW >= BitWidth) 10618 return SDValue(); 10619 10620 // If the lsb changed does not start at the type bitwidth boundary, 10621 // start at the previous one. 10622 if (ShAmt % NewBW) 10623 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10624 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10625 std::min(BitWidth, ShAmt + NewBW)); 10626 if ((Imm & Mask) == Imm) { 10627 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10628 if (Opc == ISD::AND) 10629 NewImm ^= APInt::getAllOnesValue(NewBW); 10630 uint64_t PtrOff = ShAmt / 8; 10631 // For big endian targets, we need to adjust the offset to the pointer to 10632 // load the correct bytes. 10633 if (DAG.getDataLayout().isBigEndian()) 10634 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10635 10636 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10637 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10638 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10639 return SDValue(); 10640 10641 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10642 Ptr.getValueType(), Ptr, 10643 DAG.getConstant(PtrOff, SDLoc(LD), 10644 Ptr.getValueType())); 10645 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10646 LD->getChain(), NewPtr, 10647 LD->getPointerInfo().getWithOffset(PtrOff), 10648 LD->isVolatile(), LD->isNonTemporal(), 10649 LD->isInvariant(), NewAlign, 10650 LD->getAAInfo()); 10651 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10652 DAG.getConstant(NewImm, SDLoc(Value), 10653 NewVT)); 10654 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10655 NewVal, NewPtr, 10656 ST->getPointerInfo().getWithOffset(PtrOff), 10657 false, false, NewAlign); 10658 10659 AddToWorklist(NewPtr.getNode()); 10660 AddToWorklist(NewLD.getNode()); 10661 AddToWorklist(NewVal.getNode()); 10662 WorklistRemover DeadNodes(*this); 10663 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10664 ++OpsNarrowed; 10665 return NewST; 10666 } 10667 } 10668 10669 return SDValue(); 10670 } 10671 10672 /// For a given floating point load / store pair, if the load value isn't used 10673 /// by any other operations, then consider transforming the pair to integer 10674 /// load / store operations if the target deems the transformation profitable. 10675 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10676 StoreSDNode *ST = cast<StoreSDNode>(N); 10677 SDValue Chain = ST->getChain(); 10678 SDValue Value = ST->getValue(); 10679 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10680 Value.hasOneUse() && 10681 Chain == SDValue(Value.getNode(), 1)) { 10682 LoadSDNode *LD = cast<LoadSDNode>(Value); 10683 EVT VT = LD->getMemoryVT(); 10684 if (!VT.isFloatingPoint() || 10685 VT != ST->getMemoryVT() || 10686 LD->isNonTemporal() || 10687 ST->isNonTemporal() || 10688 LD->getPointerInfo().getAddrSpace() != 0 || 10689 ST->getPointerInfo().getAddrSpace() != 0) 10690 return SDValue(); 10691 10692 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10693 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10694 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10695 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10696 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10697 return SDValue(); 10698 10699 unsigned LDAlign = LD->getAlignment(); 10700 unsigned STAlign = ST->getAlignment(); 10701 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10702 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 10703 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10704 return SDValue(); 10705 10706 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10707 LD->getChain(), LD->getBasePtr(), 10708 LD->getPointerInfo(), 10709 false, false, false, LDAlign); 10710 10711 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10712 NewLD, ST->getBasePtr(), 10713 ST->getPointerInfo(), 10714 false, false, STAlign); 10715 10716 AddToWorklist(NewLD.getNode()); 10717 AddToWorklist(NewST.getNode()); 10718 WorklistRemover DeadNodes(*this); 10719 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10720 ++LdStFP2Int; 10721 return NewST; 10722 } 10723 10724 return SDValue(); 10725 } 10726 10727 namespace { 10728 /// Helper struct to parse and store a memory address as base + index + offset. 10729 /// We ignore sign extensions when it is safe to do so. 10730 /// The following two expressions are not equivalent. To differentiate we need 10731 /// to store whether there was a sign extension involved in the index 10732 /// computation. 10733 /// (load (i64 add (i64 copyfromreg %c) 10734 /// (i64 signextend (add (i8 load %index) 10735 /// (i8 1)))) 10736 /// vs 10737 /// 10738 /// (load (i64 add (i64 copyfromreg %c) 10739 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10740 /// (i32 1))))) 10741 struct BaseIndexOffset { 10742 SDValue Base; 10743 SDValue Index; 10744 int64_t Offset; 10745 bool IsIndexSignExt; 10746 10747 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10748 10749 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10750 bool IsIndexSignExt) : 10751 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10752 10753 bool equalBaseIndex(const BaseIndexOffset &Other) { 10754 return Other.Base == Base && Other.Index == Index && 10755 Other.IsIndexSignExt == IsIndexSignExt; 10756 } 10757 10758 /// Parses tree in Ptr for base, index, offset addresses. 10759 static BaseIndexOffset match(SDValue Ptr) { 10760 bool IsIndexSignExt = false; 10761 10762 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10763 // instruction, then it could be just the BASE or everything else we don't 10764 // know how to handle. Just use Ptr as BASE and give up. 10765 if (Ptr->getOpcode() != ISD::ADD) 10766 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10767 10768 // We know that we have at least an ADD instruction. Try to pattern match 10769 // the simple case of BASE + OFFSET. 10770 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10771 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10772 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10773 IsIndexSignExt); 10774 } 10775 10776 // Inside a loop the current BASE pointer is calculated using an ADD and a 10777 // MUL instruction. In this case Ptr is the actual BASE pointer. 10778 // (i64 add (i64 %array_ptr) 10779 // (i64 mul (i64 %induction_var) 10780 // (i64 %element_size))) 10781 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10782 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10783 10784 // Look at Base + Index + Offset cases. 10785 SDValue Base = Ptr->getOperand(0); 10786 SDValue IndexOffset = Ptr->getOperand(1); 10787 10788 // Skip signextends. 10789 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10790 IndexOffset = IndexOffset->getOperand(0); 10791 IsIndexSignExt = true; 10792 } 10793 10794 // Either the case of Base + Index (no offset) or something else. 10795 if (IndexOffset->getOpcode() != ISD::ADD) 10796 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10797 10798 // Now we have the case of Base + Index + offset. 10799 SDValue Index = IndexOffset->getOperand(0); 10800 SDValue Offset = IndexOffset->getOperand(1); 10801 10802 if (!isa<ConstantSDNode>(Offset)) 10803 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10804 10805 // Ignore signextends. 10806 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 10807 Index = Index->getOperand(0); 10808 IsIndexSignExt = true; 10809 } else IsIndexSignExt = false; 10810 10811 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 10812 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 10813 } 10814 }; 10815 } // namespace 10816 10817 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG, 10818 SDLoc SL, 10819 ArrayRef<MemOpLink> Stores, 10820 EVT Ty) const { 10821 SmallVector<SDValue, 8> BuildVector; 10822 10823 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) 10824 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue()); 10825 10826 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector); 10827 } 10828 10829 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 10830 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 10831 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 10832 // Make sure we have something to merge. 10833 if (NumStores < 2) 10834 return false; 10835 10836 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 10837 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10838 unsigned LatestNodeUsed = 0; 10839 10840 for (unsigned i=0; i < NumStores; ++i) { 10841 // Find a chain for the new wide-store operand. Notice that some 10842 // of the store nodes that we found may not be selected for inclusion 10843 // in the wide store. The chain we use needs to be the chain of the 10844 // latest store node which is *used* and replaced by the wide store. 10845 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 10846 LatestNodeUsed = i; 10847 } 10848 10849 // The latest Node in the DAG. 10850 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 10851 SDLoc DL(StoreNodes[0].MemNode); 10852 10853 SDValue StoredVal; 10854 if (UseVector) { 10855 bool IsVec = MemVT.isVector(); 10856 unsigned Elts = NumStores; 10857 if (IsVec) { 10858 // When merging vector stores, get the total number of elements. 10859 Elts *= MemVT.getVectorNumElements(); 10860 } 10861 // Get the type for the merged vector store. 10862 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 10863 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 10864 10865 if (IsConstantSrc) { 10866 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty); 10867 } else { 10868 SmallVector<SDValue, 8> Ops; 10869 for (unsigned i = 0; i < NumStores; ++i) { 10870 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10871 SDValue Val = St->getValue(); 10872 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 10873 if (Val.getValueType() != MemVT) 10874 return false; 10875 Ops.push_back(Val); 10876 } 10877 10878 // Build the extracted vector elements back into a vector. 10879 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 10880 DL, Ty, Ops); } 10881 } else { 10882 // We should always use a vector store when merging extracted vector 10883 // elements, so this path implies a store of constants. 10884 assert(IsConstantSrc && "Merged vector elements should use vector store"); 10885 10886 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 10887 APInt StoreInt(SizeInBits, 0); 10888 10889 // Construct a single integer constant which is made of the smaller 10890 // constant inputs. 10891 bool IsLE = DAG.getDataLayout().isLittleEndian(); 10892 for (unsigned i = 0; i < NumStores; ++i) { 10893 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 10894 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 10895 SDValue Val = St->getValue(); 10896 StoreInt <<= ElementSizeBytes * 8; 10897 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 10898 StoreInt |= C->getAPIntValue().zext(SizeInBits); 10899 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 10900 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 10901 } else { 10902 llvm_unreachable("Invalid constant element type"); 10903 } 10904 } 10905 10906 // Create the new Load and Store operations. 10907 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 10908 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 10909 } 10910 10911 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal, 10912 FirstInChain->getBasePtr(), 10913 FirstInChain->getPointerInfo(), 10914 false, false, 10915 FirstInChain->getAlignment()); 10916 10917 // Replace the last store with the new store 10918 CombineTo(LatestOp, NewStore); 10919 // Erase all other stores. 10920 for (unsigned i = 0; i < NumStores; ++i) { 10921 if (StoreNodes[i].MemNode == LatestOp) 10922 continue; 10923 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10924 // ReplaceAllUsesWith will replace all uses that existed when it was 10925 // called, but graph optimizations may cause new ones to appear. For 10926 // example, the case in pr14333 looks like 10927 // 10928 // St's chain -> St -> another store -> X 10929 // 10930 // And the only difference from St to the other store is the chain. 10931 // When we change it's chain to be St's chain they become identical, 10932 // get CSEed and the net result is that X is now a use of St. 10933 // Since we know that St is redundant, just iterate. 10934 while (!St->use_empty()) 10935 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 10936 deleteAndRecombine(St); 10937 } 10938 10939 return true; 10940 } 10941 10942 void DAGCombiner::getStoreMergeAndAliasCandidates( 10943 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 10944 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 10945 // This holds the base pointer, index, and the offset in bytes from the base 10946 // pointer. 10947 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 10948 10949 // We must have a base and an offset. 10950 if (!BasePtr.Base.getNode()) 10951 return; 10952 10953 // Do not handle stores to undef base pointers. 10954 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 10955 return; 10956 10957 // Walk up the chain and look for nodes with offsets from the same 10958 // base pointer. Stop when reaching an instruction with a different kind 10959 // or instruction which has a different base pointer. 10960 EVT MemVT = St->getMemoryVT(); 10961 unsigned Seq = 0; 10962 StoreSDNode *Index = St; 10963 10964 10965 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10966 : DAG.getSubtarget().useAA(); 10967 10968 if (UseAA) { 10969 // Look at other users of the same chain. Stores on the same chain do not 10970 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 10971 // to be on the same chain, so don't bother looking at adjacent chains. 10972 10973 SDValue Chain = St->getChain(); 10974 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 10975 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 10976 10977 if (OtherST->isVolatile() || OtherST->isIndexed()) 10978 continue; 10979 10980 if (OtherST->getMemoryVT() != MemVT) 10981 continue; 10982 10983 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr()); 10984 10985 if (Ptr.equalBaseIndex(BasePtr)) 10986 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 10987 } 10988 } 10989 10990 return; 10991 } 10992 10993 while (Index) { 10994 // If the chain has more than one use, then we can't reorder the mem ops. 10995 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 10996 break; 10997 10998 // Find the base pointer and offset for this memory node. 10999 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 11000 11001 // Check that the base pointer is the same as the original one. 11002 if (!Ptr.equalBaseIndex(BasePtr)) 11003 break; 11004 11005 // The memory operands must not be volatile. 11006 if (Index->isVolatile() || Index->isIndexed()) 11007 break; 11008 11009 // No truncation. 11010 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 11011 if (St->isTruncatingStore()) 11012 break; 11013 11014 // The stored memory type must be the same. 11015 if (Index->getMemoryVT() != MemVT) 11016 break; 11017 11018 // We found a potential memory operand to merge. 11019 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11020 11021 // Find the next memory operand in the chain. If the next operand in the 11022 // chain is a store then move up and continue the scan with the next 11023 // memory operand. If the next operand is a load save it and use alias 11024 // information to check if it interferes with anything. 11025 SDNode *NextInChain = Index->getChain().getNode(); 11026 while (1) { 11027 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11028 // We found a store node. Use it for the next iteration. 11029 Index = STn; 11030 break; 11031 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11032 if (Ldn->isVolatile()) { 11033 Index = nullptr; 11034 break; 11035 } 11036 11037 // Save the load node for later. Continue the scan. 11038 AliasLoadNodes.push_back(Ldn); 11039 NextInChain = Ldn->getChain().getNode(); 11040 continue; 11041 } else { 11042 Index = nullptr; 11043 break; 11044 } 11045 } 11046 } 11047 } 11048 11049 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11050 if (OptLevel == CodeGenOpt::None) 11051 return false; 11052 11053 EVT MemVT = St->getMemoryVT(); 11054 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11055 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11056 Attribute::NoImplicitFloat); 11057 11058 // This function cannot currently deal with non-byte-sized memory sizes. 11059 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11060 return false; 11061 11062 // Don't merge vectors into wider inputs. 11063 if (MemVT.isVector() || !MemVT.isSimple()) 11064 return false; 11065 11066 // Perform an early exit check. Do not bother looking at stored values that 11067 // are not constants, loads, or extracted vector elements. 11068 SDValue StoredVal = St->getValue(); 11069 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11070 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11071 isa<ConstantFPSDNode>(StoredVal); 11072 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT); 11073 11074 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc) 11075 return false; 11076 11077 // Only look at ends of store sequences. 11078 SDValue Chain = SDValue(St, 0); 11079 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11080 return false; 11081 11082 // Save the LoadSDNodes that we find in the chain. 11083 // We need to make sure that these nodes do not interfere with 11084 // any of the store nodes. 11085 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11086 11087 // Save the StoreSDNodes that we find in the chain. 11088 SmallVector<MemOpLink, 8> StoreNodes; 11089 11090 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11091 11092 // Check if there is anything to merge. 11093 if (StoreNodes.size() < 2) 11094 return false; 11095 11096 // Sort the memory operands according to their distance from the base pointer. 11097 std::sort(StoreNodes.begin(), StoreNodes.end(), 11098 [](MemOpLink LHS, MemOpLink RHS) { 11099 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11100 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11101 LHS.SequenceNum > RHS.SequenceNum); 11102 }); 11103 11104 // Scan the memory operations on the chain and find the first non-consecutive 11105 // store memory address. 11106 unsigned LastConsecutiveStore = 0; 11107 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11108 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11109 11110 // Check that the addresses are consecutive starting from the second 11111 // element in the list of stores. 11112 if (i > 0) { 11113 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11114 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11115 break; 11116 } 11117 11118 bool Alias = false; 11119 // Check if this store interferes with any of the loads that we found. 11120 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 11121 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 11122 Alias = true; 11123 break; 11124 } 11125 // We found a load that alias with this store. Stop the sequence. 11126 if (Alias) 11127 break; 11128 11129 // Mark this node as useful. 11130 LastConsecutiveStore = i; 11131 } 11132 11133 // The node with the lowest store address. 11134 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11135 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11136 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11137 LLVMContext &Context = *DAG.getContext(); 11138 const DataLayout &DL = DAG.getDataLayout(); 11139 11140 // Store the constants into memory as one consecutive store. 11141 if (IsConstantSrc) { 11142 unsigned LastLegalType = 0; 11143 unsigned LastLegalVectorType = 0; 11144 bool NonZero = false; 11145 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11146 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11147 SDValue StoredVal = St->getValue(); 11148 11149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11150 NonZero |= !C->isNullValue(); 11151 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11152 NonZero |= !C->getConstantFPValue()->isNullValue(); 11153 } else { 11154 // Non-constant. 11155 break; 11156 } 11157 11158 // Find a legal type for the constant store. 11159 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11160 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11161 bool IsFast; 11162 if (TLI.isTypeLegal(StoreTy) && 11163 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11164 FirstStoreAlign, &IsFast) && IsFast) { 11165 LastLegalType = i+1; 11166 // Or check whether a truncstore is legal. 11167 } else if (TLI.getTypeAction(Context, StoreTy) == 11168 TargetLowering::TypePromoteInteger) { 11169 EVT LegalizedStoredValueTy = 11170 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11171 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11172 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11173 FirstStoreAS, FirstStoreAlign, &IsFast) && 11174 IsFast) { 11175 LastLegalType = i + 1; 11176 } 11177 } 11178 11179 // We only use vectors if the constant is known to be zero or the target 11180 // allows it and the function is not marked with the noimplicitfloat 11181 // attribute. 11182 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11183 FirstStoreAS)) && 11184 !NoVectors) { 11185 // Find a legal type for the vector store. 11186 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11187 if (TLI.isTypeLegal(Ty) && 11188 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11189 FirstStoreAlign, &IsFast) && IsFast) 11190 LastLegalVectorType = i + 1; 11191 } 11192 } 11193 11194 // Check if we found a legal integer type to store. 11195 if (LastLegalType == 0 && LastLegalVectorType == 0) 11196 return false; 11197 11198 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11199 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11200 11201 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11202 true, UseVector); 11203 } 11204 11205 // When extracting multiple vector elements, try to store them 11206 // in one vector store rather than a sequence of scalar stores. 11207 if (IsExtractVecEltSrc) { 11208 unsigned NumElem = 0; 11209 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11210 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11211 SDValue StoredVal = St->getValue(); 11212 // This restriction could be loosened. 11213 // Bail out if any stored values are not elements extracted from a vector. 11214 // It should be possible to handle mixed sources, but load sources need 11215 // more careful handling (see the block of code below that handles 11216 // consecutive loads). 11217 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11218 return false; 11219 11220 // Find a legal type for the vector store. 11221 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11222 bool IsFast; 11223 if (TLI.isTypeLegal(Ty) && 11224 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11225 FirstStoreAlign, &IsFast) && IsFast) 11226 NumElem = i + 1; 11227 } 11228 11229 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11230 false, true); 11231 } 11232 11233 // Below we handle the case of multiple consecutive stores that 11234 // come from multiple consecutive loads. We merge them into a single 11235 // wide load and a single wide store. 11236 11237 // Look for load nodes which are used by the stored values. 11238 SmallVector<MemOpLink, 8> LoadNodes; 11239 11240 // Find acceptable loads. Loads need to have the same chain (token factor), 11241 // must not be zext, volatile, indexed, and they must be consecutive. 11242 BaseIndexOffset LdBasePtr; 11243 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11244 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11245 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11246 if (!Ld) break; 11247 11248 // Loads must only have one use. 11249 if (!Ld->hasNUsesOfValue(1, 0)) 11250 break; 11251 11252 // The memory operands must not be volatile. 11253 if (Ld->isVolatile() || Ld->isIndexed()) 11254 break; 11255 11256 // We do not accept ext loads. 11257 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11258 break; 11259 11260 // The stored memory type must be the same. 11261 if (Ld->getMemoryVT() != MemVT) 11262 break; 11263 11264 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 11265 // If this is not the first ptr that we check. 11266 if (LdBasePtr.Base.getNode()) { 11267 // The base ptr must be the same. 11268 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11269 break; 11270 } else { 11271 // Check that all other base pointers are the same as this one. 11272 LdBasePtr = LdPtr; 11273 } 11274 11275 // We found a potential memory operand to merge. 11276 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11277 } 11278 11279 if (LoadNodes.size() < 2) 11280 return false; 11281 11282 // If we have load/store pair instructions and we only have two values, 11283 // don't bother. 11284 unsigned RequiredAlignment; 11285 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11286 St->getAlignment() >= RequiredAlignment) 11287 return false; 11288 11289 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11290 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11291 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11292 11293 // Scan the memory operations on the chain and find the first non-consecutive 11294 // load memory address. These variables hold the index in the store node 11295 // array. 11296 unsigned LastConsecutiveLoad = 0; 11297 // This variable refers to the size and not index in the array. 11298 unsigned LastLegalVectorType = 0; 11299 unsigned LastLegalIntegerType = 0; 11300 StartAddress = LoadNodes[0].OffsetFromBase; 11301 SDValue FirstChain = FirstLoad->getChain(); 11302 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11303 // All loads much share the same chain. 11304 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11305 break; 11306 11307 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11308 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11309 break; 11310 LastConsecutiveLoad = i; 11311 // Find a legal type for the vector store. 11312 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11313 bool IsFastSt, IsFastLd; 11314 if (TLI.isTypeLegal(StoreTy) && 11315 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11316 FirstStoreAlign, &IsFastSt) && IsFastSt && 11317 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11318 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11319 LastLegalVectorType = i + 1; 11320 } 11321 11322 // Find a legal type for the integer store. 11323 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11324 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11325 if (TLI.isTypeLegal(StoreTy) && 11326 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11327 FirstStoreAlign, &IsFastSt) && IsFastSt && 11328 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11329 FirstLoadAlign, &IsFastLd) && IsFastLd) 11330 LastLegalIntegerType = i + 1; 11331 // Or check whether a truncstore and extload is legal. 11332 else if (TLI.getTypeAction(Context, StoreTy) == 11333 TargetLowering::TypePromoteInteger) { 11334 EVT LegalizedStoredValueTy = 11335 TLI.getTypeToTransformTo(Context, StoreTy); 11336 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11337 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11338 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11339 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11340 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11341 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11342 IsFastSt && 11343 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11344 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11345 IsFastLd) 11346 LastLegalIntegerType = i+1; 11347 } 11348 } 11349 11350 // Only use vector types if the vector type is larger than the integer type. 11351 // If they are the same, use integers. 11352 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11353 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11354 11355 // We add +1 here because the LastXXX variables refer to location while 11356 // the NumElem refers to array/index size. 11357 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11358 NumElem = std::min(LastLegalType, NumElem); 11359 11360 if (NumElem < 2) 11361 return false; 11362 11363 // The latest Node in the DAG. 11364 unsigned LatestNodeUsed = 0; 11365 for (unsigned i=1; i<NumElem; ++i) { 11366 // Find a chain for the new wide-store operand. Notice that some 11367 // of the store nodes that we found may not be selected for inclusion 11368 // in the wide store. The chain we use needs to be the chain of the 11369 // latest store node which is *used* and replaced by the wide store. 11370 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11371 LatestNodeUsed = i; 11372 } 11373 11374 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11375 11376 // Find if it is better to use vectors or integers to load and store 11377 // to memory. 11378 EVT JointMemOpVT; 11379 if (UseVectorTy) { 11380 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11381 } else { 11382 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11383 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11384 } 11385 11386 SDLoc LoadDL(LoadNodes[0].MemNode); 11387 SDLoc StoreDL(StoreNodes[0].MemNode); 11388 11389 SDValue NewLoad = DAG.getLoad( 11390 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11391 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11392 11393 SDValue NewStore = DAG.getStore( 11394 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(), 11395 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11396 11397 // Replace one of the loads with the new load. 11398 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 11399 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11400 SDValue(NewLoad.getNode(), 1)); 11401 11402 // Remove the rest of the load chains. 11403 for (unsigned i = 1; i < NumElem ; ++i) { 11404 // Replace all chain users of the old load nodes with the chain of the new 11405 // load node. 11406 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11407 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 11408 } 11409 11410 // Replace the last store with the new store. 11411 CombineTo(LatestOp, NewStore); 11412 // Erase all other stores. 11413 for (unsigned i = 0; i < NumElem ; ++i) { 11414 // Remove all Store nodes. 11415 if (StoreNodes[i].MemNode == LatestOp) 11416 continue; 11417 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11418 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11419 deleteAndRecombine(St); 11420 } 11421 11422 return true; 11423 } 11424 11425 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11426 SDLoc SL(ST); 11427 SDValue ReplStore; 11428 11429 // Replace the chain to avoid dependency. 11430 if (ST->isTruncatingStore()) { 11431 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11432 ST->getBasePtr(), ST->getMemoryVT(), 11433 ST->getMemOperand()); 11434 } else { 11435 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11436 ST->getMemOperand()); 11437 } 11438 11439 // Create token to keep both nodes around. 11440 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11441 MVT::Other, ST->getChain(), ReplStore); 11442 11443 // Make sure the new and old chains are cleaned up. 11444 AddToWorklist(Token.getNode()); 11445 11446 // Don't add users to work list. 11447 return CombineTo(ST, Token, false); 11448 } 11449 11450 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11451 SDValue Value = ST->getValue(); 11452 if (Value.getOpcode() == ISD::TargetConstantFP) 11453 return SDValue(); 11454 11455 SDLoc DL(ST); 11456 11457 SDValue Chain = ST->getChain(); 11458 SDValue Ptr = ST->getBasePtr(); 11459 11460 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11461 11462 // NOTE: If the original store is volatile, this transform must not increase 11463 // the number of stores. For example, on x86-32 an f64 can be stored in one 11464 // processor operation but an i64 (which is not legal) requires two. So the 11465 // transform should not be done in this case. 11466 11467 SDValue Tmp; 11468 switch (CFP->getSimpleValueType(0).SimpleTy) { 11469 default: 11470 llvm_unreachable("Unknown FP type"); 11471 case MVT::f16: // We don't do this for these yet. 11472 case MVT::f80: 11473 case MVT::f128: 11474 case MVT::ppcf128: 11475 return SDValue(); 11476 case MVT::f32: 11477 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11478 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11479 ; 11480 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11481 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11482 MVT::i32); 11483 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11484 } 11485 11486 return SDValue(); 11487 case MVT::f64: 11488 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11489 !ST->isVolatile()) || 11490 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11491 ; 11492 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11493 getZExtValue(), SDLoc(CFP), MVT::i64); 11494 return DAG.getStore(Chain, DL, Tmp, 11495 Ptr, ST->getMemOperand()); 11496 } 11497 11498 if (!ST->isVolatile() && 11499 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11500 // Many FP stores are not made apparent until after legalize, e.g. for 11501 // argument passing. Since this is so common, custom legalize the 11502 // 64-bit integer store into two 32-bit stores. 11503 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11504 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11505 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11506 if (DAG.getDataLayout().isBigEndian()) 11507 std::swap(Lo, Hi); 11508 11509 unsigned Alignment = ST->getAlignment(); 11510 bool isVolatile = ST->isVolatile(); 11511 bool isNonTemporal = ST->isNonTemporal(); 11512 AAMDNodes AAInfo = ST->getAAInfo(); 11513 11514 SDValue St0 = DAG.getStore(Chain, DL, Lo, 11515 Ptr, ST->getPointerInfo(), 11516 isVolatile, isNonTemporal, 11517 ST->getAlignment(), AAInfo); 11518 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11519 DAG.getConstant(4, DL, Ptr.getValueType())); 11520 Alignment = MinAlign(Alignment, 4U); 11521 SDValue St1 = DAG.getStore(Chain, DL, Hi, 11522 Ptr, ST->getPointerInfo().getWithOffset(4), 11523 isVolatile, isNonTemporal, 11524 Alignment, AAInfo); 11525 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11526 St0, St1); 11527 } 11528 11529 return SDValue(); 11530 } 11531 } 11532 11533 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11534 StoreSDNode *ST = cast<StoreSDNode>(N); 11535 SDValue Chain = ST->getChain(); 11536 SDValue Value = ST->getValue(); 11537 SDValue Ptr = ST->getBasePtr(); 11538 11539 // If this is a store of a bit convert, store the input value if the 11540 // resultant store does not need a higher alignment than the original. 11541 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11542 ST->isUnindexed()) { 11543 unsigned OrigAlign = ST->getAlignment(); 11544 EVT SVT = Value.getOperand(0).getValueType(); 11545 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 11546 SVT.getTypeForEVT(*DAG.getContext())); 11547 if (Align <= OrigAlign && 11548 ((!LegalOperations && !ST->isVolatile()) || 11549 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 11550 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11551 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11552 ST->isNonTemporal(), OrigAlign, 11553 ST->getAAInfo()); 11554 } 11555 11556 // Turn 'store undef, Ptr' -> nothing. 11557 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 11558 return Chain; 11559 11560 // Try to infer better alignment information than the store already has. 11561 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 11562 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11563 if (Align > ST->getAlignment()) { 11564 SDValue NewStore = 11565 DAG.getTruncStore(Chain, SDLoc(N), Value, 11566 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 11567 ST->isVolatile(), ST->isNonTemporal(), Align, 11568 ST->getAAInfo()); 11569 if (NewStore.getNode() != N) 11570 return CombineTo(ST, NewStore, true); 11571 } 11572 } 11573 } 11574 11575 // Try transforming a pair floating point load / store ops to integer 11576 // load / store ops. 11577 if (SDValue NewST = TransformFPLoadStorePair(N)) 11578 return NewST; 11579 11580 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11581 : DAG.getSubtarget().useAA(); 11582 #ifndef NDEBUG 11583 if (CombinerAAOnlyFunc.getNumOccurrences() && 11584 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11585 UseAA = false; 11586 #endif 11587 if (UseAA && ST->isUnindexed()) { 11588 // FIXME: We should do this even without AA enabled. AA will just allow 11589 // FindBetterChain to work in more situations. The problem with this is that 11590 // any combine that expects memory operations to be on consecutive chains 11591 // first needs to be updated to look for users of the same chain. 11592 11593 // Walk up chain skipping non-aliasing memory nodes, on this store and any 11594 // adjacent stores. 11595 if (findBetterNeighborChains(ST)) { 11596 // replaceStoreChain uses CombineTo, which handled all of the worklist 11597 // manipulation. Return the original node to not do anything else. 11598 return SDValue(ST, 0); 11599 } 11600 } 11601 11602 // Try transforming N to an indexed store. 11603 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11604 return SDValue(N, 0); 11605 11606 // FIXME: is there such a thing as a truncating indexed store? 11607 if (ST->isTruncatingStore() && ST->isUnindexed() && 11608 Value.getValueType().isInteger()) { 11609 // See if we can simplify the input to this truncstore with knowledge that 11610 // only the low bits are being used. For example: 11611 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 11612 SDValue Shorter = 11613 GetDemandedBits(Value, 11614 APInt::getLowBitsSet( 11615 Value.getValueType().getScalarType().getSizeInBits(), 11616 ST->getMemoryVT().getScalarType().getSizeInBits())); 11617 AddToWorklist(Value.getNode()); 11618 if (Shorter.getNode()) 11619 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 11620 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11621 11622 // Otherwise, see if we can simplify the operation with 11623 // SimplifyDemandedBits, which only works if the value has a single use. 11624 if (SimplifyDemandedBits(Value, 11625 APInt::getLowBitsSet( 11626 Value.getValueType().getScalarType().getSizeInBits(), 11627 ST->getMemoryVT().getScalarType().getSizeInBits()))) 11628 return SDValue(N, 0); 11629 } 11630 11631 // If this is a load followed by a store to the same location, then the store 11632 // is dead/noop. 11633 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 11634 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 11635 ST->isUnindexed() && !ST->isVolatile() && 11636 // There can't be any side effects between the load and store, such as 11637 // a call or store. 11638 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 11639 // The store is dead, remove it. 11640 return Chain; 11641 } 11642 } 11643 11644 // If this is a store followed by a store with the same value to the same 11645 // location, then the store is dead/noop. 11646 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 11647 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 11648 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 11649 ST1->isUnindexed() && !ST1->isVolatile()) { 11650 // The store is dead, remove it. 11651 return Chain; 11652 } 11653 } 11654 11655 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 11656 // truncating store. We can do this even if this is already a truncstore. 11657 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 11658 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 11659 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 11660 ST->getMemoryVT())) { 11661 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 11662 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11663 } 11664 11665 // Only perform this optimization before the types are legal, because we 11666 // don't want to perform this optimization on every DAGCombine invocation. 11667 if (!LegalTypes) { 11668 bool EverChanged = false; 11669 11670 do { 11671 // There can be multiple store sequences on the same chain. 11672 // Keep trying to merge store sequences until we are unable to do so 11673 // or until we merge the last store on the chain. 11674 bool Changed = MergeConsecutiveStores(ST); 11675 EverChanged |= Changed; 11676 if (!Changed) break; 11677 } while (ST->getOpcode() != ISD::DELETED_NODE); 11678 11679 if (EverChanged) 11680 return SDValue(N, 0); 11681 } 11682 11683 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 11684 // 11685 // Make sure to do this only after attempting to merge stores in order to 11686 // avoid changing the types of some subset of stores due to visit order, 11687 // preventing their merging. 11688 if (isa<ConstantFPSDNode>(Value)) { 11689 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 11690 return NewSt; 11691 } 11692 11693 return ReduceLoadOpStoreWidth(N); 11694 } 11695 11696 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 11697 SDValue InVec = N->getOperand(0); 11698 SDValue InVal = N->getOperand(1); 11699 SDValue EltNo = N->getOperand(2); 11700 SDLoc dl(N); 11701 11702 // If the inserted element is an UNDEF, just use the input vector. 11703 if (InVal.getOpcode() == ISD::UNDEF) 11704 return InVec; 11705 11706 EVT VT = InVec.getValueType(); 11707 11708 // If we can't generate a legal BUILD_VECTOR, exit 11709 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 11710 return SDValue(); 11711 11712 // Check that we know which element is being inserted 11713 if (!isa<ConstantSDNode>(EltNo)) 11714 return SDValue(); 11715 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11716 11717 // Canonicalize insert_vector_elt dag nodes. 11718 // Example: 11719 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 11720 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 11721 // 11722 // Do this only if the child insert_vector node has one use; also 11723 // do this only if indices are both constants and Idx1 < Idx0. 11724 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 11725 && isa<ConstantSDNode>(InVec.getOperand(2))) { 11726 unsigned OtherElt = 11727 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 11728 if (Elt < OtherElt) { 11729 // Swap nodes. 11730 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 11731 InVec.getOperand(0), InVal, EltNo); 11732 AddToWorklist(NewOp.getNode()); 11733 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 11734 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 11735 } 11736 } 11737 11738 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 11739 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 11740 // vector elements. 11741 SmallVector<SDValue, 8> Ops; 11742 // Do not combine these two vectors if the output vector will not replace 11743 // the input vector. 11744 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 11745 Ops.append(InVec.getNode()->op_begin(), 11746 InVec.getNode()->op_end()); 11747 } else if (InVec.getOpcode() == ISD::UNDEF) { 11748 unsigned NElts = VT.getVectorNumElements(); 11749 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 11750 } else { 11751 return SDValue(); 11752 } 11753 11754 // Insert the element 11755 if (Elt < Ops.size()) { 11756 // All the operands of BUILD_VECTOR must have the same type; 11757 // we enforce that here. 11758 EVT OpVT = Ops[0].getValueType(); 11759 if (InVal.getValueType() != OpVT) 11760 InVal = OpVT.bitsGT(InVal.getValueType()) ? 11761 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 11762 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 11763 Ops[Elt] = InVal; 11764 } 11765 11766 // Return the new vector 11767 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 11768 } 11769 11770 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 11771 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 11772 EVT ResultVT = EVE->getValueType(0); 11773 EVT VecEltVT = InVecVT.getVectorElementType(); 11774 unsigned Align = OriginalLoad->getAlignment(); 11775 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 11776 VecEltVT.getTypeForEVT(*DAG.getContext())); 11777 11778 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 11779 return SDValue(); 11780 11781 Align = NewAlign; 11782 11783 SDValue NewPtr = OriginalLoad->getBasePtr(); 11784 SDValue Offset; 11785 EVT PtrType = NewPtr.getValueType(); 11786 MachinePointerInfo MPI; 11787 SDLoc DL(EVE); 11788 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 11789 int Elt = ConstEltNo->getZExtValue(); 11790 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 11791 Offset = DAG.getConstant(PtrOff, DL, PtrType); 11792 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 11793 } else { 11794 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 11795 Offset = DAG.getNode( 11796 ISD::MUL, DL, PtrType, Offset, 11797 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 11798 MPI = OriginalLoad->getPointerInfo(); 11799 } 11800 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 11801 11802 // The replacement we need to do here is a little tricky: we need to 11803 // replace an extractelement of a load with a load. 11804 // Use ReplaceAllUsesOfValuesWith to do the replacement. 11805 // Note that this replacement assumes that the extractvalue is the only 11806 // use of the load; that's okay because we don't want to perform this 11807 // transformation in other cases anyway. 11808 SDValue Load; 11809 SDValue Chain; 11810 if (ResultVT.bitsGT(VecEltVT)) { 11811 // If the result type of vextract is wider than the load, then issue an 11812 // extending load instead. 11813 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 11814 VecEltVT) 11815 ? ISD::ZEXTLOAD 11816 : ISD::EXTLOAD; 11817 Load = DAG.getExtLoad( 11818 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 11819 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11820 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11821 Chain = Load.getValue(1); 11822 } else { 11823 Load = DAG.getLoad( 11824 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 11825 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11826 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11827 Chain = Load.getValue(1); 11828 if (ResultVT.bitsLT(VecEltVT)) 11829 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 11830 else 11831 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 11832 } 11833 WorklistRemover DeadNodes(*this); 11834 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 11835 SDValue To[] = { Load, Chain }; 11836 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 11837 // Since we're explicitly calling ReplaceAllUses, add the new node to the 11838 // worklist explicitly as well. 11839 AddToWorklist(Load.getNode()); 11840 AddUsersToWorklist(Load.getNode()); // Add users too 11841 // Make sure to revisit this node to clean it up; it will usually be dead. 11842 AddToWorklist(EVE); 11843 ++OpsNarrowed; 11844 return SDValue(EVE, 0); 11845 } 11846 11847 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 11848 // (vextract (scalar_to_vector val, 0) -> val 11849 SDValue InVec = N->getOperand(0); 11850 EVT VT = InVec.getValueType(); 11851 EVT NVT = N->getValueType(0); 11852 11853 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 11854 // Check if the result type doesn't match the inserted element type. A 11855 // SCALAR_TO_VECTOR may truncate the inserted element and the 11856 // EXTRACT_VECTOR_ELT may widen the extracted vector. 11857 SDValue InOp = InVec.getOperand(0); 11858 if (InOp.getValueType() != NVT) { 11859 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11860 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 11861 } 11862 return InOp; 11863 } 11864 11865 SDValue EltNo = N->getOperand(1); 11866 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 11867 11868 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 11869 // We only perform this optimization before the op legalization phase because 11870 // we may introduce new vector instructions which are not backed by TD 11871 // patterns. For example on AVX, extracting elements from a wide vector 11872 // without using extract_subvector. However, if we can find an underlying 11873 // scalar value, then we can always use that. 11874 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 11875 && ConstEltNo) { 11876 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11877 int NumElem = VT.getVectorNumElements(); 11878 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 11879 // Find the new index to extract from. 11880 int OrigElt = SVOp->getMaskElt(Elt); 11881 11882 // Extracting an undef index is undef. 11883 if (OrigElt == -1) 11884 return DAG.getUNDEF(NVT); 11885 11886 // Select the right vector half to extract from. 11887 SDValue SVInVec; 11888 if (OrigElt < NumElem) { 11889 SVInVec = InVec->getOperand(0); 11890 } else { 11891 SVInVec = InVec->getOperand(1); 11892 OrigElt -= NumElem; 11893 } 11894 11895 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 11896 SDValue InOp = SVInVec.getOperand(OrigElt); 11897 if (InOp.getValueType() != NVT) { 11898 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11899 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 11900 } 11901 11902 return InOp; 11903 } 11904 11905 // FIXME: We should handle recursing on other vector shuffles and 11906 // scalar_to_vector here as well. 11907 11908 if (!LegalOperations) { 11909 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 11910 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 11911 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 11912 } 11913 } 11914 11915 bool BCNumEltsChanged = false; 11916 EVT ExtVT = VT.getVectorElementType(); 11917 EVT LVT = ExtVT; 11918 11919 // If the result of load has to be truncated, then it's not necessarily 11920 // profitable. 11921 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 11922 return SDValue(); 11923 11924 if (InVec.getOpcode() == ISD::BITCAST) { 11925 // Don't duplicate a load with other uses. 11926 if (!InVec.hasOneUse()) 11927 return SDValue(); 11928 11929 EVT BCVT = InVec.getOperand(0).getValueType(); 11930 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 11931 return SDValue(); 11932 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 11933 BCNumEltsChanged = true; 11934 InVec = InVec.getOperand(0); 11935 ExtVT = BCVT.getVectorElementType(); 11936 } 11937 11938 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 11939 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 11940 ISD::isNormalLoad(InVec.getNode()) && 11941 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 11942 SDValue Index = N->getOperand(1); 11943 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 11944 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 11945 OrigLoad); 11946 } 11947 11948 // Perform only after legalization to ensure build_vector / vector_shuffle 11949 // optimizations have already been done. 11950 if (!LegalOperations) return SDValue(); 11951 11952 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 11953 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 11954 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 11955 11956 if (ConstEltNo) { 11957 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11958 11959 LoadSDNode *LN0 = nullptr; 11960 const ShuffleVectorSDNode *SVN = nullptr; 11961 if (ISD::isNormalLoad(InVec.getNode())) { 11962 LN0 = cast<LoadSDNode>(InVec); 11963 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 11964 InVec.getOperand(0).getValueType() == ExtVT && 11965 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 11966 // Don't duplicate a load with other uses. 11967 if (!InVec.hasOneUse()) 11968 return SDValue(); 11969 11970 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 11971 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 11972 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 11973 // => 11974 // (load $addr+1*size) 11975 11976 // Don't duplicate a load with other uses. 11977 if (!InVec.hasOneUse()) 11978 return SDValue(); 11979 11980 // If the bit convert changed the number of elements, it is unsafe 11981 // to examine the mask. 11982 if (BCNumEltsChanged) 11983 return SDValue(); 11984 11985 // Select the input vector, guarding against out of range extract vector. 11986 unsigned NumElems = VT.getVectorNumElements(); 11987 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 11988 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 11989 11990 if (InVec.getOpcode() == ISD::BITCAST) { 11991 // Don't duplicate a load with other uses. 11992 if (!InVec.hasOneUse()) 11993 return SDValue(); 11994 11995 InVec = InVec.getOperand(0); 11996 } 11997 if (ISD::isNormalLoad(InVec.getNode())) { 11998 LN0 = cast<LoadSDNode>(InVec); 11999 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12000 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12001 } 12002 } 12003 12004 // Make sure we found a non-volatile load and the extractelement is 12005 // the only use. 12006 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12007 return SDValue(); 12008 12009 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12010 if (Elt == -1) 12011 return DAG.getUNDEF(LVT); 12012 12013 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12014 } 12015 12016 return SDValue(); 12017 } 12018 12019 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12020 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12021 // We perform this optimization post type-legalization because 12022 // the type-legalizer often scalarizes integer-promoted vectors. 12023 // Performing this optimization before may create bit-casts which 12024 // will be type-legalized to complex code sequences. 12025 // We perform this optimization only before the operation legalizer because we 12026 // may introduce illegal operations. 12027 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12028 return SDValue(); 12029 12030 unsigned NumInScalars = N->getNumOperands(); 12031 SDLoc dl(N); 12032 EVT VT = N->getValueType(0); 12033 12034 // Check to see if this is a BUILD_VECTOR of a bunch of values 12035 // which come from any_extend or zero_extend nodes. If so, we can create 12036 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12037 // optimizations. We do not handle sign-extend because we can't fill the sign 12038 // using shuffles. 12039 EVT SourceType = MVT::Other; 12040 bool AllAnyExt = true; 12041 12042 for (unsigned i = 0; i != NumInScalars; ++i) { 12043 SDValue In = N->getOperand(i); 12044 // Ignore undef inputs. 12045 if (In.getOpcode() == ISD::UNDEF) continue; 12046 12047 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12048 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12049 12050 // Abort if the element is not an extension. 12051 if (!ZeroExt && !AnyExt) { 12052 SourceType = MVT::Other; 12053 break; 12054 } 12055 12056 // The input is a ZeroExt or AnyExt. Check the original type. 12057 EVT InTy = In.getOperand(0).getValueType(); 12058 12059 // Check that all of the widened source types are the same. 12060 if (SourceType == MVT::Other) 12061 // First time. 12062 SourceType = InTy; 12063 else if (InTy != SourceType) { 12064 // Multiple income types. Abort. 12065 SourceType = MVT::Other; 12066 break; 12067 } 12068 12069 // Check if all of the extends are ANY_EXTENDs. 12070 AllAnyExt &= AnyExt; 12071 } 12072 12073 // In order to have valid types, all of the inputs must be extended from the 12074 // same source type and all of the inputs must be any or zero extend. 12075 // Scalar sizes must be a power of two. 12076 EVT OutScalarTy = VT.getScalarType(); 12077 bool ValidTypes = SourceType != MVT::Other && 12078 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12079 isPowerOf2_32(SourceType.getSizeInBits()); 12080 12081 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12082 // turn into a single shuffle instruction. 12083 if (!ValidTypes) 12084 return SDValue(); 12085 12086 bool isLE = DAG.getDataLayout().isLittleEndian(); 12087 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12088 assert(ElemRatio > 1 && "Invalid element size ratio"); 12089 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12090 DAG.getConstant(0, SDLoc(N), SourceType); 12091 12092 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12093 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12094 12095 // Populate the new build_vector 12096 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12097 SDValue Cast = N->getOperand(i); 12098 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12099 Cast.getOpcode() == ISD::ZERO_EXTEND || 12100 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 12101 SDValue In; 12102 if (Cast.getOpcode() == ISD::UNDEF) 12103 In = DAG.getUNDEF(SourceType); 12104 else 12105 In = Cast->getOperand(0); 12106 unsigned Index = isLE ? (i * ElemRatio) : 12107 (i * ElemRatio + (ElemRatio - 1)); 12108 12109 assert(Index < Ops.size() && "Invalid index"); 12110 Ops[Index] = In; 12111 } 12112 12113 // The type of the new BUILD_VECTOR node. 12114 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12115 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12116 "Invalid vector size"); 12117 // Check if the new vector type is legal. 12118 if (!isTypeLegal(VecVT)) return SDValue(); 12119 12120 // Make the new BUILD_VECTOR. 12121 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 12122 12123 // The new BUILD_VECTOR node has the potential to be further optimized. 12124 AddToWorklist(BV.getNode()); 12125 // Bitcast to the desired type. 12126 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12127 } 12128 12129 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12130 EVT VT = N->getValueType(0); 12131 12132 unsigned NumInScalars = N->getNumOperands(); 12133 SDLoc dl(N); 12134 12135 EVT SrcVT = MVT::Other; 12136 unsigned Opcode = ISD::DELETED_NODE; 12137 unsigned NumDefs = 0; 12138 12139 for (unsigned i = 0; i != NumInScalars; ++i) { 12140 SDValue In = N->getOperand(i); 12141 unsigned Opc = In.getOpcode(); 12142 12143 if (Opc == ISD::UNDEF) 12144 continue; 12145 12146 // If all scalar values are floats and converted from integers. 12147 if (Opcode == ISD::DELETED_NODE && 12148 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12149 Opcode = Opc; 12150 } 12151 12152 if (Opc != Opcode) 12153 return SDValue(); 12154 12155 EVT InVT = In.getOperand(0).getValueType(); 12156 12157 // If all scalar values are typed differently, bail out. It's chosen to 12158 // simplify BUILD_VECTOR of integer types. 12159 if (SrcVT == MVT::Other) 12160 SrcVT = InVT; 12161 if (SrcVT != InVT) 12162 return SDValue(); 12163 NumDefs++; 12164 } 12165 12166 // If the vector has just one element defined, it's not worth to fold it into 12167 // a vectorized one. 12168 if (NumDefs < 2) 12169 return SDValue(); 12170 12171 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12172 && "Should only handle conversion from integer to float."); 12173 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12174 12175 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12176 12177 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12178 return SDValue(); 12179 12180 // Just because the floating-point vector type is legal does not necessarily 12181 // mean that the corresponding integer vector type is. 12182 if (!isTypeLegal(NVT)) 12183 return SDValue(); 12184 12185 SmallVector<SDValue, 8> Opnds; 12186 for (unsigned i = 0; i != NumInScalars; ++i) { 12187 SDValue In = N->getOperand(i); 12188 12189 if (In.getOpcode() == ISD::UNDEF) 12190 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12191 else 12192 Opnds.push_back(In.getOperand(0)); 12193 } 12194 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 12195 AddToWorklist(BV.getNode()); 12196 12197 return DAG.getNode(Opcode, dl, VT, BV); 12198 } 12199 12200 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12201 unsigned NumInScalars = N->getNumOperands(); 12202 SDLoc dl(N); 12203 EVT VT = N->getValueType(0); 12204 12205 // A vector built entirely of undefs is undef. 12206 if (ISD::allOperandsUndef(N)) 12207 return DAG.getUNDEF(VT); 12208 12209 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12210 return V; 12211 12212 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12213 return V; 12214 12215 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12216 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12217 // at most two distinct vectors, turn this into a shuffle node. 12218 12219 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12220 if (!isTypeLegal(VT)) 12221 return SDValue(); 12222 12223 // May only combine to shuffle after legalize if shuffle is legal. 12224 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12225 return SDValue(); 12226 12227 SDValue VecIn1, VecIn2; 12228 bool UsesZeroVector = false; 12229 for (unsigned i = 0; i != NumInScalars; ++i) { 12230 SDValue Op = N->getOperand(i); 12231 // Ignore undef inputs. 12232 if (Op.getOpcode() == ISD::UNDEF) continue; 12233 12234 // See if we can combine this build_vector into a blend with a zero vector. 12235 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12236 UsesZeroVector = true; 12237 continue; 12238 } 12239 12240 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12241 // constant index, bail out. 12242 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12243 !isa<ConstantSDNode>(Op.getOperand(1))) { 12244 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12245 break; 12246 } 12247 12248 // We allow up to two distinct input vectors. 12249 SDValue ExtractedFromVec = Op.getOperand(0); 12250 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12251 continue; 12252 12253 if (!VecIn1.getNode()) { 12254 VecIn1 = ExtractedFromVec; 12255 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12256 VecIn2 = ExtractedFromVec; 12257 } else { 12258 // Too many inputs. 12259 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12260 break; 12261 } 12262 } 12263 12264 // If everything is good, we can make a shuffle operation. 12265 if (VecIn1.getNode()) { 12266 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12267 SmallVector<int, 8> Mask; 12268 for (unsigned i = 0; i != NumInScalars; ++i) { 12269 unsigned Opcode = N->getOperand(i).getOpcode(); 12270 if (Opcode == ISD::UNDEF) { 12271 Mask.push_back(-1); 12272 continue; 12273 } 12274 12275 // Operands can also be zero. 12276 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12277 assert(UsesZeroVector && 12278 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12279 "Unexpected node found!"); 12280 Mask.push_back(NumInScalars+i); 12281 continue; 12282 } 12283 12284 // If extracting from the first vector, just use the index directly. 12285 SDValue Extract = N->getOperand(i); 12286 SDValue ExtVal = Extract.getOperand(1); 12287 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12288 if (Extract.getOperand(0) == VecIn1) { 12289 Mask.push_back(ExtIndex); 12290 continue; 12291 } 12292 12293 // Otherwise, use InIdx + InputVecSize 12294 Mask.push_back(InNumElements + ExtIndex); 12295 } 12296 12297 // Avoid introducing illegal shuffles with zero. 12298 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12299 return SDValue(); 12300 12301 // We can't generate a shuffle node with mismatched input and output types. 12302 // Attempt to transform a single input vector to the correct type. 12303 if ((VT != VecIn1.getValueType())) { 12304 // If the input vector type has a different base type to the output 12305 // vector type, bail out. 12306 EVT VTElemType = VT.getVectorElementType(); 12307 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12308 (VecIn2.getNode() && 12309 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12310 return SDValue(); 12311 12312 // If the input vector is too small, widen it. 12313 // We only support widening of vectors which are half the size of the 12314 // output registers. For example XMM->YMM widening on X86 with AVX. 12315 EVT VecInT = VecIn1.getValueType(); 12316 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12317 // If we only have one small input, widen it by adding undef values. 12318 if (!VecIn2.getNode()) 12319 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12320 DAG.getUNDEF(VecIn1.getValueType())); 12321 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12322 // If we have two small inputs of the same type, try to concat them. 12323 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12324 VecIn2 = SDValue(nullptr, 0); 12325 } else 12326 return SDValue(); 12327 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12328 // If the input vector is too large, try to split it. 12329 // We don't support having two input vectors that are too large. 12330 // If the zero vector was used, we can not split the vector, 12331 // since we'd need 3 inputs. 12332 if (UsesZeroVector || VecIn2.getNode()) 12333 return SDValue(); 12334 12335 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12336 return SDValue(); 12337 12338 // Try to replace VecIn1 with two extract_subvectors 12339 // No need to update the masks, they should still be correct. 12340 VecIn2 = DAG.getNode( 12341 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12342 DAG.getConstant(VT.getVectorNumElements(), dl, 12343 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12344 VecIn1 = DAG.getNode( 12345 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12346 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12347 } else 12348 return SDValue(); 12349 } 12350 12351 if (UsesZeroVector) 12352 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12353 DAG.getConstantFP(0.0, dl, VT); 12354 else 12355 // If VecIn2 is unused then change it to undef. 12356 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12357 12358 // Check that we were able to transform all incoming values to the same 12359 // type. 12360 if (VecIn2.getValueType() != VecIn1.getValueType() || 12361 VecIn1.getValueType() != VT) 12362 return SDValue(); 12363 12364 // Return the new VECTOR_SHUFFLE node. 12365 SDValue Ops[2]; 12366 Ops[0] = VecIn1; 12367 Ops[1] = VecIn2; 12368 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12369 } 12370 12371 return SDValue(); 12372 } 12373 12374 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12375 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12376 EVT OpVT = N->getOperand(0).getValueType(); 12377 12378 // If the operands are legal vectors, leave them alone. 12379 if (TLI.isTypeLegal(OpVT)) 12380 return SDValue(); 12381 12382 SDLoc DL(N); 12383 EVT VT = N->getValueType(0); 12384 SmallVector<SDValue, 8> Ops; 12385 12386 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12387 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12388 12389 // Keep track of what we encounter. 12390 bool AnyInteger = false; 12391 bool AnyFP = false; 12392 for (const SDValue &Op : N->ops()) { 12393 if (ISD::BITCAST == Op.getOpcode() && 12394 !Op.getOperand(0).getValueType().isVector()) 12395 Ops.push_back(Op.getOperand(0)); 12396 else if (ISD::UNDEF == Op.getOpcode()) 12397 Ops.push_back(ScalarUndef); 12398 else 12399 return SDValue(); 12400 12401 // Note whether we encounter an integer or floating point scalar. 12402 // If it's neither, bail out, it could be something weird like x86mmx. 12403 EVT LastOpVT = Ops.back().getValueType(); 12404 if (LastOpVT.isFloatingPoint()) 12405 AnyFP = true; 12406 else if (LastOpVT.isInteger()) 12407 AnyInteger = true; 12408 else 12409 return SDValue(); 12410 } 12411 12412 // If any of the operands is a floating point scalar bitcast to a vector, 12413 // use floating point types throughout, and bitcast everything. 12414 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12415 if (AnyFP) { 12416 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12417 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12418 if (AnyInteger) { 12419 for (SDValue &Op : Ops) { 12420 if (Op.getValueType() == SVT) 12421 continue; 12422 if (Op.getOpcode() == ISD::UNDEF) 12423 Op = ScalarUndef; 12424 else 12425 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12426 } 12427 } 12428 } 12429 12430 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12431 VT.getSizeInBits() / SVT.getSizeInBits()); 12432 return DAG.getNode(ISD::BITCAST, DL, VT, 12433 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 12434 } 12435 12436 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12437 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12438 // most two distinct vectors the same size as the result, attempt to turn this 12439 // into a legal shuffle. 12440 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12441 EVT VT = N->getValueType(0); 12442 EVT OpVT = N->getOperand(0).getValueType(); 12443 int NumElts = VT.getVectorNumElements(); 12444 int NumOpElts = OpVT.getVectorNumElements(); 12445 12446 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12447 SmallVector<int, 8> Mask; 12448 12449 for (SDValue Op : N->ops()) { 12450 // Peek through any bitcast. 12451 while (Op.getOpcode() == ISD::BITCAST) 12452 Op = Op.getOperand(0); 12453 12454 // UNDEF nodes convert to UNDEF shuffle mask values. 12455 if (Op.getOpcode() == ISD::UNDEF) { 12456 Mask.append((unsigned)NumOpElts, -1); 12457 continue; 12458 } 12459 12460 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12461 return SDValue(); 12462 12463 // What vector are we extracting the subvector from and at what index? 12464 SDValue ExtVec = Op.getOperand(0); 12465 12466 // We want the EVT of the original extraction to correctly scale the 12467 // extraction index. 12468 EVT ExtVT = ExtVec.getValueType(); 12469 12470 // Peek through any bitcast. 12471 while (ExtVec.getOpcode() == ISD::BITCAST) 12472 ExtVec = ExtVec.getOperand(0); 12473 12474 // UNDEF nodes convert to UNDEF shuffle mask values. 12475 if (ExtVec.getOpcode() == ISD::UNDEF) { 12476 Mask.append((unsigned)NumOpElts, -1); 12477 continue; 12478 } 12479 12480 if (!isa<ConstantSDNode>(Op.getOperand(1))) 12481 return SDValue(); 12482 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 12483 12484 // Ensure that we are extracting a subvector from a vector the same 12485 // size as the result. 12486 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 12487 return SDValue(); 12488 12489 // Scale the subvector index to account for any bitcast. 12490 int NumExtElts = ExtVT.getVectorNumElements(); 12491 if (0 == (NumExtElts % NumElts)) 12492 ExtIdx /= (NumExtElts / NumElts); 12493 else if (0 == (NumElts % NumExtElts)) 12494 ExtIdx *= (NumElts / NumExtElts); 12495 else 12496 return SDValue(); 12497 12498 // At most we can reference 2 inputs in the final shuffle. 12499 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) { 12500 SV0 = ExtVec; 12501 for (int i = 0; i != NumOpElts; ++i) 12502 Mask.push_back(i + ExtIdx); 12503 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) { 12504 SV1 = ExtVec; 12505 for (int i = 0; i != NumOpElts; ++i) 12506 Mask.push_back(i + ExtIdx + NumElts); 12507 } else { 12508 return SDValue(); 12509 } 12510 } 12511 12512 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 12513 return SDValue(); 12514 12515 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 12516 DAG.getBitcast(VT, SV1), Mask); 12517 } 12518 12519 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12520 // If we only have one input vector, we don't need to do any concatenation. 12521 if (N->getNumOperands() == 1) 12522 return N->getOperand(0); 12523 12524 // Check if all of the operands are undefs. 12525 EVT VT = N->getValueType(0); 12526 if (ISD::allOperandsUndef(N)) 12527 return DAG.getUNDEF(VT); 12528 12529 // Optimize concat_vectors where all but the first of the vectors are undef. 12530 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 12531 return Op.getOpcode() == ISD::UNDEF; 12532 })) { 12533 SDValue In = N->getOperand(0); 12534 assert(In.getValueType().isVector() && "Must concat vectors"); 12535 12536 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 12537 if (In->getOpcode() == ISD::BITCAST && 12538 !In->getOperand(0)->getValueType(0).isVector()) { 12539 SDValue Scalar = In->getOperand(0); 12540 12541 // If the bitcast type isn't legal, it might be a trunc of a legal type; 12542 // look through the trunc so we can still do the transform: 12543 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 12544 if (Scalar->getOpcode() == ISD::TRUNCATE && 12545 !TLI.isTypeLegal(Scalar.getValueType()) && 12546 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 12547 Scalar = Scalar->getOperand(0); 12548 12549 EVT SclTy = Scalar->getValueType(0); 12550 12551 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 12552 return SDValue(); 12553 12554 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 12555 VT.getSizeInBits() / SclTy.getSizeInBits()); 12556 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 12557 return SDValue(); 12558 12559 SDLoc dl = SDLoc(N); 12560 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 12561 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 12562 } 12563 } 12564 12565 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 12566 // We have already tested above for an UNDEF only concatenation. 12567 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 12568 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 12569 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 12570 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 12571 }; 12572 bool AllBuildVectorsOrUndefs = 12573 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 12574 if (AllBuildVectorsOrUndefs) { 12575 SmallVector<SDValue, 8> Opnds; 12576 EVT SVT = VT.getScalarType(); 12577 12578 EVT MinVT = SVT; 12579 if (!SVT.isFloatingPoint()) { 12580 // If BUILD_VECTOR are from built from integer, they may have different 12581 // operand types. Get the smallest type and truncate all operands to it. 12582 bool FoundMinVT = false; 12583 for (const SDValue &Op : N->ops()) 12584 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12585 EVT OpSVT = Op.getOperand(0)->getValueType(0); 12586 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 12587 FoundMinVT = true; 12588 } 12589 assert(FoundMinVT && "Concat vector type mismatch"); 12590 } 12591 12592 for (const SDValue &Op : N->ops()) { 12593 EVT OpVT = Op.getValueType(); 12594 unsigned NumElts = OpVT.getVectorNumElements(); 12595 12596 if (ISD::UNDEF == Op.getOpcode()) 12597 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 12598 12599 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12600 if (SVT.isFloatingPoint()) { 12601 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 12602 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 12603 } else { 12604 for (unsigned i = 0; i != NumElts; ++i) 12605 Opnds.push_back( 12606 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 12607 } 12608 } 12609 } 12610 12611 assert(VT.getVectorNumElements() == Opnds.size() && 12612 "Concat vector type mismatch"); 12613 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 12614 } 12615 12616 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 12617 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 12618 return V; 12619 12620 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 12621 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 12622 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 12623 return V; 12624 12625 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 12626 // nodes often generate nop CONCAT_VECTOR nodes. 12627 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 12628 // place the incoming vectors at the exact same location. 12629 SDValue SingleSource = SDValue(); 12630 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 12631 12632 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12633 SDValue Op = N->getOperand(i); 12634 12635 if (Op.getOpcode() == ISD::UNDEF) 12636 continue; 12637 12638 // Check if this is the identity extract: 12639 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12640 return SDValue(); 12641 12642 // Find the single incoming vector for the extract_subvector. 12643 if (SingleSource.getNode()) { 12644 if (Op.getOperand(0) != SingleSource) 12645 return SDValue(); 12646 } else { 12647 SingleSource = Op.getOperand(0); 12648 12649 // Check the source type is the same as the type of the result. 12650 // If not, this concat may extend the vector, so we can not 12651 // optimize it away. 12652 if (SingleSource.getValueType() != N->getValueType(0)) 12653 return SDValue(); 12654 } 12655 12656 unsigned IdentityIndex = i * PartNumElem; 12657 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 12658 // The extract index must be constant. 12659 if (!CS) 12660 return SDValue(); 12661 12662 // Check that we are reading from the identity index. 12663 if (CS->getZExtValue() != IdentityIndex) 12664 return SDValue(); 12665 } 12666 12667 if (SingleSource.getNode()) 12668 return SingleSource; 12669 12670 return SDValue(); 12671 } 12672 12673 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 12674 EVT NVT = N->getValueType(0); 12675 SDValue V = N->getOperand(0); 12676 12677 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 12678 // Combine: 12679 // (extract_subvec (concat V1, V2, ...), i) 12680 // Into: 12681 // Vi if possible 12682 // Only operand 0 is checked as 'concat' assumes all inputs of the same 12683 // type. 12684 if (V->getOperand(0).getValueType() != NVT) 12685 return SDValue(); 12686 unsigned Idx = N->getConstantOperandVal(1); 12687 unsigned NumElems = NVT.getVectorNumElements(); 12688 assert((Idx % NumElems) == 0 && 12689 "IDX in concat is not a multiple of the result vector length."); 12690 return V->getOperand(Idx / NumElems); 12691 } 12692 12693 // Skip bitcasting 12694 if (V->getOpcode() == ISD::BITCAST) 12695 V = V.getOperand(0); 12696 12697 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 12698 SDLoc dl(N); 12699 // Handle only simple case where vector being inserted and vector 12700 // being extracted are of same type, and are half size of larger vectors. 12701 EVT BigVT = V->getOperand(0).getValueType(); 12702 EVT SmallVT = V->getOperand(1).getValueType(); 12703 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 12704 return SDValue(); 12705 12706 // Only handle cases where both indexes are constants with the same type. 12707 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12708 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12709 12710 if (InsIdx && ExtIdx && 12711 InsIdx->getValueType(0).getSizeInBits() <= 64 && 12712 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 12713 // Combine: 12714 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 12715 // Into: 12716 // indices are equal or bit offsets are equal => V1 12717 // otherwise => (extract_subvec V1, ExtIdx) 12718 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 12719 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 12720 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 12721 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 12722 DAG.getNode(ISD::BITCAST, dl, 12723 N->getOperand(0).getValueType(), 12724 V->getOperand(0)), N->getOperand(1)); 12725 } 12726 } 12727 12728 return SDValue(); 12729 } 12730 12731 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 12732 SDValue V, SelectionDAG &DAG) { 12733 SDLoc DL(V); 12734 EVT VT = V.getValueType(); 12735 12736 switch (V.getOpcode()) { 12737 default: 12738 return V; 12739 12740 case ISD::CONCAT_VECTORS: { 12741 EVT OpVT = V->getOperand(0).getValueType(); 12742 int OpSize = OpVT.getVectorNumElements(); 12743 SmallBitVector OpUsedElements(OpSize, false); 12744 bool FoundSimplification = false; 12745 SmallVector<SDValue, 4> NewOps; 12746 NewOps.reserve(V->getNumOperands()); 12747 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 12748 SDValue Op = V->getOperand(i); 12749 bool OpUsed = false; 12750 for (int j = 0; j < OpSize; ++j) 12751 if (UsedElements[i * OpSize + j]) { 12752 OpUsedElements[j] = true; 12753 OpUsed = true; 12754 } 12755 NewOps.push_back( 12756 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 12757 : DAG.getUNDEF(OpVT)); 12758 FoundSimplification |= Op == NewOps.back(); 12759 OpUsedElements.reset(); 12760 } 12761 if (FoundSimplification) 12762 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 12763 return V; 12764 } 12765 12766 case ISD::INSERT_SUBVECTOR: { 12767 SDValue BaseV = V->getOperand(0); 12768 SDValue SubV = V->getOperand(1); 12769 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12770 if (!IdxN) 12771 return V; 12772 12773 int SubSize = SubV.getValueType().getVectorNumElements(); 12774 int Idx = IdxN->getZExtValue(); 12775 bool SubVectorUsed = false; 12776 SmallBitVector SubUsedElements(SubSize, false); 12777 for (int i = 0; i < SubSize; ++i) 12778 if (UsedElements[i + Idx]) { 12779 SubVectorUsed = true; 12780 SubUsedElements[i] = true; 12781 UsedElements[i + Idx] = false; 12782 } 12783 12784 // Now recurse on both the base and sub vectors. 12785 SDValue SimplifiedSubV = 12786 SubVectorUsed 12787 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 12788 : DAG.getUNDEF(SubV.getValueType()); 12789 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 12790 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 12791 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 12792 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 12793 return V; 12794 } 12795 } 12796 } 12797 12798 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 12799 SDValue N1, SelectionDAG &DAG) { 12800 EVT VT = SVN->getValueType(0); 12801 int NumElts = VT.getVectorNumElements(); 12802 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 12803 for (int M : SVN->getMask()) 12804 if (M >= 0 && M < NumElts) 12805 N0UsedElements[M] = true; 12806 else if (M >= NumElts) 12807 N1UsedElements[M - NumElts] = true; 12808 12809 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 12810 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 12811 if (S0 == N0 && S1 == N1) 12812 return SDValue(); 12813 12814 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 12815 } 12816 12817 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 12818 // or turn a shuffle of a single concat into simpler shuffle then concat. 12819 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 12820 EVT VT = N->getValueType(0); 12821 unsigned NumElts = VT.getVectorNumElements(); 12822 12823 SDValue N0 = N->getOperand(0); 12824 SDValue N1 = N->getOperand(1); 12825 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12826 12827 SmallVector<SDValue, 4> Ops; 12828 EVT ConcatVT = N0.getOperand(0).getValueType(); 12829 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 12830 unsigned NumConcats = NumElts / NumElemsPerConcat; 12831 12832 // Special case: shuffle(concat(A,B)) can be more efficiently represented 12833 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 12834 // half vector elements. 12835 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 12836 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 12837 SVN->getMask().end(), [](int i) { return i == -1; })) { 12838 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 12839 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 12840 N1 = DAG.getUNDEF(ConcatVT); 12841 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 12842 } 12843 12844 // Look at every vector that's inserted. We're looking for exact 12845 // subvector-sized copies from a concatenated vector 12846 for (unsigned I = 0; I != NumConcats; ++I) { 12847 // Make sure we're dealing with a copy. 12848 unsigned Begin = I * NumElemsPerConcat; 12849 bool AllUndef = true, NoUndef = true; 12850 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 12851 if (SVN->getMaskElt(J) >= 0) 12852 AllUndef = false; 12853 else 12854 NoUndef = false; 12855 } 12856 12857 if (NoUndef) { 12858 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 12859 return SDValue(); 12860 12861 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 12862 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 12863 return SDValue(); 12864 12865 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 12866 if (FirstElt < N0.getNumOperands()) 12867 Ops.push_back(N0.getOperand(FirstElt)); 12868 else 12869 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 12870 12871 } else if (AllUndef) { 12872 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 12873 } else { // Mixed with general masks and undefs, can't do optimization. 12874 return SDValue(); 12875 } 12876 } 12877 12878 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 12879 } 12880 12881 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 12882 EVT VT = N->getValueType(0); 12883 unsigned NumElts = VT.getVectorNumElements(); 12884 12885 SDValue N0 = N->getOperand(0); 12886 SDValue N1 = N->getOperand(1); 12887 12888 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 12889 12890 // Canonicalize shuffle undef, undef -> undef 12891 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 12892 return DAG.getUNDEF(VT); 12893 12894 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12895 12896 // Canonicalize shuffle v, v -> v, undef 12897 if (N0 == N1) { 12898 SmallVector<int, 8> NewMask; 12899 for (unsigned i = 0; i != NumElts; ++i) { 12900 int Idx = SVN->getMaskElt(i); 12901 if (Idx >= (int)NumElts) Idx -= NumElts; 12902 NewMask.push_back(Idx); 12903 } 12904 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 12905 &NewMask[0]); 12906 } 12907 12908 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 12909 if (N0.getOpcode() == ISD::UNDEF) { 12910 SmallVector<int, 8> NewMask; 12911 for (unsigned i = 0; i != NumElts; ++i) { 12912 int Idx = SVN->getMaskElt(i); 12913 if (Idx >= 0) { 12914 if (Idx >= (int)NumElts) 12915 Idx -= NumElts; 12916 else 12917 Idx = -1; // remove reference to lhs 12918 } 12919 NewMask.push_back(Idx); 12920 } 12921 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 12922 &NewMask[0]); 12923 } 12924 12925 // Remove references to rhs if it is undef 12926 if (N1.getOpcode() == ISD::UNDEF) { 12927 bool Changed = false; 12928 SmallVector<int, 8> NewMask; 12929 for (unsigned i = 0; i != NumElts; ++i) { 12930 int Idx = SVN->getMaskElt(i); 12931 if (Idx >= (int)NumElts) { 12932 Idx = -1; 12933 Changed = true; 12934 } 12935 NewMask.push_back(Idx); 12936 } 12937 if (Changed) 12938 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 12939 } 12940 12941 // If it is a splat, check if the argument vector is another splat or a 12942 // build_vector. 12943 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 12944 SDNode *V = N0.getNode(); 12945 12946 // If this is a bit convert that changes the element type of the vector but 12947 // not the number of vector elements, look through it. Be careful not to 12948 // look though conversions that change things like v4f32 to v2f64. 12949 if (V->getOpcode() == ISD::BITCAST) { 12950 SDValue ConvInput = V->getOperand(0); 12951 if (ConvInput.getValueType().isVector() && 12952 ConvInput.getValueType().getVectorNumElements() == NumElts) 12953 V = ConvInput.getNode(); 12954 } 12955 12956 if (V->getOpcode() == ISD::BUILD_VECTOR) { 12957 assert(V->getNumOperands() == NumElts && 12958 "BUILD_VECTOR has wrong number of operands"); 12959 SDValue Base; 12960 bool AllSame = true; 12961 for (unsigned i = 0; i != NumElts; ++i) { 12962 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 12963 Base = V->getOperand(i); 12964 break; 12965 } 12966 } 12967 // Splat of <u, u, u, u>, return <u, u, u, u> 12968 if (!Base.getNode()) 12969 return N0; 12970 for (unsigned i = 0; i != NumElts; ++i) { 12971 if (V->getOperand(i) != Base) { 12972 AllSame = false; 12973 break; 12974 } 12975 } 12976 // Splat of <x, x, x, x>, return <x, x, x, x> 12977 if (AllSame) 12978 return N0; 12979 12980 // Canonicalize any other splat as a build_vector. 12981 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 12982 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 12983 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 12984 V->getValueType(0), Ops); 12985 12986 // We may have jumped through bitcasts, so the type of the 12987 // BUILD_VECTOR may not match the type of the shuffle. 12988 if (V->getValueType(0) != VT) 12989 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 12990 return NewBV; 12991 } 12992 } 12993 12994 // There are various patterns used to build up a vector from smaller vectors, 12995 // subvectors, or elements. Scan chains of these and replace unused insertions 12996 // or components with undef. 12997 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 12998 return S; 12999 13000 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13001 Level < AfterLegalizeVectorOps && 13002 (N1.getOpcode() == ISD::UNDEF || 13003 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13004 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13005 SDValue V = partitionShuffleOfConcats(N, DAG); 13006 13007 if (V.getNode()) 13008 return V; 13009 } 13010 13011 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13012 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13013 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13014 SmallVector<SDValue, 8> Ops; 13015 for (int M : SVN->getMask()) { 13016 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13017 if (M >= 0) { 13018 int Idx = M % NumElts; 13019 SDValue &S = (M < (int)NumElts ? N0 : N1); 13020 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13021 Op = S.getOperand(Idx); 13022 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13023 if (Idx == 0) 13024 Op = S.getOperand(0); 13025 } else { 13026 // Operand can't be combined - bail out. 13027 break; 13028 } 13029 } 13030 Ops.push_back(Op); 13031 } 13032 if (Ops.size() == VT.getVectorNumElements()) { 13033 // BUILD_VECTOR requires all inputs to be of the same type, find the 13034 // maximum type and extend them all. 13035 EVT SVT = VT.getScalarType(); 13036 if (SVT.isInteger()) 13037 for (SDValue &Op : Ops) 13038 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13039 if (SVT != VT.getScalarType()) 13040 for (SDValue &Op : Ops) 13041 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13042 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13043 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13044 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 13045 } 13046 } 13047 13048 // If this shuffle only has a single input that is a bitcasted shuffle, 13049 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13050 // back to their original types. 13051 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13052 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 13053 TLI.isTypeLegal(VT)) { 13054 13055 // Peek through the bitcast only if there is one user. 13056 SDValue BC0 = N0; 13057 while (BC0.getOpcode() == ISD::BITCAST) { 13058 if (!BC0.hasOneUse()) 13059 break; 13060 BC0 = BC0.getOperand(0); 13061 } 13062 13063 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13064 if (Scale == 1) 13065 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13066 13067 SmallVector<int, 8> NewMask; 13068 for (int M : Mask) 13069 for (int s = 0; s != Scale; ++s) 13070 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13071 return NewMask; 13072 }; 13073 13074 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13075 EVT SVT = VT.getScalarType(); 13076 EVT InnerVT = BC0->getValueType(0); 13077 EVT InnerSVT = InnerVT.getScalarType(); 13078 13079 // Determine which shuffle works with the smaller scalar type. 13080 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13081 EVT ScaleSVT = ScaleVT.getScalarType(); 13082 13083 if (TLI.isTypeLegal(ScaleVT) && 13084 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13085 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13086 13087 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13088 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13089 13090 // Scale the shuffle masks to the smaller scalar type. 13091 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13092 SmallVector<int, 8> InnerMask = 13093 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13094 SmallVector<int, 8> OuterMask = 13095 ScaleShuffleMask(SVN->getMask(), OuterScale); 13096 13097 // Merge the shuffle masks. 13098 SmallVector<int, 8> NewMask; 13099 for (int M : OuterMask) 13100 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13101 13102 // Test for shuffle mask legality over both commutations. 13103 SDValue SV0 = BC0->getOperand(0); 13104 SDValue SV1 = BC0->getOperand(1); 13105 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13106 if (!LegalMask) { 13107 std::swap(SV0, SV1); 13108 ShuffleVectorSDNode::commuteMask(NewMask); 13109 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13110 } 13111 13112 if (LegalMask) { 13113 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 13114 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 13115 return DAG.getNode( 13116 ISD::BITCAST, SDLoc(N), VT, 13117 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13118 } 13119 } 13120 } 13121 } 13122 13123 // Canonicalize shuffles according to rules: 13124 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13125 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13126 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13127 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13128 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13129 TLI.isTypeLegal(VT)) { 13130 // The incoming shuffle must be of the same type as the result of the 13131 // current shuffle. 13132 assert(N1->getOperand(0).getValueType() == VT && 13133 "Shuffle types don't match"); 13134 13135 SDValue SV0 = N1->getOperand(0); 13136 SDValue SV1 = N1->getOperand(1); 13137 bool HasSameOp0 = N0 == SV0; 13138 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 13139 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13140 // Commute the operands of this shuffle so that next rule 13141 // will trigger. 13142 return DAG.getCommutedVectorShuffle(*SVN); 13143 } 13144 13145 // Try to fold according to rules: 13146 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13147 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13148 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13149 // Don't try to fold shuffles with illegal type. 13150 // Only fold if this shuffle is the only user of the other shuffle. 13151 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13152 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13153 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13154 13155 // The incoming shuffle must be of the same type as the result of the 13156 // current shuffle. 13157 assert(OtherSV->getOperand(0).getValueType() == VT && 13158 "Shuffle types don't match"); 13159 13160 SDValue SV0, SV1; 13161 SmallVector<int, 4> Mask; 13162 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13163 // operand, and SV1 as the second operand. 13164 for (unsigned i = 0; i != NumElts; ++i) { 13165 int Idx = SVN->getMaskElt(i); 13166 if (Idx < 0) { 13167 // Propagate Undef. 13168 Mask.push_back(Idx); 13169 continue; 13170 } 13171 13172 SDValue CurrentVec; 13173 if (Idx < (int)NumElts) { 13174 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13175 // shuffle mask to identify which vector is actually referenced. 13176 Idx = OtherSV->getMaskElt(Idx); 13177 if (Idx < 0) { 13178 // Propagate Undef. 13179 Mask.push_back(Idx); 13180 continue; 13181 } 13182 13183 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13184 : OtherSV->getOperand(1); 13185 } else { 13186 // This shuffle index references an element within N1. 13187 CurrentVec = N1; 13188 } 13189 13190 // Simple case where 'CurrentVec' is UNDEF. 13191 if (CurrentVec.getOpcode() == ISD::UNDEF) { 13192 Mask.push_back(-1); 13193 continue; 13194 } 13195 13196 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13197 // will be the first or second operand of the combined shuffle. 13198 Idx = Idx % NumElts; 13199 if (!SV0.getNode() || SV0 == CurrentVec) { 13200 // Ok. CurrentVec is the left hand side. 13201 // Update the mask accordingly. 13202 SV0 = CurrentVec; 13203 Mask.push_back(Idx); 13204 continue; 13205 } 13206 13207 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13208 if (SV1.getNode() && SV1 != CurrentVec) 13209 return SDValue(); 13210 13211 // Ok. CurrentVec is the right hand side. 13212 // Update the mask accordingly. 13213 SV1 = CurrentVec; 13214 Mask.push_back(Idx + NumElts); 13215 } 13216 13217 // Check if all indices in Mask are Undef. In case, propagate Undef. 13218 bool isUndefMask = true; 13219 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13220 isUndefMask &= Mask[i] < 0; 13221 13222 if (isUndefMask) 13223 return DAG.getUNDEF(VT); 13224 13225 if (!SV0.getNode()) 13226 SV0 = DAG.getUNDEF(VT); 13227 if (!SV1.getNode()) 13228 SV1 = DAG.getUNDEF(VT); 13229 13230 // Avoid introducing shuffles with illegal mask. 13231 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13232 ShuffleVectorSDNode::commuteMask(Mask); 13233 13234 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13235 return SDValue(); 13236 13237 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13238 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13239 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13240 std::swap(SV0, SV1); 13241 } 13242 13243 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13244 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13245 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13246 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 13247 } 13248 13249 return SDValue(); 13250 } 13251 13252 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13253 SDValue InVal = N->getOperand(0); 13254 EVT VT = N->getValueType(0); 13255 13256 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13257 // with a VECTOR_SHUFFLE. 13258 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13259 SDValue InVec = InVal->getOperand(0); 13260 SDValue EltNo = InVal->getOperand(1); 13261 13262 // FIXME: We could support implicit truncation if the shuffle can be 13263 // scaled to a smaller vector scalar type. 13264 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13265 if (C0 && VT == InVec.getValueType() && 13266 VT.getScalarType() == InVal.getValueType()) { 13267 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13268 int Elt = C0->getZExtValue(); 13269 NewMask[0] = Elt; 13270 13271 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13272 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13273 NewMask); 13274 } 13275 } 13276 13277 return SDValue(); 13278 } 13279 13280 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13281 SDValue N0 = N->getOperand(0); 13282 SDValue N2 = N->getOperand(2); 13283 13284 // If the input vector is a concatenation, and the insert replaces 13285 // one of the halves, we can optimize into a single concat_vectors. 13286 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13287 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 13288 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13289 EVT VT = N->getValueType(0); 13290 13291 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13292 // (concat_vectors Z, Y) 13293 if (InsIdx == 0) 13294 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13295 N->getOperand(1), N0.getOperand(1)); 13296 13297 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13298 // (concat_vectors X, Z) 13299 if (InsIdx == VT.getVectorNumElements()/2) 13300 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13301 N0.getOperand(0), N->getOperand(1)); 13302 } 13303 13304 return SDValue(); 13305 } 13306 13307 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13308 SDValue N0 = N->getOperand(0); 13309 13310 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13311 if (N0->getOpcode() == ISD::FP16_TO_FP) 13312 return N0->getOperand(0); 13313 13314 return SDValue(); 13315 } 13316 13317 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13318 SDValue N0 = N->getOperand(0); 13319 13320 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13321 if (N0->getOpcode() == ISD::AND) { 13322 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13323 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13324 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13325 N0.getOperand(0)); 13326 } 13327 } 13328 13329 return SDValue(); 13330 } 13331 13332 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13333 /// with the destination vector and a zero vector. 13334 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13335 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13336 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13337 EVT VT = N->getValueType(0); 13338 SDValue LHS = N->getOperand(0); 13339 SDValue RHS = N->getOperand(1); 13340 SDLoc dl(N); 13341 13342 // Make sure we're not running after operation legalization where it 13343 // may have custom lowered the vector shuffles. 13344 if (LegalOperations) 13345 return SDValue(); 13346 13347 if (N->getOpcode() != ISD::AND) 13348 return SDValue(); 13349 13350 if (RHS.getOpcode() == ISD::BITCAST) 13351 RHS = RHS.getOperand(0); 13352 13353 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13354 return SDValue(); 13355 13356 EVT RVT = RHS.getValueType(); 13357 unsigned NumElts = RHS.getNumOperands(); 13358 13359 // Attempt to create a valid clear mask, splitting the mask into 13360 // sub elements and checking to see if each is 13361 // all zeros or all ones - suitable for shuffle masking. 13362 auto BuildClearMask = [&](int Split) { 13363 int NumSubElts = NumElts * Split; 13364 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13365 13366 SmallVector<int, 8> Indices; 13367 for (int i = 0; i != NumSubElts; ++i) { 13368 int EltIdx = i / Split; 13369 int SubIdx = i % Split; 13370 SDValue Elt = RHS.getOperand(EltIdx); 13371 if (Elt.getOpcode() == ISD::UNDEF) { 13372 Indices.push_back(-1); 13373 continue; 13374 } 13375 13376 APInt Bits; 13377 if (isa<ConstantSDNode>(Elt)) 13378 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13379 else if (isa<ConstantFPSDNode>(Elt)) 13380 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13381 else 13382 return SDValue(); 13383 13384 // Extract the sub element from the constant bit mask. 13385 if (DAG.getDataLayout().isBigEndian()) { 13386 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13387 } else { 13388 Bits = Bits.lshr(SubIdx * NumSubBits); 13389 } 13390 13391 if (Split > 1) 13392 Bits = Bits.trunc(NumSubBits); 13393 13394 if (Bits.isAllOnesValue()) 13395 Indices.push_back(i); 13396 else if (Bits == 0) 13397 Indices.push_back(i + NumSubElts); 13398 else 13399 return SDValue(); 13400 } 13401 13402 // Let's see if the target supports this vector_shuffle. 13403 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13404 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13405 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13406 return SDValue(); 13407 13408 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13409 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13410 DAG.getBitcast(ClearVT, LHS), 13411 Zero, &Indices[0])); 13412 }; 13413 13414 // Determine maximum split level (byte level masking). 13415 int MaxSplit = 1; 13416 if (RVT.getScalarSizeInBits() % 8 == 0) 13417 MaxSplit = RVT.getScalarSizeInBits() / 8; 13418 13419 for (int Split = 1; Split <= MaxSplit; ++Split) 13420 if (RVT.getScalarSizeInBits() % Split == 0) 13421 if (SDValue S = BuildClearMask(Split)) 13422 return S; 13423 13424 return SDValue(); 13425 } 13426 13427 /// Visit a binary vector operation, like ADD. 13428 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13429 assert(N->getValueType(0).isVector() && 13430 "SimplifyVBinOp only works on vectors!"); 13431 13432 SDValue LHS = N->getOperand(0); 13433 SDValue RHS = N->getOperand(1); 13434 13435 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 13436 // this operation. 13437 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 13438 RHS.getOpcode() == ISD::BUILD_VECTOR) { 13439 // Check if both vectors are constants. If not bail out. 13440 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 13441 cast<BuildVectorSDNode>(RHS)->isConstant())) 13442 return SDValue(); 13443 13444 SmallVector<SDValue, 8> Ops; 13445 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 13446 SDValue LHSOp = LHS.getOperand(i); 13447 SDValue RHSOp = RHS.getOperand(i); 13448 13449 // Can't fold divide by zero. 13450 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 13451 N->getOpcode() == ISD::FDIV) { 13452 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP && 13453 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero())) 13454 break; 13455 } 13456 13457 EVT VT = LHSOp.getValueType(); 13458 EVT RVT = RHSOp.getValueType(); 13459 EVT ST = VT; 13460 13461 if (RVT.getSizeInBits() < VT.getSizeInBits()) 13462 ST = RVT; 13463 13464 // Integer BUILD_VECTOR operands may have types larger than the element 13465 // size (e.g., when the element type is not legal). Prior to type 13466 // legalization, the types may not match between the two BUILD_VECTORS. 13467 // Truncate the operands to make them match. 13468 if (VT.getSizeInBits() != LHS.getValueType().getScalarSizeInBits()) { 13469 EVT ScalarT = LHS.getValueType().getScalarType(); 13470 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, LHSOp); 13471 VT = LHSOp.getValueType(); 13472 } 13473 if (RVT.getSizeInBits() != RHS.getValueType().getScalarSizeInBits()) { 13474 EVT ScalarT = RHS.getValueType().getScalarType(); 13475 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), ScalarT, RHSOp); 13476 RVT = RHSOp.getValueType(); 13477 } 13478 13479 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 13480 LHSOp, RHSOp, N->getFlags()); 13481 13482 // We need the resulting constant to be legal if we are in a phase after 13483 // legalization, so zero extend to the smallest operand type if required. 13484 if (ST != VT && Level != BeforeLegalizeTypes) 13485 FoldOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LHS), ST, FoldOp); 13486 13487 if (FoldOp.getOpcode() != ISD::UNDEF && 13488 FoldOp.getOpcode() != ISD::Constant && 13489 FoldOp.getOpcode() != ISD::ConstantFP) 13490 break; 13491 Ops.push_back(FoldOp); 13492 AddToWorklist(FoldOp.getNode()); 13493 } 13494 13495 if (Ops.size() == LHS.getNumOperands()) 13496 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 13497 } 13498 13499 // Try to convert a constant mask AND into a shuffle clear mask. 13500 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13501 return Shuffle; 13502 13503 // Type legalization might introduce new shuffles in the DAG. 13504 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13505 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13506 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13507 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13508 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 13509 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 13510 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13511 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13512 13513 if (SVN0->getMask().equals(SVN1->getMask())) { 13514 EVT VT = N->getValueType(0); 13515 SDValue UndefVector = LHS.getOperand(1); 13516 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13517 LHS.getOperand(0), RHS.getOperand(0), 13518 N->getFlags()); 13519 AddUsersToWorklist(N); 13520 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13521 &SVN0->getMask()[0]); 13522 } 13523 } 13524 13525 return SDValue(); 13526 } 13527 13528 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13529 SDValue N1, SDValue N2){ 13530 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13531 13532 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13533 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13534 13535 // If we got a simplified select_cc node back from SimplifySelectCC, then 13536 // break it down into a new SETCC node, and a new SELECT node, and then return 13537 // the SELECT node, since we were called with a SELECT node. 13538 if (SCC.getNode()) { 13539 // Check to see if we got a select_cc back (to turn into setcc/select). 13540 // Otherwise, just return whatever node we got back, like fabs. 13541 if (SCC.getOpcode() == ISD::SELECT_CC) { 13542 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13543 N0.getValueType(), 13544 SCC.getOperand(0), SCC.getOperand(1), 13545 SCC.getOperand(4)); 13546 AddToWorklist(SETCC.getNode()); 13547 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13548 SCC.getOperand(2), SCC.getOperand(3)); 13549 } 13550 13551 return SCC; 13552 } 13553 return SDValue(); 13554 } 13555 13556 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13557 /// being selected between, see if we can simplify the select. Callers of this 13558 /// should assume that TheSelect is deleted if this returns true. As such, they 13559 /// should return the appropriate thing (e.g. the node) back to the top-level of 13560 /// the DAG combiner loop to avoid it being looked at. 13561 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13562 SDValue RHS) { 13563 13564 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13565 // The select + setcc is redundant, because fsqrt returns NaN for X < -0. 13566 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13567 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13568 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13569 SDValue Sqrt = RHS; 13570 ISD::CondCode CC; 13571 SDValue CmpLHS; 13572 const ConstantFPSDNode *NegZero = nullptr; 13573 13574 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13575 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13576 CmpLHS = TheSelect->getOperand(0); 13577 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13578 } else { 13579 // SELECT or VSELECT 13580 SDValue Cmp = TheSelect->getOperand(0); 13581 if (Cmp.getOpcode() == ISD::SETCC) { 13582 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13583 CmpLHS = Cmp.getOperand(0); 13584 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13585 } 13586 } 13587 if (NegZero && NegZero->isNegative() && NegZero->isZero() && 13588 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13589 CC == ISD::SETULT || CC == ISD::SETLT)) { 13590 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13591 CombineTo(TheSelect, Sqrt); 13592 return true; 13593 } 13594 } 13595 } 13596 // Cannot simplify select with vector condition 13597 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 13598 13599 // If this is a select from two identical things, try to pull the operation 13600 // through the select. 13601 if (LHS.getOpcode() != RHS.getOpcode() || 13602 !LHS.hasOneUse() || !RHS.hasOneUse()) 13603 return false; 13604 13605 // If this is a load and the token chain is identical, replace the select 13606 // of two loads with a load through a select of the address to load from. 13607 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 13608 // constants have been dropped into the constant pool. 13609 if (LHS.getOpcode() == ISD::LOAD) { 13610 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 13611 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 13612 13613 // Token chains must be identical. 13614 if (LHS.getOperand(0) != RHS.getOperand(0) || 13615 // Do not let this transformation reduce the number of volatile loads. 13616 LLD->isVolatile() || RLD->isVolatile() || 13617 // FIXME: If either is a pre/post inc/dec load, 13618 // we'd need to split out the address adjustment. 13619 LLD->isIndexed() || RLD->isIndexed() || 13620 // If this is an EXTLOAD, the VT's must match. 13621 LLD->getMemoryVT() != RLD->getMemoryVT() || 13622 // If this is an EXTLOAD, the kind of extension must match. 13623 (LLD->getExtensionType() != RLD->getExtensionType() && 13624 // The only exception is if one of the extensions is anyext. 13625 LLD->getExtensionType() != ISD::EXTLOAD && 13626 RLD->getExtensionType() != ISD::EXTLOAD) || 13627 // FIXME: this discards src value information. This is 13628 // over-conservative. It would be beneficial to be able to remember 13629 // both potential memory locations. Since we are discarding 13630 // src value info, don't do the transformation if the memory 13631 // locations are not in the default address space. 13632 LLD->getPointerInfo().getAddrSpace() != 0 || 13633 RLD->getPointerInfo().getAddrSpace() != 0 || 13634 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 13635 LLD->getBasePtr().getValueType())) 13636 return false; 13637 13638 // Check that the select condition doesn't reach either load. If so, 13639 // folding this will induce a cycle into the DAG. If not, this is safe to 13640 // xform, so create a select of the addresses. 13641 SDValue Addr; 13642 if (TheSelect->getOpcode() == ISD::SELECT) { 13643 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 13644 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 13645 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 13646 return false; 13647 // The loads must not depend on one another. 13648 if (LLD->isPredecessorOf(RLD) || 13649 RLD->isPredecessorOf(LLD)) 13650 return false; 13651 Addr = DAG.getSelect(SDLoc(TheSelect), 13652 LLD->getBasePtr().getValueType(), 13653 TheSelect->getOperand(0), LLD->getBasePtr(), 13654 RLD->getBasePtr()); 13655 } else { // Otherwise SELECT_CC 13656 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 13657 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 13658 13659 if ((LLD->hasAnyUseOfValue(1) && 13660 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 13661 (RLD->hasAnyUseOfValue(1) && 13662 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 13663 return false; 13664 13665 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 13666 LLD->getBasePtr().getValueType(), 13667 TheSelect->getOperand(0), 13668 TheSelect->getOperand(1), 13669 LLD->getBasePtr(), RLD->getBasePtr(), 13670 TheSelect->getOperand(4)); 13671 } 13672 13673 SDValue Load; 13674 // It is safe to replace the two loads if they have different alignments, 13675 // but the new load must be the minimum (most restrictive) alignment of the 13676 // inputs. 13677 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 13678 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 13679 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 13680 Load = DAG.getLoad(TheSelect->getValueType(0), 13681 SDLoc(TheSelect), 13682 // FIXME: Discards pointer and AA info. 13683 LLD->getChain(), Addr, MachinePointerInfo(), 13684 LLD->isVolatile(), LLD->isNonTemporal(), 13685 isInvariant, Alignment); 13686 } else { 13687 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 13688 RLD->getExtensionType() : LLD->getExtensionType(), 13689 SDLoc(TheSelect), 13690 TheSelect->getValueType(0), 13691 // FIXME: Discards pointer and AA info. 13692 LLD->getChain(), Addr, MachinePointerInfo(), 13693 LLD->getMemoryVT(), LLD->isVolatile(), 13694 LLD->isNonTemporal(), isInvariant, Alignment); 13695 } 13696 13697 // Users of the select now use the result of the load. 13698 CombineTo(TheSelect, Load); 13699 13700 // Users of the old loads now use the new load's chain. We know the 13701 // old-load value is dead now. 13702 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 13703 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 13704 return true; 13705 } 13706 13707 return false; 13708 } 13709 13710 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 13711 /// where 'cond' is the comparison specified by CC. 13712 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 13713 SDValue N2, SDValue N3, 13714 ISD::CondCode CC, bool NotExtCompare) { 13715 // (x ? y : y) -> y. 13716 if (N2 == N3) return N2; 13717 13718 EVT VT = N2.getValueType(); 13719 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 13720 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 13721 13722 // Determine if the condition we're dealing with is constant 13723 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 13724 N0, N1, CC, DL, false); 13725 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 13726 13727 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 13728 // fold select_cc true, x, y -> x 13729 // fold select_cc false, x, y -> y 13730 return !SCCC->isNullValue() ? N2 : N3; 13731 } 13732 13733 // Check to see if we can simplify the select into an fabs node 13734 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 13735 // Allow either -0.0 or 0.0 13736 if (CFP->isZero()) { 13737 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 13738 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 13739 N0 == N2 && N3.getOpcode() == ISD::FNEG && 13740 N2 == N3.getOperand(0)) 13741 return DAG.getNode(ISD::FABS, DL, VT, N0); 13742 13743 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 13744 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 13745 N0 == N3 && N2.getOpcode() == ISD::FNEG && 13746 N2.getOperand(0) == N3) 13747 return DAG.getNode(ISD::FABS, DL, VT, N3); 13748 } 13749 } 13750 13751 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 13752 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 13753 // in it. This is a win when the constant is not otherwise available because 13754 // it replaces two constant pool loads with one. We only do this if the FP 13755 // type is known to be legal, because if it isn't, then we are before legalize 13756 // types an we want the other legalization to happen first (e.g. to avoid 13757 // messing with soft float) and if the ConstantFP is not legal, because if 13758 // it is legal, we may not need to store the FP constant in a constant pool. 13759 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 13760 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 13761 if (TLI.isTypeLegal(N2.getValueType()) && 13762 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 13763 TargetLowering::Legal && 13764 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 13765 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 13766 // If both constants have multiple uses, then we won't need to do an 13767 // extra load, they are likely around in registers for other users. 13768 (TV->hasOneUse() || FV->hasOneUse())) { 13769 Constant *Elts[] = { 13770 const_cast<ConstantFP*>(FV->getConstantFPValue()), 13771 const_cast<ConstantFP*>(TV->getConstantFPValue()) 13772 }; 13773 Type *FPTy = Elts[0]->getType(); 13774 const DataLayout &TD = DAG.getDataLayout(); 13775 13776 // Create a ConstantArray of the two constants. 13777 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 13778 SDValue CPIdx = 13779 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 13780 TD.getPrefTypeAlignment(FPTy)); 13781 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 13782 13783 // Get the offsets to the 0 and 1 element of the array so that we can 13784 // select between them. 13785 SDValue Zero = DAG.getIntPtrConstant(0, DL); 13786 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 13787 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 13788 13789 SDValue Cond = DAG.getSetCC(DL, 13790 getSetCCResultType(N0.getValueType()), 13791 N0, N1, CC); 13792 AddToWorklist(Cond.getNode()); 13793 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 13794 Cond, One, Zero); 13795 AddToWorklist(CstOffset.getNode()); 13796 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 13797 CstOffset); 13798 AddToWorklist(CPIdx.getNode()); 13799 return DAG.getLoad( 13800 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 13801 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 13802 false, false, false, Alignment); 13803 } 13804 } 13805 13806 // Check to see if we can perform the "gzip trick", transforming 13807 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 13808 if (isNullConstant(N3) && CC == ISD::SETLT && 13809 (isNullConstant(N1) || // (a < 0) ? b : 0 13810 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 13811 EVT XType = N0.getValueType(); 13812 EVT AType = N2.getValueType(); 13813 if (XType.bitsGE(AType)) { 13814 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 13815 // single-bit constant. 13816 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 13817 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 13818 ShCtV = XType.getSizeInBits() - ShCtV - 1; 13819 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 13820 getShiftAmountTy(N0.getValueType())); 13821 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 13822 XType, N0, ShCt); 13823 AddToWorklist(Shift.getNode()); 13824 13825 if (XType.bitsGT(AType)) { 13826 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13827 AddToWorklist(Shift.getNode()); 13828 } 13829 13830 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13831 } 13832 13833 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 13834 XType, N0, 13835 DAG.getConstant(XType.getSizeInBits() - 1, 13836 SDLoc(N0), 13837 getShiftAmountTy(N0.getValueType()))); 13838 AddToWorklist(Shift.getNode()); 13839 13840 if (XType.bitsGT(AType)) { 13841 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13842 AddToWorklist(Shift.getNode()); 13843 } 13844 13845 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13846 } 13847 } 13848 13849 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 13850 // where y is has a single bit set. 13851 // A plaintext description would be, we can turn the SELECT_CC into an AND 13852 // when the condition can be materialized as an all-ones register. Any 13853 // single bit-test can be materialized as an all-ones register with 13854 // shift-left and shift-right-arith. 13855 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 13856 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 13857 SDValue AndLHS = N0->getOperand(0); 13858 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13859 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 13860 // Shift the tested bit over the sign bit. 13861 APInt AndMask = ConstAndRHS->getAPIntValue(); 13862 SDValue ShlAmt = 13863 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 13864 getShiftAmountTy(AndLHS.getValueType())); 13865 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 13866 13867 // Now arithmetic right shift it all the way over, so the result is either 13868 // all-ones, or zero. 13869 SDValue ShrAmt = 13870 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 13871 getShiftAmountTy(Shl.getValueType())); 13872 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 13873 13874 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 13875 } 13876 } 13877 13878 // fold select C, 16, 0 -> shl C, 4 13879 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 13880 TLI.getBooleanContents(N0.getValueType()) == 13881 TargetLowering::ZeroOrOneBooleanContent) { 13882 13883 // If the caller doesn't want us to simplify this into a zext of a compare, 13884 // don't do it. 13885 if (NotExtCompare && N2C->isOne()) 13886 return SDValue(); 13887 13888 // Get a SetCC of the condition 13889 // NOTE: Don't create a SETCC if it's not legal on this target. 13890 if (!LegalOperations || 13891 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 13892 SDValue Temp, SCC; 13893 // cast from setcc result type to select result type 13894 if (LegalTypes) { 13895 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 13896 N0, N1, CC); 13897 if (N2.getValueType().bitsLT(SCC.getValueType())) 13898 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 13899 N2.getValueType()); 13900 else 13901 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13902 N2.getValueType(), SCC); 13903 } else { 13904 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 13905 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13906 N2.getValueType(), SCC); 13907 } 13908 13909 AddToWorklist(SCC.getNode()); 13910 AddToWorklist(Temp.getNode()); 13911 13912 if (N2C->isOne()) 13913 return Temp; 13914 13915 // shl setcc result by log2 n2c 13916 return DAG.getNode( 13917 ISD::SHL, DL, N2.getValueType(), Temp, 13918 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 13919 getShiftAmountTy(Temp.getValueType()))); 13920 } 13921 } 13922 13923 // Check to see if this is an integer abs. 13924 // select_cc setg[te] X, 0, X, -X -> 13925 // select_cc setgt X, -1, X, -X -> 13926 // select_cc setl[te] X, 0, -X, X -> 13927 // select_cc setlt X, 1, -X, X -> 13928 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 13929 if (N1C) { 13930 ConstantSDNode *SubC = nullptr; 13931 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 13932 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 13933 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 13934 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 13935 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 13936 (N1C->isOne() && CC == ISD::SETLT)) && 13937 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 13938 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 13939 13940 EVT XType = N0.getValueType(); 13941 if (SubC && SubC->isNullValue() && XType.isInteger()) { 13942 SDLoc DL(N0); 13943 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 13944 N0, 13945 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13946 getShiftAmountTy(N0.getValueType()))); 13947 SDValue Add = DAG.getNode(ISD::ADD, DL, 13948 XType, N0, Shift); 13949 AddToWorklist(Shift.getNode()); 13950 AddToWorklist(Add.getNode()); 13951 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 13952 } 13953 } 13954 13955 return SDValue(); 13956 } 13957 13958 /// This is a stub for TargetLowering::SimplifySetCC. 13959 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 13960 SDValue N1, ISD::CondCode Cond, 13961 SDLoc DL, bool foldBooleans) { 13962 TargetLowering::DAGCombinerInfo 13963 DagCombineInfo(DAG, Level, false, this); 13964 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 13965 } 13966 13967 /// Given an ISD::SDIV node expressing a divide by constant, return 13968 /// a DAG expression to select that will generate the same value by multiplying 13969 /// by a magic number. 13970 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 13971 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 13972 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13973 if (!C) 13974 return SDValue(); 13975 13976 // Avoid division by zero. 13977 if (C->isNullValue()) 13978 return SDValue(); 13979 13980 std::vector<SDNode*> Built; 13981 SDValue S = 13982 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 13983 13984 for (SDNode *N : Built) 13985 AddToWorklist(N); 13986 return S; 13987 } 13988 13989 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 13990 /// DAG expression that will generate the same value by right shifting. 13991 SDValue DAGCombiner::BuildSDIVPow2(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 = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14002 14003 for (SDNode *N : Built) 14004 AddToWorklist(N); 14005 return S; 14006 } 14007 14008 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14009 /// expression that will generate the same value by multiplying by a magic 14010 /// number. 14011 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14012 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14013 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14014 if (!C) 14015 return SDValue(); 14016 14017 // Avoid division by zero. 14018 if (C->isNullValue()) 14019 return SDValue(); 14020 14021 std::vector<SDNode*> Built; 14022 SDValue S = 14023 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14024 14025 for (SDNode *N : Built) 14026 AddToWorklist(N); 14027 return S; 14028 } 14029 14030 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14031 if (Level >= AfterLegalizeDAG) 14032 return SDValue(); 14033 14034 // Expose the DAG combiner to the target combiner implementations. 14035 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14036 14037 unsigned Iterations = 0; 14038 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14039 if (Iterations) { 14040 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14041 // For the reciprocal, we need to find the zero of the function: 14042 // F(X) = A X - 1 [which has a zero at X = 1/A] 14043 // => 14044 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14045 // does not require additional intermediate precision] 14046 EVT VT = Op.getValueType(); 14047 SDLoc DL(Op); 14048 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14049 14050 AddToWorklist(Est.getNode()); 14051 14052 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14053 for (unsigned i = 0; i < Iterations; ++i) { 14054 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14055 AddToWorklist(NewEst.getNode()); 14056 14057 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14058 AddToWorklist(NewEst.getNode()); 14059 14060 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14061 AddToWorklist(NewEst.getNode()); 14062 14063 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14064 AddToWorklist(Est.getNode()); 14065 } 14066 } 14067 return Est; 14068 } 14069 14070 return SDValue(); 14071 } 14072 14073 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14074 /// For the reciprocal sqrt, we need to find the zero of the function: 14075 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14076 /// => 14077 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14078 /// As a result, we precompute A/2 prior to the iteration loop. 14079 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 14080 unsigned Iterations, 14081 SDNodeFlags *Flags) { 14082 EVT VT = Arg.getValueType(); 14083 SDLoc DL(Arg); 14084 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14085 14086 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14087 // this entire sequence requires only one FP constant. 14088 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14089 AddToWorklist(HalfArg.getNode()); 14090 14091 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14092 AddToWorklist(HalfArg.getNode()); 14093 14094 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14095 for (unsigned i = 0; i < Iterations; ++i) { 14096 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14097 AddToWorklist(NewEst.getNode()); 14098 14099 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14100 AddToWorklist(NewEst.getNode()); 14101 14102 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14103 AddToWorklist(NewEst.getNode()); 14104 14105 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14106 AddToWorklist(Est.getNode()); 14107 } 14108 return Est; 14109 } 14110 14111 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14112 /// For the reciprocal sqrt, we need to find the zero of the function: 14113 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14114 /// => 14115 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14116 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 14117 unsigned Iterations, 14118 SDNodeFlags *Flags) { 14119 EVT VT = Arg.getValueType(); 14120 SDLoc DL(Arg); 14121 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14122 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14123 14124 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 14125 for (unsigned i = 0; i < Iterations; ++i) { 14126 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14127 AddToWorklist(HalfEst.getNode()); 14128 14129 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14130 AddToWorklist(Est.getNode()); 14131 14132 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14133 AddToWorklist(Est.getNode()); 14134 14135 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags); 14136 AddToWorklist(Est.getNode()); 14137 14138 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags); 14139 AddToWorklist(Est.getNode()); 14140 } 14141 return Est; 14142 } 14143 14144 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14145 if (Level >= AfterLegalizeDAG) 14146 return SDValue(); 14147 14148 // Expose the DAG combiner to the target combiner implementations. 14149 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14150 unsigned Iterations = 0; 14151 bool UseOneConstNR = false; 14152 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14153 AddToWorklist(Est.getNode()); 14154 if (Iterations) { 14155 Est = UseOneConstNR ? 14156 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) : 14157 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags); 14158 } 14159 return Est; 14160 } 14161 14162 return SDValue(); 14163 } 14164 14165 /// Return true if base is a frame index, which is known not to alias with 14166 /// anything but itself. Provides base object and offset as results. 14167 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14168 const GlobalValue *&GV, const void *&CV) { 14169 // Assume it is a primitive operation. 14170 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14171 14172 // If it's an adding a simple constant then integrate the offset. 14173 if (Base.getOpcode() == ISD::ADD) { 14174 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14175 Base = Base.getOperand(0); 14176 Offset += C->getZExtValue(); 14177 } 14178 } 14179 14180 // Return the underlying GlobalValue, and update the Offset. Return false 14181 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14182 // by multiple nodes with different offsets. 14183 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14184 GV = G->getGlobal(); 14185 Offset += G->getOffset(); 14186 return false; 14187 } 14188 14189 // Return the underlying Constant value, and update the Offset. Return false 14190 // for ConstantSDNodes since the same constant pool entry may be represented 14191 // by multiple nodes with different offsets. 14192 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14193 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14194 : (const void *)C->getConstVal(); 14195 Offset += C->getOffset(); 14196 return false; 14197 } 14198 // If it's any of the following then it can't alias with anything but itself. 14199 return isa<FrameIndexSDNode>(Base); 14200 } 14201 14202 /// Return true if there is any possibility that the two addresses overlap. 14203 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14204 // If they are the same then they must be aliases. 14205 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14206 14207 // If they are both volatile then they cannot be reordered. 14208 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14209 14210 // If one operation reads from invariant memory, and the other may store, they 14211 // cannot alias. These should really be checking the equivalent of mayWrite, 14212 // but it only matters for memory nodes other than load /store. 14213 if (Op0->isInvariant() && Op1->writeMem()) 14214 return false; 14215 14216 if (Op1->isInvariant() && Op0->writeMem()) 14217 return false; 14218 14219 // Gather base node and offset information. 14220 SDValue Base1, Base2; 14221 int64_t Offset1, Offset2; 14222 const GlobalValue *GV1, *GV2; 14223 const void *CV1, *CV2; 14224 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14225 Base1, Offset1, GV1, CV1); 14226 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14227 Base2, Offset2, GV2, CV2); 14228 14229 // If they have a same base address then check to see if they overlap. 14230 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14231 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14232 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14233 14234 // It is possible for different frame indices to alias each other, mostly 14235 // when tail call optimization reuses return address slots for arguments. 14236 // To catch this case, look up the actual index of frame indices to compute 14237 // the real alias relationship. 14238 if (isFrameIndex1 && isFrameIndex2) { 14239 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 14240 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14241 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14242 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14243 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14244 } 14245 14246 // Otherwise, if we know what the bases are, and they aren't identical, then 14247 // we know they cannot alias. 14248 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14249 return false; 14250 14251 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14252 // compared to the size and offset of the access, we may be able to prove they 14253 // do not alias. This check is conservative for now to catch cases created by 14254 // splitting vector types. 14255 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14256 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14257 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14258 Op1->getMemoryVT().getSizeInBits() >> 3) && 14259 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 14260 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14261 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14262 14263 // There is no overlap between these relatively aligned accesses of similar 14264 // size, return no alias. 14265 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14266 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14267 return false; 14268 } 14269 14270 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14271 ? CombinerGlobalAA 14272 : DAG.getSubtarget().useAA(); 14273 #ifndef NDEBUG 14274 if (CombinerAAOnlyFunc.getNumOccurrences() && 14275 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14276 UseAA = false; 14277 #endif 14278 if (UseAA && 14279 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14280 // Use alias analysis information. 14281 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14282 Op1->getSrcValueOffset()); 14283 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14284 Op0->getSrcValueOffset() - MinOffset; 14285 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14286 Op1->getSrcValueOffset() - MinOffset; 14287 AliasResult AAResult = 14288 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14289 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14290 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14291 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14292 if (AAResult == NoAlias) 14293 return false; 14294 } 14295 14296 // Otherwise we have to assume they alias. 14297 return true; 14298 } 14299 14300 /// Walk up chain skipping non-aliasing memory nodes, 14301 /// looking for aliasing nodes and adding them to the Aliases vector. 14302 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14303 SmallVectorImpl<SDValue> &Aliases) { 14304 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14305 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14306 14307 // Get alias information for node. 14308 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14309 14310 // Starting off. 14311 Chains.push_back(OriginalChain); 14312 unsigned Depth = 0; 14313 14314 // Look at each chain and determine if it is an alias. If so, add it to the 14315 // aliases list. If not, then continue up the chain looking for the next 14316 // candidate. 14317 while (!Chains.empty()) { 14318 SDValue Chain = Chains.pop_back_val(); 14319 14320 // For TokenFactor nodes, look at each operand and only continue up the 14321 // chain until we find two aliases. If we've seen two aliases, assume we'll 14322 // find more and revert to original chain since the xform is unlikely to be 14323 // profitable. 14324 // 14325 // FIXME: The depth check could be made to return the last non-aliasing 14326 // chain we found before we hit a tokenfactor rather than the original 14327 // chain. 14328 if (Depth > 6 || Aliases.size() == 2) { 14329 Aliases.clear(); 14330 Aliases.push_back(OriginalChain); 14331 return; 14332 } 14333 14334 // Don't bother if we've been before. 14335 if (!Visited.insert(Chain.getNode()).second) 14336 continue; 14337 14338 switch (Chain.getOpcode()) { 14339 case ISD::EntryToken: 14340 // Entry token is ideal chain operand, but handled in FindBetterChain. 14341 break; 14342 14343 case ISD::LOAD: 14344 case ISD::STORE: { 14345 // Get alias information for Chain. 14346 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14347 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14348 14349 // If chain is alias then stop here. 14350 if (!(IsLoad && IsOpLoad) && 14351 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14352 Aliases.push_back(Chain); 14353 } else { 14354 // Look further up the chain. 14355 Chains.push_back(Chain.getOperand(0)); 14356 ++Depth; 14357 } 14358 break; 14359 } 14360 14361 case ISD::TokenFactor: 14362 // We have to check each of the operands of the token factor for "small" 14363 // token factors, so we queue them up. Adding the operands to the queue 14364 // (stack) in reverse order maintains the original order and increases the 14365 // likelihood that getNode will find a matching token factor (CSE.) 14366 if (Chain.getNumOperands() > 16) { 14367 Aliases.push_back(Chain); 14368 break; 14369 } 14370 for (unsigned n = Chain.getNumOperands(); n;) 14371 Chains.push_back(Chain.getOperand(--n)); 14372 ++Depth; 14373 break; 14374 14375 default: 14376 // For all other instructions we will just have to take what we can get. 14377 Aliases.push_back(Chain); 14378 break; 14379 } 14380 } 14381 14382 // We need to be careful here to also search for aliases through the 14383 // value operand of a store, etc. Consider the following situation: 14384 // Token1 = ... 14385 // L1 = load Token1, %52 14386 // S1 = store Token1, L1, %51 14387 // L2 = load Token1, %52+8 14388 // S2 = store Token1, L2, %51+8 14389 // Token2 = Token(S1, S2) 14390 // L3 = load Token2, %53 14391 // S3 = store Token2, L3, %52 14392 // L4 = load Token2, %53+8 14393 // S4 = store Token2, L4, %52+8 14394 // If we search for aliases of S3 (which loads address %52), and we look 14395 // only through the chain, then we'll miss the trivial dependence on L1 14396 // (which also loads from %52). We then might change all loads and 14397 // stores to use Token1 as their chain operand, which could result in 14398 // copying %53 into %52 before copying %52 into %51 (which should 14399 // happen first). 14400 // 14401 // The problem is, however, that searching for such data dependencies 14402 // can become expensive, and the cost is not directly related to the 14403 // chain depth. Instead, we'll rule out such configurations here by 14404 // insisting that we've visited all chain users (except for users 14405 // of the original chain, which is not necessary). When doing this, 14406 // we need to look through nodes we don't care about (otherwise, things 14407 // like register copies will interfere with trivial cases). 14408 14409 SmallVector<const SDNode *, 16> Worklist; 14410 for (const SDNode *N : Visited) 14411 if (N != OriginalChain.getNode()) 14412 Worklist.push_back(N); 14413 14414 while (!Worklist.empty()) { 14415 const SDNode *M = Worklist.pop_back_val(); 14416 14417 // We have already visited M, and want to make sure we've visited any uses 14418 // of M that we care about. For uses that we've not visisted, and don't 14419 // care about, queue them to the worklist. 14420 14421 for (SDNode::use_iterator UI = M->use_begin(), 14422 UIE = M->use_end(); UI != UIE; ++UI) 14423 if (UI.getUse().getValueType() == MVT::Other && 14424 Visited.insert(*UI).second) { 14425 if (isa<MemSDNode>(*UI)) { 14426 // We've not visited this use, and we care about it (it could have an 14427 // ordering dependency with the original node). 14428 Aliases.clear(); 14429 Aliases.push_back(OriginalChain); 14430 return; 14431 } 14432 14433 // We've not visited this use, but we don't care about it. Mark it as 14434 // visited and enqueue it to the worklist. 14435 Worklist.push_back(*UI); 14436 } 14437 } 14438 } 14439 14440 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14441 /// (aliasing node.) 14442 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14443 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14444 14445 // Accumulate all the aliases to this node. 14446 GatherAllAliases(N, OldChain, Aliases); 14447 14448 // If no operands then chain to entry token. 14449 if (Aliases.size() == 0) 14450 return DAG.getEntryNode(); 14451 14452 // If a single operand then chain to it. We don't need to revisit it. 14453 if (Aliases.size() == 1) 14454 return Aliases[0]; 14455 14456 // Construct a custom tailored token factor. 14457 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14458 } 14459 14460 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) { 14461 // This holds the base pointer, index, and the offset in bytes from the base 14462 // pointer. 14463 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 14464 14465 // We must have a base and an offset. 14466 if (!BasePtr.Base.getNode()) 14467 return false; 14468 14469 // Do not handle stores to undef base pointers. 14470 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 14471 return false; 14472 14473 SmallVector<StoreSDNode *, 8> ChainedStores; 14474 ChainedStores.push_back(St); 14475 14476 // Walk up the chain and look for nodes with offsets from the same 14477 // base pointer. Stop when reaching an instruction with a different kind 14478 // or instruction which has a different base pointer. 14479 StoreSDNode *Index = St; 14480 while (Index) { 14481 // If the chain has more than one use, then we can't reorder the mem ops. 14482 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14483 break; 14484 14485 // Find the base pointer and offset for this memory node. 14486 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 14487 14488 // Check that the base pointer is the same as the original one. 14489 if (!Ptr.equalBaseIndex(BasePtr)) 14490 break; 14491 14492 if (Index->isVolatile() || Index->isIndexed()) 14493 break; 14494 14495 // Find the next memory operand in the chain. If the next operand in the 14496 // chain is a store then move up and continue the scan with the next 14497 // memory operand. If the next operand is a load save it and use alias 14498 // information to check if it interferes with anything. 14499 SDNode *NextInChain = Index->getChain().getNode(); 14500 while (true) { 14501 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14502 // We found a store node. Use it for the next iteration. 14503 ChainedStores.push_back(STn); 14504 Index = STn; 14505 break; 14506 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14507 NextInChain = Ldn->getChain().getNode(); 14508 continue; 14509 } else { 14510 Index = nullptr; 14511 break; 14512 } 14513 } 14514 } 14515 14516 bool MadeChange = false; 14517 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 14518 14519 for (StoreSDNode *ChainedStore : ChainedStores) { 14520 SDValue Chain = ChainedStore->getChain(); 14521 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 14522 14523 if (Chain != BetterChain) { 14524 MadeChange = true; 14525 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 14526 } 14527 } 14528 14529 // Do all replacements after finding the replacements to make to avoid making 14530 // the chains more complicated by introducing new TokenFactors. 14531 for (auto Replacement : BetterChains) 14532 replaceStoreChain(Replacement.first, Replacement.second); 14533 14534 return MadeChange; 14535 } 14536 14537 /// This is the entry point for the file. 14538 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 14539 CodeGenOpt::Level OptLevel) { 14540 /// This is the main entry point to this class. 14541 DAGCombiner(*this, AA, OptLevel).Run(Level); 14542 } 14543