1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/SelectionDAG.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetLowering.h" 37 #include "llvm/Target/TargetOptions.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 #define DEBUG_TYPE "dagcombine" 44 45 STATISTIC(NodesCombined , "Number of dag nodes combined"); 46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 50 STATISTIC(SlicedLoads, "Number of load sliced"); 51 52 namespace { 53 static cl::opt<bool> 54 CombinerAA("combiner-alias-analysis", cl::Hidden, 55 cl::desc("Enable DAG combiner alias-analysis heuristics")); 56 57 static cl::opt<bool> 58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 59 cl::desc("Enable DAG combiner's use of IR alias analysis")); 60 61 static cl::opt<bool> 62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 63 cl::desc("Enable DAG combiner's use of TBAA")); 64 65 #ifndef NDEBUG 66 static cl::opt<std::string> 67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 68 cl::desc("Only use DAG-combiner alias analysis in this" 69 " function")); 70 #endif 71 72 /// Hidden option to stress test load slicing, i.e., when this option 73 /// is enabled, load slicing bypasses most of its profitability guards. 74 static cl::opt<bool> 75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 76 cl::desc("Bypass the profitability model of load " 77 "slicing"), 78 cl::init(false)); 79 80 static cl::opt<bool> 81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 82 cl::desc("DAG combiner may split indexing from loads")); 83 84 //------------------------------ DAGCombiner ---------------------------------// 85 86 class DAGCombiner { 87 SelectionDAG &DAG; 88 const TargetLowering &TLI; 89 CombineLevel Level; 90 CodeGenOpt::Level OptLevel; 91 bool LegalOperations; 92 bool LegalTypes; 93 bool ForCodeSize; 94 95 /// \brief Worklist of all of the nodes that need to be simplified. 96 /// 97 /// This must behave as a stack -- new nodes to process are pushed onto the 98 /// back and when processing we pop off of the back. 99 /// 100 /// The worklist will not contain duplicates but may contain null entries 101 /// due to nodes being deleted from the underlying DAG. 102 SmallVector<SDNode *, 64> Worklist; 103 104 /// \brief Mapping from an SDNode to its position on the worklist. 105 /// 106 /// This is used to find and remove nodes from the worklist (by nulling 107 /// them) when they are deleted from the underlying DAG. It relies on 108 /// stable indices of nodes within the worklist. 109 DenseMap<SDNode *, unsigned> WorklistMap; 110 111 /// \brief Set of nodes which have been combined (at least once). 112 /// 113 /// This is used to allow us to reliably add any operands of a DAG node 114 /// which have not yet been combined to the worklist. 115 SmallPtrSet<SDNode *, 64> CombinedNodes; 116 117 // AA - Used for DAG load/store alias analysis. 118 AliasAnalysis &AA; 119 120 /// When an instruction is simplified, add all users of the instruction to 121 /// the work lists because they might get more simplified now. 122 void AddUsersToWorklist(SDNode *N) { 123 for (SDNode *Node : N->uses()) 124 AddToWorklist(Node); 125 } 126 127 /// Call the node-specific routine that folds each particular type of node. 128 SDValue visit(SDNode *N); 129 130 public: 131 /// Add to the worklist making sure its instance is at the back (next to be 132 /// processed.) 133 void AddToWorklist(SDNode *N) { 134 // Skip handle nodes as they can't usefully be combined and confuse the 135 // zero-use deletion strategy. 136 if (N->getOpcode() == ISD::HANDLENODE) 137 return; 138 139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 140 Worklist.push_back(N); 141 } 142 143 /// Remove all instances of N from the worklist. 144 void removeFromWorklist(SDNode *N) { 145 CombinedNodes.erase(N); 146 147 auto It = WorklistMap.find(N); 148 if (It == WorklistMap.end()) 149 return; // Not in the worklist. 150 151 // Null out the entry rather than erasing it to avoid a linear operation. 152 Worklist[It->second] = nullptr; 153 WorklistMap.erase(It); 154 } 155 156 void deleteAndRecombine(SDNode *N); 157 bool recursivelyDeleteUnusedNodes(SDNode *N); 158 159 /// Replaces all uses of the results of one DAG node with new values. 160 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 161 bool AddTo = true); 162 163 /// Replaces all uses of the results of one DAG node with new values. 164 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 165 return CombineTo(N, &Res, 1, AddTo); 166 } 167 168 /// Replaces all uses of the results of one DAG node with new values. 169 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 170 bool AddTo = true) { 171 SDValue To[] = { Res0, Res1 }; 172 return CombineTo(N, To, 2, AddTo); 173 } 174 175 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 176 177 private: 178 179 /// Check the specified integer node value to see if it can be simplified or 180 /// if things it uses can be simplified by bit propagation. 181 /// If so, return true. 182 bool SimplifyDemandedBits(SDValue Op) { 183 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 184 APInt Demanded = APInt::getAllOnesValue(BitWidth); 185 return SimplifyDemandedBits(Op, Demanded); 186 } 187 188 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 189 190 bool CombineToPreIndexedLoadStore(SDNode *N); 191 bool CombineToPostIndexedLoadStore(SDNode *N); 192 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 193 bool SliceUpLoad(SDNode *N); 194 195 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 196 /// load. 197 /// 198 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 199 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 200 /// \param EltNo index of the vector element to load. 201 /// \param OriginalLoad load that EVE came from to be replaced. 202 /// \returns EVE on success SDValue() on failure. 203 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 204 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 205 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 206 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 207 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 208 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 209 SDValue PromoteIntBinOp(SDValue Op); 210 SDValue PromoteIntShiftOp(SDValue Op); 211 SDValue PromoteExtend(SDValue Op); 212 bool PromoteLoad(SDValue Op); 213 214 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 215 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 216 ISD::NodeType ExtType); 217 218 /// Call the node-specific routine that knows how to fold each 219 /// particular type of node. If that doesn't do anything, try the 220 /// target-specific DAG combines. 221 SDValue combine(SDNode *N); 222 223 // Visitation implementation - Implement dag node combining for different 224 // node types. The semantics are as follows: 225 // Return Value: 226 // SDValue.getNode() == 0 - No change was made 227 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 228 // otherwise - N should be replaced by the returned Operand. 229 // 230 SDValue visitTokenFactor(SDNode *N); 231 SDValue visitMERGE_VALUES(SDNode *N); 232 SDValue visitADD(SDNode *N); 233 SDValue visitSUB(SDNode *N); 234 SDValue visitADDC(SDNode *N); 235 SDValue visitSUBC(SDNode *N); 236 SDValue visitADDE(SDNode *N); 237 SDValue visitSUBE(SDNode *N); 238 SDValue visitMUL(SDNode *N); 239 SDValue useDivRem(SDNode *N); 240 SDValue visitSDIV(SDNode *N); 241 SDValue visitUDIV(SDNode *N); 242 SDValue visitREM(SDNode *N); 243 SDValue visitMULHU(SDNode *N); 244 SDValue visitMULHS(SDNode *N); 245 SDValue visitSMUL_LOHI(SDNode *N); 246 SDValue visitUMUL_LOHI(SDNode *N); 247 SDValue visitSMULO(SDNode *N); 248 SDValue visitUMULO(SDNode *N); 249 SDValue visitIMINMAX(SDNode *N); 250 SDValue visitAND(SDNode *N); 251 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 252 SDValue visitOR(SDNode *N); 253 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 254 SDValue visitXOR(SDNode *N); 255 SDValue SimplifyVBinOp(SDNode *N); 256 SDValue visitSHL(SDNode *N); 257 SDValue visitSRA(SDNode *N); 258 SDValue visitSRL(SDNode *N); 259 SDValue visitRotate(SDNode *N); 260 SDValue visitBSWAP(SDNode *N); 261 SDValue visitCTLZ(SDNode *N); 262 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 263 SDValue visitCTTZ(SDNode *N); 264 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 265 SDValue visitCTPOP(SDNode *N); 266 SDValue visitSELECT(SDNode *N); 267 SDValue visitVSELECT(SDNode *N); 268 SDValue visitSELECT_CC(SDNode *N); 269 SDValue visitSETCC(SDNode *N); 270 SDValue visitSIGN_EXTEND(SDNode *N); 271 SDValue visitZERO_EXTEND(SDNode *N); 272 SDValue visitANY_EXTEND(SDNode *N); 273 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 274 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 275 SDValue visitTRUNCATE(SDNode *N); 276 SDValue visitBITCAST(SDNode *N); 277 SDValue visitBUILD_PAIR(SDNode *N); 278 SDValue visitFADD(SDNode *N); 279 SDValue visitFSUB(SDNode *N); 280 SDValue visitFMUL(SDNode *N); 281 SDValue visitFMA(SDNode *N); 282 SDValue visitFDIV(SDNode *N); 283 SDValue visitFREM(SDNode *N); 284 SDValue visitFSQRT(SDNode *N); 285 SDValue visitFCOPYSIGN(SDNode *N); 286 SDValue visitSINT_TO_FP(SDNode *N); 287 SDValue visitUINT_TO_FP(SDNode *N); 288 SDValue visitFP_TO_SINT(SDNode *N); 289 SDValue visitFP_TO_UINT(SDNode *N); 290 SDValue visitFP_ROUND(SDNode *N); 291 SDValue visitFP_ROUND_INREG(SDNode *N); 292 SDValue visitFP_EXTEND(SDNode *N); 293 SDValue visitFNEG(SDNode *N); 294 SDValue visitFABS(SDNode *N); 295 SDValue visitFCEIL(SDNode *N); 296 SDValue visitFTRUNC(SDNode *N); 297 SDValue visitFFLOOR(SDNode *N); 298 SDValue visitFMINNUM(SDNode *N); 299 SDValue visitFMAXNUM(SDNode *N); 300 SDValue visitBRCOND(SDNode *N); 301 SDValue visitBR_CC(SDNode *N); 302 SDValue visitLOAD(SDNode *N); 303 304 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 305 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 306 307 SDValue visitSTORE(SDNode *N); 308 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 309 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 310 SDValue visitBUILD_VECTOR(SDNode *N); 311 SDValue visitCONCAT_VECTORS(SDNode *N); 312 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 313 SDValue visitVECTOR_SHUFFLE(SDNode *N); 314 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 315 SDValue visitINSERT_SUBVECTOR(SDNode *N); 316 SDValue visitMLOAD(SDNode *N); 317 SDValue visitMSTORE(SDNode *N); 318 SDValue visitMGATHER(SDNode *N); 319 SDValue visitMSCATTER(SDNode *N); 320 SDValue visitFP_TO_FP16(SDNode *N); 321 SDValue visitFP16_TO_FP(SDNode *N); 322 323 SDValue visitFADDForFMACombine(SDNode *N); 324 SDValue visitFSUBForFMACombine(SDNode *N); 325 SDValue visitFMULForFMACombine(SDNode *N); 326 327 SDValue XformToShuffleWithZero(SDNode *N); 328 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 329 330 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 331 332 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 333 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 334 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 335 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 336 SDValue N3, ISD::CondCode CC, 337 bool NotExtCompare = false); 338 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 339 SDLoc DL, bool foldBooleans = true); 340 341 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 342 SDValue &CC) const; 343 bool isOneUseSetCC(SDValue N) const; 344 345 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 346 unsigned HiOp); 347 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 348 SDValue CombineExtLoad(SDNode *N); 349 SDValue combineRepeatedFPDivisors(SDNode *N); 350 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 351 SDValue BuildSDIV(SDNode *N); 352 SDValue BuildSDIVPow2(SDNode *N); 353 SDValue BuildUDIV(SDNode *N); 354 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 355 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 356 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 357 SDNodeFlags *Flags); 358 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 359 SDNodeFlags *Flags); 360 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 361 bool DemandHighBits = true); 362 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 363 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 364 SDValue InnerPos, SDValue InnerNeg, 365 unsigned PosOpcode, unsigned NegOpcode, 366 SDLoc DL); 367 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 368 SDValue ReduceLoadWidth(SDNode *N); 369 SDValue ReduceLoadOpStoreWidth(SDNode *N); 370 SDValue TransformFPLoadStorePair(SDNode *N); 371 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 372 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 373 374 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 375 376 /// Walk up chain skipping non-aliasing memory nodes, 377 /// looking for aliasing nodes and adding them to the Aliases vector. 378 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 379 SmallVectorImpl<SDValue> &Aliases); 380 381 /// Return true if there is any possibility that the two addresses overlap. 382 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 383 384 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 385 /// chain (aliasing node.) 386 SDValue FindBetterChain(SDNode *N, SDValue Chain); 387 388 /// Do FindBetterChain for a store and any possibly adjacent stores on 389 /// consecutive chains. 390 bool findBetterNeighborChains(StoreSDNode *St); 391 392 /// Holds a pointer to an LSBaseSDNode as well as information on where it 393 /// is located in a sequence of memory operations connected by a chain. 394 struct MemOpLink { 395 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 396 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 397 // Ptr to the mem node. 398 LSBaseSDNode *MemNode; 399 // Offset from the base ptr. 400 int64_t OffsetFromBase; 401 // What is the sequence number of this mem node. 402 // Lowest mem operand in the DAG starts at zero. 403 unsigned SequenceNum; 404 }; 405 406 /// This is a helper function for visitMUL to check the profitability 407 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 408 /// MulNode is the original multiply, AddNode is (add x, c1), 409 /// and ConstNode is c2. 410 bool isMulAddWithConstProfitable(SDNode *MulNode, 411 SDValue &AddNode, 412 SDValue &ConstNode); 413 414 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 415 /// constant build_vector of the stored constant values in Stores. 416 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, 417 SDLoc SL, 418 ArrayRef<MemOpLink> Stores, 419 SmallVectorImpl<SDValue> &Chains, 420 EVT Ty) const; 421 422 /// This is a helper function for MergeConsecutiveStores. When the source 423 /// elements of the consecutive stores are all constants or all extracted 424 /// vector elements, try to merge them into one larger store. 425 /// \return True if a merged store was created. 426 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 427 EVT MemVT, unsigned NumStores, 428 bool IsConstantSrc, bool UseVector); 429 430 /// This is a helper function for MergeConsecutiveStores. 431 /// Stores that may be merged are placed in StoreNodes. 432 /// Loads that may alias with those stores are placed in AliasLoadNodes. 433 void getStoreMergeAndAliasCandidates( 434 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 435 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 436 437 /// Merge consecutive store operations into a wide store. 438 /// This optimization uses wide integers or vectors when possible. 439 /// \return True if some memory operations were changed. 440 bool MergeConsecutiveStores(StoreSDNode *N); 441 442 /// \brief Try to transform a truncation where C is a constant: 443 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 444 /// 445 /// \p N needs to be a truncation and its first operand an AND. Other 446 /// requirements are checked by the function (e.g. that trunc is 447 /// single-use) and if missed an empty SDValue is returned. 448 SDValue distributeTruncateThroughAnd(SDNode *N); 449 450 public: 451 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 452 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 453 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 454 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 455 } 456 457 /// Runs the dag combiner on all nodes in the work list 458 void Run(CombineLevel AtLevel); 459 460 SelectionDAG &getDAG() const { return DAG; } 461 462 /// Returns a type large enough to hold any valid shift amount - before type 463 /// legalization these can be huge. 464 EVT getShiftAmountTy(EVT LHSTy) { 465 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 466 if (LHSTy.isVector()) 467 return LHSTy; 468 auto &DL = DAG.getDataLayout(); 469 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 470 : TLI.getPointerTy(DL); 471 } 472 473 /// This method returns true if we are running before type legalization or 474 /// if the specified VT is legal. 475 bool isTypeLegal(const EVT &VT) { 476 if (!LegalTypes) return true; 477 return TLI.isTypeLegal(VT); 478 } 479 480 /// Convenience wrapper around TargetLowering::getSetCCResultType 481 EVT getSetCCResultType(EVT VT) const { 482 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 483 } 484 }; 485 } 486 487 488 namespace { 489 /// This class is a DAGUpdateListener that removes any deleted 490 /// nodes from the worklist. 491 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 492 DAGCombiner &DC; 493 public: 494 explicit WorklistRemover(DAGCombiner &dc) 495 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 496 497 void NodeDeleted(SDNode *N, SDNode *E) override { 498 DC.removeFromWorklist(N); 499 } 500 }; 501 } 502 503 //===----------------------------------------------------------------------===// 504 // TargetLowering::DAGCombinerInfo implementation 505 //===----------------------------------------------------------------------===// 506 507 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 508 ((DAGCombiner*)DC)->AddToWorklist(N); 509 } 510 511 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 512 ((DAGCombiner*)DC)->removeFromWorklist(N); 513 } 514 515 SDValue TargetLowering::DAGCombinerInfo:: 516 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 517 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 518 } 519 520 SDValue TargetLowering::DAGCombinerInfo:: 521 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 522 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 523 } 524 525 526 SDValue TargetLowering::DAGCombinerInfo:: 527 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 528 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 529 } 530 531 void TargetLowering::DAGCombinerInfo:: 532 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 533 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 534 } 535 536 //===----------------------------------------------------------------------===// 537 // Helper Functions 538 //===----------------------------------------------------------------------===// 539 540 void DAGCombiner::deleteAndRecombine(SDNode *N) { 541 removeFromWorklist(N); 542 543 // If the operands of this node are only used by the node, they will now be 544 // dead. Make sure to re-visit them and recursively delete dead nodes. 545 for (const SDValue &Op : N->ops()) 546 // For an operand generating multiple values, one of the values may 547 // become dead allowing further simplification (e.g. split index 548 // arithmetic from an indexed load). 549 if (Op->hasOneUse() || Op->getNumValues() > 1) 550 AddToWorklist(Op.getNode()); 551 552 DAG.DeleteNode(N); 553 } 554 555 /// Return 1 if we can compute the negated form of the specified expression for 556 /// the same cost as the expression itself, or 2 if we can compute the negated 557 /// form more cheaply than the expression itself. 558 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 559 const TargetLowering &TLI, 560 const TargetOptions *Options, 561 unsigned Depth = 0) { 562 // fneg is removable even if it has multiple uses. 563 if (Op.getOpcode() == ISD::FNEG) return 2; 564 565 // Don't allow anything with multiple uses. 566 if (!Op.hasOneUse()) return 0; 567 568 // Don't recurse exponentially. 569 if (Depth > 6) return 0; 570 571 switch (Op.getOpcode()) { 572 default: return false; 573 case ISD::ConstantFP: 574 // Don't invert constant FP values after legalize. The negated constant 575 // isn't necessarily legal. 576 return LegalOperations ? 0 : 1; 577 case ISD::FADD: 578 // FIXME: determine better conditions for this xform. 579 if (!Options->UnsafeFPMath) return 0; 580 581 // After operation legalization, it might not be legal to create new FSUBs. 582 if (LegalOperations && 583 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 584 return 0; 585 586 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 587 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 588 Options, Depth + 1)) 589 return V; 590 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 591 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 592 Depth + 1); 593 case ISD::FSUB: 594 // We can't turn -(A-B) into B-A when we honor signed zeros. 595 if (!Options->UnsafeFPMath) return 0; 596 597 // fold (fneg (fsub A, B)) -> (fsub B, A) 598 return 1; 599 600 case ISD::FMUL: 601 case ISD::FDIV: 602 if (Options->HonorSignDependentRoundingFPMath()) return 0; 603 604 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 605 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 606 Options, Depth + 1)) 607 return V; 608 609 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 610 Depth + 1); 611 612 case ISD::FP_EXTEND: 613 case ISD::FP_ROUND: 614 case ISD::FSIN: 615 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 616 Depth + 1); 617 } 618 } 619 620 /// If isNegatibleForFree returns true, return the newly negated expression. 621 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 622 bool LegalOperations, unsigned Depth = 0) { 623 const TargetOptions &Options = DAG.getTarget().Options; 624 // fneg is removable even if it has multiple uses. 625 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 626 627 // Don't allow anything with multiple uses. 628 assert(Op.hasOneUse() && "Unknown reuse!"); 629 630 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 631 632 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 633 634 switch (Op.getOpcode()) { 635 default: llvm_unreachable("Unknown code"); 636 case ISD::ConstantFP: { 637 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 638 V.changeSign(); 639 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 640 } 641 case ISD::FADD: 642 // FIXME: determine better conditions for this xform. 643 assert(Options.UnsafeFPMath); 644 645 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 646 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 647 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 648 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 649 GetNegatedExpression(Op.getOperand(0), DAG, 650 LegalOperations, Depth+1), 651 Op.getOperand(1), Flags); 652 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 653 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 654 GetNegatedExpression(Op.getOperand(1), DAG, 655 LegalOperations, Depth+1), 656 Op.getOperand(0), Flags); 657 case ISD::FSUB: 658 // We can't turn -(A-B) into B-A when we honor signed zeros. 659 assert(Options.UnsafeFPMath); 660 661 // fold (fneg (fsub 0, B)) -> B 662 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 663 if (N0CFP->isZero()) 664 return Op.getOperand(1); 665 666 // fold (fneg (fsub A, B)) -> (fsub B, A) 667 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 668 Op.getOperand(1), Op.getOperand(0), Flags); 669 670 case ISD::FMUL: 671 case ISD::FDIV: 672 assert(!Options.HonorSignDependentRoundingFPMath()); 673 674 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 675 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 676 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 677 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 678 GetNegatedExpression(Op.getOperand(0), DAG, 679 LegalOperations, Depth+1), 680 Op.getOperand(1), Flags); 681 682 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 683 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 684 Op.getOperand(0), 685 GetNegatedExpression(Op.getOperand(1), DAG, 686 LegalOperations, Depth+1), Flags); 687 688 case ISD::FP_EXTEND: 689 case ISD::FSIN: 690 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 691 GetNegatedExpression(Op.getOperand(0), DAG, 692 LegalOperations, Depth+1)); 693 case ISD::FP_ROUND: 694 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 695 GetNegatedExpression(Op.getOperand(0), DAG, 696 LegalOperations, Depth+1), 697 Op.getOperand(1)); 698 } 699 } 700 701 // Return true if this node is a setcc, or is a select_cc 702 // that selects between the target values used for true and false, making it 703 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 704 // the appropriate nodes based on the type of node we are checking. This 705 // simplifies life a bit for the callers. 706 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 707 SDValue &CC) const { 708 if (N.getOpcode() == ISD::SETCC) { 709 LHS = N.getOperand(0); 710 RHS = N.getOperand(1); 711 CC = N.getOperand(2); 712 return true; 713 } 714 715 if (N.getOpcode() != ISD::SELECT_CC || 716 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 717 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 718 return false; 719 720 if (TLI.getBooleanContents(N.getValueType()) == 721 TargetLowering::UndefinedBooleanContent) 722 return false; 723 724 LHS = N.getOperand(0); 725 RHS = N.getOperand(1); 726 CC = N.getOperand(4); 727 return true; 728 } 729 730 /// Return true if this is a SetCC-equivalent operation with only one use. 731 /// If this is true, it allows the users to invert the operation for free when 732 /// it is profitable to do so. 733 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 734 SDValue N0, N1, N2; 735 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 736 return true; 737 return false; 738 } 739 740 /// Returns true if N is a BUILD_VECTOR node whose 741 /// elements are all the same constant or undefined. 742 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 743 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 744 if (!C) 745 return false; 746 747 APInt SplatUndef; 748 unsigned SplatBitSize; 749 bool HasAnyUndefs; 750 EVT EltVT = N->getValueType(0).getVectorElementType(); 751 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 752 HasAnyUndefs) && 753 EltVT.getSizeInBits() >= SplatBitSize); 754 } 755 756 // \brief Returns the SDNode if it is a constant integer BuildVector 757 // or constant integer. 758 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) { 759 if (isa<ConstantSDNode>(N)) 760 return N.getNode(); 761 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 762 return N.getNode(); 763 return nullptr; 764 } 765 766 // \brief Returns the SDNode if it is a constant float BuildVector 767 // or constant float. 768 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 769 if (isa<ConstantFPSDNode>(N)) 770 return N.getNode(); 771 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 772 return N.getNode(); 773 return nullptr; 774 } 775 776 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 777 // int. 778 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 779 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 780 return CN; 781 782 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 783 BitVector UndefElements; 784 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 785 786 // BuildVectors can truncate their operands. Ignore that case here. 787 // FIXME: We blindly ignore splats which include undef which is overly 788 // pessimistic. 789 if (CN && UndefElements.none() && 790 CN->getValueType(0) == N.getValueType().getScalarType()) 791 return CN; 792 } 793 794 return nullptr; 795 } 796 797 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 798 // float. 799 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 800 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 801 return CN; 802 803 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 804 BitVector UndefElements; 805 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 806 807 if (CN && UndefElements.none()) 808 return CN; 809 } 810 811 return nullptr; 812 } 813 814 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 815 SDValue N0, SDValue N1) { 816 EVT VT = N0.getValueType(); 817 if (N0.getOpcode() == Opc) { 818 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 819 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) { 820 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 821 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 822 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 823 return SDValue(); 824 } 825 if (N0.hasOneUse()) { 826 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 827 // use 828 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 829 if (!OpNode.getNode()) 830 return SDValue(); 831 AddToWorklist(OpNode.getNode()); 832 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 833 } 834 } 835 } 836 837 if (N1.getOpcode() == Opc) { 838 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 839 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) { 840 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 841 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 842 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 843 return SDValue(); 844 } 845 if (N1.hasOneUse()) { 846 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 847 // use 848 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 849 if (!OpNode.getNode()) 850 return SDValue(); 851 AddToWorklist(OpNode.getNode()); 852 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 853 } 854 } 855 } 856 857 return SDValue(); 858 } 859 860 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 861 bool AddTo) { 862 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 863 ++NodesCombined; 864 DEBUG(dbgs() << "\nReplacing.1 "; 865 N->dump(&DAG); 866 dbgs() << "\nWith: "; 867 To[0].getNode()->dump(&DAG); 868 dbgs() << " and " << NumTo-1 << " other values\n"); 869 for (unsigned i = 0, e = NumTo; i != e; ++i) 870 assert((!To[i].getNode() || 871 N->getValueType(i) == To[i].getValueType()) && 872 "Cannot combine value to value of different type!"); 873 874 WorklistRemover DeadNodes(*this); 875 DAG.ReplaceAllUsesWith(N, To); 876 if (AddTo) { 877 // Push the new nodes and any users onto the worklist 878 for (unsigned i = 0, e = NumTo; i != e; ++i) { 879 if (To[i].getNode()) { 880 AddToWorklist(To[i].getNode()); 881 AddUsersToWorklist(To[i].getNode()); 882 } 883 } 884 } 885 886 // Finally, if the node is now dead, remove it from the graph. The node 887 // may not be dead if the replacement process recursively simplified to 888 // something else needing this node. 889 if (N->use_empty()) 890 deleteAndRecombine(N); 891 return SDValue(N, 0); 892 } 893 894 void DAGCombiner:: 895 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 896 // Replace all uses. If any nodes become isomorphic to other nodes and 897 // are deleted, make sure to remove them from our worklist. 898 WorklistRemover DeadNodes(*this); 899 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 900 901 // Push the new node and any (possibly new) users onto the worklist. 902 AddToWorklist(TLO.New.getNode()); 903 AddUsersToWorklist(TLO.New.getNode()); 904 905 // Finally, if the node is now dead, remove it from the graph. The node 906 // may not be dead if the replacement process recursively simplified to 907 // something else needing this node. 908 if (TLO.Old.getNode()->use_empty()) 909 deleteAndRecombine(TLO.Old.getNode()); 910 } 911 912 /// Check the specified integer node value to see if it can be simplified or if 913 /// things it uses can be simplified by bit propagation. If so, return true. 914 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 915 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 916 APInt KnownZero, KnownOne; 917 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 918 return false; 919 920 // Revisit the node. 921 AddToWorklist(Op.getNode()); 922 923 // Replace the old value with the new one. 924 ++NodesCombined; 925 DEBUG(dbgs() << "\nReplacing.2 "; 926 TLO.Old.getNode()->dump(&DAG); 927 dbgs() << "\nWith: "; 928 TLO.New.getNode()->dump(&DAG); 929 dbgs() << '\n'); 930 931 CommitTargetLoweringOpt(TLO); 932 return true; 933 } 934 935 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 936 SDLoc dl(Load); 937 EVT VT = Load->getValueType(0); 938 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 939 940 DEBUG(dbgs() << "\nReplacing.9 "; 941 Load->dump(&DAG); 942 dbgs() << "\nWith: "; 943 Trunc.getNode()->dump(&DAG); 944 dbgs() << '\n'); 945 WorklistRemover DeadNodes(*this); 946 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 947 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 948 deleteAndRecombine(Load); 949 AddToWorklist(Trunc.getNode()); 950 } 951 952 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 953 Replace = false; 954 SDLoc dl(Op); 955 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 956 EVT MemVT = LD->getMemoryVT(); 957 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 958 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 959 : ISD::EXTLOAD) 960 : LD->getExtensionType(); 961 Replace = true; 962 return DAG.getExtLoad(ExtType, dl, PVT, 963 LD->getChain(), LD->getBasePtr(), 964 MemVT, LD->getMemOperand()); 965 } 966 967 unsigned Opc = Op.getOpcode(); 968 switch (Opc) { 969 default: break; 970 case ISD::AssertSext: 971 return DAG.getNode(ISD::AssertSext, dl, PVT, 972 SExtPromoteOperand(Op.getOperand(0), PVT), 973 Op.getOperand(1)); 974 case ISD::AssertZext: 975 return DAG.getNode(ISD::AssertZext, dl, PVT, 976 ZExtPromoteOperand(Op.getOperand(0), PVT), 977 Op.getOperand(1)); 978 case ISD::Constant: { 979 unsigned ExtOpc = 980 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 981 return DAG.getNode(ExtOpc, dl, PVT, Op); 982 } 983 } 984 985 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 986 return SDValue(); 987 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 988 } 989 990 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 991 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 992 return SDValue(); 993 EVT OldVT = Op.getValueType(); 994 SDLoc dl(Op); 995 bool Replace = false; 996 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 997 if (!NewOp.getNode()) 998 return SDValue(); 999 AddToWorklist(NewOp.getNode()); 1000 1001 if (Replace) 1002 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1003 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 1004 DAG.getValueType(OldVT)); 1005 } 1006 1007 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1008 EVT OldVT = Op.getValueType(); 1009 SDLoc dl(Op); 1010 bool Replace = false; 1011 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1012 if (!NewOp.getNode()) 1013 return SDValue(); 1014 AddToWorklist(NewOp.getNode()); 1015 1016 if (Replace) 1017 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1018 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1019 } 1020 1021 /// Promote the specified integer binary operation if the target indicates it is 1022 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1023 /// i32 since i16 instructions are longer. 1024 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1025 if (!LegalOperations) 1026 return SDValue(); 1027 1028 EVT VT = Op.getValueType(); 1029 if (VT.isVector() || !VT.isInteger()) 1030 return SDValue(); 1031 1032 // If operation type is 'undesirable', e.g. i16 on x86, consider 1033 // promoting it. 1034 unsigned Opc = Op.getOpcode(); 1035 if (TLI.isTypeDesirableForOp(Opc, VT)) 1036 return SDValue(); 1037 1038 EVT PVT = VT; 1039 // Consult target whether it is a good idea to promote this operation and 1040 // what's the right type to promote it to. 1041 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1042 assert(PVT != VT && "Don't know what type to promote to!"); 1043 1044 bool Replace0 = false; 1045 SDValue N0 = Op.getOperand(0); 1046 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1047 if (!NN0.getNode()) 1048 return SDValue(); 1049 1050 bool Replace1 = false; 1051 SDValue N1 = Op.getOperand(1); 1052 SDValue NN1; 1053 if (N0 == N1) 1054 NN1 = NN0; 1055 else { 1056 NN1 = PromoteOperand(N1, PVT, Replace1); 1057 if (!NN1.getNode()) 1058 return SDValue(); 1059 } 1060 1061 AddToWorklist(NN0.getNode()); 1062 if (NN1.getNode()) 1063 AddToWorklist(NN1.getNode()); 1064 1065 if (Replace0) 1066 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1067 if (Replace1) 1068 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1069 1070 DEBUG(dbgs() << "\nPromoting "; 1071 Op.getNode()->dump(&DAG)); 1072 SDLoc dl(Op); 1073 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1074 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1075 } 1076 return SDValue(); 1077 } 1078 1079 /// Promote the specified integer shift operation if the target indicates it is 1080 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1081 /// i32 since i16 instructions are longer. 1082 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1083 if (!LegalOperations) 1084 return SDValue(); 1085 1086 EVT VT = Op.getValueType(); 1087 if (VT.isVector() || !VT.isInteger()) 1088 return SDValue(); 1089 1090 // If operation type is 'undesirable', e.g. i16 on x86, consider 1091 // promoting it. 1092 unsigned Opc = Op.getOpcode(); 1093 if (TLI.isTypeDesirableForOp(Opc, VT)) 1094 return SDValue(); 1095 1096 EVT PVT = VT; 1097 // Consult target whether it is a good idea to promote this operation and 1098 // what's the right type to promote it to. 1099 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1100 assert(PVT != VT && "Don't know what type to promote to!"); 1101 1102 bool Replace = false; 1103 SDValue N0 = Op.getOperand(0); 1104 if (Opc == ISD::SRA) 1105 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1106 else if (Opc == ISD::SRL) 1107 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1108 else 1109 N0 = PromoteOperand(N0, PVT, Replace); 1110 if (!N0.getNode()) 1111 return SDValue(); 1112 1113 AddToWorklist(N0.getNode()); 1114 if (Replace) 1115 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1116 1117 DEBUG(dbgs() << "\nPromoting "; 1118 Op.getNode()->dump(&DAG)); 1119 SDLoc dl(Op); 1120 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1121 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1122 } 1123 return SDValue(); 1124 } 1125 1126 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1127 if (!LegalOperations) 1128 return SDValue(); 1129 1130 EVT VT = Op.getValueType(); 1131 if (VT.isVector() || !VT.isInteger()) 1132 return SDValue(); 1133 1134 // If operation type is 'undesirable', e.g. i16 on x86, consider 1135 // promoting it. 1136 unsigned Opc = Op.getOpcode(); 1137 if (TLI.isTypeDesirableForOp(Opc, VT)) 1138 return SDValue(); 1139 1140 EVT PVT = VT; 1141 // Consult target whether it is a good idea to promote this operation and 1142 // what's the right type to promote it to. 1143 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1144 assert(PVT != VT && "Don't know what type to promote to!"); 1145 // fold (aext (aext x)) -> (aext x) 1146 // fold (aext (zext x)) -> (zext x) 1147 // fold (aext (sext x)) -> (sext x) 1148 DEBUG(dbgs() << "\nPromoting "; 1149 Op.getNode()->dump(&DAG)); 1150 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1151 } 1152 return SDValue(); 1153 } 1154 1155 bool DAGCombiner::PromoteLoad(SDValue Op) { 1156 if (!LegalOperations) 1157 return false; 1158 1159 EVT VT = Op.getValueType(); 1160 if (VT.isVector() || !VT.isInteger()) 1161 return false; 1162 1163 // If operation type is 'undesirable', e.g. i16 on x86, consider 1164 // promoting it. 1165 unsigned Opc = Op.getOpcode(); 1166 if (TLI.isTypeDesirableForOp(Opc, VT)) 1167 return false; 1168 1169 EVT PVT = VT; 1170 // Consult target whether it is a good idea to promote this operation and 1171 // what's the right type to promote it to. 1172 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1173 assert(PVT != VT && "Don't know what type to promote to!"); 1174 1175 SDLoc dl(Op); 1176 SDNode *N = Op.getNode(); 1177 LoadSDNode *LD = cast<LoadSDNode>(N); 1178 EVT MemVT = LD->getMemoryVT(); 1179 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1180 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1181 : ISD::EXTLOAD) 1182 : LD->getExtensionType(); 1183 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1184 LD->getChain(), LD->getBasePtr(), 1185 MemVT, LD->getMemOperand()); 1186 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1187 1188 DEBUG(dbgs() << "\nPromoting "; 1189 N->dump(&DAG); 1190 dbgs() << "\nTo: "; 1191 Result.getNode()->dump(&DAG); 1192 dbgs() << '\n'); 1193 WorklistRemover DeadNodes(*this); 1194 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1195 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1196 deleteAndRecombine(N); 1197 AddToWorklist(Result.getNode()); 1198 return true; 1199 } 1200 return false; 1201 } 1202 1203 /// \brief Recursively delete a node which has no uses and any operands for 1204 /// which it is the only use. 1205 /// 1206 /// Note that this both deletes the nodes and removes them from the worklist. 1207 /// It also adds any nodes who have had a user deleted to the worklist as they 1208 /// may now have only one use and subject to other combines. 1209 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1210 if (!N->use_empty()) 1211 return false; 1212 1213 SmallSetVector<SDNode *, 16> Nodes; 1214 Nodes.insert(N); 1215 do { 1216 N = Nodes.pop_back_val(); 1217 if (!N) 1218 continue; 1219 1220 if (N->use_empty()) { 1221 for (const SDValue &ChildN : N->op_values()) 1222 Nodes.insert(ChildN.getNode()); 1223 1224 removeFromWorklist(N); 1225 DAG.DeleteNode(N); 1226 } else { 1227 AddToWorklist(N); 1228 } 1229 } while (!Nodes.empty()); 1230 return true; 1231 } 1232 1233 //===----------------------------------------------------------------------===// 1234 // Main DAG Combiner implementation 1235 //===----------------------------------------------------------------------===// 1236 1237 void DAGCombiner::Run(CombineLevel AtLevel) { 1238 // set the instance variables, so that the various visit routines may use it. 1239 Level = AtLevel; 1240 LegalOperations = Level >= AfterLegalizeVectorOps; 1241 LegalTypes = Level >= AfterLegalizeTypes; 1242 1243 // Add all the dag nodes to the worklist. 1244 for (SDNode &Node : DAG.allnodes()) 1245 AddToWorklist(&Node); 1246 1247 // Create a dummy node (which is not added to allnodes), that adds a reference 1248 // to the root node, preventing it from being deleted, and tracking any 1249 // changes of the root. 1250 HandleSDNode Dummy(DAG.getRoot()); 1251 1252 // while the worklist isn't empty, find a node and 1253 // try and combine it. 1254 while (!WorklistMap.empty()) { 1255 SDNode *N; 1256 // The Worklist holds the SDNodes in order, but it may contain null entries. 1257 do { 1258 N = Worklist.pop_back_val(); 1259 } while (!N); 1260 1261 bool GoodWorklistEntry = WorklistMap.erase(N); 1262 (void)GoodWorklistEntry; 1263 assert(GoodWorklistEntry && 1264 "Found a worklist entry without a corresponding map entry!"); 1265 1266 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1267 // N is deleted from the DAG, since they too may now be dead or may have a 1268 // reduced number of uses, allowing other xforms. 1269 if (recursivelyDeleteUnusedNodes(N)) 1270 continue; 1271 1272 WorklistRemover DeadNodes(*this); 1273 1274 // If this combine is running after legalizing the DAG, re-legalize any 1275 // nodes pulled off the worklist. 1276 if (Level == AfterLegalizeDAG) { 1277 SmallSetVector<SDNode *, 16> UpdatedNodes; 1278 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1279 1280 for (SDNode *LN : UpdatedNodes) { 1281 AddToWorklist(LN); 1282 AddUsersToWorklist(LN); 1283 } 1284 if (!NIsValid) 1285 continue; 1286 } 1287 1288 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1289 1290 // Add any operands of the new node which have not yet been combined to the 1291 // worklist as well. Because the worklist uniques things already, this 1292 // won't repeatedly process the same operand. 1293 CombinedNodes.insert(N); 1294 for (const SDValue &ChildN : N->op_values()) 1295 if (!CombinedNodes.count(ChildN.getNode())) 1296 AddToWorklist(ChildN.getNode()); 1297 1298 SDValue RV = combine(N); 1299 1300 if (!RV.getNode()) 1301 continue; 1302 1303 ++NodesCombined; 1304 1305 // If we get back the same node we passed in, rather than a new node or 1306 // zero, we know that the node must have defined multiple values and 1307 // CombineTo was used. Since CombineTo takes care of the worklist 1308 // mechanics for us, we have no work to do in this case. 1309 if (RV.getNode() == N) 1310 continue; 1311 1312 assert(N->getOpcode() != ISD::DELETED_NODE && 1313 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1314 "Node was deleted but visit returned new node!"); 1315 1316 DEBUG(dbgs() << " ... into: "; 1317 RV.getNode()->dump(&DAG)); 1318 1319 // Transfer debug value. 1320 DAG.TransferDbgValues(SDValue(N, 0), RV); 1321 if (N->getNumValues() == RV.getNode()->getNumValues()) 1322 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1323 else { 1324 assert(N->getValueType(0) == RV.getValueType() && 1325 N->getNumValues() == 1 && "Type mismatch"); 1326 SDValue OpV = RV; 1327 DAG.ReplaceAllUsesWith(N, &OpV); 1328 } 1329 1330 // Push the new node and any users onto the worklist 1331 AddToWorklist(RV.getNode()); 1332 AddUsersToWorklist(RV.getNode()); 1333 1334 // Finally, if the node is now dead, remove it from the graph. The node 1335 // may not be dead if the replacement process recursively simplified to 1336 // something else needing this node. This will also take care of adding any 1337 // operands which have lost a user to the worklist. 1338 recursivelyDeleteUnusedNodes(N); 1339 } 1340 1341 // If the root changed (e.g. it was a dead load, update the root). 1342 DAG.setRoot(Dummy.getValue()); 1343 DAG.RemoveDeadNodes(); 1344 } 1345 1346 SDValue DAGCombiner::visit(SDNode *N) { 1347 switch (N->getOpcode()) { 1348 default: break; 1349 case ISD::TokenFactor: return visitTokenFactor(N); 1350 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1351 case ISD::ADD: return visitADD(N); 1352 case ISD::SUB: return visitSUB(N); 1353 case ISD::ADDC: return visitADDC(N); 1354 case ISD::SUBC: return visitSUBC(N); 1355 case ISD::ADDE: return visitADDE(N); 1356 case ISD::SUBE: return visitSUBE(N); 1357 case ISD::MUL: return visitMUL(N); 1358 case ISD::SDIV: return visitSDIV(N); 1359 case ISD::UDIV: return visitUDIV(N); 1360 case ISD::SREM: 1361 case ISD::UREM: return visitREM(N); 1362 case ISD::MULHU: return visitMULHU(N); 1363 case ISD::MULHS: return visitMULHS(N); 1364 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1365 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1366 case ISD::SMULO: return visitSMULO(N); 1367 case ISD::UMULO: return visitUMULO(N); 1368 case ISD::SMIN: 1369 case ISD::SMAX: 1370 case ISD::UMIN: 1371 case ISD::UMAX: return visitIMINMAX(N); 1372 case ISD::AND: return visitAND(N); 1373 case ISD::OR: return visitOR(N); 1374 case ISD::XOR: return visitXOR(N); 1375 case ISD::SHL: return visitSHL(N); 1376 case ISD::SRA: return visitSRA(N); 1377 case ISD::SRL: return visitSRL(N); 1378 case ISD::ROTR: 1379 case ISD::ROTL: return visitRotate(N); 1380 case ISD::BSWAP: return visitBSWAP(N); 1381 case ISD::CTLZ: return visitCTLZ(N); 1382 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1383 case ISD::CTTZ: return visitCTTZ(N); 1384 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1385 case ISD::CTPOP: return visitCTPOP(N); 1386 case ISD::SELECT: return visitSELECT(N); 1387 case ISD::VSELECT: return visitVSELECT(N); 1388 case ISD::SELECT_CC: return visitSELECT_CC(N); 1389 case ISD::SETCC: return visitSETCC(N); 1390 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1391 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1392 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1393 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1394 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1395 case ISD::TRUNCATE: return visitTRUNCATE(N); 1396 case ISD::BITCAST: return visitBITCAST(N); 1397 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1398 case ISD::FADD: return visitFADD(N); 1399 case ISD::FSUB: return visitFSUB(N); 1400 case ISD::FMUL: return visitFMUL(N); 1401 case ISD::FMA: return visitFMA(N); 1402 case ISD::FDIV: return visitFDIV(N); 1403 case ISD::FREM: return visitFREM(N); 1404 case ISD::FSQRT: return visitFSQRT(N); 1405 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1406 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1407 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1408 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1409 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1410 case ISD::FP_ROUND: return visitFP_ROUND(N); 1411 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1412 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1413 case ISD::FNEG: return visitFNEG(N); 1414 case ISD::FABS: return visitFABS(N); 1415 case ISD::FFLOOR: return visitFFLOOR(N); 1416 case ISD::FMINNUM: return visitFMINNUM(N); 1417 case ISD::FMAXNUM: return visitFMAXNUM(N); 1418 case ISD::FCEIL: return visitFCEIL(N); 1419 case ISD::FTRUNC: return visitFTRUNC(N); 1420 case ISD::BRCOND: return visitBRCOND(N); 1421 case ISD::BR_CC: return visitBR_CC(N); 1422 case ISD::LOAD: return visitLOAD(N); 1423 case ISD::STORE: return visitSTORE(N); 1424 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1425 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1426 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1427 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1428 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1429 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1430 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1431 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1432 case ISD::MGATHER: return visitMGATHER(N); 1433 case ISD::MLOAD: return visitMLOAD(N); 1434 case ISD::MSCATTER: return visitMSCATTER(N); 1435 case ISD::MSTORE: return visitMSTORE(N); 1436 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1437 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1438 } 1439 return SDValue(); 1440 } 1441 1442 SDValue DAGCombiner::combine(SDNode *N) { 1443 SDValue RV = visit(N); 1444 1445 // If nothing happened, try a target-specific DAG combine. 1446 if (!RV.getNode()) { 1447 assert(N->getOpcode() != ISD::DELETED_NODE && 1448 "Node was deleted but visit returned NULL!"); 1449 1450 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1451 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1452 1453 // Expose the DAG combiner to the target combiner impls. 1454 TargetLowering::DAGCombinerInfo 1455 DagCombineInfo(DAG, Level, false, this); 1456 1457 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1458 } 1459 } 1460 1461 // If nothing happened still, try promoting the operation. 1462 if (!RV.getNode()) { 1463 switch (N->getOpcode()) { 1464 default: break; 1465 case ISD::ADD: 1466 case ISD::SUB: 1467 case ISD::MUL: 1468 case ISD::AND: 1469 case ISD::OR: 1470 case ISD::XOR: 1471 RV = PromoteIntBinOp(SDValue(N, 0)); 1472 break; 1473 case ISD::SHL: 1474 case ISD::SRA: 1475 case ISD::SRL: 1476 RV = PromoteIntShiftOp(SDValue(N, 0)); 1477 break; 1478 case ISD::SIGN_EXTEND: 1479 case ISD::ZERO_EXTEND: 1480 case ISD::ANY_EXTEND: 1481 RV = PromoteExtend(SDValue(N, 0)); 1482 break; 1483 case ISD::LOAD: 1484 if (PromoteLoad(SDValue(N, 0))) 1485 RV = SDValue(N, 0); 1486 break; 1487 } 1488 } 1489 1490 // If N is a commutative binary node, try commuting it to enable more 1491 // sdisel CSE. 1492 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1493 N->getNumValues() == 1) { 1494 SDValue N0 = N->getOperand(0); 1495 SDValue N1 = N->getOperand(1); 1496 1497 // Constant operands are canonicalized to RHS. 1498 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1499 SDValue Ops[] = {N1, N0}; 1500 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1501 N->getFlags()); 1502 if (CSENode) 1503 return SDValue(CSENode, 0); 1504 } 1505 } 1506 1507 return RV; 1508 } 1509 1510 /// Given a node, return its input chain if it has one, otherwise return a null 1511 /// sd operand. 1512 static SDValue getInputChainForNode(SDNode *N) { 1513 if (unsigned NumOps = N->getNumOperands()) { 1514 if (N->getOperand(0).getValueType() == MVT::Other) 1515 return N->getOperand(0); 1516 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1517 return N->getOperand(NumOps-1); 1518 for (unsigned i = 1; i < NumOps-1; ++i) 1519 if (N->getOperand(i).getValueType() == MVT::Other) 1520 return N->getOperand(i); 1521 } 1522 return SDValue(); 1523 } 1524 1525 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1526 // If N has two operands, where one has an input chain equal to the other, 1527 // the 'other' chain is redundant. 1528 if (N->getNumOperands() == 2) { 1529 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1530 return N->getOperand(0); 1531 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1532 return N->getOperand(1); 1533 } 1534 1535 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1536 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1537 SmallPtrSet<SDNode*, 16> SeenOps; 1538 bool Changed = false; // If we should replace this token factor. 1539 1540 // Start out with this token factor. 1541 TFs.push_back(N); 1542 1543 // Iterate through token factors. The TFs grows when new token factors are 1544 // encountered. 1545 for (unsigned i = 0; i < TFs.size(); ++i) { 1546 SDNode *TF = TFs[i]; 1547 1548 // Check each of the operands. 1549 for (const SDValue &Op : TF->op_values()) { 1550 1551 switch (Op.getOpcode()) { 1552 case ISD::EntryToken: 1553 // Entry tokens don't need to be added to the list. They are 1554 // redundant. 1555 Changed = true; 1556 break; 1557 1558 case ISD::TokenFactor: 1559 if (Op.hasOneUse() && 1560 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1561 // Queue up for processing. 1562 TFs.push_back(Op.getNode()); 1563 // Clean up in case the token factor is removed. 1564 AddToWorklist(Op.getNode()); 1565 Changed = true; 1566 break; 1567 } 1568 // Fall thru 1569 1570 default: 1571 // Only add if it isn't already in the list. 1572 if (SeenOps.insert(Op.getNode()).second) 1573 Ops.push_back(Op); 1574 else 1575 Changed = true; 1576 break; 1577 } 1578 } 1579 } 1580 1581 SDValue Result; 1582 1583 // If we've changed things around then replace token factor. 1584 if (Changed) { 1585 if (Ops.empty()) { 1586 // The entry token is the only possible outcome. 1587 Result = DAG.getEntryNode(); 1588 } else { 1589 // New and improved token factor. 1590 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1591 } 1592 1593 // Add users to worklist if AA is enabled, since it may introduce 1594 // a lot of new chained token factors while removing memory deps. 1595 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1596 : DAG.getSubtarget().useAA(); 1597 return CombineTo(N, Result, UseAA /*add to worklist*/); 1598 } 1599 1600 return Result; 1601 } 1602 1603 /// MERGE_VALUES can always be eliminated. 1604 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1605 WorklistRemover DeadNodes(*this); 1606 // Replacing results may cause a different MERGE_VALUES to suddenly 1607 // be CSE'd with N, and carry its uses with it. Iterate until no 1608 // uses remain, to ensure that the node can be safely deleted. 1609 // First add the users of this node to the work list so that they 1610 // can be tried again once they have new operands. 1611 AddUsersToWorklist(N); 1612 do { 1613 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1614 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1615 } while (!N->use_empty()); 1616 deleteAndRecombine(N); 1617 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1618 } 1619 1620 static bool isNullConstant(SDValue V) { 1621 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1622 return Const != nullptr && Const->isNullValue(); 1623 } 1624 1625 static bool isNullFPConstant(SDValue V) { 1626 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 1627 return Const != nullptr && Const->isZero() && !Const->isNegative(); 1628 } 1629 1630 static bool isAllOnesConstant(SDValue V) { 1631 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1632 return Const != nullptr && Const->isAllOnesValue(); 1633 } 1634 1635 static bool isOneConstant(SDValue V) { 1636 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1637 return Const != nullptr && Const->isOne(); 1638 } 1639 1640 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a 1641 /// ContantSDNode pointer else nullptr. 1642 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1643 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1644 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1645 } 1646 1647 SDValue DAGCombiner::visitADD(SDNode *N) { 1648 SDValue N0 = N->getOperand(0); 1649 SDValue N1 = N->getOperand(1); 1650 EVT VT = N0.getValueType(); 1651 1652 // fold vector ops 1653 if (VT.isVector()) { 1654 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1655 return FoldedVOp; 1656 1657 // fold (add x, 0) -> x, vector edition 1658 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1659 return N0; 1660 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1661 return N1; 1662 } 1663 1664 // fold (add x, undef) -> undef 1665 if (N0.getOpcode() == ISD::UNDEF) 1666 return N0; 1667 if (N1.getOpcode() == ISD::UNDEF) 1668 return N1; 1669 // fold (add c1, c2) -> c1+c2 1670 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1671 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1672 if (N0C && N1C) 1673 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C); 1674 // canonicalize constant to RHS 1675 if (isConstantIntBuildVectorOrConstantInt(N0) && 1676 !isConstantIntBuildVectorOrConstantInt(N1)) 1677 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1678 // fold (add x, 0) -> x 1679 if (isNullConstant(N1)) 1680 return N0; 1681 // fold (add Sym, c) -> Sym+c 1682 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1683 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1684 GA->getOpcode() == ISD::GlobalAddress) 1685 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1686 GA->getOffset() + 1687 (uint64_t)N1C->getSExtValue()); 1688 // fold ((c1-A)+c2) -> (c1+c2)-A 1689 if (N1C && N0.getOpcode() == ISD::SUB) 1690 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1691 SDLoc DL(N); 1692 return DAG.getNode(ISD::SUB, DL, VT, 1693 DAG.getConstant(N1C->getAPIntValue()+ 1694 N0C->getAPIntValue(), DL, VT), 1695 N0.getOperand(1)); 1696 } 1697 // reassociate add 1698 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1699 return RADD; 1700 // fold ((0-A) + B) -> B-A 1701 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1702 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1703 // fold (A + (0-B)) -> A-B 1704 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1705 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1706 // fold (A+(B-A)) -> B 1707 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1708 return N1.getOperand(0); 1709 // fold ((B-A)+A) -> B 1710 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1711 return N0.getOperand(0); 1712 // fold (A+(B-(A+C))) to (B-C) 1713 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1714 N0 == N1.getOperand(1).getOperand(0)) 1715 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1716 N1.getOperand(1).getOperand(1)); 1717 // fold (A+(B-(C+A))) to (B-C) 1718 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1719 N0 == N1.getOperand(1).getOperand(1)) 1720 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1721 N1.getOperand(1).getOperand(0)); 1722 // fold (A+((B-A)+or-C)) to (B+or-C) 1723 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1724 N1.getOperand(0).getOpcode() == ISD::SUB && 1725 N0 == N1.getOperand(0).getOperand(1)) 1726 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1727 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1728 1729 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1730 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1731 SDValue N00 = N0.getOperand(0); 1732 SDValue N01 = N0.getOperand(1); 1733 SDValue N10 = N1.getOperand(0); 1734 SDValue N11 = N1.getOperand(1); 1735 1736 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1737 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1738 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1739 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1740 } 1741 1742 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1743 return SDValue(N, 0); 1744 1745 // fold (a+b) -> (a|b) iff a and b share no bits. 1746 if (VT.isInteger() && !VT.isVector()) { 1747 APInt LHSZero, LHSOne; 1748 APInt RHSZero, RHSOne; 1749 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1750 1751 if (LHSZero.getBoolValue()) { 1752 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1753 1754 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1755 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1756 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1757 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1758 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1759 } 1760 } 1761 } 1762 1763 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1764 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1765 isNullConstant(N1.getOperand(0).getOperand(0))) 1766 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1767 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1768 N1.getOperand(0).getOperand(1), 1769 N1.getOperand(1))); 1770 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1771 isNullConstant(N0.getOperand(0).getOperand(0))) 1772 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1773 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1774 N0.getOperand(0).getOperand(1), 1775 N0.getOperand(1))); 1776 1777 if (N1.getOpcode() == ISD::AND) { 1778 SDValue AndOp0 = N1.getOperand(0); 1779 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1780 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1781 1782 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1783 // and similar xforms where the inner op is either ~0 or 0. 1784 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1785 SDLoc DL(N); 1786 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1787 } 1788 } 1789 1790 // add (sext i1), X -> sub X, (zext i1) 1791 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1792 N0.getOperand(0).getValueType() == MVT::i1 && 1793 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1794 SDLoc DL(N); 1795 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1796 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1797 } 1798 1799 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1800 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1801 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1802 if (TN->getVT() == MVT::i1) { 1803 SDLoc DL(N); 1804 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1805 DAG.getConstant(1, DL, VT)); 1806 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1807 } 1808 } 1809 1810 return SDValue(); 1811 } 1812 1813 SDValue DAGCombiner::visitADDC(SDNode *N) { 1814 SDValue N0 = N->getOperand(0); 1815 SDValue N1 = N->getOperand(1); 1816 EVT VT = N0.getValueType(); 1817 1818 // If the flag result is dead, turn this into an ADD. 1819 if (!N->hasAnyUseOfValue(1)) 1820 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1821 DAG.getNode(ISD::CARRY_FALSE, 1822 SDLoc(N), MVT::Glue)); 1823 1824 // canonicalize constant to RHS. 1825 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1826 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1827 if (N0C && !N1C) 1828 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1829 1830 // fold (addc x, 0) -> x + no carry out 1831 if (isNullConstant(N1)) 1832 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1833 SDLoc(N), MVT::Glue)); 1834 1835 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1836 APInt LHSZero, LHSOne; 1837 APInt RHSZero, RHSOne; 1838 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1839 1840 if (LHSZero.getBoolValue()) { 1841 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1842 1843 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1844 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1845 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1846 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1847 DAG.getNode(ISD::CARRY_FALSE, 1848 SDLoc(N), MVT::Glue)); 1849 } 1850 1851 return SDValue(); 1852 } 1853 1854 SDValue DAGCombiner::visitADDE(SDNode *N) { 1855 SDValue N0 = N->getOperand(0); 1856 SDValue N1 = N->getOperand(1); 1857 SDValue CarryIn = N->getOperand(2); 1858 1859 // canonicalize constant to RHS 1860 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1861 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1862 if (N0C && !N1C) 1863 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1864 N1, N0, CarryIn); 1865 1866 // fold (adde x, y, false) -> (addc x, y) 1867 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1868 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1869 1870 return SDValue(); 1871 } 1872 1873 // Since it may not be valid to emit a fold to zero for vector initializers 1874 // check if we can before folding. 1875 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1876 SelectionDAG &DAG, 1877 bool LegalOperations, bool LegalTypes) { 1878 if (!VT.isVector()) 1879 return DAG.getConstant(0, DL, VT); 1880 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1881 return DAG.getConstant(0, DL, VT); 1882 return SDValue(); 1883 } 1884 1885 SDValue DAGCombiner::visitSUB(SDNode *N) { 1886 SDValue N0 = N->getOperand(0); 1887 SDValue N1 = N->getOperand(1); 1888 EVT VT = N0.getValueType(); 1889 1890 // fold vector ops 1891 if (VT.isVector()) { 1892 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1893 return FoldedVOp; 1894 1895 // fold (sub x, 0) -> x, vector edition 1896 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1897 return N0; 1898 } 1899 1900 // fold (sub x, x) -> 0 1901 // FIXME: Refactor this and xor and other similar operations together. 1902 if (N0 == N1) 1903 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1904 // fold (sub c1, c2) -> c1-c2 1905 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1906 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1907 if (N0C && N1C) 1908 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C); 1909 // fold (sub x, c) -> (add x, -c) 1910 if (N1C) { 1911 SDLoc DL(N); 1912 return DAG.getNode(ISD::ADD, DL, VT, N0, 1913 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1914 } 1915 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1916 if (isAllOnesConstant(N0)) 1917 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1918 // fold A-(A-B) -> B 1919 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1920 return N1.getOperand(1); 1921 // fold (A+B)-A -> B 1922 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1923 return N0.getOperand(1); 1924 // fold (A+B)-B -> A 1925 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1926 return N0.getOperand(0); 1927 // fold C2-(A+C1) -> (C2-C1)-A 1928 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1929 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1930 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1931 SDLoc DL(N); 1932 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1933 DL, VT); 1934 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1935 N1.getOperand(0)); 1936 } 1937 // fold ((A+(B+or-C))-B) -> A+or-C 1938 if (N0.getOpcode() == ISD::ADD && 1939 (N0.getOperand(1).getOpcode() == ISD::SUB || 1940 N0.getOperand(1).getOpcode() == ISD::ADD) && 1941 N0.getOperand(1).getOperand(0) == N1) 1942 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1943 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1944 // fold ((A+(C+B))-B) -> A+C 1945 if (N0.getOpcode() == ISD::ADD && 1946 N0.getOperand(1).getOpcode() == ISD::ADD && 1947 N0.getOperand(1).getOperand(1) == N1) 1948 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1949 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1950 // fold ((A-(B-C))-C) -> A-B 1951 if (N0.getOpcode() == ISD::SUB && 1952 N0.getOperand(1).getOpcode() == ISD::SUB && 1953 N0.getOperand(1).getOperand(1) == N1) 1954 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1955 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1956 1957 // If either operand of a sub is undef, the result is undef 1958 if (N0.getOpcode() == ISD::UNDEF) 1959 return N0; 1960 if (N1.getOpcode() == ISD::UNDEF) 1961 return N1; 1962 1963 // If the relocation model supports it, consider symbol offsets. 1964 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1965 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1966 // fold (sub Sym, c) -> Sym-c 1967 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1968 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1969 GA->getOffset() - 1970 (uint64_t)N1C->getSExtValue()); 1971 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1972 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1973 if (GA->getGlobal() == GB->getGlobal()) 1974 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1975 SDLoc(N), VT); 1976 } 1977 1978 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1979 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1980 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1981 if (TN->getVT() == MVT::i1) { 1982 SDLoc DL(N); 1983 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1984 DAG.getConstant(1, DL, VT)); 1985 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1986 } 1987 } 1988 1989 return SDValue(); 1990 } 1991 1992 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1993 SDValue N0 = N->getOperand(0); 1994 SDValue N1 = N->getOperand(1); 1995 EVT VT = N0.getValueType(); 1996 SDLoc DL(N); 1997 1998 // If the flag result is dead, turn this into an SUB. 1999 if (!N->hasAnyUseOfValue(1)) 2000 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 2001 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2002 2003 // fold (subc x, x) -> 0 + no borrow 2004 if (N0 == N1) 2005 return CombineTo(N, DAG.getConstant(0, DL, VT), 2006 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2007 2008 // fold (subc x, 0) -> x + no borrow 2009 if (isNullConstant(N1)) 2010 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2011 2012 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 2013 if (isAllOnesConstant(N0)) 2014 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 2015 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2016 2017 return SDValue(); 2018 } 2019 2020 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2021 SDValue N0 = N->getOperand(0); 2022 SDValue N1 = N->getOperand(1); 2023 SDValue CarryIn = N->getOperand(2); 2024 2025 // fold (sube x, y, false) -> (subc x, y) 2026 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2027 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2028 2029 return SDValue(); 2030 } 2031 2032 SDValue DAGCombiner::visitMUL(SDNode *N) { 2033 SDValue N0 = N->getOperand(0); 2034 SDValue N1 = N->getOperand(1); 2035 EVT VT = N0.getValueType(); 2036 2037 // fold (mul x, undef) -> 0 2038 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2039 return DAG.getConstant(0, SDLoc(N), VT); 2040 2041 bool N0IsConst = false; 2042 bool N1IsConst = false; 2043 bool N1IsOpaqueConst = false; 2044 bool N0IsOpaqueConst = false; 2045 APInt ConstValue0, ConstValue1; 2046 // fold vector ops 2047 if (VT.isVector()) { 2048 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2049 return FoldedVOp; 2050 2051 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2052 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2053 } else { 2054 N0IsConst = isa<ConstantSDNode>(N0); 2055 if (N0IsConst) { 2056 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2057 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2058 } 2059 N1IsConst = isa<ConstantSDNode>(N1); 2060 if (N1IsConst) { 2061 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2062 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2063 } 2064 } 2065 2066 // fold (mul c1, c2) -> c1*c2 2067 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2068 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2069 N0.getNode(), N1.getNode()); 2070 2071 // canonicalize constant to RHS (vector doesn't have to splat) 2072 if (isConstantIntBuildVectorOrConstantInt(N0) && 2073 !isConstantIntBuildVectorOrConstantInt(N1)) 2074 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2075 // fold (mul x, 0) -> 0 2076 if (N1IsConst && ConstValue1 == 0) 2077 return N1; 2078 // We require a splat of the entire scalar bit width for non-contiguous 2079 // bit patterns. 2080 bool IsFullSplat = 2081 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2082 // fold (mul x, 1) -> x 2083 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2084 return N0; 2085 // fold (mul x, -1) -> 0-x 2086 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2087 SDLoc DL(N); 2088 return DAG.getNode(ISD::SUB, DL, VT, 2089 DAG.getConstant(0, DL, VT), N0); 2090 } 2091 // fold (mul x, (1 << c)) -> x << c 2092 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2093 IsFullSplat) { 2094 SDLoc DL(N); 2095 return DAG.getNode(ISD::SHL, DL, VT, N0, 2096 DAG.getConstant(ConstValue1.logBase2(), DL, 2097 getShiftAmountTy(N0.getValueType()))); 2098 } 2099 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2100 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2101 IsFullSplat) { 2102 unsigned Log2Val = (-ConstValue1).logBase2(); 2103 SDLoc DL(N); 2104 // FIXME: If the input is something that is easily negated (e.g. a 2105 // single-use add), we should put the negate there. 2106 return DAG.getNode(ISD::SUB, DL, VT, 2107 DAG.getConstant(0, DL, VT), 2108 DAG.getNode(ISD::SHL, DL, VT, N0, 2109 DAG.getConstant(Log2Val, DL, 2110 getShiftAmountTy(N0.getValueType())))); 2111 } 2112 2113 APInt Val; 2114 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2115 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2116 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2117 isa<ConstantSDNode>(N0.getOperand(1)))) { 2118 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2119 N1, N0.getOperand(1)); 2120 AddToWorklist(C3.getNode()); 2121 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2122 N0.getOperand(0), C3); 2123 } 2124 2125 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2126 // use. 2127 { 2128 SDValue Sh(nullptr,0), Y(nullptr,0); 2129 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2130 if (N0.getOpcode() == ISD::SHL && 2131 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2132 isa<ConstantSDNode>(N0.getOperand(1))) && 2133 N0.getNode()->hasOneUse()) { 2134 Sh = N0; Y = N1; 2135 } else if (N1.getOpcode() == ISD::SHL && 2136 isa<ConstantSDNode>(N1.getOperand(1)) && 2137 N1.getNode()->hasOneUse()) { 2138 Sh = N1; Y = N0; 2139 } 2140 2141 if (Sh.getNode()) { 2142 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2143 Sh.getOperand(0), Y); 2144 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2145 Mul, Sh.getOperand(1)); 2146 } 2147 } 2148 2149 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2150 if (isConstantIntBuildVectorOrConstantInt(N1) && 2151 N0.getOpcode() == ISD::ADD && 2152 isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2153 isMulAddWithConstProfitable(N, N0, N1)) 2154 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2155 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2156 N0.getOperand(0), N1), 2157 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2158 N0.getOperand(1), N1)); 2159 2160 // reassociate mul 2161 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2162 return RMUL; 2163 2164 return SDValue(); 2165 } 2166 2167 /// Return true if divmod libcall is available. 2168 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2169 const TargetLowering &TLI) { 2170 RTLIB::Libcall LC; 2171 switch (Node->getSimpleValueType(0).SimpleTy) { 2172 default: return false; // No libcall for vector types. 2173 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2174 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2175 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2176 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2177 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2178 } 2179 2180 return TLI.getLibcallName(LC) != nullptr; 2181 } 2182 2183 /// Issue divrem if both quotient and remainder are needed. 2184 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2185 if (Node->use_empty()) 2186 return SDValue(); // This is a dead node, leave it alone. 2187 2188 EVT VT = Node->getValueType(0); 2189 if (!TLI.isTypeLegal(VT)) 2190 return SDValue(); 2191 2192 unsigned Opcode = Node->getOpcode(); 2193 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2194 2195 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2196 // If DIVREM is going to get expanded into a libcall, 2197 // but there is no libcall available, then don't combine. 2198 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2199 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2200 return SDValue(); 2201 2202 // If div is legal, it's better to do the normal expansion 2203 unsigned OtherOpcode = 0; 2204 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2205 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2206 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2207 return SDValue(); 2208 } else { 2209 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2210 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2211 return SDValue(); 2212 } 2213 2214 SDValue Op0 = Node->getOperand(0); 2215 SDValue Op1 = Node->getOperand(1); 2216 SDValue combined; 2217 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2218 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2219 SDNode *User = *UI; 2220 if (User == Node || User->use_empty()) 2221 continue; 2222 // Convert the other matching node(s), too; 2223 // otherwise, the DIVREM may get target-legalized into something 2224 // target-specific that we won't be able to recognize. 2225 unsigned UserOpc = User->getOpcode(); 2226 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2227 User->getOperand(0) == Op0 && 2228 User->getOperand(1) == Op1) { 2229 if (!combined) { 2230 if (UserOpc == OtherOpcode) { 2231 SDVTList VTs = DAG.getVTList(VT, VT); 2232 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2233 } else if (UserOpc == DivRemOpc) { 2234 combined = SDValue(User, 0); 2235 } else { 2236 assert(UserOpc == Opcode); 2237 continue; 2238 } 2239 } 2240 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2241 CombineTo(User, combined); 2242 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2243 CombineTo(User, combined.getValue(1)); 2244 } 2245 } 2246 return combined; 2247 } 2248 2249 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2250 SDValue N0 = N->getOperand(0); 2251 SDValue N1 = N->getOperand(1); 2252 EVT VT = N->getValueType(0); 2253 2254 // fold vector ops 2255 if (VT.isVector()) 2256 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2257 return FoldedVOp; 2258 2259 SDLoc DL(N); 2260 2261 // fold (sdiv c1, c2) -> c1/c2 2262 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2263 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2264 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2265 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2266 // fold (sdiv X, 1) -> X 2267 if (N1C && N1C->isOne()) 2268 return N0; 2269 // fold (sdiv X, -1) -> 0-X 2270 if (N1C && N1C->isAllOnesValue()) 2271 return DAG.getNode(ISD::SUB, DL, VT, 2272 DAG.getConstant(0, DL, VT), N0); 2273 2274 // If we know the sign bits of both operands are zero, strength reduce to a 2275 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2276 if (!VT.isVector()) { 2277 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2278 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2279 } 2280 2281 // fold (sdiv X, pow2) -> simple ops after legalize 2282 // FIXME: We check for the exact bit here because the generic lowering gives 2283 // better results in that case. The target-specific lowering should learn how 2284 // to handle exact sdivs efficiently. 2285 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2286 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2287 (N1C->getAPIntValue().isPowerOf2() || 2288 (-N1C->getAPIntValue()).isPowerOf2())) { 2289 // Target-specific implementation of sdiv x, pow2. 2290 if (SDValue Res = BuildSDIVPow2(N)) 2291 return Res; 2292 2293 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2294 2295 // Splat the sign bit into the register 2296 SDValue SGN = 2297 DAG.getNode(ISD::SRA, DL, VT, N0, 2298 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2299 getShiftAmountTy(N0.getValueType()))); 2300 AddToWorklist(SGN.getNode()); 2301 2302 // Add (N0 < 0) ? abs2 - 1 : 0; 2303 SDValue SRL = 2304 DAG.getNode(ISD::SRL, DL, VT, SGN, 2305 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2306 getShiftAmountTy(SGN.getValueType()))); 2307 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2308 AddToWorklist(SRL.getNode()); 2309 AddToWorklist(ADD.getNode()); // Divide by pow2 2310 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2311 DAG.getConstant(lg2, DL, 2312 getShiftAmountTy(ADD.getValueType()))); 2313 2314 // If we're dividing by a positive value, we're done. Otherwise, we must 2315 // negate the result. 2316 if (N1C->getAPIntValue().isNonNegative()) 2317 return SRA; 2318 2319 AddToWorklist(SRA.getNode()); 2320 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2321 } 2322 2323 // If integer divide is expensive and we satisfy the requirements, emit an 2324 // alternate sequence. Targets may check function attributes for size/speed 2325 // trade-offs. 2326 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2327 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2328 if (SDValue Op = BuildSDIV(N)) 2329 return Op; 2330 2331 // sdiv, srem -> sdivrem 2332 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2333 // Otherwise, we break the simplification logic in visitREM(). 2334 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2335 if (SDValue DivRem = useDivRem(N)) 2336 return DivRem; 2337 2338 // undef / X -> 0 2339 if (N0.getOpcode() == ISD::UNDEF) 2340 return DAG.getConstant(0, DL, VT); 2341 // X / undef -> undef 2342 if (N1.getOpcode() == ISD::UNDEF) 2343 return N1; 2344 2345 return SDValue(); 2346 } 2347 2348 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2349 SDValue N0 = N->getOperand(0); 2350 SDValue N1 = N->getOperand(1); 2351 EVT VT = N->getValueType(0); 2352 2353 // fold vector ops 2354 if (VT.isVector()) 2355 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2356 return FoldedVOp; 2357 2358 SDLoc DL(N); 2359 2360 // fold (udiv c1, c2) -> c1/c2 2361 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2362 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2363 if (N0C && N1C) 2364 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2365 N0C, N1C)) 2366 return Folded; 2367 // fold (udiv x, (1 << c)) -> x >>u c 2368 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2369 return DAG.getNode(ISD::SRL, DL, VT, N0, 2370 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2371 getShiftAmountTy(N0.getValueType()))); 2372 2373 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2374 if (N1.getOpcode() == ISD::SHL) { 2375 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2376 if (SHC->getAPIntValue().isPowerOf2()) { 2377 EVT ADDVT = N1.getOperand(1).getValueType(); 2378 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2379 N1.getOperand(1), 2380 DAG.getConstant(SHC->getAPIntValue() 2381 .logBase2(), 2382 DL, ADDVT)); 2383 AddToWorklist(Add.getNode()); 2384 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2385 } 2386 } 2387 } 2388 2389 // fold (udiv x, c) -> alternate 2390 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2391 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2392 if (SDValue Op = BuildUDIV(N)) 2393 return Op; 2394 2395 // sdiv, srem -> sdivrem 2396 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2397 // Otherwise, we break the simplification logic in visitREM(). 2398 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2399 if (SDValue DivRem = useDivRem(N)) 2400 return DivRem; 2401 2402 // undef / X -> 0 2403 if (N0.getOpcode() == ISD::UNDEF) 2404 return DAG.getConstant(0, DL, VT); 2405 // X / undef -> undef 2406 if (N1.getOpcode() == ISD::UNDEF) 2407 return N1; 2408 2409 return SDValue(); 2410 } 2411 2412 // handles ISD::SREM and ISD::UREM 2413 SDValue DAGCombiner::visitREM(SDNode *N) { 2414 unsigned Opcode = N->getOpcode(); 2415 SDValue N0 = N->getOperand(0); 2416 SDValue N1 = N->getOperand(1); 2417 EVT VT = N->getValueType(0); 2418 bool isSigned = (Opcode == ISD::SREM); 2419 SDLoc DL(N); 2420 2421 // fold (rem c1, c2) -> c1%c2 2422 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2423 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2424 if (N0C && N1C) 2425 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2426 return Folded; 2427 2428 if (isSigned) { 2429 // If we know the sign bits of both operands are zero, strength reduce to a 2430 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2431 if (!VT.isVector()) { 2432 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2433 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2434 } 2435 } else { 2436 // fold (urem x, pow2) -> (and x, pow2-1) 2437 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2438 N1C->getAPIntValue().isPowerOf2()) { 2439 return DAG.getNode(ISD::AND, DL, VT, N0, 2440 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2441 } 2442 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2443 if (N1.getOpcode() == ISD::SHL) { 2444 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2445 if (SHC->getAPIntValue().isPowerOf2()) { 2446 SDValue Add = 2447 DAG.getNode(ISD::ADD, DL, VT, N1, 2448 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2449 VT)); 2450 AddToWorklist(Add.getNode()); 2451 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2452 } 2453 } 2454 } 2455 } 2456 2457 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2458 2459 // If X/C can be simplified by the division-by-constant logic, lower 2460 // X%C to the equivalent of X-X/C*C. 2461 // To avoid mangling nodes, this simplification requires that the combine() 2462 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2463 // against this by skipping the simplification if isIntDivCheap(). When 2464 // div is not cheap, combine will not return a DIVREM. Regardless, 2465 // checking cheapness here makes sense since the simplification results in 2466 // fatter code. 2467 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2468 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2469 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2470 AddToWorklist(Div.getNode()); 2471 SDValue OptimizedDiv = combine(Div.getNode()); 2472 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2473 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2474 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2475 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2476 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2477 AddToWorklist(Mul.getNode()); 2478 return Sub; 2479 } 2480 } 2481 2482 // sdiv, srem -> sdivrem 2483 if (SDValue DivRem = useDivRem(N)) 2484 return DivRem.getValue(1); 2485 2486 // undef % X -> 0 2487 if (N0.getOpcode() == ISD::UNDEF) 2488 return DAG.getConstant(0, DL, VT); 2489 // X % undef -> undef 2490 if (N1.getOpcode() == ISD::UNDEF) 2491 return N1; 2492 2493 return SDValue(); 2494 } 2495 2496 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2497 SDValue N0 = N->getOperand(0); 2498 SDValue N1 = N->getOperand(1); 2499 EVT VT = N->getValueType(0); 2500 SDLoc DL(N); 2501 2502 // fold (mulhs x, 0) -> 0 2503 if (isNullConstant(N1)) 2504 return N1; 2505 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2506 if (isOneConstant(N1)) { 2507 SDLoc DL(N); 2508 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2509 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2510 DL, 2511 getShiftAmountTy(N0.getValueType()))); 2512 } 2513 // fold (mulhs x, undef) -> 0 2514 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2515 return DAG.getConstant(0, SDLoc(N), VT); 2516 2517 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2518 // plus a shift. 2519 if (VT.isSimple() && !VT.isVector()) { 2520 MVT Simple = VT.getSimpleVT(); 2521 unsigned SimpleSize = Simple.getSizeInBits(); 2522 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2523 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2524 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2525 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2526 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2527 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2528 DAG.getConstant(SimpleSize, DL, 2529 getShiftAmountTy(N1.getValueType()))); 2530 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2531 } 2532 } 2533 2534 return SDValue(); 2535 } 2536 2537 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2538 SDValue N0 = N->getOperand(0); 2539 SDValue N1 = N->getOperand(1); 2540 EVT VT = N->getValueType(0); 2541 SDLoc DL(N); 2542 2543 // fold (mulhu x, 0) -> 0 2544 if (isNullConstant(N1)) 2545 return N1; 2546 // fold (mulhu x, 1) -> 0 2547 if (isOneConstant(N1)) 2548 return DAG.getConstant(0, DL, N0.getValueType()); 2549 // fold (mulhu x, undef) -> 0 2550 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2551 return DAG.getConstant(0, DL, VT); 2552 2553 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2554 // plus a shift. 2555 if (VT.isSimple() && !VT.isVector()) { 2556 MVT Simple = VT.getSimpleVT(); 2557 unsigned SimpleSize = Simple.getSizeInBits(); 2558 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2559 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2560 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2561 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2562 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2563 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2564 DAG.getConstant(SimpleSize, DL, 2565 getShiftAmountTy(N1.getValueType()))); 2566 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2567 } 2568 } 2569 2570 return SDValue(); 2571 } 2572 2573 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2574 /// give the opcodes for the two computations that are being performed. Return 2575 /// true if a simplification was made. 2576 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2577 unsigned HiOp) { 2578 // If the high half is not needed, just compute the low half. 2579 bool HiExists = N->hasAnyUseOfValue(1); 2580 if (!HiExists && 2581 (!LegalOperations || 2582 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2583 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2584 return CombineTo(N, Res, Res); 2585 } 2586 2587 // If the low half is not needed, just compute the high half. 2588 bool LoExists = N->hasAnyUseOfValue(0); 2589 if (!LoExists && 2590 (!LegalOperations || 2591 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2592 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2593 return CombineTo(N, Res, Res); 2594 } 2595 2596 // If both halves are used, return as it is. 2597 if (LoExists && HiExists) 2598 return SDValue(); 2599 2600 // If the two computed results can be simplified separately, separate them. 2601 if (LoExists) { 2602 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2603 AddToWorklist(Lo.getNode()); 2604 SDValue LoOpt = combine(Lo.getNode()); 2605 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2606 (!LegalOperations || 2607 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2608 return CombineTo(N, LoOpt, LoOpt); 2609 } 2610 2611 if (HiExists) { 2612 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2613 AddToWorklist(Hi.getNode()); 2614 SDValue HiOpt = combine(Hi.getNode()); 2615 if (HiOpt.getNode() && HiOpt != Hi && 2616 (!LegalOperations || 2617 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2618 return CombineTo(N, HiOpt, HiOpt); 2619 } 2620 2621 return SDValue(); 2622 } 2623 2624 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2625 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2626 return Res; 2627 2628 EVT VT = N->getValueType(0); 2629 SDLoc DL(N); 2630 2631 // If the type is twice as wide is legal, transform the mulhu to a wider 2632 // multiply plus a shift. 2633 if (VT.isSimple() && !VT.isVector()) { 2634 MVT Simple = VT.getSimpleVT(); 2635 unsigned SimpleSize = Simple.getSizeInBits(); 2636 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2637 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2638 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2639 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2640 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2641 // Compute the high part as N1. 2642 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2643 DAG.getConstant(SimpleSize, DL, 2644 getShiftAmountTy(Lo.getValueType()))); 2645 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2646 // Compute the low part as N0. 2647 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2648 return CombineTo(N, Lo, Hi); 2649 } 2650 } 2651 2652 return SDValue(); 2653 } 2654 2655 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2656 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2657 return Res; 2658 2659 EVT VT = N->getValueType(0); 2660 SDLoc DL(N); 2661 2662 // If the type is twice as wide is legal, transform the mulhu to a wider 2663 // multiply plus a shift. 2664 if (VT.isSimple() && !VT.isVector()) { 2665 MVT Simple = VT.getSimpleVT(); 2666 unsigned SimpleSize = Simple.getSizeInBits(); 2667 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2668 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2669 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2670 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2671 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2672 // Compute the high part as N1. 2673 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2674 DAG.getConstant(SimpleSize, DL, 2675 getShiftAmountTy(Lo.getValueType()))); 2676 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2677 // Compute the low part as N0. 2678 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2679 return CombineTo(N, Lo, Hi); 2680 } 2681 } 2682 2683 return SDValue(); 2684 } 2685 2686 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2687 // (smulo x, 2) -> (saddo x, x) 2688 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2689 if (C2->getAPIntValue() == 2) 2690 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2691 N->getOperand(0), N->getOperand(0)); 2692 2693 return SDValue(); 2694 } 2695 2696 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2697 // (umulo x, 2) -> (uaddo x, x) 2698 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2699 if (C2->getAPIntValue() == 2) 2700 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2701 N->getOperand(0), N->getOperand(0)); 2702 2703 return SDValue(); 2704 } 2705 2706 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2707 SDValue N0 = N->getOperand(0); 2708 SDValue N1 = N->getOperand(1); 2709 EVT VT = N0.getValueType(); 2710 2711 // fold vector ops 2712 if (VT.isVector()) 2713 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2714 return FoldedVOp; 2715 2716 // fold (add c1, c2) -> c1+c2 2717 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2718 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2719 if (N0C && N1C) 2720 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2721 2722 // canonicalize constant to RHS 2723 if (isConstantIntBuildVectorOrConstantInt(N0) && 2724 !isConstantIntBuildVectorOrConstantInt(N1)) 2725 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2726 2727 return SDValue(); 2728 } 2729 2730 /// If this is a binary operator with two operands of the same opcode, try to 2731 /// simplify it. 2732 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2733 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2734 EVT VT = N0.getValueType(); 2735 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2736 2737 // Bail early if none of these transforms apply. 2738 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2739 2740 // For each of OP in AND/OR/XOR: 2741 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2742 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2743 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2744 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2745 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2746 // 2747 // do not sink logical op inside of a vector extend, since it may combine 2748 // into a vsetcc. 2749 EVT Op0VT = N0.getOperand(0).getValueType(); 2750 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2751 N0.getOpcode() == ISD::SIGN_EXTEND || 2752 N0.getOpcode() == ISD::BSWAP || 2753 // Avoid infinite looping with PromoteIntBinOp. 2754 (N0.getOpcode() == ISD::ANY_EXTEND && 2755 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2756 (N0.getOpcode() == ISD::TRUNCATE && 2757 (!TLI.isZExtFree(VT, Op0VT) || 2758 !TLI.isTruncateFree(Op0VT, VT)) && 2759 TLI.isTypeLegal(Op0VT))) && 2760 !VT.isVector() && 2761 Op0VT == N1.getOperand(0).getValueType() && 2762 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2763 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2764 N0.getOperand(0).getValueType(), 2765 N0.getOperand(0), N1.getOperand(0)); 2766 AddToWorklist(ORNode.getNode()); 2767 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2768 } 2769 2770 // For each of OP in SHL/SRL/SRA/AND... 2771 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2772 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2773 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2774 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2775 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2776 N0.getOperand(1) == N1.getOperand(1)) { 2777 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2778 N0.getOperand(0).getValueType(), 2779 N0.getOperand(0), N1.getOperand(0)); 2780 AddToWorklist(ORNode.getNode()); 2781 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2782 ORNode, N0.getOperand(1)); 2783 } 2784 2785 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2786 // Only perform this optimization after type legalization and before 2787 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2788 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2789 // we don't want to undo this promotion. 2790 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2791 // on scalars. 2792 if ((N0.getOpcode() == ISD::BITCAST || 2793 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2794 Level == AfterLegalizeTypes) { 2795 SDValue In0 = N0.getOperand(0); 2796 SDValue In1 = N1.getOperand(0); 2797 EVT In0Ty = In0.getValueType(); 2798 EVT In1Ty = In1.getValueType(); 2799 SDLoc DL(N); 2800 // If both incoming values are integers, and the original types are the 2801 // same. 2802 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2803 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2804 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2805 AddToWorklist(Op.getNode()); 2806 return BC; 2807 } 2808 } 2809 2810 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2811 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2812 // If both shuffles use the same mask, and both shuffle within a single 2813 // vector, then it is worthwhile to move the swizzle after the operation. 2814 // The type-legalizer generates this pattern when loading illegal 2815 // vector types from memory. In many cases this allows additional shuffle 2816 // optimizations. 2817 // There are other cases where moving the shuffle after the xor/and/or 2818 // is profitable even if shuffles don't perform a swizzle. 2819 // If both shuffles use the same mask, and both shuffles have the same first 2820 // or second operand, then it might still be profitable to move the shuffle 2821 // after the xor/and/or operation. 2822 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2823 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2824 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2825 2826 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2827 "Inputs to shuffles are not the same type"); 2828 2829 // Check that both shuffles use the same mask. The masks are known to be of 2830 // the same length because the result vector type is the same. 2831 // Check also that shuffles have only one use to avoid introducing extra 2832 // instructions. 2833 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2834 SVN0->getMask().equals(SVN1->getMask())) { 2835 SDValue ShOp = N0->getOperand(1); 2836 2837 // Don't try to fold this node if it requires introducing a 2838 // build vector of all zeros that might be illegal at this stage. 2839 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2840 if (!LegalTypes) 2841 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2842 else 2843 ShOp = SDValue(); 2844 } 2845 2846 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2847 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2848 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2849 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2850 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2851 N0->getOperand(0), N1->getOperand(0)); 2852 AddToWorklist(NewNode.getNode()); 2853 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2854 &SVN0->getMask()[0]); 2855 } 2856 2857 // Don't try to fold this node if it requires introducing a 2858 // build vector of all zeros that might be illegal at this stage. 2859 ShOp = N0->getOperand(0); 2860 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2861 if (!LegalTypes) 2862 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2863 else 2864 ShOp = SDValue(); 2865 } 2866 2867 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2868 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2869 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2870 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2871 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2872 N0->getOperand(1), N1->getOperand(1)); 2873 AddToWorklist(NewNode.getNode()); 2874 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2875 &SVN0->getMask()[0]); 2876 } 2877 } 2878 } 2879 2880 return SDValue(); 2881 } 2882 2883 /// This contains all DAGCombine rules which reduce two values combined by 2884 /// an And operation to a single value. This makes them reusable in the context 2885 /// of visitSELECT(). Rules involving constants are not included as 2886 /// visitSELECT() already handles those cases. 2887 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2888 SDNode *LocReference) { 2889 EVT VT = N1.getValueType(); 2890 2891 // fold (and x, undef) -> 0 2892 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2893 return DAG.getConstant(0, SDLoc(LocReference), VT); 2894 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2895 SDValue LL, LR, RL, RR, CC0, CC1; 2896 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2897 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2898 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2899 2900 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2901 LL.getValueType().isInteger()) { 2902 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2903 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2904 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2905 LR.getValueType(), LL, RL); 2906 AddToWorklist(ORNode.getNode()); 2907 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2908 } 2909 if (isAllOnesConstant(LR)) { 2910 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2911 if (Op1 == ISD::SETEQ) { 2912 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2913 LR.getValueType(), LL, RL); 2914 AddToWorklist(ANDNode.getNode()); 2915 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2916 } 2917 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2918 if (Op1 == ISD::SETGT) { 2919 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2920 LR.getValueType(), LL, RL); 2921 AddToWorklist(ORNode.getNode()); 2922 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2923 } 2924 } 2925 } 2926 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2927 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2928 Op0 == Op1 && LL.getValueType().isInteger() && 2929 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2930 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2931 SDLoc DL(N0); 2932 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2933 LL, DAG.getConstant(1, DL, 2934 LL.getValueType())); 2935 AddToWorklist(ADDNode.getNode()); 2936 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2937 DAG.getConstant(2, DL, LL.getValueType()), 2938 ISD::SETUGE); 2939 } 2940 // canonicalize equivalent to ll == rl 2941 if (LL == RR && LR == RL) { 2942 Op1 = ISD::getSetCCSwappedOperands(Op1); 2943 std::swap(RL, RR); 2944 } 2945 if (LL == RL && LR == RR) { 2946 bool isInteger = LL.getValueType().isInteger(); 2947 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2948 if (Result != ISD::SETCC_INVALID && 2949 (!LegalOperations || 2950 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2951 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2952 EVT CCVT = getSetCCResultType(LL.getValueType()); 2953 if (N0.getValueType() == CCVT || 2954 (!LegalOperations && N0.getValueType() == MVT::i1)) 2955 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2956 LL, LR, Result); 2957 } 2958 } 2959 } 2960 2961 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2962 VT.getSizeInBits() <= 64) { 2963 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2964 APInt ADDC = ADDI->getAPIntValue(); 2965 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2966 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2967 // immediate for an add, but it is legal if its top c2 bits are set, 2968 // transform the ADD so the immediate doesn't need to be materialized 2969 // in a register. 2970 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2971 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2972 SRLI->getZExtValue()); 2973 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2974 ADDC |= Mask; 2975 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2976 SDLoc DL(N0); 2977 SDValue NewAdd = 2978 DAG.getNode(ISD::ADD, DL, VT, 2979 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2980 CombineTo(N0.getNode(), NewAdd); 2981 // Return N so it doesn't get rechecked! 2982 return SDValue(LocReference, 0); 2983 } 2984 } 2985 } 2986 } 2987 } 2988 } 2989 2990 return SDValue(); 2991 } 2992 2993 SDValue DAGCombiner::visitAND(SDNode *N) { 2994 SDValue N0 = N->getOperand(0); 2995 SDValue N1 = N->getOperand(1); 2996 EVT VT = N1.getValueType(); 2997 2998 // fold vector ops 2999 if (VT.isVector()) { 3000 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3001 return FoldedVOp; 3002 3003 // fold (and x, 0) -> 0, vector edition 3004 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3005 // do not return N0, because undef node may exist in N0 3006 return DAG.getConstant( 3007 APInt::getNullValue( 3008 N0.getValueType().getScalarType().getSizeInBits()), 3009 SDLoc(N), N0.getValueType()); 3010 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3011 // do not return N1, because undef node may exist in N1 3012 return DAG.getConstant( 3013 APInt::getNullValue( 3014 N1.getValueType().getScalarType().getSizeInBits()), 3015 SDLoc(N), N1.getValueType()); 3016 3017 // fold (and x, -1) -> x, vector edition 3018 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3019 return N1; 3020 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3021 return N0; 3022 } 3023 3024 // fold (and c1, c2) -> c1&c2 3025 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3026 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3027 if (N0C && N1C && !N1C->isOpaque()) 3028 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3029 // canonicalize constant to RHS 3030 if (isConstantIntBuildVectorOrConstantInt(N0) && 3031 !isConstantIntBuildVectorOrConstantInt(N1)) 3032 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3033 // fold (and x, -1) -> x 3034 if (isAllOnesConstant(N1)) 3035 return N0; 3036 // if (and x, c) is known to be zero, return 0 3037 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3038 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3039 APInt::getAllOnesValue(BitWidth))) 3040 return DAG.getConstant(0, SDLoc(N), VT); 3041 // reassociate and 3042 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3043 return RAND; 3044 // fold (and (or x, C), D) -> D if (C & D) == D 3045 if (N1C && N0.getOpcode() == ISD::OR) 3046 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3047 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3048 return N1; 3049 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3050 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3051 SDValue N0Op0 = N0.getOperand(0); 3052 APInt Mask = ~N1C->getAPIntValue(); 3053 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 3054 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3055 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3056 N0.getValueType(), N0Op0); 3057 3058 // Replace uses of the AND with uses of the Zero extend node. 3059 CombineTo(N, Zext); 3060 3061 // We actually want to replace all uses of the any_extend with the 3062 // zero_extend, to avoid duplicating things. This will later cause this 3063 // AND to be folded. 3064 CombineTo(N0.getNode(), Zext); 3065 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3066 } 3067 } 3068 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3069 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3070 // already be zero by virtue of the width of the base type of the load. 3071 // 3072 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3073 // more cases. 3074 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3075 N0.getOperand(0).getOpcode() == ISD::LOAD) || 3076 N0.getOpcode() == ISD::LOAD) { 3077 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3078 N0 : N0.getOperand(0) ); 3079 3080 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3081 // This can be a pure constant or a vector splat, in which case we treat the 3082 // vector as a scalar and use the splat value. 3083 APInt Constant = APInt::getNullValue(1); 3084 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3085 Constant = C->getAPIntValue(); 3086 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3087 APInt SplatValue, SplatUndef; 3088 unsigned SplatBitSize; 3089 bool HasAnyUndefs; 3090 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3091 SplatBitSize, HasAnyUndefs); 3092 if (IsSplat) { 3093 // Undef bits can contribute to a possible optimisation if set, so 3094 // set them. 3095 SplatValue |= SplatUndef; 3096 3097 // The splat value may be something like "0x00FFFFFF", which means 0 for 3098 // the first vector value and FF for the rest, repeating. We need a mask 3099 // that will apply equally to all members of the vector, so AND all the 3100 // lanes of the constant together. 3101 EVT VT = Vector->getValueType(0); 3102 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3103 3104 // If the splat value has been compressed to a bitlength lower 3105 // than the size of the vector lane, we need to re-expand it to 3106 // the lane size. 3107 if (BitWidth > SplatBitSize) 3108 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3109 SplatBitSize < BitWidth; 3110 SplatBitSize = SplatBitSize * 2) 3111 SplatValue |= SplatValue.shl(SplatBitSize); 3112 3113 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3114 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3115 if (SplatBitSize % BitWidth == 0) { 3116 Constant = APInt::getAllOnesValue(BitWidth); 3117 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3118 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3119 } 3120 } 3121 } 3122 3123 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3124 // actually legal and isn't going to get expanded, else this is a false 3125 // optimisation. 3126 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3127 Load->getValueType(0), 3128 Load->getMemoryVT()); 3129 3130 // Resize the constant to the same size as the original memory access before 3131 // extension. If it is still the AllOnesValue then this AND is completely 3132 // unneeded. 3133 Constant = 3134 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3135 3136 bool B; 3137 switch (Load->getExtensionType()) { 3138 default: B = false; break; 3139 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3140 case ISD::ZEXTLOAD: 3141 case ISD::NON_EXTLOAD: B = true; break; 3142 } 3143 3144 if (B && Constant.isAllOnesValue()) { 3145 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3146 // preserve semantics once we get rid of the AND. 3147 SDValue NewLoad(Load, 0); 3148 if (Load->getExtensionType() == ISD::EXTLOAD) { 3149 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3150 Load->getValueType(0), SDLoc(Load), 3151 Load->getChain(), Load->getBasePtr(), 3152 Load->getOffset(), Load->getMemoryVT(), 3153 Load->getMemOperand()); 3154 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3155 if (Load->getNumValues() == 3) { 3156 // PRE/POST_INC loads have 3 values. 3157 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3158 NewLoad.getValue(2) }; 3159 CombineTo(Load, To, 3, true); 3160 } else { 3161 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3162 } 3163 } 3164 3165 // Fold the AND away, taking care not to fold to the old load node if we 3166 // replaced it. 3167 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3168 3169 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3170 } 3171 } 3172 3173 // fold (and (load x), 255) -> (zextload x, i8) 3174 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3175 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3176 if (N1C && (N0.getOpcode() == ISD::LOAD || 3177 (N0.getOpcode() == ISD::ANY_EXTEND && 3178 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3179 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3180 LoadSDNode *LN0 = HasAnyExt 3181 ? cast<LoadSDNode>(N0.getOperand(0)) 3182 : cast<LoadSDNode>(N0); 3183 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3184 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3185 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 3186 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 3187 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3188 EVT LoadedVT = LN0->getMemoryVT(); 3189 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3190 3191 if (ExtVT == LoadedVT && 3192 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3193 ExtVT))) { 3194 3195 SDValue NewLoad = 3196 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3197 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3198 LN0->getMemOperand()); 3199 AddToWorklist(N); 3200 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3201 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3202 } 3203 3204 // Do not change the width of a volatile load. 3205 // Do not generate loads of non-round integer types since these can 3206 // be expensive (and would be wrong if the type is not byte sized). 3207 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 3208 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3209 ExtVT))) { 3210 EVT PtrType = LN0->getOperand(1).getValueType(); 3211 3212 unsigned Alignment = LN0->getAlignment(); 3213 SDValue NewPtr = LN0->getBasePtr(); 3214 3215 // For big endian targets, we need to add an offset to the pointer 3216 // to load the correct bytes. For little endian systems, we merely 3217 // need to read fewer bytes from the same pointer. 3218 if (DAG.getDataLayout().isBigEndian()) { 3219 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3220 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3221 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3222 SDLoc DL(LN0); 3223 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3224 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3225 Alignment = MinAlign(Alignment, PtrOff); 3226 } 3227 3228 AddToWorklist(NewPtr.getNode()); 3229 3230 SDValue Load = 3231 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3232 LN0->getChain(), NewPtr, 3233 LN0->getPointerInfo(), 3234 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3235 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3236 AddToWorklist(N); 3237 CombineTo(LN0, Load, Load.getValue(1)); 3238 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3239 } 3240 } 3241 } 3242 } 3243 3244 if (SDValue Combined = visitANDLike(N0, N1, N)) 3245 return Combined; 3246 3247 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3248 if (N0.getOpcode() == N1.getOpcode()) 3249 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3250 return Tmp; 3251 3252 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3253 // fold (and (sra)) -> (and (srl)) when possible. 3254 if (!VT.isVector() && 3255 SimplifyDemandedBits(SDValue(N, 0))) 3256 return SDValue(N, 0); 3257 3258 // fold (zext_inreg (extload x)) -> (zextload x) 3259 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3260 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3261 EVT MemVT = LN0->getMemoryVT(); 3262 // If we zero all the possible extended bits, then we can turn this into 3263 // a zextload if we are running before legalize or the operation is legal. 3264 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3265 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3266 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3267 ((!LegalOperations && !LN0->isVolatile()) || 3268 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3269 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3270 LN0->getChain(), LN0->getBasePtr(), 3271 MemVT, LN0->getMemOperand()); 3272 AddToWorklist(N); 3273 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3274 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3275 } 3276 } 3277 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3278 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3279 N0.hasOneUse()) { 3280 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3281 EVT MemVT = LN0->getMemoryVT(); 3282 // If we zero all the possible extended bits, then we can turn this into 3283 // a zextload if we are running before legalize or the operation is legal. 3284 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3285 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3286 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3287 ((!LegalOperations && !LN0->isVolatile()) || 3288 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3289 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3290 LN0->getChain(), LN0->getBasePtr(), 3291 MemVT, LN0->getMemOperand()); 3292 AddToWorklist(N); 3293 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3294 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3295 } 3296 } 3297 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3298 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3299 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3300 N0.getOperand(1), false); 3301 if (BSwap.getNode()) 3302 return BSwap; 3303 } 3304 3305 return SDValue(); 3306 } 3307 3308 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3309 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3310 bool DemandHighBits) { 3311 if (!LegalOperations) 3312 return SDValue(); 3313 3314 EVT VT = N->getValueType(0); 3315 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3316 return SDValue(); 3317 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3318 return SDValue(); 3319 3320 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3321 bool LookPassAnd0 = false; 3322 bool LookPassAnd1 = false; 3323 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3324 std::swap(N0, N1); 3325 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3326 std::swap(N0, N1); 3327 if (N0.getOpcode() == ISD::AND) { 3328 if (!N0.getNode()->hasOneUse()) 3329 return SDValue(); 3330 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3331 if (!N01C || N01C->getZExtValue() != 0xFF00) 3332 return SDValue(); 3333 N0 = N0.getOperand(0); 3334 LookPassAnd0 = true; 3335 } 3336 3337 if (N1.getOpcode() == ISD::AND) { 3338 if (!N1.getNode()->hasOneUse()) 3339 return SDValue(); 3340 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3341 if (!N11C || N11C->getZExtValue() != 0xFF) 3342 return SDValue(); 3343 N1 = N1.getOperand(0); 3344 LookPassAnd1 = true; 3345 } 3346 3347 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3348 std::swap(N0, N1); 3349 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3350 return SDValue(); 3351 if (!N0.getNode()->hasOneUse() || 3352 !N1.getNode()->hasOneUse()) 3353 return SDValue(); 3354 3355 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3356 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3357 if (!N01C || !N11C) 3358 return SDValue(); 3359 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3360 return SDValue(); 3361 3362 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3363 SDValue N00 = N0->getOperand(0); 3364 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3365 if (!N00.getNode()->hasOneUse()) 3366 return SDValue(); 3367 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3368 if (!N001C || N001C->getZExtValue() != 0xFF) 3369 return SDValue(); 3370 N00 = N00.getOperand(0); 3371 LookPassAnd0 = true; 3372 } 3373 3374 SDValue N10 = N1->getOperand(0); 3375 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3376 if (!N10.getNode()->hasOneUse()) 3377 return SDValue(); 3378 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3379 if (!N101C || N101C->getZExtValue() != 0xFF00) 3380 return SDValue(); 3381 N10 = N10.getOperand(0); 3382 LookPassAnd1 = true; 3383 } 3384 3385 if (N00 != N10) 3386 return SDValue(); 3387 3388 // Make sure everything beyond the low halfword gets set to zero since the SRL 3389 // 16 will clear the top bits. 3390 unsigned OpSizeInBits = VT.getSizeInBits(); 3391 if (DemandHighBits && OpSizeInBits > 16) { 3392 // If the left-shift isn't masked out then the only way this is a bswap is 3393 // if all bits beyond the low 8 are 0. In that case the entire pattern 3394 // reduces to a left shift anyway: leave it for other parts of the combiner. 3395 if (!LookPassAnd0) 3396 return SDValue(); 3397 3398 // However, if the right shift isn't masked out then it might be because 3399 // it's not needed. See if we can spot that too. 3400 if (!LookPassAnd1 && 3401 !DAG.MaskedValueIsZero( 3402 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3403 return SDValue(); 3404 } 3405 3406 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3407 if (OpSizeInBits > 16) { 3408 SDLoc DL(N); 3409 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3410 DAG.getConstant(OpSizeInBits - 16, DL, 3411 getShiftAmountTy(VT))); 3412 } 3413 return Res; 3414 } 3415 3416 /// Return true if the specified node is an element that makes up a 32-bit 3417 /// packed halfword byteswap. 3418 /// ((x & 0x000000ff) << 8) | 3419 /// ((x & 0x0000ff00) >> 8) | 3420 /// ((x & 0x00ff0000) << 8) | 3421 /// ((x & 0xff000000) >> 8) 3422 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3423 if (!N.getNode()->hasOneUse()) 3424 return false; 3425 3426 unsigned Opc = N.getOpcode(); 3427 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3428 return false; 3429 3430 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3431 if (!N1C) 3432 return false; 3433 3434 unsigned Num; 3435 switch (N1C->getZExtValue()) { 3436 default: 3437 return false; 3438 case 0xFF: Num = 0; break; 3439 case 0xFF00: Num = 1; break; 3440 case 0xFF0000: Num = 2; break; 3441 case 0xFF000000: Num = 3; break; 3442 } 3443 3444 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3445 SDValue N0 = N.getOperand(0); 3446 if (Opc == ISD::AND) { 3447 if (Num == 0 || Num == 2) { 3448 // (x >> 8) & 0xff 3449 // (x >> 8) & 0xff0000 3450 if (N0.getOpcode() != ISD::SRL) 3451 return false; 3452 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3453 if (!C || C->getZExtValue() != 8) 3454 return false; 3455 } else { 3456 // (x << 8) & 0xff00 3457 // (x << 8) & 0xff000000 3458 if (N0.getOpcode() != ISD::SHL) 3459 return false; 3460 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3461 if (!C || C->getZExtValue() != 8) 3462 return false; 3463 } 3464 } else if (Opc == ISD::SHL) { 3465 // (x & 0xff) << 8 3466 // (x & 0xff0000) << 8 3467 if (Num != 0 && Num != 2) 3468 return false; 3469 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3470 if (!C || C->getZExtValue() != 8) 3471 return false; 3472 } else { // Opc == ISD::SRL 3473 // (x & 0xff00) >> 8 3474 // (x & 0xff000000) >> 8 3475 if (Num != 1 && Num != 3) 3476 return false; 3477 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3478 if (!C || C->getZExtValue() != 8) 3479 return false; 3480 } 3481 3482 if (Parts[Num]) 3483 return false; 3484 3485 Parts[Num] = N0.getOperand(0).getNode(); 3486 return true; 3487 } 3488 3489 /// Match a 32-bit packed halfword bswap. That is 3490 /// ((x & 0x000000ff) << 8) | 3491 /// ((x & 0x0000ff00) >> 8) | 3492 /// ((x & 0x00ff0000) << 8) | 3493 /// ((x & 0xff000000) >> 8) 3494 /// => (rotl (bswap x), 16) 3495 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3496 if (!LegalOperations) 3497 return SDValue(); 3498 3499 EVT VT = N->getValueType(0); 3500 if (VT != MVT::i32) 3501 return SDValue(); 3502 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3503 return SDValue(); 3504 3505 // Look for either 3506 // (or (or (and), (and)), (or (and), (and))) 3507 // (or (or (or (and), (and)), (and)), (and)) 3508 if (N0.getOpcode() != ISD::OR) 3509 return SDValue(); 3510 SDValue N00 = N0.getOperand(0); 3511 SDValue N01 = N0.getOperand(1); 3512 SDNode *Parts[4] = {}; 3513 3514 if (N1.getOpcode() == ISD::OR && 3515 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3516 // (or (or (and), (and)), (or (and), (and))) 3517 SDValue N000 = N00.getOperand(0); 3518 if (!isBSwapHWordElement(N000, Parts)) 3519 return SDValue(); 3520 3521 SDValue N001 = N00.getOperand(1); 3522 if (!isBSwapHWordElement(N001, Parts)) 3523 return SDValue(); 3524 SDValue N010 = N01.getOperand(0); 3525 if (!isBSwapHWordElement(N010, Parts)) 3526 return SDValue(); 3527 SDValue N011 = N01.getOperand(1); 3528 if (!isBSwapHWordElement(N011, Parts)) 3529 return SDValue(); 3530 } else { 3531 // (or (or (or (and), (and)), (and)), (and)) 3532 if (!isBSwapHWordElement(N1, Parts)) 3533 return SDValue(); 3534 if (!isBSwapHWordElement(N01, Parts)) 3535 return SDValue(); 3536 if (N00.getOpcode() != ISD::OR) 3537 return SDValue(); 3538 SDValue N000 = N00.getOperand(0); 3539 if (!isBSwapHWordElement(N000, Parts)) 3540 return SDValue(); 3541 SDValue N001 = N00.getOperand(1); 3542 if (!isBSwapHWordElement(N001, Parts)) 3543 return SDValue(); 3544 } 3545 3546 // Make sure the parts are all coming from the same node. 3547 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3548 return SDValue(); 3549 3550 SDLoc DL(N); 3551 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3552 SDValue(Parts[0], 0)); 3553 3554 // Result of the bswap should be rotated by 16. If it's not legal, then 3555 // do (x << 16) | (x >> 16). 3556 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3557 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3558 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3559 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3560 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3561 return DAG.getNode(ISD::OR, DL, VT, 3562 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3563 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3564 } 3565 3566 /// This contains all DAGCombine rules which reduce two values combined by 3567 /// an Or operation to a single value \see visitANDLike(). 3568 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3569 EVT VT = N1.getValueType(); 3570 // fold (or x, undef) -> -1 3571 if (!LegalOperations && 3572 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3573 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3574 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3575 SDLoc(LocReference), VT); 3576 } 3577 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3578 SDValue LL, LR, RL, RR, CC0, CC1; 3579 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3580 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3581 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3582 3583 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3584 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3585 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3586 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3587 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3588 LR.getValueType(), LL, RL); 3589 AddToWorklist(ORNode.getNode()); 3590 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3591 } 3592 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3593 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3594 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3595 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3596 LR.getValueType(), LL, RL); 3597 AddToWorklist(ANDNode.getNode()); 3598 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3599 } 3600 } 3601 // canonicalize equivalent to ll == rl 3602 if (LL == RR && LR == RL) { 3603 Op1 = ISD::getSetCCSwappedOperands(Op1); 3604 std::swap(RL, RR); 3605 } 3606 if (LL == RL && LR == RR) { 3607 bool isInteger = LL.getValueType().isInteger(); 3608 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3609 if (Result != ISD::SETCC_INVALID && 3610 (!LegalOperations || 3611 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3612 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3613 EVT CCVT = getSetCCResultType(LL.getValueType()); 3614 if (N0.getValueType() == CCVT || 3615 (!LegalOperations && N0.getValueType() == MVT::i1)) 3616 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3617 LL, LR, Result); 3618 } 3619 } 3620 } 3621 3622 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3623 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3624 // Don't increase # computations. 3625 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3626 // We can only do this xform if we know that bits from X that are set in C2 3627 // but not in C1 are already zero. Likewise for Y. 3628 if (const ConstantSDNode *N0O1C = 3629 getAsNonOpaqueConstant(N0.getOperand(1))) { 3630 if (const ConstantSDNode *N1O1C = 3631 getAsNonOpaqueConstant(N1.getOperand(1))) { 3632 // We can only do this xform if we know that bits from X that are set in 3633 // C2 but not in C1 are already zero. Likewise for Y. 3634 const APInt &LHSMask = N0O1C->getAPIntValue(); 3635 const APInt &RHSMask = N1O1C->getAPIntValue(); 3636 3637 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3638 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3639 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3640 N0.getOperand(0), N1.getOperand(0)); 3641 SDLoc DL(LocReference); 3642 return DAG.getNode(ISD::AND, DL, VT, X, 3643 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3644 } 3645 } 3646 } 3647 } 3648 3649 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3650 if (N0.getOpcode() == ISD::AND && 3651 N1.getOpcode() == ISD::AND && 3652 N0.getOperand(0) == N1.getOperand(0) && 3653 // Don't increase # computations. 3654 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3655 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3656 N0.getOperand(1), N1.getOperand(1)); 3657 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3658 } 3659 3660 return SDValue(); 3661 } 3662 3663 SDValue DAGCombiner::visitOR(SDNode *N) { 3664 SDValue N0 = N->getOperand(0); 3665 SDValue N1 = N->getOperand(1); 3666 EVT VT = N1.getValueType(); 3667 3668 // fold vector ops 3669 if (VT.isVector()) { 3670 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3671 return FoldedVOp; 3672 3673 // fold (or x, 0) -> x, vector edition 3674 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3675 return N1; 3676 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3677 return N0; 3678 3679 // fold (or x, -1) -> -1, vector edition 3680 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3681 // do not return N0, because undef node may exist in N0 3682 return DAG.getConstant( 3683 APInt::getAllOnesValue( 3684 N0.getValueType().getScalarType().getSizeInBits()), 3685 SDLoc(N), N0.getValueType()); 3686 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3687 // do not return N1, because undef node may exist in N1 3688 return DAG.getConstant( 3689 APInt::getAllOnesValue( 3690 N1.getValueType().getScalarType().getSizeInBits()), 3691 SDLoc(N), N1.getValueType()); 3692 3693 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3694 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3695 // Do this only if the resulting shuffle is legal. 3696 if (isa<ShuffleVectorSDNode>(N0) && 3697 isa<ShuffleVectorSDNode>(N1) && 3698 // Avoid folding a node with illegal type. 3699 TLI.isTypeLegal(VT) && 3700 N0->getOperand(1) == N1->getOperand(1) && 3701 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3702 bool CanFold = true; 3703 unsigned NumElts = VT.getVectorNumElements(); 3704 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3705 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3706 // We construct two shuffle masks: 3707 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3708 // and N1 as the second operand. 3709 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3710 // and N0 as the second operand. 3711 // We do this because OR is commutable and therefore there might be 3712 // two ways to fold this node into a shuffle. 3713 SmallVector<int,4> Mask1; 3714 SmallVector<int,4> Mask2; 3715 3716 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3717 int M0 = SV0->getMaskElt(i); 3718 int M1 = SV1->getMaskElt(i); 3719 3720 // Both shuffle indexes are undef. Propagate Undef. 3721 if (M0 < 0 && M1 < 0) { 3722 Mask1.push_back(M0); 3723 Mask2.push_back(M0); 3724 continue; 3725 } 3726 3727 if (M0 < 0 || M1 < 0 || 3728 (M0 < (int)NumElts && M1 < (int)NumElts) || 3729 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3730 CanFold = false; 3731 break; 3732 } 3733 3734 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3735 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3736 } 3737 3738 if (CanFold) { 3739 // Fold this sequence only if the resulting shuffle is 'legal'. 3740 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3741 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3742 N1->getOperand(0), &Mask1[0]); 3743 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3744 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3745 N0->getOperand(0), &Mask2[0]); 3746 } 3747 } 3748 } 3749 3750 // fold (or c1, c2) -> c1|c2 3751 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3752 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3753 if (N0C && N1C && !N1C->isOpaque()) 3754 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3755 // canonicalize constant to RHS 3756 if (isConstantIntBuildVectorOrConstantInt(N0) && 3757 !isConstantIntBuildVectorOrConstantInt(N1)) 3758 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3759 // fold (or x, 0) -> x 3760 if (isNullConstant(N1)) 3761 return N0; 3762 // fold (or x, -1) -> -1 3763 if (isAllOnesConstant(N1)) 3764 return N1; 3765 // fold (or x, c) -> c iff (x & ~c) == 0 3766 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3767 return N1; 3768 3769 if (SDValue Combined = visitORLike(N0, N1, N)) 3770 return Combined; 3771 3772 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3773 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3774 return BSwap; 3775 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3776 return BSwap; 3777 3778 // reassociate or 3779 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3780 return ROR; 3781 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3782 // iff (c1 & c2) == 0. 3783 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3784 isa<ConstantSDNode>(N0.getOperand(1))) { 3785 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3786 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3787 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3788 N1C, C1)) 3789 return DAG.getNode( 3790 ISD::AND, SDLoc(N), VT, 3791 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3792 return SDValue(); 3793 } 3794 } 3795 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3796 if (N0.getOpcode() == N1.getOpcode()) 3797 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3798 return Tmp; 3799 3800 // See if this is some rotate idiom. 3801 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3802 return SDValue(Rot, 0); 3803 3804 // Simplify the operands using demanded-bits information. 3805 if (!VT.isVector() && 3806 SimplifyDemandedBits(SDValue(N, 0))) 3807 return SDValue(N, 0); 3808 3809 return SDValue(); 3810 } 3811 3812 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3813 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3814 if (Op.getOpcode() == ISD::AND) { 3815 if (isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3816 Mask = Op.getOperand(1); 3817 Op = Op.getOperand(0); 3818 } else { 3819 return false; 3820 } 3821 } 3822 3823 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3824 Shift = Op; 3825 return true; 3826 } 3827 3828 return false; 3829 } 3830 3831 // Return true if we can prove that, whenever Neg and Pos are both in the 3832 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 3833 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3834 // 3835 // (or (shift1 X, Neg), (shift2 X, Pos)) 3836 // 3837 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3838 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 3839 // to consider shift amounts with defined behavior. 3840 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 3841 // If EltSize is a power of 2 then: 3842 // 3843 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 3844 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 3845 // 3846 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 3847 // for the stronger condition: 3848 // 3849 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 3850 // 3851 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 3852 // we can just replace Neg with Neg' for the rest of the function. 3853 // 3854 // In other cases we check for the even stronger condition: 3855 // 3856 // Neg == EltSize - Pos [B] 3857 // 3858 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3859 // behavior if Pos == 0 (and consequently Neg == EltSize). 3860 // 3861 // We could actually use [A] whenever EltSize is a power of 2, but the 3862 // only extra cases that it would match are those uninteresting ones 3863 // where Neg and Pos are never in range at the same time. E.g. for 3864 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3865 // as well as (sub 32, Pos), but: 3866 // 3867 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3868 // 3869 // always invokes undefined behavior for 32-bit X. 3870 // 3871 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 3872 unsigned MaskLoBits = 0; 3873 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 3874 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 3875 if (NegC->getAPIntValue() == EltSize - 1) { 3876 Neg = Neg.getOperand(0); 3877 MaskLoBits = Log2_64(EltSize); 3878 } 3879 } 3880 } 3881 3882 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3883 if (Neg.getOpcode() != ISD::SUB) 3884 return 0; 3885 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 3886 if (!NegC) 3887 return 0; 3888 SDValue NegOp1 = Neg.getOperand(1); 3889 3890 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 3891 // Pos'. The truncation is redundant for the purpose of the equality. 3892 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 3893 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3894 if (PosC->getAPIntValue() == EltSize - 1) 3895 Pos = Pos.getOperand(0); 3896 3897 // The condition we need is now: 3898 // 3899 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 3900 // 3901 // If NegOp1 == Pos then we need: 3902 // 3903 // EltSize & Mask == NegC & Mask 3904 // 3905 // (because "x & Mask" is a truncation and distributes through subtraction). 3906 APInt Width; 3907 if (Pos == NegOp1) 3908 Width = NegC->getAPIntValue(); 3909 3910 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3911 // Then the condition we want to prove becomes: 3912 // 3913 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 3914 // 3915 // which, again because "x & Mask" is a truncation, becomes: 3916 // 3917 // NegC & Mask == (EltSize - PosC) & Mask 3918 // EltSize & Mask == (NegC + PosC) & Mask 3919 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 3920 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3921 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 3922 else 3923 return false; 3924 } else 3925 return false; 3926 3927 // Now we just need to check that EltSize & Mask == Width & Mask. 3928 if (MaskLoBits) 3929 // EltSize & Mask is 0 since Mask is EltSize - 1. 3930 return Width.getLoBits(MaskLoBits) == 0; 3931 return Width == EltSize; 3932 } 3933 3934 // A subroutine of MatchRotate used once we have found an OR of two opposite 3935 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3936 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3937 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3938 // Neg with outer conversions stripped away. 3939 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3940 SDValue Neg, SDValue InnerPos, 3941 SDValue InnerNeg, unsigned PosOpcode, 3942 unsigned NegOpcode, SDLoc DL) { 3943 // fold (or (shl x, (*ext y)), 3944 // (srl x, (*ext (sub 32, y)))) -> 3945 // (rotl x, y) or (rotr x, (sub 32, y)) 3946 // 3947 // fold (or (shl x, (*ext (sub 32, y))), 3948 // (srl x, (*ext y))) -> 3949 // (rotr x, y) or (rotl x, (sub 32, y)) 3950 EVT VT = Shifted.getValueType(); 3951 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 3952 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3953 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3954 HasPos ? Pos : Neg).getNode(); 3955 } 3956 3957 return nullptr; 3958 } 3959 3960 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3961 // idioms for rotate, and if the target supports rotation instructions, generate 3962 // a rot[lr]. 3963 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3964 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3965 EVT VT = LHS.getValueType(); 3966 if (!TLI.isTypeLegal(VT)) return nullptr; 3967 3968 // The target must have at least one rotate flavor. 3969 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3970 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3971 if (!HasROTL && !HasROTR) return nullptr; 3972 3973 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3974 SDValue LHSShift; // The shift. 3975 SDValue LHSMask; // AND value if any. 3976 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3977 return nullptr; // Not part of a rotate. 3978 3979 SDValue RHSShift; // The shift. 3980 SDValue RHSMask; // AND value if any. 3981 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3982 return nullptr; // Not part of a rotate. 3983 3984 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3985 return nullptr; // Not shifting the same value. 3986 3987 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3988 return nullptr; // Shifts must disagree. 3989 3990 // Canonicalize shl to left side in a shl/srl pair. 3991 if (RHSShift.getOpcode() == ISD::SHL) { 3992 std::swap(LHS, RHS); 3993 std::swap(LHSShift, RHSShift); 3994 std::swap(LHSMask, RHSMask); 3995 } 3996 3997 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 3998 SDValue LHSShiftArg = LHSShift.getOperand(0); 3999 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4000 SDValue RHSShiftArg = RHSShift.getOperand(0); 4001 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4002 4003 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4004 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4005 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4006 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4007 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4008 if ((LShVal + RShVal) != EltSizeInBits) 4009 return nullptr; 4010 4011 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4012 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4013 4014 // If there is an AND of either shifted operand, apply it to the result. 4015 if (LHSMask.getNode() || RHSMask.getNode()) { 4016 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4017 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4018 4019 if (LHSMask.getNode()) { 4020 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4021 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4022 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4023 DAG.getConstant(RHSBits, DL, VT))); 4024 } 4025 if (RHSMask.getNode()) { 4026 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4027 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4028 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4029 DAG.getConstant(LHSBits, DL, VT))); 4030 } 4031 4032 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4033 } 4034 4035 return Rot.getNode(); 4036 } 4037 4038 // If there is a mask here, and we have a variable shift, we can't be sure 4039 // that we're masking out the right stuff. 4040 if (LHSMask.getNode() || RHSMask.getNode()) 4041 return nullptr; 4042 4043 // If the shift amount is sign/zext/any-extended just peel it off. 4044 SDValue LExtOp0 = LHSShiftAmt; 4045 SDValue RExtOp0 = RHSShiftAmt; 4046 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4047 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4048 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4049 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4050 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4051 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4052 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4053 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4054 LExtOp0 = LHSShiftAmt.getOperand(0); 4055 RExtOp0 = RHSShiftAmt.getOperand(0); 4056 } 4057 4058 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4059 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4060 if (TryL) 4061 return TryL; 4062 4063 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4064 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4065 if (TryR) 4066 return TryR; 4067 4068 return nullptr; 4069 } 4070 4071 SDValue DAGCombiner::visitXOR(SDNode *N) { 4072 SDValue N0 = N->getOperand(0); 4073 SDValue N1 = N->getOperand(1); 4074 EVT VT = N0.getValueType(); 4075 4076 // fold vector ops 4077 if (VT.isVector()) { 4078 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4079 return FoldedVOp; 4080 4081 // fold (xor x, 0) -> x, vector edition 4082 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4083 return N1; 4084 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4085 return N0; 4086 } 4087 4088 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4089 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 4090 return DAG.getConstant(0, SDLoc(N), VT); 4091 // fold (xor x, undef) -> undef 4092 if (N0.getOpcode() == ISD::UNDEF) 4093 return N0; 4094 if (N1.getOpcode() == ISD::UNDEF) 4095 return N1; 4096 // fold (xor c1, c2) -> c1^c2 4097 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4098 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4099 if (N0C && N1C) 4100 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4101 // canonicalize constant to RHS 4102 if (isConstantIntBuildVectorOrConstantInt(N0) && 4103 !isConstantIntBuildVectorOrConstantInt(N1)) 4104 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4105 // fold (xor x, 0) -> x 4106 if (isNullConstant(N1)) 4107 return N0; 4108 // reassociate xor 4109 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4110 return RXOR; 4111 4112 // fold !(x cc y) -> (x !cc y) 4113 SDValue LHS, RHS, CC; 4114 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4115 bool isInt = LHS.getValueType().isInteger(); 4116 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4117 isInt); 4118 4119 if (!LegalOperations || 4120 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4121 switch (N0.getOpcode()) { 4122 default: 4123 llvm_unreachable("Unhandled SetCC Equivalent!"); 4124 case ISD::SETCC: 4125 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4126 case ISD::SELECT_CC: 4127 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4128 N0.getOperand(3), NotCC); 4129 } 4130 } 4131 } 4132 4133 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4134 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4135 N0.getNode()->hasOneUse() && 4136 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4137 SDValue V = N0.getOperand(0); 4138 SDLoc DL(N0); 4139 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4140 DAG.getConstant(1, DL, V.getValueType())); 4141 AddToWorklist(V.getNode()); 4142 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4143 } 4144 4145 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4146 if (isOneConstant(N1) && VT == MVT::i1 && 4147 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4148 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4149 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4150 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4151 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4152 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4153 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4154 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4155 } 4156 } 4157 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4158 if (isAllOnesConstant(N1) && 4159 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4160 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4161 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4162 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4163 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4164 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4165 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4166 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4167 } 4168 } 4169 // fold (xor (and x, y), y) -> (and (not x), y) 4170 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4171 N0->getOperand(1) == N1) { 4172 SDValue X = N0->getOperand(0); 4173 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4174 AddToWorklist(NotX.getNode()); 4175 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4176 } 4177 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4178 if (N1C && N0.getOpcode() == ISD::XOR) { 4179 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4180 SDLoc DL(N); 4181 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4182 DAG.getConstant(N1C->getAPIntValue() ^ 4183 N00C->getAPIntValue(), DL, VT)); 4184 } 4185 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4186 SDLoc DL(N); 4187 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4188 DAG.getConstant(N1C->getAPIntValue() ^ 4189 N01C->getAPIntValue(), DL, VT)); 4190 } 4191 } 4192 // fold (xor x, x) -> 0 4193 if (N0 == N1) 4194 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4195 4196 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4197 // Here is a concrete example of this equivalence: 4198 // i16 x == 14 4199 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4200 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4201 // 4202 // => 4203 // 4204 // i16 ~1 == 0b1111111111111110 4205 // i16 rol(~1, 14) == 0b1011111111111111 4206 // 4207 // Some additional tips to help conceptualize this transform: 4208 // - Try to see the operation as placing a single zero in a value of all ones. 4209 // - There exists no value for x which would allow the result to contain zero. 4210 // - Values of x larger than the bitwidth are undefined and do not require a 4211 // consistent result. 4212 // - Pushing the zero left requires shifting one bits in from the right. 4213 // A rotate left of ~1 is a nice way of achieving the desired result. 4214 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4215 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4216 SDLoc DL(N); 4217 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4218 N0.getOperand(1)); 4219 } 4220 4221 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4222 if (N0.getOpcode() == N1.getOpcode()) 4223 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4224 return Tmp; 4225 4226 // Simplify the expression using non-local knowledge. 4227 if (!VT.isVector() && 4228 SimplifyDemandedBits(SDValue(N, 0))) 4229 return SDValue(N, 0); 4230 4231 return SDValue(); 4232 } 4233 4234 /// Handle transforms common to the three shifts, when the shift amount is a 4235 /// constant. 4236 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4237 SDNode *LHS = N->getOperand(0).getNode(); 4238 if (!LHS->hasOneUse()) return SDValue(); 4239 4240 // We want to pull some binops through shifts, so that we have (and (shift)) 4241 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4242 // thing happens with address calculations, so it's important to canonicalize 4243 // it. 4244 bool HighBitSet = false; // Can we transform this if the high bit is set? 4245 4246 switch (LHS->getOpcode()) { 4247 default: return SDValue(); 4248 case ISD::OR: 4249 case ISD::XOR: 4250 HighBitSet = false; // We can only transform sra if the high bit is clear. 4251 break; 4252 case ISD::AND: 4253 HighBitSet = true; // We can only transform sra if the high bit is set. 4254 break; 4255 case ISD::ADD: 4256 if (N->getOpcode() != ISD::SHL) 4257 return SDValue(); // only shl(add) not sr[al](add). 4258 HighBitSet = false; // We can only transform sra if the high bit is clear. 4259 break; 4260 } 4261 4262 // We require the RHS of the binop to be a constant and not opaque as well. 4263 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4264 if (!BinOpCst) return SDValue(); 4265 4266 // FIXME: disable this unless the input to the binop is a shift by a constant. 4267 // If it is not a shift, it pessimizes some common cases like: 4268 // 4269 // void foo(int *X, int i) { X[i & 1235] = 1; } 4270 // int bar(int *X, int i) { return X[i & 255]; } 4271 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4272 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4273 BinOpLHSVal->getOpcode() != ISD::SRA && 4274 BinOpLHSVal->getOpcode() != ISD::SRL) || 4275 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4276 return SDValue(); 4277 4278 EVT VT = N->getValueType(0); 4279 4280 // If this is a signed shift right, and the high bit is modified by the 4281 // logical operation, do not perform the transformation. The highBitSet 4282 // boolean indicates the value of the high bit of the constant which would 4283 // cause it to be modified for this operation. 4284 if (N->getOpcode() == ISD::SRA) { 4285 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4286 if (BinOpRHSSignSet != HighBitSet) 4287 return SDValue(); 4288 } 4289 4290 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4291 return SDValue(); 4292 4293 // Fold the constants, shifting the binop RHS by the shift amount. 4294 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4295 N->getValueType(0), 4296 LHS->getOperand(1), N->getOperand(1)); 4297 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4298 4299 // Create the new shift. 4300 SDValue NewShift = DAG.getNode(N->getOpcode(), 4301 SDLoc(LHS->getOperand(0)), 4302 VT, LHS->getOperand(0), N->getOperand(1)); 4303 4304 // Create the new binop. 4305 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4306 } 4307 4308 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4309 assert(N->getOpcode() == ISD::TRUNCATE); 4310 assert(N->getOperand(0).getOpcode() == ISD::AND); 4311 4312 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4313 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4314 SDValue N01 = N->getOperand(0).getOperand(1); 4315 4316 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4317 if (!N01C->isOpaque()) { 4318 EVT TruncVT = N->getValueType(0); 4319 SDValue N00 = N->getOperand(0).getOperand(0); 4320 APInt TruncC = N01C->getAPIntValue(); 4321 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4322 SDLoc DL(N); 4323 4324 return DAG.getNode(ISD::AND, DL, TruncVT, 4325 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4326 DAG.getConstant(TruncC, DL, TruncVT)); 4327 } 4328 } 4329 } 4330 4331 return SDValue(); 4332 } 4333 4334 SDValue DAGCombiner::visitRotate(SDNode *N) { 4335 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4336 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4337 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4338 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4339 if (NewOp1.getNode()) 4340 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4341 N->getOperand(0), NewOp1); 4342 } 4343 return SDValue(); 4344 } 4345 4346 SDValue DAGCombiner::visitSHL(SDNode *N) { 4347 SDValue N0 = N->getOperand(0); 4348 SDValue N1 = N->getOperand(1); 4349 EVT VT = N0.getValueType(); 4350 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4351 4352 // fold vector ops 4353 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4354 if (VT.isVector()) { 4355 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4356 return FoldedVOp; 4357 4358 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4359 // If setcc produces all-one true value then: 4360 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4361 if (N1CV && N1CV->isConstant()) { 4362 if (N0.getOpcode() == ISD::AND) { 4363 SDValue N00 = N0->getOperand(0); 4364 SDValue N01 = N0->getOperand(1); 4365 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4366 4367 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4368 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4369 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4370 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4371 N01CV, N1CV)) 4372 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4373 } 4374 } else { 4375 N1C = isConstOrConstSplat(N1); 4376 } 4377 } 4378 } 4379 4380 // fold (shl c1, c2) -> c1<<c2 4381 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4382 if (N0C && N1C && !N1C->isOpaque()) 4383 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4384 // fold (shl 0, x) -> 0 4385 if (isNullConstant(N0)) 4386 return N0; 4387 // fold (shl x, c >= size(x)) -> undef 4388 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4389 return DAG.getUNDEF(VT); 4390 // fold (shl x, 0) -> x 4391 if (N1C && N1C->isNullValue()) 4392 return N0; 4393 // fold (shl undef, x) -> 0 4394 if (N0.getOpcode() == ISD::UNDEF) 4395 return DAG.getConstant(0, SDLoc(N), VT); 4396 // if (shl x, c) is known to be zero, return 0 4397 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4398 APInt::getAllOnesValue(OpSizeInBits))) 4399 return DAG.getConstant(0, SDLoc(N), VT); 4400 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4401 if (N1.getOpcode() == ISD::TRUNCATE && 4402 N1.getOperand(0).getOpcode() == ISD::AND) { 4403 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4404 if (NewOp1.getNode()) 4405 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4406 } 4407 4408 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4409 return SDValue(N, 0); 4410 4411 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4412 if (N1C && N0.getOpcode() == ISD::SHL) { 4413 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4414 uint64_t c1 = N0C1->getZExtValue(); 4415 uint64_t c2 = N1C->getZExtValue(); 4416 SDLoc DL(N); 4417 if (c1 + c2 >= OpSizeInBits) 4418 return DAG.getConstant(0, DL, VT); 4419 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4420 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4421 } 4422 } 4423 4424 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4425 // For this to be valid, the second form must not preserve any of the bits 4426 // that are shifted out by the inner shift in the first form. This means 4427 // the outer shift size must be >= the number of bits added by the ext. 4428 // As a corollary, we don't care what kind of ext it is. 4429 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4430 N0.getOpcode() == ISD::ANY_EXTEND || 4431 N0.getOpcode() == ISD::SIGN_EXTEND) && 4432 N0.getOperand(0).getOpcode() == ISD::SHL) { 4433 SDValue N0Op0 = N0.getOperand(0); 4434 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4435 uint64_t c1 = N0Op0C1->getZExtValue(); 4436 uint64_t c2 = N1C->getZExtValue(); 4437 EVT InnerShiftVT = N0Op0.getValueType(); 4438 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4439 if (c2 >= OpSizeInBits - InnerShiftSize) { 4440 SDLoc DL(N0); 4441 if (c1 + c2 >= OpSizeInBits) 4442 return DAG.getConstant(0, DL, VT); 4443 return DAG.getNode(ISD::SHL, DL, VT, 4444 DAG.getNode(N0.getOpcode(), DL, VT, 4445 N0Op0->getOperand(0)), 4446 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4447 } 4448 } 4449 } 4450 4451 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4452 // Only fold this if the inner zext has no other uses to avoid increasing 4453 // the total number of instructions. 4454 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4455 N0.getOperand(0).getOpcode() == ISD::SRL) { 4456 SDValue N0Op0 = N0.getOperand(0); 4457 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4458 uint64_t c1 = N0Op0C1->getZExtValue(); 4459 if (c1 < VT.getScalarSizeInBits()) { 4460 uint64_t c2 = N1C->getZExtValue(); 4461 if (c1 == c2) { 4462 SDValue NewOp0 = N0.getOperand(0); 4463 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4464 SDLoc DL(N); 4465 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4466 NewOp0, 4467 DAG.getConstant(c2, DL, CountVT)); 4468 AddToWorklist(NewSHL.getNode()); 4469 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4470 } 4471 } 4472 } 4473 } 4474 4475 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4476 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4477 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4478 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4479 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4480 uint64_t C1 = N0C1->getZExtValue(); 4481 uint64_t C2 = N1C->getZExtValue(); 4482 SDLoc DL(N); 4483 if (C1 <= C2) 4484 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4485 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4486 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4487 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4488 } 4489 } 4490 4491 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4492 // (and (srl x, (sub c1, c2), MASK) 4493 // Only fold this if the inner shift has no other uses -- if it does, folding 4494 // this will increase the total number of instructions. 4495 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4496 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4497 uint64_t c1 = N0C1->getZExtValue(); 4498 if (c1 < OpSizeInBits) { 4499 uint64_t c2 = N1C->getZExtValue(); 4500 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4501 SDValue Shift; 4502 if (c2 > c1) { 4503 Mask = Mask.shl(c2 - c1); 4504 SDLoc DL(N); 4505 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4506 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4507 } else { 4508 Mask = Mask.lshr(c1 - c2); 4509 SDLoc DL(N); 4510 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4511 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4512 } 4513 SDLoc DL(N0); 4514 return DAG.getNode(ISD::AND, DL, VT, Shift, 4515 DAG.getConstant(Mask, DL, VT)); 4516 } 4517 } 4518 } 4519 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4520 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4521 unsigned BitSize = VT.getScalarSizeInBits(); 4522 SDLoc DL(N); 4523 SDValue HiBitsMask = 4524 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4525 BitSize - N1C->getZExtValue()), 4526 DL, VT); 4527 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4528 HiBitsMask); 4529 } 4530 4531 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4532 // Variant of version done on multiply, except mul by a power of 2 is turned 4533 // into a shift. 4534 APInt Val; 4535 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4536 (isa<ConstantSDNode>(N0.getOperand(1)) || 4537 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4538 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4539 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4540 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4541 } 4542 4543 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4544 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4545 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4546 if (SDValue Folded = 4547 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4548 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4549 } 4550 } 4551 4552 if (N1C && !N1C->isOpaque()) 4553 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4554 return NewSHL; 4555 4556 return SDValue(); 4557 } 4558 4559 SDValue DAGCombiner::visitSRA(SDNode *N) { 4560 SDValue N0 = N->getOperand(0); 4561 SDValue N1 = N->getOperand(1); 4562 EVT VT = N0.getValueType(); 4563 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4564 4565 // fold vector ops 4566 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4567 if (VT.isVector()) { 4568 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4569 return FoldedVOp; 4570 4571 N1C = isConstOrConstSplat(N1); 4572 } 4573 4574 // fold (sra c1, c2) -> (sra c1, c2) 4575 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4576 if (N0C && N1C && !N1C->isOpaque()) 4577 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4578 // fold (sra 0, x) -> 0 4579 if (isNullConstant(N0)) 4580 return N0; 4581 // fold (sra -1, x) -> -1 4582 if (isAllOnesConstant(N0)) 4583 return N0; 4584 // fold (sra x, (setge c, size(x))) -> undef 4585 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4586 return DAG.getUNDEF(VT); 4587 // fold (sra x, 0) -> x 4588 if (N1C && N1C->isNullValue()) 4589 return N0; 4590 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4591 // sext_inreg. 4592 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4593 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4594 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4595 if (VT.isVector()) 4596 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4597 ExtVT, VT.getVectorNumElements()); 4598 if ((!LegalOperations || 4599 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4600 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4601 N0.getOperand(0), DAG.getValueType(ExtVT)); 4602 } 4603 4604 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4605 if (N1C && N0.getOpcode() == ISD::SRA) { 4606 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4607 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4608 if (Sum >= OpSizeInBits) 4609 Sum = OpSizeInBits - 1; 4610 SDLoc DL(N); 4611 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4612 DAG.getConstant(Sum, DL, N1.getValueType())); 4613 } 4614 } 4615 4616 // fold (sra (shl X, m), (sub result_size, n)) 4617 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4618 // result_size - n != m. 4619 // If truncate is free for the target sext(shl) is likely to result in better 4620 // code. 4621 if (N0.getOpcode() == ISD::SHL && N1C) { 4622 // Get the two constanst of the shifts, CN0 = m, CN = n. 4623 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4624 if (N01C) { 4625 LLVMContext &Ctx = *DAG.getContext(); 4626 // Determine what the truncate's result bitsize and type would be. 4627 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4628 4629 if (VT.isVector()) 4630 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4631 4632 // Determine the residual right-shift amount. 4633 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4634 4635 // If the shift is not a no-op (in which case this should be just a sign 4636 // extend already), the truncated to type is legal, sign_extend is legal 4637 // on that type, and the truncate to that type is both legal and free, 4638 // perform the transform. 4639 if ((ShiftAmt > 0) && 4640 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4641 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4642 TLI.isTruncateFree(VT, TruncVT)) { 4643 4644 SDLoc DL(N); 4645 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4646 getShiftAmountTy(N0.getOperand(0).getValueType())); 4647 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4648 N0.getOperand(0), Amt); 4649 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4650 Shift); 4651 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4652 N->getValueType(0), Trunc); 4653 } 4654 } 4655 } 4656 4657 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4658 if (N1.getOpcode() == ISD::TRUNCATE && 4659 N1.getOperand(0).getOpcode() == ISD::AND) { 4660 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4661 if (NewOp1.getNode()) 4662 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4663 } 4664 4665 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4666 // if c1 is equal to the number of bits the trunc removes 4667 if (N0.getOpcode() == ISD::TRUNCATE && 4668 (N0.getOperand(0).getOpcode() == ISD::SRL || 4669 N0.getOperand(0).getOpcode() == ISD::SRA) && 4670 N0.getOperand(0).hasOneUse() && 4671 N0.getOperand(0).getOperand(1).hasOneUse() && 4672 N1C) { 4673 SDValue N0Op0 = N0.getOperand(0); 4674 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4675 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4676 EVT LargeVT = N0Op0.getValueType(); 4677 4678 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4679 SDLoc DL(N); 4680 SDValue Amt = 4681 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4682 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4683 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4684 N0Op0.getOperand(0), Amt); 4685 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4686 } 4687 } 4688 } 4689 4690 // Simplify, based on bits shifted out of the LHS. 4691 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4692 return SDValue(N, 0); 4693 4694 4695 // If the sign bit is known to be zero, switch this to a SRL. 4696 if (DAG.SignBitIsZero(N0)) 4697 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4698 4699 if (N1C && !N1C->isOpaque()) 4700 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4701 return NewSRA; 4702 4703 return SDValue(); 4704 } 4705 4706 SDValue DAGCombiner::visitSRL(SDNode *N) { 4707 SDValue N0 = N->getOperand(0); 4708 SDValue N1 = N->getOperand(1); 4709 EVT VT = N0.getValueType(); 4710 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4711 4712 // fold vector ops 4713 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4714 if (VT.isVector()) { 4715 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4716 return FoldedVOp; 4717 4718 N1C = isConstOrConstSplat(N1); 4719 } 4720 4721 // fold (srl c1, c2) -> c1 >>u c2 4722 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4723 if (N0C && N1C && !N1C->isOpaque()) 4724 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4725 // fold (srl 0, x) -> 0 4726 if (isNullConstant(N0)) 4727 return N0; 4728 // fold (srl x, c >= size(x)) -> undef 4729 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4730 return DAG.getUNDEF(VT); 4731 // fold (srl x, 0) -> x 4732 if (N1C && N1C->isNullValue()) 4733 return N0; 4734 // if (srl x, c) is known to be zero, return 0 4735 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4736 APInt::getAllOnesValue(OpSizeInBits))) 4737 return DAG.getConstant(0, SDLoc(N), VT); 4738 4739 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4740 if (N1C && N0.getOpcode() == ISD::SRL) { 4741 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4742 uint64_t c1 = N01C->getZExtValue(); 4743 uint64_t c2 = N1C->getZExtValue(); 4744 SDLoc DL(N); 4745 if (c1 + c2 >= OpSizeInBits) 4746 return DAG.getConstant(0, DL, VT); 4747 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4748 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4749 } 4750 } 4751 4752 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4753 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4754 N0.getOperand(0).getOpcode() == ISD::SRL && 4755 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4756 uint64_t c1 = 4757 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4758 uint64_t c2 = N1C->getZExtValue(); 4759 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4760 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4761 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4762 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4763 if (c1 + OpSizeInBits == InnerShiftSize) { 4764 SDLoc DL(N0); 4765 if (c1 + c2 >= InnerShiftSize) 4766 return DAG.getConstant(0, DL, VT); 4767 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4768 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4769 N0.getOperand(0)->getOperand(0), 4770 DAG.getConstant(c1 + c2, DL, 4771 ShiftCountVT))); 4772 } 4773 } 4774 4775 // fold (srl (shl x, c), c) -> (and x, cst2) 4776 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4777 unsigned BitSize = N0.getScalarValueSizeInBits(); 4778 if (BitSize <= 64) { 4779 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4780 SDLoc DL(N); 4781 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4782 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4783 } 4784 } 4785 4786 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4787 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4788 // Shifting in all undef bits? 4789 EVT SmallVT = N0.getOperand(0).getValueType(); 4790 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4791 if (N1C->getZExtValue() >= BitSize) 4792 return DAG.getUNDEF(VT); 4793 4794 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4795 uint64_t ShiftAmt = N1C->getZExtValue(); 4796 SDLoc DL0(N0); 4797 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4798 N0.getOperand(0), 4799 DAG.getConstant(ShiftAmt, DL0, 4800 getShiftAmountTy(SmallVT))); 4801 AddToWorklist(SmallShift.getNode()); 4802 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4803 SDLoc DL(N); 4804 return DAG.getNode(ISD::AND, DL, VT, 4805 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4806 DAG.getConstant(Mask, DL, VT)); 4807 } 4808 } 4809 4810 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4811 // bit, which is unmodified by sra. 4812 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4813 if (N0.getOpcode() == ISD::SRA) 4814 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4815 } 4816 4817 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4818 if (N1C && N0.getOpcode() == ISD::CTLZ && 4819 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4820 APInt KnownZero, KnownOne; 4821 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4822 4823 // If any of the input bits are KnownOne, then the input couldn't be all 4824 // zeros, thus the result of the srl will always be zero. 4825 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4826 4827 // If all of the bits input the to ctlz node are known to be zero, then 4828 // the result of the ctlz is "32" and the result of the shift is one. 4829 APInt UnknownBits = ~KnownZero; 4830 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4831 4832 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4833 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4834 // Okay, we know that only that the single bit specified by UnknownBits 4835 // could be set on input to the CTLZ node. If this bit is set, the SRL 4836 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4837 // to an SRL/XOR pair, which is likely to simplify more. 4838 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4839 SDValue Op = N0.getOperand(0); 4840 4841 if (ShAmt) { 4842 SDLoc DL(N0); 4843 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4844 DAG.getConstant(ShAmt, DL, 4845 getShiftAmountTy(Op.getValueType()))); 4846 AddToWorklist(Op.getNode()); 4847 } 4848 4849 SDLoc DL(N); 4850 return DAG.getNode(ISD::XOR, DL, VT, 4851 Op, DAG.getConstant(1, DL, VT)); 4852 } 4853 } 4854 4855 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4856 if (N1.getOpcode() == ISD::TRUNCATE && 4857 N1.getOperand(0).getOpcode() == ISD::AND) { 4858 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4859 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4860 } 4861 4862 // fold operands of srl based on knowledge that the low bits are not 4863 // demanded. 4864 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4865 return SDValue(N, 0); 4866 4867 if (N1C && !N1C->isOpaque()) 4868 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4869 return NewSRL; 4870 4871 // Attempt to convert a srl of a load into a narrower zero-extending load. 4872 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4873 return NarrowLoad; 4874 4875 // Here is a common situation. We want to optimize: 4876 // 4877 // %a = ... 4878 // %b = and i32 %a, 2 4879 // %c = srl i32 %b, 1 4880 // brcond i32 %c ... 4881 // 4882 // into 4883 // 4884 // %a = ... 4885 // %b = and %a, 2 4886 // %c = setcc eq %b, 0 4887 // brcond %c ... 4888 // 4889 // However when after the source operand of SRL is optimized into AND, the SRL 4890 // itself may not be optimized further. Look for it and add the BRCOND into 4891 // the worklist. 4892 if (N->hasOneUse()) { 4893 SDNode *Use = *N->use_begin(); 4894 if (Use->getOpcode() == ISD::BRCOND) 4895 AddToWorklist(Use); 4896 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4897 // Also look pass the truncate. 4898 Use = *Use->use_begin(); 4899 if (Use->getOpcode() == ISD::BRCOND) 4900 AddToWorklist(Use); 4901 } 4902 } 4903 4904 return SDValue(); 4905 } 4906 4907 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4908 SDValue N0 = N->getOperand(0); 4909 EVT VT = N->getValueType(0); 4910 4911 // fold (bswap c1) -> c2 4912 if (isConstantIntBuildVectorOrConstantInt(N0)) 4913 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4914 // fold (bswap (bswap x)) -> x 4915 if (N0.getOpcode() == ISD::BSWAP) 4916 return N0->getOperand(0); 4917 return SDValue(); 4918 } 4919 4920 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4921 SDValue N0 = N->getOperand(0); 4922 EVT VT = N->getValueType(0); 4923 4924 // fold (ctlz c1) -> c2 4925 if (isConstantIntBuildVectorOrConstantInt(N0)) 4926 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4927 return SDValue(); 4928 } 4929 4930 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4931 SDValue N0 = N->getOperand(0); 4932 EVT VT = N->getValueType(0); 4933 4934 // fold (ctlz_zero_undef c1) -> c2 4935 if (isConstantIntBuildVectorOrConstantInt(N0)) 4936 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4937 return SDValue(); 4938 } 4939 4940 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4941 SDValue N0 = N->getOperand(0); 4942 EVT VT = N->getValueType(0); 4943 4944 // fold (cttz c1) -> c2 4945 if (isConstantIntBuildVectorOrConstantInt(N0)) 4946 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4947 return SDValue(); 4948 } 4949 4950 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4951 SDValue N0 = N->getOperand(0); 4952 EVT VT = N->getValueType(0); 4953 4954 // fold (cttz_zero_undef c1) -> c2 4955 if (isConstantIntBuildVectorOrConstantInt(N0)) 4956 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4957 return SDValue(); 4958 } 4959 4960 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4961 SDValue N0 = N->getOperand(0); 4962 EVT VT = N->getValueType(0); 4963 4964 // fold (ctpop c1) -> c2 4965 if (isConstantIntBuildVectorOrConstantInt(N0)) 4966 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4967 return SDValue(); 4968 } 4969 4970 4971 /// \brief Generate Min/Max node 4972 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4973 SDValue True, SDValue False, 4974 ISD::CondCode CC, const TargetLowering &TLI, 4975 SelectionDAG &DAG) { 4976 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4977 return SDValue(); 4978 4979 switch (CC) { 4980 case ISD::SETOLT: 4981 case ISD::SETOLE: 4982 case ISD::SETLT: 4983 case ISD::SETLE: 4984 case ISD::SETULT: 4985 case ISD::SETULE: { 4986 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4987 if (TLI.isOperationLegal(Opcode, VT)) 4988 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4989 return SDValue(); 4990 } 4991 case ISD::SETOGT: 4992 case ISD::SETOGE: 4993 case ISD::SETGT: 4994 case ISD::SETGE: 4995 case ISD::SETUGT: 4996 case ISD::SETUGE: { 4997 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4998 if (TLI.isOperationLegal(Opcode, VT)) 4999 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5000 return SDValue(); 5001 } 5002 default: 5003 return SDValue(); 5004 } 5005 } 5006 5007 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5008 SDValue N0 = N->getOperand(0); 5009 SDValue N1 = N->getOperand(1); 5010 SDValue N2 = N->getOperand(2); 5011 EVT VT = N->getValueType(0); 5012 EVT VT0 = N0.getValueType(); 5013 5014 // fold (select C, X, X) -> X 5015 if (N1 == N2) 5016 return N1; 5017 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5018 // fold (select true, X, Y) -> X 5019 // fold (select false, X, Y) -> Y 5020 return !N0C->isNullValue() ? N1 : N2; 5021 } 5022 // fold (select C, 1, X) -> (or C, X) 5023 if (VT == MVT::i1 && isOneConstant(N1)) 5024 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5025 // fold (select C, 0, 1) -> (xor C, 1) 5026 // We can't do this reliably if integer based booleans have different contents 5027 // to floating point based booleans. This is because we can't tell whether we 5028 // have an integer-based boolean or a floating-point-based boolean unless we 5029 // can find the SETCC that produced it and inspect its operands. This is 5030 // fairly easy if C is the SETCC node, but it can potentially be 5031 // undiscoverable (or not reasonably discoverable). For example, it could be 5032 // in another basic block or it could require searching a complicated 5033 // expression. 5034 if (VT.isInteger() && 5035 (VT0 == MVT::i1 || (VT0.isInteger() && 5036 TLI.getBooleanContents(false, false) == 5037 TLI.getBooleanContents(false, true) && 5038 TLI.getBooleanContents(false, false) == 5039 TargetLowering::ZeroOrOneBooleanContent)) && 5040 isNullConstant(N1) && isOneConstant(N2)) { 5041 SDValue XORNode; 5042 if (VT == VT0) { 5043 SDLoc DL(N); 5044 return DAG.getNode(ISD::XOR, DL, VT0, 5045 N0, DAG.getConstant(1, DL, VT0)); 5046 } 5047 SDLoc DL0(N0); 5048 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5049 N0, DAG.getConstant(1, DL0, VT0)); 5050 AddToWorklist(XORNode.getNode()); 5051 if (VT.bitsGT(VT0)) 5052 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5053 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5054 } 5055 // fold (select C, 0, X) -> (and (not C), X) 5056 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5057 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5058 AddToWorklist(NOTNode.getNode()); 5059 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5060 } 5061 // fold (select C, X, 1) -> (or (not C), X) 5062 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5063 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5064 AddToWorklist(NOTNode.getNode()); 5065 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5066 } 5067 // fold (select C, X, 0) -> (and C, X) 5068 if (VT == MVT::i1 && isNullConstant(N2)) 5069 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5070 // fold (select X, X, Y) -> (or X, Y) 5071 // fold (select X, 1, Y) -> (or X, Y) 5072 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5073 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5074 // fold (select X, Y, X) -> (and X, Y) 5075 // fold (select X, Y, 0) -> (and X, Y) 5076 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5077 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5078 5079 // If we can fold this based on the true/false value, do so. 5080 if (SimplifySelectOps(N, N1, N2)) 5081 return SDValue(N, 0); // Don't revisit N. 5082 5083 if (VT0 == MVT::i1) { 5084 // The code in this block deals with the following 2 equivalences: 5085 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5086 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5087 // The target can specify its prefered form with the 5088 // shouldNormalizeToSelectSequence() callback. However we always transform 5089 // to the right anyway if we find the inner select exists in the DAG anyway 5090 // and we always transform to the left side if we know that we can further 5091 // optimize the combination of the conditions. 5092 bool normalizeToSequence 5093 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5094 // select (and Cond0, Cond1), X, Y 5095 // -> select Cond0, (select Cond1, X, Y), Y 5096 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5097 SDValue Cond0 = N0->getOperand(0); 5098 SDValue Cond1 = N0->getOperand(1); 5099 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5100 N1.getValueType(), Cond1, N1, N2); 5101 if (normalizeToSequence || !InnerSelect.use_empty()) 5102 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5103 InnerSelect, N2); 5104 } 5105 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5106 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5107 SDValue Cond0 = N0->getOperand(0); 5108 SDValue Cond1 = N0->getOperand(1); 5109 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5110 N1.getValueType(), Cond1, N1, N2); 5111 if (normalizeToSequence || !InnerSelect.use_empty()) 5112 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5113 InnerSelect); 5114 } 5115 5116 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5117 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5118 SDValue N1_0 = N1->getOperand(0); 5119 SDValue N1_1 = N1->getOperand(1); 5120 SDValue N1_2 = N1->getOperand(2); 5121 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5122 // Create the actual and node if we can generate good code for it. 5123 if (!normalizeToSequence) { 5124 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5125 N0, N1_0); 5126 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5127 N1_1, N2); 5128 } 5129 // Otherwise see if we can optimize the "and" to a better pattern. 5130 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5131 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5132 N1_1, N2); 5133 } 5134 } 5135 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5136 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5137 SDValue N2_0 = N2->getOperand(0); 5138 SDValue N2_1 = N2->getOperand(1); 5139 SDValue N2_2 = N2->getOperand(2); 5140 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5141 // Create the actual or node if we can generate good code for it. 5142 if (!normalizeToSequence) { 5143 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5144 N0, N2_0); 5145 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5146 N1, N2_2); 5147 } 5148 // Otherwise see if we can optimize to a better pattern. 5149 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5150 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5151 N1, N2_2); 5152 } 5153 } 5154 } 5155 5156 // fold selects based on a setcc into other things, such as min/max/abs 5157 if (N0.getOpcode() == ISD::SETCC) { 5158 // select x, y (fcmp lt x, y) -> fminnum x, y 5159 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5160 // 5161 // This is OK if we don't care about what happens if either operand is a 5162 // NaN. 5163 // 5164 5165 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5166 // no signed zeros as well as no nans. 5167 const TargetOptions &Options = DAG.getTarget().Options; 5168 if (Options.UnsafeFPMath && 5169 VT.isFloatingPoint() && N0.hasOneUse() && 5170 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5171 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5172 5173 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5174 N0.getOperand(1), N1, N2, CC, 5175 TLI, DAG)) 5176 return FMinMax; 5177 } 5178 5179 if ((!LegalOperations && 5180 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5181 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5182 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5183 N0.getOperand(0), N0.getOperand(1), 5184 N1, N2, N0.getOperand(2)); 5185 return SimplifySelect(SDLoc(N), N0, N1, N2); 5186 } 5187 5188 return SDValue(); 5189 } 5190 5191 static 5192 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5193 SDLoc DL(N); 5194 EVT LoVT, HiVT; 5195 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5196 5197 // Split the inputs. 5198 SDValue Lo, Hi, LL, LH, RL, RH; 5199 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5200 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5201 5202 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5203 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5204 5205 return std::make_pair(Lo, Hi); 5206 } 5207 5208 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5209 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5210 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5211 SDLoc dl(N); 5212 SDValue Cond = N->getOperand(0); 5213 SDValue LHS = N->getOperand(1); 5214 SDValue RHS = N->getOperand(2); 5215 EVT VT = N->getValueType(0); 5216 int NumElems = VT.getVectorNumElements(); 5217 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5218 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5219 Cond.getOpcode() == ISD::BUILD_VECTOR); 5220 5221 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5222 // binary ones here. 5223 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5224 return SDValue(); 5225 5226 // We're sure we have an even number of elements due to the 5227 // concat_vectors we have as arguments to vselect. 5228 // Skip BV elements until we find one that's not an UNDEF 5229 // After we find an UNDEF element, keep looping until we get to half the 5230 // length of the BV and see if all the non-undef nodes are the same. 5231 ConstantSDNode *BottomHalf = nullptr; 5232 for (int i = 0; i < NumElems / 2; ++i) { 5233 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5234 continue; 5235 5236 if (BottomHalf == nullptr) 5237 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5238 else if (Cond->getOperand(i).getNode() != BottomHalf) 5239 return SDValue(); 5240 } 5241 5242 // Do the same for the second half of the BuildVector 5243 ConstantSDNode *TopHalf = nullptr; 5244 for (int i = NumElems / 2; i < NumElems; ++i) { 5245 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5246 continue; 5247 5248 if (TopHalf == nullptr) 5249 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5250 else if (Cond->getOperand(i).getNode() != TopHalf) 5251 return SDValue(); 5252 } 5253 5254 assert(TopHalf && BottomHalf && 5255 "One half of the selector was all UNDEFs and the other was all the " 5256 "same value. This should have been addressed before this function."); 5257 return DAG.getNode( 5258 ISD::CONCAT_VECTORS, dl, VT, 5259 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5260 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5261 } 5262 5263 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5264 5265 if (Level >= AfterLegalizeTypes) 5266 return SDValue(); 5267 5268 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5269 SDValue Mask = MSC->getMask(); 5270 SDValue Data = MSC->getValue(); 5271 SDLoc DL(N); 5272 5273 // If the MSCATTER data type requires splitting and the mask is provided by a 5274 // SETCC, then split both nodes and its operands before legalization. This 5275 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5276 // and enables future optimizations (e.g. min/max pattern matching on X86). 5277 if (Mask.getOpcode() != ISD::SETCC) 5278 return SDValue(); 5279 5280 // Check if any splitting is required. 5281 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5282 TargetLowering::TypeSplitVector) 5283 return SDValue(); 5284 SDValue MaskLo, MaskHi, Lo, Hi; 5285 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5286 5287 EVT LoVT, HiVT; 5288 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5289 5290 SDValue Chain = MSC->getChain(); 5291 5292 EVT MemoryVT = MSC->getMemoryVT(); 5293 unsigned Alignment = MSC->getOriginalAlignment(); 5294 5295 EVT LoMemVT, HiMemVT; 5296 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5297 5298 SDValue DataLo, DataHi; 5299 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5300 5301 SDValue BasePtr = MSC->getBasePtr(); 5302 SDValue IndexLo, IndexHi; 5303 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5304 5305 MachineMemOperand *MMO = DAG.getMachineFunction(). 5306 getMachineMemOperand(MSC->getPointerInfo(), 5307 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5308 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5309 5310 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5311 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5312 DL, OpsLo, MMO); 5313 5314 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5315 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5316 DL, OpsHi, MMO); 5317 5318 AddToWorklist(Lo.getNode()); 5319 AddToWorklist(Hi.getNode()); 5320 5321 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5322 } 5323 5324 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5325 5326 if (Level >= AfterLegalizeTypes) 5327 return SDValue(); 5328 5329 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5330 SDValue Mask = MST->getMask(); 5331 SDValue Data = MST->getValue(); 5332 SDLoc DL(N); 5333 5334 // If the MSTORE data type requires splitting and the mask is provided by a 5335 // SETCC, then split both nodes and its operands before legalization. This 5336 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5337 // and enables future optimizations (e.g. min/max pattern matching on X86). 5338 if (Mask.getOpcode() == ISD::SETCC) { 5339 5340 // Check if any splitting is required. 5341 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5342 TargetLowering::TypeSplitVector) 5343 return SDValue(); 5344 5345 SDValue MaskLo, MaskHi, Lo, Hi; 5346 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5347 5348 EVT LoVT, HiVT; 5349 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5350 5351 SDValue Chain = MST->getChain(); 5352 SDValue Ptr = MST->getBasePtr(); 5353 5354 EVT MemoryVT = MST->getMemoryVT(); 5355 unsigned Alignment = MST->getOriginalAlignment(); 5356 5357 // if Alignment is equal to the vector size, 5358 // take the half of it for the second part 5359 unsigned SecondHalfAlignment = 5360 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5361 Alignment/2 : Alignment; 5362 5363 EVT LoMemVT, HiMemVT; 5364 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5365 5366 SDValue DataLo, DataHi; 5367 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5368 5369 MachineMemOperand *MMO = DAG.getMachineFunction(). 5370 getMachineMemOperand(MST->getPointerInfo(), 5371 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5372 Alignment, MST->getAAInfo(), MST->getRanges()); 5373 5374 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5375 MST->isTruncatingStore()); 5376 5377 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5378 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5379 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5380 5381 MMO = DAG.getMachineFunction(). 5382 getMachineMemOperand(MST->getPointerInfo(), 5383 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5384 SecondHalfAlignment, MST->getAAInfo(), 5385 MST->getRanges()); 5386 5387 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5388 MST->isTruncatingStore()); 5389 5390 AddToWorklist(Lo.getNode()); 5391 AddToWorklist(Hi.getNode()); 5392 5393 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5394 } 5395 return SDValue(); 5396 } 5397 5398 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5399 5400 if (Level >= AfterLegalizeTypes) 5401 return SDValue(); 5402 5403 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5404 SDValue Mask = MGT->getMask(); 5405 SDLoc DL(N); 5406 5407 // If the MGATHER result requires splitting and the mask is provided by a 5408 // SETCC, then split both nodes and its operands before legalization. This 5409 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5410 // and enables future optimizations (e.g. min/max pattern matching on X86). 5411 5412 if (Mask.getOpcode() != ISD::SETCC) 5413 return SDValue(); 5414 5415 EVT VT = N->getValueType(0); 5416 5417 // Check if any splitting is required. 5418 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5419 TargetLowering::TypeSplitVector) 5420 return SDValue(); 5421 5422 SDValue MaskLo, MaskHi, Lo, Hi; 5423 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5424 5425 SDValue Src0 = MGT->getValue(); 5426 SDValue Src0Lo, Src0Hi; 5427 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5428 5429 EVT LoVT, HiVT; 5430 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5431 5432 SDValue Chain = MGT->getChain(); 5433 EVT MemoryVT = MGT->getMemoryVT(); 5434 unsigned Alignment = MGT->getOriginalAlignment(); 5435 5436 EVT LoMemVT, HiMemVT; 5437 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5438 5439 SDValue BasePtr = MGT->getBasePtr(); 5440 SDValue Index = MGT->getIndex(); 5441 SDValue IndexLo, IndexHi; 5442 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5443 5444 MachineMemOperand *MMO = DAG.getMachineFunction(). 5445 getMachineMemOperand(MGT->getPointerInfo(), 5446 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5447 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5448 5449 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5450 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5451 MMO); 5452 5453 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5454 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5455 MMO); 5456 5457 AddToWorklist(Lo.getNode()); 5458 AddToWorklist(Hi.getNode()); 5459 5460 // Build a factor node to remember that this load is independent of the 5461 // other one. 5462 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5463 Hi.getValue(1)); 5464 5465 // Legalized the chain result - switch anything that used the old chain to 5466 // use the new one. 5467 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5468 5469 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5470 5471 SDValue RetOps[] = { GatherRes, Chain }; 5472 return DAG.getMergeValues(RetOps, DL); 5473 } 5474 5475 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5476 5477 if (Level >= AfterLegalizeTypes) 5478 return SDValue(); 5479 5480 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5481 SDValue Mask = MLD->getMask(); 5482 SDLoc DL(N); 5483 5484 // If the MLOAD result requires splitting and the mask is provided by a 5485 // SETCC, then split both nodes and its operands before legalization. This 5486 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5487 // and enables future optimizations (e.g. min/max pattern matching on X86). 5488 5489 if (Mask.getOpcode() == ISD::SETCC) { 5490 EVT VT = N->getValueType(0); 5491 5492 // Check if any splitting is required. 5493 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5494 TargetLowering::TypeSplitVector) 5495 return SDValue(); 5496 5497 SDValue MaskLo, MaskHi, Lo, Hi; 5498 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5499 5500 SDValue Src0 = MLD->getSrc0(); 5501 SDValue Src0Lo, Src0Hi; 5502 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5503 5504 EVT LoVT, HiVT; 5505 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5506 5507 SDValue Chain = MLD->getChain(); 5508 SDValue Ptr = MLD->getBasePtr(); 5509 EVT MemoryVT = MLD->getMemoryVT(); 5510 unsigned Alignment = MLD->getOriginalAlignment(); 5511 5512 // if Alignment is equal to the vector size, 5513 // take the half of it for the second part 5514 unsigned SecondHalfAlignment = 5515 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5516 Alignment/2 : Alignment; 5517 5518 EVT LoMemVT, HiMemVT; 5519 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5520 5521 MachineMemOperand *MMO = DAG.getMachineFunction(). 5522 getMachineMemOperand(MLD->getPointerInfo(), 5523 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5524 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5525 5526 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5527 ISD::NON_EXTLOAD); 5528 5529 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5530 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5531 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5532 5533 MMO = DAG.getMachineFunction(). 5534 getMachineMemOperand(MLD->getPointerInfo(), 5535 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5536 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5537 5538 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5539 ISD::NON_EXTLOAD); 5540 5541 AddToWorklist(Lo.getNode()); 5542 AddToWorklist(Hi.getNode()); 5543 5544 // Build a factor node to remember that this load is independent of the 5545 // other one. 5546 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5547 Hi.getValue(1)); 5548 5549 // Legalized the chain result - switch anything that used the old chain to 5550 // use the new one. 5551 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5552 5553 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5554 5555 SDValue RetOps[] = { LoadRes, Chain }; 5556 return DAG.getMergeValues(RetOps, DL); 5557 } 5558 return SDValue(); 5559 } 5560 5561 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5562 SDValue N0 = N->getOperand(0); 5563 SDValue N1 = N->getOperand(1); 5564 SDValue N2 = N->getOperand(2); 5565 SDLoc DL(N); 5566 5567 // Canonicalize integer abs. 5568 // vselect (setg[te] X, 0), X, -X -> 5569 // vselect (setgt X, -1), X, -X -> 5570 // vselect (setl[te] X, 0), -X, X -> 5571 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5572 if (N0.getOpcode() == ISD::SETCC) { 5573 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5574 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5575 bool isAbs = false; 5576 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5577 5578 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5579 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5580 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5581 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5582 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5583 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5584 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5585 5586 if (isAbs) { 5587 EVT VT = LHS.getValueType(); 5588 SDValue Shift = DAG.getNode( 5589 ISD::SRA, DL, VT, LHS, 5590 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5591 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5592 AddToWorklist(Shift.getNode()); 5593 AddToWorklist(Add.getNode()); 5594 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5595 } 5596 } 5597 5598 if (SimplifySelectOps(N, N1, N2)) 5599 return SDValue(N, 0); // Don't revisit N. 5600 5601 // If the VSELECT result requires splitting and the mask is provided by a 5602 // SETCC, then split both nodes and its operands before legalization. This 5603 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5604 // and enables future optimizations (e.g. min/max pattern matching on X86). 5605 if (N0.getOpcode() == ISD::SETCC) { 5606 EVT VT = N->getValueType(0); 5607 5608 // Check if any splitting is required. 5609 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5610 TargetLowering::TypeSplitVector) 5611 return SDValue(); 5612 5613 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5614 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5615 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5616 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5617 5618 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5619 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5620 5621 // Add the new VSELECT nodes to the work list in case they need to be split 5622 // again. 5623 AddToWorklist(Lo.getNode()); 5624 AddToWorklist(Hi.getNode()); 5625 5626 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5627 } 5628 5629 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5630 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5631 return N1; 5632 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5633 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5634 return N2; 5635 5636 // The ConvertSelectToConcatVector function is assuming both the above 5637 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5638 // and addressed. 5639 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5640 N2.getOpcode() == ISD::CONCAT_VECTORS && 5641 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5642 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5643 return CV; 5644 } 5645 5646 return SDValue(); 5647 } 5648 5649 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5650 SDValue N0 = N->getOperand(0); 5651 SDValue N1 = N->getOperand(1); 5652 SDValue N2 = N->getOperand(2); 5653 SDValue N3 = N->getOperand(3); 5654 SDValue N4 = N->getOperand(4); 5655 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5656 5657 // fold select_cc lhs, rhs, x, x, cc -> x 5658 if (N2 == N3) 5659 return N2; 5660 5661 // Determine if the condition we're dealing with is constant 5662 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5663 N0, N1, CC, SDLoc(N), false); 5664 if (SCC.getNode()) { 5665 AddToWorklist(SCC.getNode()); 5666 5667 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5668 if (!SCCC->isNullValue()) 5669 return N2; // cond always true -> true val 5670 else 5671 return N3; // cond always false -> false val 5672 } else if (SCC->getOpcode() == ISD::UNDEF) { 5673 // When the condition is UNDEF, just return the first operand. This is 5674 // coherent the DAG creation, no setcc node is created in this case 5675 return N2; 5676 } else if (SCC.getOpcode() == ISD::SETCC) { 5677 // Fold to a simpler select_cc 5678 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5679 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5680 SCC.getOperand(2)); 5681 } 5682 } 5683 5684 // If we can fold this based on the true/false value, do so. 5685 if (SimplifySelectOps(N, N2, N3)) 5686 return SDValue(N, 0); // Don't revisit N. 5687 5688 // fold select_cc into other things, such as min/max/abs 5689 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5690 } 5691 5692 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5693 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5694 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5695 SDLoc(N)); 5696 } 5697 5698 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5699 /// a build_vector of constants. 5700 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5701 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5702 /// Vector extends are not folded if operations are legal; this is to 5703 /// avoid introducing illegal build_vector dag nodes. 5704 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5705 SelectionDAG &DAG, bool LegalTypes, 5706 bool LegalOperations) { 5707 unsigned Opcode = N->getOpcode(); 5708 SDValue N0 = N->getOperand(0); 5709 EVT VT = N->getValueType(0); 5710 5711 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5712 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5713 && "Expected EXTEND dag node in input!"); 5714 5715 // fold (sext c1) -> c1 5716 // fold (zext c1) -> c1 5717 // fold (aext c1) -> c1 5718 if (isa<ConstantSDNode>(N0)) 5719 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5720 5721 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5722 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5723 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5724 EVT SVT = VT.getScalarType(); 5725 if (!(VT.isVector() && 5726 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5727 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5728 return nullptr; 5729 5730 // We can fold this node into a build_vector. 5731 unsigned VTBits = SVT.getSizeInBits(); 5732 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5733 SmallVector<SDValue, 8> Elts; 5734 unsigned NumElts = VT.getVectorNumElements(); 5735 SDLoc DL(N); 5736 5737 for (unsigned i=0; i != NumElts; ++i) { 5738 SDValue Op = N0->getOperand(i); 5739 if (Op->getOpcode() == ISD::UNDEF) { 5740 Elts.push_back(DAG.getUNDEF(SVT)); 5741 continue; 5742 } 5743 5744 SDLoc DL(Op); 5745 // Get the constant value and if needed trunc it to the size of the type. 5746 // Nodes like build_vector might have constants wider than the scalar type. 5747 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5748 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5749 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5750 else 5751 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5752 } 5753 5754 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5755 } 5756 5757 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5758 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5759 // transformation. Returns true if extension are possible and the above 5760 // mentioned transformation is profitable. 5761 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5762 unsigned ExtOpc, 5763 SmallVectorImpl<SDNode *> &ExtendNodes, 5764 const TargetLowering &TLI) { 5765 bool HasCopyToRegUses = false; 5766 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5767 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5768 UE = N0.getNode()->use_end(); 5769 UI != UE; ++UI) { 5770 SDNode *User = *UI; 5771 if (User == N) 5772 continue; 5773 if (UI.getUse().getResNo() != N0.getResNo()) 5774 continue; 5775 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5776 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5777 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5778 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5779 // Sign bits will be lost after a zext. 5780 return false; 5781 bool Add = false; 5782 for (unsigned i = 0; i != 2; ++i) { 5783 SDValue UseOp = User->getOperand(i); 5784 if (UseOp == N0) 5785 continue; 5786 if (!isa<ConstantSDNode>(UseOp)) 5787 return false; 5788 Add = true; 5789 } 5790 if (Add) 5791 ExtendNodes.push_back(User); 5792 continue; 5793 } 5794 // If truncates aren't free and there are users we can't 5795 // extend, it isn't worthwhile. 5796 if (!isTruncFree) 5797 return false; 5798 // Remember if this value is live-out. 5799 if (User->getOpcode() == ISD::CopyToReg) 5800 HasCopyToRegUses = true; 5801 } 5802 5803 if (HasCopyToRegUses) { 5804 bool BothLiveOut = false; 5805 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5806 UI != UE; ++UI) { 5807 SDUse &Use = UI.getUse(); 5808 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5809 BothLiveOut = true; 5810 break; 5811 } 5812 } 5813 if (BothLiveOut) 5814 // Both unextended and extended values are live out. There had better be 5815 // a good reason for the transformation. 5816 return ExtendNodes.size(); 5817 } 5818 return true; 5819 } 5820 5821 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5822 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5823 ISD::NodeType ExtType) { 5824 // Extend SetCC uses if necessary. 5825 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5826 SDNode *SetCC = SetCCs[i]; 5827 SmallVector<SDValue, 4> Ops; 5828 5829 for (unsigned j = 0; j != 2; ++j) { 5830 SDValue SOp = SetCC->getOperand(j); 5831 if (SOp == Trunc) 5832 Ops.push_back(ExtLoad); 5833 else 5834 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5835 } 5836 5837 Ops.push_back(SetCC->getOperand(2)); 5838 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5839 } 5840 } 5841 5842 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5843 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5844 SDValue N0 = N->getOperand(0); 5845 EVT DstVT = N->getValueType(0); 5846 EVT SrcVT = N0.getValueType(); 5847 5848 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5849 N->getOpcode() == ISD::ZERO_EXTEND) && 5850 "Unexpected node type (not an extend)!"); 5851 5852 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5853 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5854 // (v8i32 (sext (v8i16 (load x)))) 5855 // into: 5856 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5857 // (v4i32 (sextload (x + 16))))) 5858 // Where uses of the original load, i.e.: 5859 // (v8i16 (load x)) 5860 // are replaced with: 5861 // (v8i16 (truncate 5862 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5863 // (v4i32 (sextload (x + 16))))))) 5864 // 5865 // This combine is only applicable to illegal, but splittable, vectors. 5866 // All legal types, and illegal non-vector types, are handled elsewhere. 5867 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5868 // 5869 if (N0->getOpcode() != ISD::LOAD) 5870 return SDValue(); 5871 5872 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5873 5874 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5875 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5876 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5877 return SDValue(); 5878 5879 SmallVector<SDNode *, 4> SetCCs; 5880 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5881 return SDValue(); 5882 5883 ISD::LoadExtType ExtType = 5884 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5885 5886 // Try to split the vector types to get down to legal types. 5887 EVT SplitSrcVT = SrcVT; 5888 EVT SplitDstVT = DstVT; 5889 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5890 SplitSrcVT.getVectorNumElements() > 1) { 5891 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5892 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5893 } 5894 5895 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5896 return SDValue(); 5897 5898 SDLoc DL(N); 5899 const unsigned NumSplits = 5900 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5901 const unsigned Stride = SplitSrcVT.getStoreSize(); 5902 SmallVector<SDValue, 4> Loads; 5903 SmallVector<SDValue, 4> Chains; 5904 5905 SDValue BasePtr = LN0->getBasePtr(); 5906 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5907 const unsigned Offset = Idx * Stride; 5908 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5909 5910 SDValue SplitLoad = DAG.getExtLoad( 5911 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5912 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5913 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5914 Align, LN0->getAAInfo()); 5915 5916 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5917 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5918 5919 Loads.push_back(SplitLoad.getValue(0)); 5920 Chains.push_back(SplitLoad.getValue(1)); 5921 } 5922 5923 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5924 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5925 5926 CombineTo(N, NewValue); 5927 5928 // Replace uses of the original load (before extension) 5929 // with a truncate of the concatenated sextloaded vectors. 5930 SDValue Trunc = 5931 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5932 CombineTo(N0.getNode(), Trunc, NewChain); 5933 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5934 (ISD::NodeType)N->getOpcode()); 5935 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5936 } 5937 5938 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5939 SDValue N0 = N->getOperand(0); 5940 EVT VT = N->getValueType(0); 5941 5942 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5943 LegalOperations)) 5944 return SDValue(Res, 0); 5945 5946 // fold (sext (sext x)) -> (sext x) 5947 // fold (sext (aext x)) -> (sext x) 5948 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5949 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5950 N0.getOperand(0)); 5951 5952 if (N0.getOpcode() == ISD::TRUNCATE) { 5953 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5954 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5955 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 5956 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5957 if (NarrowLoad.getNode() != N0.getNode()) { 5958 CombineTo(N0.getNode(), NarrowLoad); 5959 // CombineTo deleted the truncate, if needed, but not what's under it. 5960 AddToWorklist(oye); 5961 } 5962 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5963 } 5964 5965 // See if the value being truncated is already sign extended. If so, just 5966 // eliminate the trunc/sext pair. 5967 SDValue Op = N0.getOperand(0); 5968 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5969 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5970 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5971 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5972 5973 if (OpBits == DestBits) { 5974 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5975 // bits, it is already ready. 5976 if (NumSignBits > DestBits-MidBits) 5977 return Op; 5978 } else if (OpBits < DestBits) { 5979 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5980 // bits, just sext from i32. 5981 if (NumSignBits > OpBits-MidBits) 5982 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5983 } else { 5984 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5985 // bits, just truncate to i32. 5986 if (NumSignBits > OpBits-MidBits) 5987 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5988 } 5989 5990 // fold (sext (truncate x)) -> (sextinreg x). 5991 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5992 N0.getValueType())) { 5993 if (OpBits < DestBits) 5994 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5995 else if (OpBits > DestBits) 5996 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5997 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5998 DAG.getValueType(N0.getValueType())); 5999 } 6000 } 6001 6002 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6003 // Only generate vector extloads when 1) they're legal, and 2) they are 6004 // deemed desirable by the target. 6005 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6006 ((!LegalOperations && !VT.isVector() && 6007 !cast<LoadSDNode>(N0)->isVolatile()) || 6008 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6009 bool DoXform = true; 6010 SmallVector<SDNode*, 4> SetCCs; 6011 if (!N0.hasOneUse()) 6012 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6013 if (VT.isVector()) 6014 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6015 if (DoXform) { 6016 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6017 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6018 LN0->getChain(), 6019 LN0->getBasePtr(), N0.getValueType(), 6020 LN0->getMemOperand()); 6021 CombineTo(N, ExtLoad); 6022 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6023 N0.getValueType(), ExtLoad); 6024 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6025 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6026 ISD::SIGN_EXTEND); 6027 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6028 } 6029 } 6030 6031 // fold (sext (load x)) to multiple smaller sextloads. 6032 // Only on illegal but splittable vectors. 6033 if (SDValue ExtLoad = CombineExtLoad(N)) 6034 return ExtLoad; 6035 6036 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6037 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6038 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6039 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6040 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6041 EVT MemVT = LN0->getMemoryVT(); 6042 if ((!LegalOperations && !LN0->isVolatile()) || 6043 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6044 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6045 LN0->getChain(), 6046 LN0->getBasePtr(), MemVT, 6047 LN0->getMemOperand()); 6048 CombineTo(N, ExtLoad); 6049 CombineTo(N0.getNode(), 6050 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6051 N0.getValueType(), ExtLoad), 6052 ExtLoad.getValue(1)); 6053 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6054 } 6055 } 6056 6057 // fold (sext (and/or/xor (load x), cst)) -> 6058 // (and/or/xor (sextload x), (sext cst)) 6059 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6060 N0.getOpcode() == ISD::XOR) && 6061 isa<LoadSDNode>(N0.getOperand(0)) && 6062 N0.getOperand(1).getOpcode() == ISD::Constant && 6063 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6064 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6065 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6066 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6067 bool DoXform = true; 6068 SmallVector<SDNode*, 4> SetCCs; 6069 if (!N0.hasOneUse()) 6070 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6071 SetCCs, TLI); 6072 if (DoXform) { 6073 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6074 LN0->getChain(), LN0->getBasePtr(), 6075 LN0->getMemoryVT(), 6076 LN0->getMemOperand()); 6077 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6078 Mask = Mask.sext(VT.getSizeInBits()); 6079 SDLoc DL(N); 6080 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6081 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6082 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6083 SDLoc(N0.getOperand(0)), 6084 N0.getOperand(0).getValueType(), ExtLoad); 6085 CombineTo(N, And); 6086 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6087 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6088 ISD::SIGN_EXTEND); 6089 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6090 } 6091 } 6092 } 6093 6094 if (N0.getOpcode() == ISD::SETCC) { 6095 EVT N0VT = N0.getOperand(0).getValueType(); 6096 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6097 // Only do this before legalize for now. 6098 if (VT.isVector() && !LegalOperations && 6099 TLI.getBooleanContents(N0VT) == 6100 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6101 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6102 // of the same size as the compared operands. Only optimize sext(setcc()) 6103 // if this is the case. 6104 EVT SVT = getSetCCResultType(N0VT); 6105 6106 // We know that the # elements of the results is the same as the 6107 // # elements of the compare (and the # elements of the compare result 6108 // for that matter). Check to see that they are the same size. If so, 6109 // we know that the element size of the sext'd result matches the 6110 // element size of the compare operands. 6111 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6112 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6113 N0.getOperand(1), 6114 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6115 6116 // If the desired elements are smaller or larger than the source 6117 // elements we can use a matching integer vector type and then 6118 // truncate/sign extend 6119 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6120 if (SVT == MatchingVectorType) { 6121 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6122 N0.getOperand(0), N0.getOperand(1), 6123 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6124 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6125 } 6126 } 6127 6128 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6129 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6130 SDLoc DL(N); 6131 SDValue NegOne = 6132 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6133 SDValue SCC = 6134 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6135 NegOne, DAG.getConstant(0, DL, VT), 6136 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6137 if (SCC.getNode()) return SCC; 6138 6139 if (!VT.isVector()) { 6140 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6141 if (!LegalOperations || 6142 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6143 SDLoc DL(N); 6144 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6145 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6146 N0.getOperand(0), N0.getOperand(1), CC); 6147 return DAG.getSelect(DL, VT, SetCC, 6148 NegOne, DAG.getConstant(0, DL, VT)); 6149 } 6150 } 6151 } 6152 6153 // fold (sext x) -> (zext x) if the sign bit is known zero. 6154 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6155 DAG.SignBitIsZero(N0)) 6156 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6157 6158 return SDValue(); 6159 } 6160 6161 // isTruncateOf - If N is a truncate of some other value, return true, record 6162 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6163 // This function computes KnownZero to avoid a duplicated call to 6164 // computeKnownBits in the caller. 6165 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6166 APInt &KnownZero) { 6167 APInt KnownOne; 6168 if (N->getOpcode() == ISD::TRUNCATE) { 6169 Op = N->getOperand(0); 6170 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6171 return true; 6172 } 6173 6174 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6175 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6176 return false; 6177 6178 SDValue Op0 = N->getOperand(0); 6179 SDValue Op1 = N->getOperand(1); 6180 assert(Op0.getValueType() == Op1.getValueType()); 6181 6182 if (isNullConstant(Op0)) 6183 Op = Op1; 6184 else if (isNullConstant(Op1)) 6185 Op = Op0; 6186 else 6187 return false; 6188 6189 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6190 6191 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6192 return false; 6193 6194 return true; 6195 } 6196 6197 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6198 SDValue N0 = N->getOperand(0); 6199 EVT VT = N->getValueType(0); 6200 6201 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6202 LegalOperations)) 6203 return SDValue(Res, 0); 6204 6205 // fold (zext (zext x)) -> (zext x) 6206 // fold (zext (aext x)) -> (zext x) 6207 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6208 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6209 N0.getOperand(0)); 6210 6211 // fold (zext (truncate x)) -> (zext x) or 6212 // (zext (truncate x)) -> (truncate x) 6213 // This is valid when the truncated bits of x are already zero. 6214 // FIXME: We should extend this to work for vectors too. 6215 SDValue Op; 6216 APInt KnownZero; 6217 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6218 APInt TruncatedBits = 6219 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6220 APInt(Op.getValueSizeInBits(), 0) : 6221 APInt::getBitsSet(Op.getValueSizeInBits(), 6222 N0.getValueSizeInBits(), 6223 std::min(Op.getValueSizeInBits(), 6224 VT.getSizeInBits())); 6225 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6226 if (VT.bitsGT(Op.getValueType())) 6227 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6228 if (VT.bitsLT(Op.getValueType())) 6229 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6230 6231 return Op; 6232 } 6233 } 6234 6235 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6236 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6237 if (N0.getOpcode() == ISD::TRUNCATE) { 6238 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6239 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6240 if (NarrowLoad.getNode() != N0.getNode()) { 6241 CombineTo(N0.getNode(), NarrowLoad); 6242 // CombineTo deleted the truncate, if needed, but not what's under it. 6243 AddToWorklist(oye); 6244 } 6245 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6246 } 6247 } 6248 6249 // fold (zext (truncate x)) -> (and x, mask) 6250 if (N0.getOpcode() == ISD::TRUNCATE) { 6251 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6252 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6253 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6254 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6255 if (NarrowLoad.getNode() != N0.getNode()) { 6256 CombineTo(N0.getNode(), NarrowLoad); 6257 // CombineTo deleted the truncate, if needed, but not what's under it. 6258 AddToWorklist(oye); 6259 } 6260 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6261 } 6262 6263 EVT SrcVT = N0.getOperand(0).getValueType(); 6264 EVT MinVT = N0.getValueType(); 6265 6266 // Try to mask before the extension to avoid having to generate a larger mask, 6267 // possibly over several sub-vectors. 6268 if (SrcVT.bitsLT(VT)) { 6269 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6270 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6271 SDValue Op = N0.getOperand(0); 6272 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6273 AddToWorklist(Op.getNode()); 6274 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6275 } 6276 } 6277 6278 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6279 SDValue Op = N0.getOperand(0); 6280 if (SrcVT.bitsLT(VT)) { 6281 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6282 AddToWorklist(Op.getNode()); 6283 } else if (SrcVT.bitsGT(VT)) { 6284 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6285 AddToWorklist(Op.getNode()); 6286 } 6287 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6288 } 6289 } 6290 6291 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6292 // if either of the casts is not free. 6293 if (N0.getOpcode() == ISD::AND && 6294 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6295 N0.getOperand(1).getOpcode() == ISD::Constant && 6296 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6297 N0.getValueType()) || 6298 !TLI.isZExtFree(N0.getValueType(), VT))) { 6299 SDValue X = N0.getOperand(0).getOperand(0); 6300 if (X.getValueType().bitsLT(VT)) { 6301 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6302 } else if (X.getValueType().bitsGT(VT)) { 6303 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6304 } 6305 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6306 Mask = Mask.zext(VT.getSizeInBits()); 6307 SDLoc DL(N); 6308 return DAG.getNode(ISD::AND, DL, VT, 6309 X, DAG.getConstant(Mask, DL, VT)); 6310 } 6311 6312 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6313 // Only generate vector extloads when 1) they're legal, and 2) they are 6314 // deemed desirable by the target. 6315 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6316 ((!LegalOperations && !VT.isVector() && 6317 !cast<LoadSDNode>(N0)->isVolatile()) || 6318 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6319 bool DoXform = true; 6320 SmallVector<SDNode*, 4> SetCCs; 6321 if (!N0.hasOneUse()) 6322 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6323 if (VT.isVector()) 6324 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6325 if (DoXform) { 6326 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6327 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6328 LN0->getChain(), 6329 LN0->getBasePtr(), N0.getValueType(), 6330 LN0->getMemOperand()); 6331 CombineTo(N, ExtLoad); 6332 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6333 N0.getValueType(), ExtLoad); 6334 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6335 6336 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6337 ISD::ZERO_EXTEND); 6338 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6339 } 6340 } 6341 6342 // fold (zext (load x)) to multiple smaller zextloads. 6343 // Only on illegal but splittable vectors. 6344 if (SDValue ExtLoad = CombineExtLoad(N)) 6345 return ExtLoad; 6346 6347 // fold (zext (and/or/xor (load x), cst)) -> 6348 // (and/or/xor (zextload x), (zext cst)) 6349 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6350 N0.getOpcode() == ISD::XOR) && 6351 isa<LoadSDNode>(N0.getOperand(0)) && 6352 N0.getOperand(1).getOpcode() == ISD::Constant && 6353 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6354 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6355 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6356 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6357 bool DoXform = true; 6358 SmallVector<SDNode*, 4> SetCCs; 6359 if (!N0.hasOneUse()) 6360 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 6361 SetCCs, TLI); 6362 if (DoXform) { 6363 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6364 LN0->getChain(), LN0->getBasePtr(), 6365 LN0->getMemoryVT(), 6366 LN0->getMemOperand()); 6367 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6368 Mask = Mask.zext(VT.getSizeInBits()); 6369 SDLoc DL(N); 6370 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6371 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6372 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6373 SDLoc(N0.getOperand(0)), 6374 N0.getOperand(0).getValueType(), ExtLoad); 6375 CombineTo(N, And); 6376 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6377 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6378 ISD::ZERO_EXTEND); 6379 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6380 } 6381 } 6382 } 6383 6384 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6385 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6386 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6387 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6388 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6389 EVT MemVT = LN0->getMemoryVT(); 6390 if ((!LegalOperations && !LN0->isVolatile()) || 6391 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6392 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6393 LN0->getChain(), 6394 LN0->getBasePtr(), MemVT, 6395 LN0->getMemOperand()); 6396 CombineTo(N, ExtLoad); 6397 CombineTo(N0.getNode(), 6398 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6399 ExtLoad), 6400 ExtLoad.getValue(1)); 6401 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6402 } 6403 } 6404 6405 if (N0.getOpcode() == ISD::SETCC) { 6406 if (!LegalOperations && VT.isVector() && 6407 N0.getValueType().getVectorElementType() == MVT::i1) { 6408 EVT N0VT = N0.getOperand(0).getValueType(); 6409 if (getSetCCResultType(N0VT) == N0.getValueType()) 6410 return SDValue(); 6411 6412 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6413 // Only do this before legalize for now. 6414 EVT EltVT = VT.getVectorElementType(); 6415 SDLoc DL(N); 6416 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 6417 DAG.getConstant(1, DL, EltVT)); 6418 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6419 // We know that the # elements of the results is the same as the 6420 // # elements of the compare (and the # elements of the compare result 6421 // for that matter). Check to see that they are the same size. If so, 6422 // we know that the element size of the sext'd result matches the 6423 // element size of the compare operands. 6424 return DAG.getNode(ISD::AND, DL, VT, 6425 DAG.getSetCC(DL, VT, N0.getOperand(0), 6426 N0.getOperand(1), 6427 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6428 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 6429 OneOps)); 6430 6431 // If the desired elements are smaller or larger than the source 6432 // elements we can use a matching integer vector type and then 6433 // truncate/sign extend 6434 EVT MatchingElementType = 6435 EVT::getIntegerVT(*DAG.getContext(), 6436 N0VT.getScalarType().getSizeInBits()); 6437 EVT MatchingVectorType = 6438 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6439 N0VT.getVectorNumElements()); 6440 SDValue VsetCC = 6441 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6442 N0.getOperand(1), 6443 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6444 return DAG.getNode(ISD::AND, DL, VT, 6445 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6446 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps)); 6447 } 6448 6449 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6450 SDLoc DL(N); 6451 SDValue SCC = 6452 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6453 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6454 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6455 if (SCC.getNode()) return SCC; 6456 } 6457 6458 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6459 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6460 isa<ConstantSDNode>(N0.getOperand(1)) && 6461 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6462 N0.hasOneUse()) { 6463 SDValue ShAmt = N0.getOperand(1); 6464 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6465 if (N0.getOpcode() == ISD::SHL) { 6466 SDValue InnerZExt = N0.getOperand(0); 6467 // If the original shl may be shifting out bits, do not perform this 6468 // transformation. 6469 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6470 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6471 if (ShAmtVal > KnownZeroBits) 6472 return SDValue(); 6473 } 6474 6475 SDLoc DL(N); 6476 6477 // Ensure that the shift amount is wide enough for the shifted value. 6478 if (VT.getSizeInBits() >= 256) 6479 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6480 6481 return DAG.getNode(N0.getOpcode(), DL, VT, 6482 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6483 ShAmt); 6484 } 6485 6486 return SDValue(); 6487 } 6488 6489 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6490 SDValue N0 = N->getOperand(0); 6491 EVT VT = N->getValueType(0); 6492 6493 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6494 LegalOperations)) 6495 return SDValue(Res, 0); 6496 6497 // fold (aext (aext x)) -> (aext x) 6498 // fold (aext (zext x)) -> (zext x) 6499 // fold (aext (sext x)) -> (sext x) 6500 if (N0.getOpcode() == ISD::ANY_EXTEND || 6501 N0.getOpcode() == ISD::ZERO_EXTEND || 6502 N0.getOpcode() == ISD::SIGN_EXTEND) 6503 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6504 6505 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6506 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6507 if (N0.getOpcode() == ISD::TRUNCATE) { 6508 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6509 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6510 if (NarrowLoad.getNode() != N0.getNode()) { 6511 CombineTo(N0.getNode(), NarrowLoad); 6512 // CombineTo deleted the truncate, if needed, but not what's under it. 6513 AddToWorklist(oye); 6514 } 6515 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6516 } 6517 } 6518 6519 // fold (aext (truncate x)) 6520 if (N0.getOpcode() == ISD::TRUNCATE) { 6521 SDValue TruncOp = N0.getOperand(0); 6522 if (TruncOp.getValueType() == VT) 6523 return TruncOp; // x iff x size == zext size. 6524 if (TruncOp.getValueType().bitsGT(VT)) 6525 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6526 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6527 } 6528 6529 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6530 // if the trunc is not free. 6531 if (N0.getOpcode() == ISD::AND && 6532 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6533 N0.getOperand(1).getOpcode() == ISD::Constant && 6534 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6535 N0.getValueType())) { 6536 SDValue X = N0.getOperand(0).getOperand(0); 6537 if (X.getValueType().bitsLT(VT)) { 6538 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6539 } else if (X.getValueType().bitsGT(VT)) { 6540 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6541 } 6542 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6543 Mask = Mask.zext(VT.getSizeInBits()); 6544 SDLoc DL(N); 6545 return DAG.getNode(ISD::AND, DL, VT, 6546 X, DAG.getConstant(Mask, DL, VT)); 6547 } 6548 6549 // fold (aext (load x)) -> (aext (truncate (extload x))) 6550 // None of the supported targets knows how to perform load and any_ext 6551 // on vectors in one instruction. We only perform this transformation on 6552 // scalars. 6553 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6554 ISD::isUNINDEXEDLoad(N0.getNode()) && 6555 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6556 bool DoXform = true; 6557 SmallVector<SDNode*, 4> SetCCs; 6558 if (!N0.hasOneUse()) 6559 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6560 if (DoXform) { 6561 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6562 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6563 LN0->getChain(), 6564 LN0->getBasePtr(), N0.getValueType(), 6565 LN0->getMemOperand()); 6566 CombineTo(N, ExtLoad); 6567 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6568 N0.getValueType(), ExtLoad); 6569 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6570 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6571 ISD::ANY_EXTEND); 6572 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6573 } 6574 } 6575 6576 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6577 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6578 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6579 if (N0.getOpcode() == ISD::LOAD && 6580 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6581 N0.hasOneUse()) { 6582 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6583 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6584 EVT MemVT = LN0->getMemoryVT(); 6585 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6586 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6587 VT, LN0->getChain(), LN0->getBasePtr(), 6588 MemVT, LN0->getMemOperand()); 6589 CombineTo(N, ExtLoad); 6590 CombineTo(N0.getNode(), 6591 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6592 N0.getValueType(), ExtLoad), 6593 ExtLoad.getValue(1)); 6594 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6595 } 6596 } 6597 6598 if (N0.getOpcode() == ISD::SETCC) { 6599 // For vectors: 6600 // aext(setcc) -> vsetcc 6601 // aext(setcc) -> truncate(vsetcc) 6602 // aext(setcc) -> aext(vsetcc) 6603 // Only do this before legalize for now. 6604 if (VT.isVector() && !LegalOperations) { 6605 EVT N0VT = N0.getOperand(0).getValueType(); 6606 // We know that the # elements of the results is the same as the 6607 // # elements of the compare (and the # elements of the compare result 6608 // for that matter). Check to see that they are the same size. If so, 6609 // we know that the element size of the sext'd result matches the 6610 // element size of the compare operands. 6611 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6612 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6613 N0.getOperand(1), 6614 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6615 // If the desired elements are smaller or larger than the source 6616 // elements we can use a matching integer vector type and then 6617 // truncate/any extend 6618 else { 6619 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6620 SDValue VsetCC = 6621 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6622 N0.getOperand(1), 6623 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6624 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6625 } 6626 } 6627 6628 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6629 SDLoc DL(N); 6630 SDValue SCC = 6631 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6632 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6633 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6634 if (SCC.getNode()) 6635 return SCC; 6636 } 6637 6638 return SDValue(); 6639 } 6640 6641 /// See if the specified operand can be simplified with the knowledge that only 6642 /// the bits specified by Mask are used. If so, return the simpler operand, 6643 /// otherwise return a null SDValue. 6644 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6645 switch (V.getOpcode()) { 6646 default: break; 6647 case ISD::Constant: { 6648 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6649 assert(CV && "Const value should be ConstSDNode."); 6650 const APInt &CVal = CV->getAPIntValue(); 6651 APInt NewVal = CVal & Mask; 6652 if (NewVal != CVal) 6653 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6654 break; 6655 } 6656 case ISD::OR: 6657 case ISD::XOR: 6658 // If the LHS or RHS don't contribute bits to the or, drop them. 6659 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6660 return V.getOperand(1); 6661 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6662 return V.getOperand(0); 6663 break; 6664 case ISD::SRL: 6665 // Only look at single-use SRLs. 6666 if (!V.getNode()->hasOneUse()) 6667 break; 6668 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6669 // See if we can recursively simplify the LHS. 6670 unsigned Amt = RHSC->getZExtValue(); 6671 6672 // Watch out for shift count overflow though. 6673 if (Amt >= Mask.getBitWidth()) break; 6674 APInt NewMask = Mask << Amt; 6675 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6676 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6677 SimplifyLHS, V.getOperand(1)); 6678 } 6679 } 6680 return SDValue(); 6681 } 6682 6683 /// If the result of a wider load is shifted to right of N bits and then 6684 /// truncated to a narrower type and where N is a multiple of number of bits of 6685 /// the narrower type, transform it to a narrower load from address + N / num of 6686 /// bits of new type. If the result is to be extended, also fold the extension 6687 /// to form a extending load. 6688 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6689 unsigned Opc = N->getOpcode(); 6690 6691 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6692 SDValue N0 = N->getOperand(0); 6693 EVT VT = N->getValueType(0); 6694 EVT ExtVT = VT; 6695 6696 // This transformation isn't valid for vector loads. 6697 if (VT.isVector()) 6698 return SDValue(); 6699 6700 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6701 // extended to VT. 6702 if (Opc == ISD::SIGN_EXTEND_INREG) { 6703 ExtType = ISD::SEXTLOAD; 6704 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6705 } else if (Opc == ISD::SRL) { 6706 // Another special-case: SRL is basically zero-extending a narrower value. 6707 ExtType = ISD::ZEXTLOAD; 6708 N0 = SDValue(N, 0); 6709 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6710 if (!N01) return SDValue(); 6711 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6712 VT.getSizeInBits() - N01->getZExtValue()); 6713 } 6714 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6715 return SDValue(); 6716 6717 unsigned EVTBits = ExtVT.getSizeInBits(); 6718 6719 // Do not generate loads of non-round integer types since these can 6720 // be expensive (and would be wrong if the type is not byte sized). 6721 if (!ExtVT.isRound()) 6722 return SDValue(); 6723 6724 unsigned ShAmt = 0; 6725 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6726 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6727 ShAmt = N01->getZExtValue(); 6728 // Is the shift amount a multiple of size of VT? 6729 if ((ShAmt & (EVTBits-1)) == 0) { 6730 N0 = N0.getOperand(0); 6731 // Is the load width a multiple of size of VT? 6732 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6733 return SDValue(); 6734 } 6735 6736 // At this point, we must have a load or else we can't do the transform. 6737 if (!isa<LoadSDNode>(N0)) return SDValue(); 6738 6739 // Because a SRL must be assumed to *need* to zero-extend the high bits 6740 // (as opposed to anyext the high bits), we can't combine the zextload 6741 // lowering of SRL and an sextload. 6742 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6743 return SDValue(); 6744 6745 // If the shift amount is larger than the input type then we're not 6746 // accessing any of the loaded bytes. If the load was a zextload/extload 6747 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6748 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6749 return SDValue(); 6750 } 6751 } 6752 6753 // If the load is shifted left (and the result isn't shifted back right), 6754 // we can fold the truncate through the shift. 6755 unsigned ShLeftAmt = 0; 6756 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6757 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6758 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6759 ShLeftAmt = N01->getZExtValue(); 6760 N0 = N0.getOperand(0); 6761 } 6762 } 6763 6764 // If we haven't found a load, we can't narrow it. Don't transform one with 6765 // multiple uses, this would require adding a new load. 6766 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6767 return SDValue(); 6768 6769 // Don't change the width of a volatile load. 6770 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6771 if (LN0->isVolatile()) 6772 return SDValue(); 6773 6774 // Verify that we are actually reducing a load width here. 6775 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6776 return SDValue(); 6777 6778 // For the transform to be legal, the load must produce only two values 6779 // (the value loaded and the chain). Don't transform a pre-increment 6780 // load, for example, which produces an extra value. Otherwise the 6781 // transformation is not equivalent, and the downstream logic to replace 6782 // uses gets things wrong. 6783 if (LN0->getNumValues() > 2) 6784 return SDValue(); 6785 6786 // If the load that we're shrinking is an extload and we're not just 6787 // discarding the extension we can't simply shrink the load. Bail. 6788 // TODO: It would be possible to merge the extensions in some cases. 6789 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6790 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6791 return SDValue(); 6792 6793 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6794 return SDValue(); 6795 6796 EVT PtrType = N0.getOperand(1).getValueType(); 6797 6798 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6799 // It's not possible to generate a constant of extended or untyped type. 6800 return SDValue(); 6801 6802 // For big endian targets, we need to adjust the offset to the pointer to 6803 // load the correct bytes. 6804 if (DAG.getDataLayout().isBigEndian()) { 6805 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6806 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6807 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6808 } 6809 6810 uint64_t PtrOff = ShAmt / 8; 6811 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6812 SDLoc DL(LN0); 6813 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6814 PtrType, LN0->getBasePtr(), 6815 DAG.getConstant(PtrOff, DL, PtrType)); 6816 AddToWorklist(NewPtr.getNode()); 6817 6818 SDValue Load; 6819 if (ExtType == ISD::NON_EXTLOAD) 6820 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6821 LN0->getPointerInfo().getWithOffset(PtrOff), 6822 LN0->isVolatile(), LN0->isNonTemporal(), 6823 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6824 else 6825 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6826 LN0->getPointerInfo().getWithOffset(PtrOff), 6827 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6828 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6829 6830 // Replace the old load's chain with the new load's chain. 6831 WorklistRemover DeadNodes(*this); 6832 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6833 6834 // Shift the result left, if we've swallowed a left shift. 6835 SDValue Result = Load; 6836 if (ShLeftAmt != 0) { 6837 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6838 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6839 ShImmTy = VT; 6840 // If the shift amount is as large as the result size (but, presumably, 6841 // no larger than the source) then the useful bits of the result are 6842 // zero; we can't simply return the shortened shift, because the result 6843 // of that operation is undefined. 6844 SDLoc DL(N0); 6845 if (ShLeftAmt >= VT.getSizeInBits()) 6846 Result = DAG.getConstant(0, DL, VT); 6847 else 6848 Result = DAG.getNode(ISD::SHL, DL, VT, 6849 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6850 } 6851 6852 // Return the new loaded value. 6853 return Result; 6854 } 6855 6856 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6857 SDValue N0 = N->getOperand(0); 6858 SDValue N1 = N->getOperand(1); 6859 EVT VT = N->getValueType(0); 6860 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6861 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6862 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6863 6864 if (N0.isUndef()) 6865 return DAG.getUNDEF(VT); 6866 6867 // fold (sext_in_reg c1) -> c1 6868 if (isConstantIntBuildVectorOrConstantInt(N0)) 6869 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6870 6871 // If the input is already sign extended, just drop the extension. 6872 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6873 return N0; 6874 6875 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6876 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6877 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6878 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6879 N0.getOperand(0), N1); 6880 6881 // fold (sext_in_reg (sext x)) -> (sext x) 6882 // fold (sext_in_reg (aext x)) -> (sext x) 6883 // if x is small enough. 6884 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6885 SDValue N00 = N0.getOperand(0); 6886 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6887 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6888 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6889 } 6890 6891 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6892 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6893 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6894 6895 // fold operands of sext_in_reg based on knowledge that the top bits are not 6896 // demanded. 6897 if (SimplifyDemandedBits(SDValue(N, 0))) 6898 return SDValue(N, 0); 6899 6900 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6901 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6902 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6903 return NarrowLoad; 6904 6905 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6906 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6907 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6908 if (N0.getOpcode() == ISD::SRL) { 6909 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6910 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6911 // We can turn this into an SRA iff the input to the SRL is already sign 6912 // extended enough. 6913 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6914 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6915 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6916 N0.getOperand(0), N0.getOperand(1)); 6917 } 6918 } 6919 6920 // fold (sext_inreg (extload x)) -> (sextload x) 6921 if (ISD::isEXTLoad(N0.getNode()) && 6922 ISD::isUNINDEXEDLoad(N0.getNode()) && 6923 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6924 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6925 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6926 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6927 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6928 LN0->getChain(), 6929 LN0->getBasePtr(), EVT, 6930 LN0->getMemOperand()); 6931 CombineTo(N, ExtLoad); 6932 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6933 AddToWorklist(ExtLoad.getNode()); 6934 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6935 } 6936 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6937 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6938 N0.hasOneUse() && 6939 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6940 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6941 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6942 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6943 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6944 LN0->getChain(), 6945 LN0->getBasePtr(), EVT, 6946 LN0->getMemOperand()); 6947 CombineTo(N, ExtLoad); 6948 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6949 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6950 } 6951 6952 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6953 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6954 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6955 N0.getOperand(1), false); 6956 if (BSwap.getNode()) 6957 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6958 BSwap, N1); 6959 } 6960 6961 return SDValue(); 6962 } 6963 6964 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 6965 SDValue N0 = N->getOperand(0); 6966 EVT VT = N->getValueType(0); 6967 6968 if (N0.getOpcode() == ISD::UNDEF) 6969 return DAG.getUNDEF(VT); 6970 6971 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6972 LegalOperations)) 6973 return SDValue(Res, 0); 6974 6975 return SDValue(); 6976 } 6977 6978 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6979 SDValue N0 = N->getOperand(0); 6980 EVT VT = N->getValueType(0); 6981 bool isLE = DAG.getDataLayout().isLittleEndian(); 6982 6983 // noop truncate 6984 if (N0.getValueType() == N->getValueType(0)) 6985 return N0; 6986 // fold (truncate c1) -> c1 6987 if (isConstantIntBuildVectorOrConstantInt(N0)) 6988 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6989 // fold (truncate (truncate x)) -> (truncate x) 6990 if (N0.getOpcode() == ISD::TRUNCATE) 6991 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6992 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6993 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6994 N0.getOpcode() == ISD::SIGN_EXTEND || 6995 N0.getOpcode() == ISD::ANY_EXTEND) { 6996 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6997 // if the source is smaller than the dest, we still need an extend 6998 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6999 N0.getOperand(0)); 7000 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7001 // if the source is larger than the dest, than we just need the truncate 7002 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7003 // if the source and dest are the same type, we can drop both the extend 7004 // and the truncate. 7005 return N0.getOperand(0); 7006 } 7007 7008 // Fold extract-and-trunc into a narrow extract. For example: 7009 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7010 // i32 y = TRUNCATE(i64 x) 7011 // -- becomes -- 7012 // v16i8 b = BITCAST (v2i64 val) 7013 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7014 // 7015 // Note: We only run this optimization after type legalization (which often 7016 // creates this pattern) and before operation legalization after which 7017 // we need to be more careful about the vector instructions that we generate. 7018 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7019 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7020 7021 EVT VecTy = N0.getOperand(0).getValueType(); 7022 EVT ExTy = N0.getValueType(); 7023 EVT TrTy = N->getValueType(0); 7024 7025 unsigned NumElem = VecTy.getVectorNumElements(); 7026 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7027 7028 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7029 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7030 7031 SDValue EltNo = N0->getOperand(1); 7032 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7033 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7034 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7035 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7036 7037 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 7038 NVT, N0.getOperand(0)); 7039 7040 SDLoc DL(N); 7041 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 7042 DL, TrTy, V, 7043 DAG.getConstant(Index, DL, IndexTy)); 7044 } 7045 } 7046 7047 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7048 if (N0.getOpcode() == ISD::SELECT) { 7049 EVT SrcVT = N0.getValueType(); 7050 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7051 TLI.isTruncateFree(SrcVT, VT)) { 7052 SDLoc SL(N0); 7053 SDValue Cond = N0.getOperand(0); 7054 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7055 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7056 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7057 } 7058 } 7059 7060 // Fold a series of buildvector, bitcast, and truncate if possible. 7061 // For example fold 7062 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7063 // (2xi32 (buildvector x, y)). 7064 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7065 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7066 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7067 N0.getOperand(0).hasOneUse()) { 7068 7069 SDValue BuildVect = N0.getOperand(0); 7070 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7071 EVT TruncVecEltTy = VT.getVectorElementType(); 7072 7073 // Check that the element types match. 7074 if (BuildVectEltTy == TruncVecEltTy) { 7075 // Now we only need to compute the offset of the truncated elements. 7076 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7077 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7078 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7079 7080 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7081 "Invalid number of elements"); 7082 7083 SmallVector<SDValue, 8> Opnds; 7084 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7085 Opnds.push_back(BuildVect.getOperand(i)); 7086 7087 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 7088 } 7089 } 7090 7091 // See if we can simplify the input to this truncate through knowledge that 7092 // only the low bits are being used. 7093 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7094 // Currently we only perform this optimization on scalars because vectors 7095 // may have different active low bits. 7096 if (!VT.isVector()) { 7097 SDValue Shorter = 7098 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7099 VT.getSizeInBits())); 7100 if (Shorter.getNode()) 7101 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7102 } 7103 // fold (truncate (load x)) -> (smaller load x) 7104 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7105 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7106 if (SDValue Reduced = ReduceLoadWidth(N)) 7107 return Reduced; 7108 7109 // Handle the case where the load remains an extending load even 7110 // after truncation. 7111 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7112 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7113 if (!LN0->isVolatile() && 7114 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7115 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7116 VT, LN0->getChain(), LN0->getBasePtr(), 7117 LN0->getMemoryVT(), 7118 LN0->getMemOperand()); 7119 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7120 return NewLoad; 7121 } 7122 } 7123 } 7124 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7125 // where ... are all 'undef'. 7126 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7127 SmallVector<EVT, 8> VTs; 7128 SDValue V; 7129 unsigned Idx = 0; 7130 unsigned NumDefs = 0; 7131 7132 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7133 SDValue X = N0.getOperand(i); 7134 if (X.getOpcode() != ISD::UNDEF) { 7135 V = X; 7136 Idx = i; 7137 NumDefs++; 7138 } 7139 // Stop if more than one members are non-undef. 7140 if (NumDefs > 1) 7141 break; 7142 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7143 VT.getVectorElementType(), 7144 X.getValueType().getVectorNumElements())); 7145 } 7146 7147 if (NumDefs == 0) 7148 return DAG.getUNDEF(VT); 7149 7150 if (NumDefs == 1) { 7151 assert(V.getNode() && "The single defined operand is empty!"); 7152 SmallVector<SDValue, 8> Opnds; 7153 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7154 if (i != Idx) { 7155 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7156 continue; 7157 } 7158 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7159 AddToWorklist(NV.getNode()); 7160 Opnds.push_back(NV); 7161 } 7162 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7163 } 7164 } 7165 7166 // Simplify the operands using demanded-bits information. 7167 if (!VT.isVector() && 7168 SimplifyDemandedBits(SDValue(N, 0))) 7169 return SDValue(N, 0); 7170 7171 return SDValue(); 7172 } 7173 7174 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7175 SDValue Elt = N->getOperand(i); 7176 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7177 return Elt.getNode(); 7178 return Elt.getOperand(Elt.getResNo()).getNode(); 7179 } 7180 7181 /// build_pair (load, load) -> load 7182 /// if load locations are consecutive. 7183 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7184 assert(N->getOpcode() == ISD::BUILD_PAIR); 7185 7186 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7187 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7188 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7189 LD1->getAddressSpace() != LD2->getAddressSpace()) 7190 return SDValue(); 7191 EVT LD1VT = LD1->getValueType(0); 7192 7193 if (ISD::isNON_EXTLoad(LD2) && 7194 LD2->hasOneUse() && 7195 // If both are volatile this would reduce the number of volatile loads. 7196 // If one is volatile it might be ok, but play conservative and bail out. 7197 !LD1->isVolatile() && 7198 !LD2->isVolatile() && 7199 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 7200 unsigned Align = LD1->getAlignment(); 7201 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7202 VT.getTypeForEVT(*DAG.getContext())); 7203 7204 if (NewAlign <= Align && 7205 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7206 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7207 LD1->getBasePtr(), LD1->getPointerInfo(), 7208 false, false, false, Align); 7209 } 7210 7211 return SDValue(); 7212 } 7213 7214 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7215 SDValue N0 = N->getOperand(0); 7216 EVT VT = N->getValueType(0); 7217 7218 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7219 // Only do this before legalize, since afterward the target may be depending 7220 // on the bitconvert. 7221 // First check to see if this is all constant. 7222 if (!LegalTypes && 7223 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7224 VT.isVector()) { 7225 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7226 7227 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7228 assert(!DestEltVT.isVector() && 7229 "Element type of vector ValueType must not be vector!"); 7230 if (isSimple) 7231 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7232 } 7233 7234 // If the input is a constant, let getNode fold it. 7235 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7236 // If we can't allow illegal operations, we need to check that this is just 7237 // a fp -> int or int -> conversion and that the resulting operation will 7238 // be legal. 7239 if (!LegalOperations || 7240 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7241 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7242 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7243 TLI.isOperationLegal(ISD::Constant, VT))) 7244 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7245 } 7246 7247 // (conv (conv x, t1), t2) -> (conv x, t2) 7248 if (N0.getOpcode() == ISD::BITCAST) 7249 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7250 N0.getOperand(0)); 7251 7252 // fold (conv (load x)) -> (load (conv*)x) 7253 // If the resultant load doesn't need a higher alignment than the original! 7254 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7255 // Do not change the width of a volatile load. 7256 !cast<LoadSDNode>(N0)->isVolatile() && 7257 // Do not remove the cast if the types differ in endian layout. 7258 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7259 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7260 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7261 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7262 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7263 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 7264 VT.getTypeForEVT(*DAG.getContext())); 7265 unsigned OrigAlign = LN0->getAlignment(); 7266 7267 if (Align <= OrigAlign) { 7268 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7269 LN0->getBasePtr(), LN0->getPointerInfo(), 7270 LN0->isVolatile(), LN0->isNonTemporal(), 7271 LN0->isInvariant(), OrigAlign, 7272 LN0->getAAInfo()); 7273 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7274 return Load; 7275 } 7276 } 7277 7278 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7279 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7280 // This often reduces constant pool loads. 7281 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7282 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7283 N0.getNode()->hasOneUse() && VT.isInteger() && 7284 !VT.isVector() && !N0.getValueType().isVector()) { 7285 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7286 N0.getOperand(0)); 7287 AddToWorklist(NewConv.getNode()); 7288 7289 SDLoc DL(N); 7290 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7291 if (N0.getOpcode() == ISD::FNEG) 7292 return DAG.getNode(ISD::XOR, DL, VT, 7293 NewConv, DAG.getConstant(SignBit, DL, VT)); 7294 assert(N0.getOpcode() == ISD::FABS); 7295 return DAG.getNode(ISD::AND, DL, VT, 7296 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7297 } 7298 7299 // fold (bitconvert (fcopysign cst, x)) -> 7300 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7301 // Note that we don't handle (copysign x, cst) because this can always be 7302 // folded to an fneg or fabs. 7303 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7304 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7305 VT.isInteger() && !VT.isVector()) { 7306 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7307 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7308 if (isTypeLegal(IntXVT)) { 7309 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7310 IntXVT, N0.getOperand(1)); 7311 AddToWorklist(X.getNode()); 7312 7313 // If X has a different width than the result/lhs, sext it or truncate it. 7314 unsigned VTWidth = VT.getSizeInBits(); 7315 if (OrigXWidth < VTWidth) { 7316 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7317 AddToWorklist(X.getNode()); 7318 } else if (OrigXWidth > VTWidth) { 7319 // To get the sign bit in the right place, we have to shift it right 7320 // before truncating. 7321 SDLoc DL(X); 7322 X = DAG.getNode(ISD::SRL, DL, 7323 X.getValueType(), X, 7324 DAG.getConstant(OrigXWidth-VTWidth, DL, 7325 X.getValueType())); 7326 AddToWorklist(X.getNode()); 7327 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7328 AddToWorklist(X.getNode()); 7329 } 7330 7331 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7332 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7333 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7334 AddToWorklist(X.getNode()); 7335 7336 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7337 VT, N0.getOperand(0)); 7338 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7339 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7340 AddToWorklist(Cst.getNode()); 7341 7342 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7343 } 7344 } 7345 7346 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7347 if (N0.getOpcode() == ISD::BUILD_PAIR) 7348 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7349 return CombineLD; 7350 7351 // Remove double bitcasts from shuffles - this is often a legacy of 7352 // XformToShuffleWithZero being used to combine bitmaskings (of 7353 // float vectors bitcast to integer vectors) into shuffles. 7354 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7355 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7356 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7357 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7358 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7359 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7360 7361 // If operands are a bitcast, peek through if it casts the original VT. 7362 // If operands are a constant, just bitcast back to original VT. 7363 auto PeekThroughBitcast = [&](SDValue Op) { 7364 if (Op.getOpcode() == ISD::BITCAST && 7365 Op.getOperand(0).getValueType() == VT) 7366 return SDValue(Op.getOperand(0)); 7367 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7368 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7369 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7370 return SDValue(); 7371 }; 7372 7373 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7374 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7375 if (!(SV0 && SV1)) 7376 return SDValue(); 7377 7378 int MaskScale = 7379 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7380 SmallVector<int, 8> NewMask; 7381 for (int M : SVN->getMask()) 7382 for (int i = 0; i != MaskScale; ++i) 7383 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7384 7385 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7386 if (!LegalMask) { 7387 std::swap(SV0, SV1); 7388 ShuffleVectorSDNode::commuteMask(NewMask); 7389 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7390 } 7391 7392 if (LegalMask) 7393 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7394 } 7395 7396 return SDValue(); 7397 } 7398 7399 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7400 EVT VT = N->getValueType(0); 7401 return CombineConsecutiveLoads(N, VT); 7402 } 7403 7404 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7405 /// operands. DstEltVT indicates the destination element value type. 7406 SDValue DAGCombiner:: 7407 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7408 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7409 7410 // If this is already the right type, we're done. 7411 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7412 7413 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7414 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7415 7416 // If this is a conversion of N elements of one type to N elements of another 7417 // type, convert each element. This handles FP<->INT cases. 7418 if (SrcBitSize == DstBitSize) { 7419 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7420 BV->getValueType(0).getVectorNumElements()); 7421 7422 // Due to the FP element handling below calling this routine recursively, 7423 // we can end up with a scalar-to-vector node here. 7424 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7425 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7426 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7427 DstEltVT, BV->getOperand(0))); 7428 7429 SmallVector<SDValue, 8> Ops; 7430 for (SDValue Op : BV->op_values()) { 7431 // If the vector element type is not legal, the BUILD_VECTOR operands 7432 // are promoted and implicitly truncated. Make that explicit here. 7433 if (Op.getValueType() != SrcEltVT) 7434 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7435 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7436 DstEltVT, Op)); 7437 AddToWorklist(Ops.back().getNode()); 7438 } 7439 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7440 } 7441 7442 // Otherwise, we're growing or shrinking the elements. To avoid having to 7443 // handle annoying details of growing/shrinking FP values, we convert them to 7444 // int first. 7445 if (SrcEltVT.isFloatingPoint()) { 7446 // Convert the input float vector to a int vector where the elements are the 7447 // same sizes. 7448 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7449 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7450 SrcEltVT = IntVT; 7451 } 7452 7453 // Now we know the input is an integer vector. If the output is a FP type, 7454 // convert to integer first, then to FP of the right size. 7455 if (DstEltVT.isFloatingPoint()) { 7456 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7457 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7458 7459 // Next, convert to FP elements of the same size. 7460 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7461 } 7462 7463 SDLoc DL(BV); 7464 7465 // Okay, we know the src/dst types are both integers of differing types. 7466 // Handling growing first. 7467 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7468 if (SrcBitSize < DstBitSize) { 7469 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7470 7471 SmallVector<SDValue, 8> Ops; 7472 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7473 i += NumInputsPerOutput) { 7474 bool isLE = DAG.getDataLayout().isLittleEndian(); 7475 APInt NewBits = APInt(DstBitSize, 0); 7476 bool EltIsUndef = true; 7477 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7478 // Shift the previously computed bits over. 7479 NewBits <<= SrcBitSize; 7480 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7481 if (Op.getOpcode() == ISD::UNDEF) continue; 7482 EltIsUndef = false; 7483 7484 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7485 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7486 } 7487 7488 if (EltIsUndef) 7489 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7490 else 7491 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7492 } 7493 7494 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7495 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7496 } 7497 7498 // Finally, this must be the case where we are shrinking elements: each input 7499 // turns into multiple outputs. 7500 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7501 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7502 NumOutputsPerInput*BV->getNumOperands()); 7503 SmallVector<SDValue, 8> Ops; 7504 7505 for (const SDValue &Op : BV->op_values()) { 7506 if (Op.getOpcode() == ISD::UNDEF) { 7507 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7508 continue; 7509 } 7510 7511 APInt OpVal = cast<ConstantSDNode>(Op)-> 7512 getAPIntValue().zextOrTrunc(SrcBitSize); 7513 7514 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7515 APInt ThisVal = OpVal.trunc(DstBitSize); 7516 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7517 OpVal = OpVal.lshr(DstBitSize); 7518 } 7519 7520 // For big endian targets, swap the order of the pieces of each element. 7521 if (DAG.getDataLayout().isBigEndian()) 7522 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7523 } 7524 7525 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7526 } 7527 7528 /// Try to perform FMA combining on a given FADD node. 7529 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7530 SDValue N0 = N->getOperand(0); 7531 SDValue N1 = N->getOperand(1); 7532 EVT VT = N->getValueType(0); 7533 SDLoc SL(N); 7534 7535 const TargetOptions &Options = DAG.getTarget().Options; 7536 bool AllowFusion = 7537 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7538 7539 // Floating-point multiply-add with intermediate rounding. 7540 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7541 7542 // Floating-point multiply-add without intermediate rounding. 7543 bool HasFMA = 7544 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7545 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7546 7547 // No valid opcode, do not combine. 7548 if (!HasFMAD && !HasFMA) 7549 return SDValue(); 7550 7551 // Always prefer FMAD to FMA for precision. 7552 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7553 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7554 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7555 7556 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7557 // prefer to fold the multiply with fewer uses. 7558 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7559 N1.getOpcode() == ISD::FMUL) { 7560 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7561 std::swap(N0, N1); 7562 } 7563 7564 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7565 if (N0.getOpcode() == ISD::FMUL && 7566 (Aggressive || N0->hasOneUse())) { 7567 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7568 N0.getOperand(0), N0.getOperand(1), N1); 7569 } 7570 7571 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7572 // Note: Commutes FADD operands. 7573 if (N1.getOpcode() == ISD::FMUL && 7574 (Aggressive || N1->hasOneUse())) { 7575 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7576 N1.getOperand(0), N1.getOperand(1), N0); 7577 } 7578 7579 // Look through FP_EXTEND nodes to do more combining. 7580 if (AllowFusion && LookThroughFPExt) { 7581 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7582 if (N0.getOpcode() == ISD::FP_EXTEND) { 7583 SDValue N00 = N0.getOperand(0); 7584 if (N00.getOpcode() == ISD::FMUL) 7585 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7586 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7587 N00.getOperand(0)), 7588 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7589 N00.getOperand(1)), N1); 7590 } 7591 7592 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7593 // Note: Commutes FADD operands. 7594 if (N1.getOpcode() == ISD::FP_EXTEND) { 7595 SDValue N10 = N1.getOperand(0); 7596 if (N10.getOpcode() == ISD::FMUL) 7597 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7598 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7599 N10.getOperand(0)), 7600 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7601 N10.getOperand(1)), N0); 7602 } 7603 } 7604 7605 // More folding opportunities when target permits. 7606 if ((AllowFusion || HasFMAD) && Aggressive) { 7607 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7608 if (N0.getOpcode() == PreferredFusedOpcode && 7609 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7610 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7611 N0.getOperand(0), N0.getOperand(1), 7612 DAG.getNode(PreferredFusedOpcode, SL, VT, 7613 N0.getOperand(2).getOperand(0), 7614 N0.getOperand(2).getOperand(1), 7615 N1)); 7616 } 7617 7618 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7619 if (N1->getOpcode() == PreferredFusedOpcode && 7620 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7621 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7622 N1.getOperand(0), N1.getOperand(1), 7623 DAG.getNode(PreferredFusedOpcode, SL, VT, 7624 N1.getOperand(2).getOperand(0), 7625 N1.getOperand(2).getOperand(1), 7626 N0)); 7627 } 7628 7629 if (AllowFusion && LookThroughFPExt) { 7630 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7631 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7632 auto FoldFAddFMAFPExtFMul = [&] ( 7633 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7634 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7635 DAG.getNode(PreferredFusedOpcode, SL, VT, 7636 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7637 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7638 Z)); 7639 }; 7640 if (N0.getOpcode() == PreferredFusedOpcode) { 7641 SDValue N02 = N0.getOperand(2); 7642 if (N02.getOpcode() == ISD::FP_EXTEND) { 7643 SDValue N020 = N02.getOperand(0); 7644 if (N020.getOpcode() == ISD::FMUL) 7645 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7646 N020.getOperand(0), N020.getOperand(1), 7647 N1); 7648 } 7649 } 7650 7651 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7652 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7653 // FIXME: This turns two single-precision and one double-precision 7654 // operation into two double-precision operations, which might not be 7655 // interesting for all targets, especially GPUs. 7656 auto FoldFAddFPExtFMAFMul = [&] ( 7657 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7658 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7659 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7660 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7661 DAG.getNode(PreferredFusedOpcode, SL, VT, 7662 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7663 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7664 Z)); 7665 }; 7666 if (N0.getOpcode() == ISD::FP_EXTEND) { 7667 SDValue N00 = N0.getOperand(0); 7668 if (N00.getOpcode() == PreferredFusedOpcode) { 7669 SDValue N002 = N00.getOperand(2); 7670 if (N002.getOpcode() == ISD::FMUL) 7671 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7672 N002.getOperand(0), N002.getOperand(1), 7673 N1); 7674 } 7675 } 7676 7677 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7678 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7679 if (N1.getOpcode() == PreferredFusedOpcode) { 7680 SDValue N12 = N1.getOperand(2); 7681 if (N12.getOpcode() == ISD::FP_EXTEND) { 7682 SDValue N120 = N12.getOperand(0); 7683 if (N120.getOpcode() == ISD::FMUL) 7684 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7685 N120.getOperand(0), N120.getOperand(1), 7686 N0); 7687 } 7688 } 7689 7690 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7691 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7692 // FIXME: This turns two single-precision and one double-precision 7693 // operation into two double-precision operations, which might not be 7694 // interesting for all targets, especially GPUs. 7695 if (N1.getOpcode() == ISD::FP_EXTEND) { 7696 SDValue N10 = N1.getOperand(0); 7697 if (N10.getOpcode() == PreferredFusedOpcode) { 7698 SDValue N102 = N10.getOperand(2); 7699 if (N102.getOpcode() == ISD::FMUL) 7700 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7701 N102.getOperand(0), N102.getOperand(1), 7702 N0); 7703 } 7704 } 7705 } 7706 } 7707 7708 return SDValue(); 7709 } 7710 7711 /// Try to perform FMA combining on a given FSUB node. 7712 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7713 SDValue N0 = N->getOperand(0); 7714 SDValue N1 = N->getOperand(1); 7715 EVT VT = N->getValueType(0); 7716 SDLoc SL(N); 7717 7718 const TargetOptions &Options = DAG.getTarget().Options; 7719 bool AllowFusion = 7720 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7721 7722 // Floating-point multiply-add with intermediate rounding. 7723 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7724 7725 // Floating-point multiply-add without intermediate rounding. 7726 bool HasFMA = 7727 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7728 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7729 7730 // No valid opcode, do not combine. 7731 if (!HasFMAD && !HasFMA) 7732 return SDValue(); 7733 7734 // Always prefer FMAD to FMA for precision. 7735 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7736 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7737 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7738 7739 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7740 if (N0.getOpcode() == ISD::FMUL && 7741 (Aggressive || N0->hasOneUse())) { 7742 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7743 N0.getOperand(0), N0.getOperand(1), 7744 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7745 } 7746 7747 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7748 // Note: Commutes FSUB operands. 7749 if (N1.getOpcode() == ISD::FMUL && 7750 (Aggressive || N1->hasOneUse())) 7751 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7752 DAG.getNode(ISD::FNEG, SL, VT, 7753 N1.getOperand(0)), 7754 N1.getOperand(1), N0); 7755 7756 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7757 if (N0.getOpcode() == ISD::FNEG && 7758 N0.getOperand(0).getOpcode() == ISD::FMUL && 7759 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7760 SDValue N00 = N0.getOperand(0).getOperand(0); 7761 SDValue N01 = N0.getOperand(0).getOperand(1); 7762 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7763 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7764 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7765 } 7766 7767 // Look through FP_EXTEND nodes to do more combining. 7768 if (AllowFusion && LookThroughFPExt) { 7769 // fold (fsub (fpext (fmul x, y)), z) 7770 // -> (fma (fpext x), (fpext y), (fneg z)) 7771 if (N0.getOpcode() == ISD::FP_EXTEND) { 7772 SDValue N00 = N0.getOperand(0); 7773 if (N00.getOpcode() == ISD::FMUL) 7774 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7775 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7776 N00.getOperand(0)), 7777 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7778 N00.getOperand(1)), 7779 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7780 } 7781 7782 // fold (fsub x, (fpext (fmul y, z))) 7783 // -> (fma (fneg (fpext y)), (fpext z), x) 7784 // Note: Commutes FSUB operands. 7785 if (N1.getOpcode() == ISD::FP_EXTEND) { 7786 SDValue N10 = N1.getOperand(0); 7787 if (N10.getOpcode() == ISD::FMUL) 7788 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7789 DAG.getNode(ISD::FNEG, SL, VT, 7790 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7791 N10.getOperand(0))), 7792 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7793 N10.getOperand(1)), 7794 N0); 7795 } 7796 7797 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7798 // -> (fneg (fma (fpext x), (fpext y), z)) 7799 // Note: This could be removed with appropriate canonicalization of the 7800 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7801 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7802 // from implementing the canonicalization in visitFSUB. 7803 if (N0.getOpcode() == ISD::FP_EXTEND) { 7804 SDValue N00 = N0.getOperand(0); 7805 if (N00.getOpcode() == ISD::FNEG) { 7806 SDValue N000 = N00.getOperand(0); 7807 if (N000.getOpcode() == ISD::FMUL) { 7808 return DAG.getNode(ISD::FNEG, SL, VT, 7809 DAG.getNode(PreferredFusedOpcode, SL, VT, 7810 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7811 N000.getOperand(0)), 7812 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7813 N000.getOperand(1)), 7814 N1)); 7815 } 7816 } 7817 } 7818 7819 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7820 // -> (fneg (fma (fpext x)), (fpext y), z) 7821 // Note: This could be removed with appropriate canonicalization of the 7822 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7823 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7824 // from implementing the canonicalization in visitFSUB. 7825 if (N0.getOpcode() == ISD::FNEG) { 7826 SDValue N00 = N0.getOperand(0); 7827 if (N00.getOpcode() == ISD::FP_EXTEND) { 7828 SDValue N000 = N00.getOperand(0); 7829 if (N000.getOpcode() == ISD::FMUL) { 7830 return DAG.getNode(ISD::FNEG, SL, VT, 7831 DAG.getNode(PreferredFusedOpcode, SL, VT, 7832 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7833 N000.getOperand(0)), 7834 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7835 N000.getOperand(1)), 7836 N1)); 7837 } 7838 } 7839 } 7840 7841 } 7842 7843 // More folding opportunities when target permits. 7844 if ((AllowFusion || HasFMAD) && Aggressive) { 7845 // fold (fsub (fma x, y, (fmul u, v)), z) 7846 // -> (fma x, y (fma u, v, (fneg z))) 7847 if (N0.getOpcode() == PreferredFusedOpcode && 7848 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7849 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7850 N0.getOperand(0), N0.getOperand(1), 7851 DAG.getNode(PreferredFusedOpcode, SL, VT, 7852 N0.getOperand(2).getOperand(0), 7853 N0.getOperand(2).getOperand(1), 7854 DAG.getNode(ISD::FNEG, SL, VT, 7855 N1))); 7856 } 7857 7858 // fold (fsub x, (fma y, z, (fmul u, v))) 7859 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7860 if (N1.getOpcode() == PreferredFusedOpcode && 7861 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7862 SDValue N20 = N1.getOperand(2).getOperand(0); 7863 SDValue N21 = N1.getOperand(2).getOperand(1); 7864 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7865 DAG.getNode(ISD::FNEG, SL, VT, 7866 N1.getOperand(0)), 7867 N1.getOperand(1), 7868 DAG.getNode(PreferredFusedOpcode, SL, VT, 7869 DAG.getNode(ISD::FNEG, SL, VT, N20), 7870 7871 N21, N0)); 7872 } 7873 7874 if (AllowFusion && LookThroughFPExt) { 7875 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7876 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 7877 if (N0.getOpcode() == PreferredFusedOpcode) { 7878 SDValue N02 = N0.getOperand(2); 7879 if (N02.getOpcode() == ISD::FP_EXTEND) { 7880 SDValue N020 = N02.getOperand(0); 7881 if (N020.getOpcode() == ISD::FMUL) 7882 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7883 N0.getOperand(0), N0.getOperand(1), 7884 DAG.getNode(PreferredFusedOpcode, SL, VT, 7885 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7886 N020.getOperand(0)), 7887 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7888 N020.getOperand(1)), 7889 DAG.getNode(ISD::FNEG, SL, VT, 7890 N1))); 7891 } 7892 } 7893 7894 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 7895 // -> (fma (fpext x), (fpext y), 7896 // (fma (fpext u), (fpext v), (fneg z))) 7897 // FIXME: This turns two single-precision and one double-precision 7898 // operation into two double-precision operations, which might not be 7899 // interesting for all targets, especially GPUs. 7900 if (N0.getOpcode() == ISD::FP_EXTEND) { 7901 SDValue N00 = N0.getOperand(0); 7902 if (N00.getOpcode() == PreferredFusedOpcode) { 7903 SDValue N002 = N00.getOperand(2); 7904 if (N002.getOpcode() == ISD::FMUL) 7905 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7906 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7907 N00.getOperand(0)), 7908 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7909 N00.getOperand(1)), 7910 DAG.getNode(PreferredFusedOpcode, SL, VT, 7911 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7912 N002.getOperand(0)), 7913 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7914 N002.getOperand(1)), 7915 DAG.getNode(ISD::FNEG, SL, VT, 7916 N1))); 7917 } 7918 } 7919 7920 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 7921 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 7922 if (N1.getOpcode() == PreferredFusedOpcode && 7923 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 7924 SDValue N120 = N1.getOperand(2).getOperand(0); 7925 if (N120.getOpcode() == ISD::FMUL) { 7926 SDValue N1200 = N120.getOperand(0); 7927 SDValue N1201 = N120.getOperand(1); 7928 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7929 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 7930 N1.getOperand(1), 7931 DAG.getNode(PreferredFusedOpcode, SL, VT, 7932 DAG.getNode(ISD::FNEG, SL, VT, 7933 DAG.getNode(ISD::FP_EXTEND, SL, 7934 VT, N1200)), 7935 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7936 N1201), 7937 N0)); 7938 } 7939 } 7940 7941 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 7942 // -> (fma (fneg (fpext y)), (fpext z), 7943 // (fma (fneg (fpext u)), (fpext v), x)) 7944 // FIXME: This turns two single-precision and one double-precision 7945 // operation into two double-precision operations, which might not be 7946 // interesting for all targets, especially GPUs. 7947 if (N1.getOpcode() == ISD::FP_EXTEND && 7948 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 7949 SDValue N100 = N1.getOperand(0).getOperand(0); 7950 SDValue N101 = N1.getOperand(0).getOperand(1); 7951 SDValue N102 = N1.getOperand(0).getOperand(2); 7952 if (N102.getOpcode() == ISD::FMUL) { 7953 SDValue N1020 = N102.getOperand(0); 7954 SDValue N1021 = N102.getOperand(1); 7955 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7956 DAG.getNode(ISD::FNEG, SL, VT, 7957 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7958 N100)), 7959 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 7960 DAG.getNode(PreferredFusedOpcode, SL, VT, 7961 DAG.getNode(ISD::FNEG, SL, VT, 7962 DAG.getNode(ISD::FP_EXTEND, SL, 7963 VT, N1020)), 7964 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7965 N1021), 7966 N0)); 7967 } 7968 } 7969 } 7970 } 7971 7972 return SDValue(); 7973 } 7974 7975 /// Try to perform FMA combining on a given FMUL node. 7976 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 7977 SDValue N0 = N->getOperand(0); 7978 SDValue N1 = N->getOperand(1); 7979 EVT VT = N->getValueType(0); 7980 SDLoc SL(N); 7981 7982 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 7983 7984 const TargetOptions &Options = DAG.getTarget().Options; 7985 bool AllowFusion = 7986 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7987 7988 // Floating-point multiply-add with intermediate rounding. 7989 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7990 7991 // Floating-point multiply-add without intermediate rounding. 7992 bool HasFMA = 7993 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7994 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7995 7996 // No valid opcode, do not combine. 7997 if (!HasFMAD && !HasFMA) 7998 return SDValue(); 7999 8000 // Always prefer FMAD to FMA for precision. 8001 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8002 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8003 8004 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8005 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8006 auto FuseFADD = [&](SDValue X, SDValue Y) { 8007 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8008 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8009 if (XC1 && XC1->isExactlyValue(+1.0)) 8010 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8011 if (XC1 && XC1->isExactlyValue(-1.0)) 8012 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8013 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8014 } 8015 return SDValue(); 8016 }; 8017 8018 if (SDValue FMA = FuseFADD(N0, N1)) 8019 return FMA; 8020 if (SDValue FMA = FuseFADD(N1, N0)) 8021 return FMA; 8022 8023 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8024 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8025 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8026 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8027 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8028 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8029 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8030 if (XC0 && XC0->isExactlyValue(+1.0)) 8031 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8032 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8033 Y); 8034 if (XC0 && XC0->isExactlyValue(-1.0)) 8035 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8036 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8037 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8038 8039 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8040 if (XC1 && XC1->isExactlyValue(+1.0)) 8041 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8042 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8043 if (XC1 && XC1->isExactlyValue(-1.0)) 8044 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8045 } 8046 return SDValue(); 8047 }; 8048 8049 if (SDValue FMA = FuseFSUB(N0, N1)) 8050 return FMA; 8051 if (SDValue FMA = FuseFSUB(N1, N0)) 8052 return FMA; 8053 8054 return SDValue(); 8055 } 8056 8057 SDValue DAGCombiner::visitFADD(SDNode *N) { 8058 SDValue N0 = N->getOperand(0); 8059 SDValue N1 = N->getOperand(1); 8060 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8061 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8062 EVT VT = N->getValueType(0); 8063 SDLoc DL(N); 8064 const TargetOptions &Options = DAG.getTarget().Options; 8065 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8066 8067 // fold vector ops 8068 if (VT.isVector()) 8069 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8070 return FoldedVOp; 8071 8072 // fold (fadd c1, c2) -> c1 + c2 8073 if (N0CFP && N1CFP) 8074 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8075 8076 // canonicalize constant to RHS 8077 if (N0CFP && !N1CFP) 8078 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8079 8080 // fold (fadd A, (fneg B)) -> (fsub A, B) 8081 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8082 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8083 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8084 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8085 8086 // fold (fadd (fneg A), B) -> (fsub B, A) 8087 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8088 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8089 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8090 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8091 8092 // If 'unsafe math' is enabled, fold lots of things. 8093 if (Options.UnsafeFPMath) { 8094 // No FP constant should be created after legalization as Instruction 8095 // Selection pass has a hard time dealing with FP constants. 8096 bool AllowNewConst = (Level < AfterLegalizeDAG); 8097 8098 // fold (fadd A, 0) -> A 8099 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8100 if (N1C->isZero()) 8101 return N0; 8102 8103 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8104 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8105 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8106 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8107 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8108 Flags), 8109 Flags); 8110 8111 // If allowed, fold (fadd (fneg x), x) -> 0.0 8112 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8113 return DAG.getConstantFP(0.0, DL, VT); 8114 8115 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8116 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8117 return DAG.getConstantFP(0.0, DL, VT); 8118 8119 // We can fold chains of FADD's of the same value into multiplications. 8120 // This transform is not safe in general because we are reducing the number 8121 // of rounding steps. 8122 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8123 if (N0.getOpcode() == ISD::FMUL) { 8124 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8125 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8126 8127 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8128 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8129 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8130 DAG.getConstantFP(1.0, DL, VT), Flags); 8131 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8132 } 8133 8134 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8135 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8136 N1.getOperand(0) == N1.getOperand(1) && 8137 N0.getOperand(0) == N1.getOperand(0)) { 8138 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8139 DAG.getConstantFP(2.0, DL, VT), Flags); 8140 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8141 } 8142 } 8143 8144 if (N1.getOpcode() == ISD::FMUL) { 8145 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8146 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8147 8148 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8149 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8150 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8151 DAG.getConstantFP(1.0, DL, VT), Flags); 8152 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8153 } 8154 8155 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8156 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8157 N0.getOperand(0) == N0.getOperand(1) && 8158 N1.getOperand(0) == N0.getOperand(0)) { 8159 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8160 DAG.getConstantFP(2.0, DL, VT), Flags); 8161 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8162 } 8163 } 8164 8165 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8166 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8167 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8168 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8169 (N0.getOperand(0) == N1)) { 8170 return DAG.getNode(ISD::FMUL, DL, VT, 8171 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8172 } 8173 } 8174 8175 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8176 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8177 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8178 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8179 N1.getOperand(0) == N0) { 8180 return DAG.getNode(ISD::FMUL, DL, VT, 8181 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8182 } 8183 } 8184 8185 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8186 if (AllowNewConst && 8187 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8188 N0.getOperand(0) == N0.getOperand(1) && 8189 N1.getOperand(0) == N1.getOperand(1) && 8190 N0.getOperand(0) == N1.getOperand(0)) { 8191 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8192 DAG.getConstantFP(4.0, DL, VT), Flags); 8193 } 8194 } 8195 } // enable-unsafe-fp-math 8196 8197 // FADD -> FMA combines: 8198 if (SDValue Fused = visitFADDForFMACombine(N)) { 8199 AddToWorklist(Fused.getNode()); 8200 return Fused; 8201 } 8202 8203 return SDValue(); 8204 } 8205 8206 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8207 SDValue N0 = N->getOperand(0); 8208 SDValue N1 = N->getOperand(1); 8209 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8210 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8211 EVT VT = N->getValueType(0); 8212 SDLoc dl(N); 8213 const TargetOptions &Options = DAG.getTarget().Options; 8214 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8215 8216 // fold vector ops 8217 if (VT.isVector()) 8218 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8219 return FoldedVOp; 8220 8221 // fold (fsub c1, c2) -> c1-c2 8222 if (N0CFP && N1CFP) 8223 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8224 8225 // fold (fsub A, (fneg B)) -> (fadd A, B) 8226 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8227 return DAG.getNode(ISD::FADD, dl, VT, N0, 8228 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8229 8230 // If 'unsafe math' is enabled, fold lots of things. 8231 if (Options.UnsafeFPMath) { 8232 // (fsub A, 0) -> A 8233 if (N1CFP && N1CFP->isZero()) 8234 return N0; 8235 8236 // (fsub 0, B) -> -B 8237 if (N0CFP && N0CFP->isZero()) { 8238 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8239 return GetNegatedExpression(N1, DAG, LegalOperations); 8240 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8241 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8242 } 8243 8244 // (fsub x, x) -> 0.0 8245 if (N0 == N1) 8246 return DAG.getConstantFP(0.0f, dl, VT); 8247 8248 // (fsub x, (fadd x, y)) -> (fneg y) 8249 // (fsub x, (fadd y, x)) -> (fneg y) 8250 if (N1.getOpcode() == ISD::FADD) { 8251 SDValue N10 = N1->getOperand(0); 8252 SDValue N11 = N1->getOperand(1); 8253 8254 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8255 return GetNegatedExpression(N11, DAG, LegalOperations); 8256 8257 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8258 return GetNegatedExpression(N10, DAG, LegalOperations); 8259 } 8260 } 8261 8262 // FSUB -> FMA combines: 8263 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8264 AddToWorklist(Fused.getNode()); 8265 return Fused; 8266 } 8267 8268 return SDValue(); 8269 } 8270 8271 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8272 SDValue N0 = N->getOperand(0); 8273 SDValue N1 = N->getOperand(1); 8274 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8275 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8276 EVT VT = N->getValueType(0); 8277 SDLoc DL(N); 8278 const TargetOptions &Options = DAG.getTarget().Options; 8279 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8280 8281 // fold vector ops 8282 if (VT.isVector()) { 8283 // This just handles C1 * C2 for vectors. Other vector folds are below. 8284 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8285 return FoldedVOp; 8286 } 8287 8288 // fold (fmul c1, c2) -> c1*c2 8289 if (N0CFP && N1CFP) 8290 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8291 8292 // canonicalize constant to RHS 8293 if (isConstantFPBuildVectorOrConstantFP(N0) && 8294 !isConstantFPBuildVectorOrConstantFP(N1)) 8295 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8296 8297 // fold (fmul A, 1.0) -> A 8298 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8299 return N0; 8300 8301 if (Options.UnsafeFPMath) { 8302 // fold (fmul A, 0) -> 0 8303 if (N1CFP && N1CFP->isZero()) 8304 return N1; 8305 8306 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8307 if (N0.getOpcode() == ISD::FMUL) { 8308 // Fold scalars or any vector constants (not just splats). 8309 // This fold is done in general by InstCombine, but extra fmul insts 8310 // may have been generated during lowering. 8311 SDValue N00 = N0.getOperand(0); 8312 SDValue N01 = N0.getOperand(1); 8313 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8314 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8315 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8316 8317 // Check 1: Make sure that the first operand of the inner multiply is NOT 8318 // a constant. Otherwise, we may induce infinite looping. 8319 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8320 // Check 2: Make sure that the second operand of the inner multiply and 8321 // the second operand of the outer multiply are constants. 8322 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8323 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8324 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8325 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8326 } 8327 } 8328 } 8329 8330 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8331 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8332 // during an early run of DAGCombiner can prevent folding with fmuls 8333 // inserted during lowering. 8334 if (N0.getOpcode() == ISD::FADD && 8335 (N0.getOperand(0) == N0.getOperand(1)) && 8336 N0.hasOneUse()) { 8337 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8338 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8339 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8340 } 8341 } 8342 8343 // fold (fmul X, 2.0) -> (fadd X, X) 8344 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8345 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8346 8347 // fold (fmul X, -1.0) -> (fneg X) 8348 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8349 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8350 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8351 8352 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8353 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8354 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8355 // Both can be negated for free, check to see if at least one is cheaper 8356 // negated. 8357 if (LHSNeg == 2 || RHSNeg == 2) 8358 return DAG.getNode(ISD::FMUL, DL, VT, 8359 GetNegatedExpression(N0, DAG, LegalOperations), 8360 GetNegatedExpression(N1, DAG, LegalOperations), 8361 Flags); 8362 } 8363 } 8364 8365 // FMUL -> FMA combines: 8366 if (SDValue Fused = visitFMULForFMACombine(N)) { 8367 AddToWorklist(Fused.getNode()); 8368 return Fused; 8369 } 8370 8371 return SDValue(); 8372 } 8373 8374 SDValue DAGCombiner::visitFMA(SDNode *N) { 8375 SDValue N0 = N->getOperand(0); 8376 SDValue N1 = N->getOperand(1); 8377 SDValue N2 = N->getOperand(2); 8378 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8379 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8380 EVT VT = N->getValueType(0); 8381 SDLoc dl(N); 8382 const TargetOptions &Options = DAG.getTarget().Options; 8383 8384 // Constant fold FMA. 8385 if (isa<ConstantFPSDNode>(N0) && 8386 isa<ConstantFPSDNode>(N1) && 8387 isa<ConstantFPSDNode>(N2)) { 8388 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8389 } 8390 8391 if (Options.UnsafeFPMath) { 8392 if (N0CFP && N0CFP->isZero()) 8393 return N2; 8394 if (N1CFP && N1CFP->isZero()) 8395 return N2; 8396 } 8397 // TODO: The FMA node should have flags that propagate to these nodes. 8398 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8399 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8400 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8401 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8402 8403 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8404 if (isConstantFPBuildVectorOrConstantFP(N0) && 8405 !isConstantFPBuildVectorOrConstantFP(N1)) 8406 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8407 8408 // TODO: FMA nodes should have flags that propagate to the created nodes. 8409 // For now, create a Flags object for use with all unsafe math transforms. 8410 SDNodeFlags Flags; 8411 Flags.setUnsafeAlgebra(true); 8412 8413 if (Options.UnsafeFPMath) { 8414 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8415 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8416 isConstantFPBuildVectorOrConstantFP(N1) && 8417 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8418 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8419 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8420 &Flags), &Flags); 8421 } 8422 8423 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8424 if (N0.getOpcode() == ISD::FMUL && 8425 isConstantFPBuildVectorOrConstantFP(N1) && 8426 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8427 return DAG.getNode(ISD::FMA, dl, VT, 8428 N0.getOperand(0), 8429 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8430 &Flags), 8431 N2); 8432 } 8433 } 8434 8435 // (fma x, 1, y) -> (fadd x, y) 8436 // (fma x, -1, y) -> (fadd (fneg x), y) 8437 if (N1CFP) { 8438 if (N1CFP->isExactlyValue(1.0)) 8439 // TODO: The FMA node should have flags that propagate to this node. 8440 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8441 8442 if (N1CFP->isExactlyValue(-1.0) && 8443 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8444 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8445 AddToWorklist(RHSNeg.getNode()); 8446 // TODO: The FMA node should have flags that propagate to this node. 8447 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8448 } 8449 } 8450 8451 if (Options.UnsafeFPMath) { 8452 // (fma x, c, x) -> (fmul x, (c+1)) 8453 if (N1CFP && N0 == N2) { 8454 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8455 DAG.getNode(ISD::FADD, dl, VT, 8456 N1, DAG.getConstantFP(1.0, dl, VT), 8457 &Flags), &Flags); 8458 } 8459 8460 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8461 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8462 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8463 DAG.getNode(ISD::FADD, dl, VT, 8464 N1, DAG.getConstantFP(-1.0, dl, VT), 8465 &Flags), &Flags); 8466 } 8467 } 8468 8469 return SDValue(); 8470 } 8471 8472 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8473 // reciprocal. 8474 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8475 // Notice that this is not always beneficial. One reason is different target 8476 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8477 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8478 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8479 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8480 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8481 const SDNodeFlags *Flags = N->getFlags(); 8482 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8483 return SDValue(); 8484 8485 // Skip if current node is a reciprocal. 8486 SDValue N0 = N->getOperand(0); 8487 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8488 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8489 return SDValue(); 8490 8491 // Exit early if the target does not want this transform or if there can't 8492 // possibly be enough uses of the divisor to make the transform worthwhile. 8493 SDValue N1 = N->getOperand(1); 8494 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8495 if (!MinUses || N1->use_size() < MinUses) 8496 return SDValue(); 8497 8498 // Find all FDIV users of the same divisor. 8499 // Use a set because duplicates may be present in the user list. 8500 SetVector<SDNode *> Users; 8501 for (auto *U : N1->uses()) { 8502 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8503 // This division is eligible for optimization only if global unsafe math 8504 // is enabled or if this division allows reciprocal formation. 8505 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8506 Users.insert(U); 8507 } 8508 } 8509 8510 // Now that we have the actual number of divisor uses, make sure it meets 8511 // the minimum threshold specified by the target. 8512 if (Users.size() < MinUses) 8513 return SDValue(); 8514 8515 EVT VT = N->getValueType(0); 8516 SDLoc DL(N); 8517 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8518 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8519 8520 // Dividend / Divisor -> Dividend * Reciprocal 8521 for (auto *U : Users) { 8522 SDValue Dividend = U->getOperand(0); 8523 if (Dividend != FPOne) { 8524 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8525 Reciprocal, Flags); 8526 CombineTo(U, NewNode); 8527 } else if (U != Reciprocal.getNode()) { 8528 // In the absence of fast-math-flags, this user node is always the 8529 // same node as Reciprocal, but with FMF they may be different nodes. 8530 CombineTo(U, Reciprocal); 8531 } 8532 } 8533 return SDValue(N, 0); // N was replaced. 8534 } 8535 8536 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8537 SDValue N0 = N->getOperand(0); 8538 SDValue N1 = N->getOperand(1); 8539 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8540 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8541 EVT VT = N->getValueType(0); 8542 SDLoc DL(N); 8543 const TargetOptions &Options = DAG.getTarget().Options; 8544 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8545 8546 // fold vector ops 8547 if (VT.isVector()) 8548 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8549 return FoldedVOp; 8550 8551 // fold (fdiv c1, c2) -> c1/c2 8552 if (N0CFP && N1CFP) 8553 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8554 8555 if (Options.UnsafeFPMath) { 8556 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8557 if (N1CFP) { 8558 // Compute the reciprocal 1.0 / c2. 8559 APFloat N1APF = N1CFP->getValueAPF(); 8560 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8561 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8562 // Only do the transform if the reciprocal is a legal fp immediate that 8563 // isn't too nasty (eg NaN, denormal, ...). 8564 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8565 (!LegalOperations || 8566 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8567 // backend)... we should handle this gracefully after Legalize. 8568 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8569 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8570 TLI.isFPImmLegal(Recip, VT))) 8571 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8572 DAG.getConstantFP(Recip, DL, VT), Flags); 8573 } 8574 8575 // If this FDIV is part of a reciprocal square root, it may be folded 8576 // into a target-specific square root estimate instruction. 8577 if (N1.getOpcode() == ISD::FSQRT) { 8578 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) { 8579 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8580 } 8581 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8582 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8583 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8584 Flags)) { 8585 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8586 AddToWorklist(RV.getNode()); 8587 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8588 } 8589 } else if (N1.getOpcode() == ISD::FP_ROUND && 8590 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8591 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8592 Flags)) { 8593 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8594 AddToWorklist(RV.getNode()); 8595 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8596 } 8597 } else if (N1.getOpcode() == ISD::FMUL) { 8598 // Look through an FMUL. Even though this won't remove the FDIV directly, 8599 // it's still worthwhile to get rid of the FSQRT if possible. 8600 SDValue SqrtOp; 8601 SDValue OtherOp; 8602 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8603 SqrtOp = N1.getOperand(0); 8604 OtherOp = N1.getOperand(1); 8605 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8606 SqrtOp = N1.getOperand(1); 8607 OtherOp = N1.getOperand(0); 8608 } 8609 if (SqrtOp.getNode()) { 8610 // We found a FSQRT, so try to make this fold: 8611 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8612 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8613 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8614 AddToWorklist(RV.getNode()); 8615 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8616 } 8617 } 8618 } 8619 8620 // Fold into a reciprocal estimate and multiply instead of a real divide. 8621 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8622 AddToWorklist(RV.getNode()); 8623 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8624 } 8625 } 8626 8627 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8628 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8629 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8630 // Both can be negated for free, check to see if at least one is cheaper 8631 // negated. 8632 if (LHSNeg == 2 || RHSNeg == 2) 8633 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8634 GetNegatedExpression(N0, DAG, LegalOperations), 8635 GetNegatedExpression(N1, DAG, LegalOperations), 8636 Flags); 8637 } 8638 } 8639 8640 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8641 return CombineRepeatedDivisors; 8642 8643 return SDValue(); 8644 } 8645 8646 SDValue DAGCombiner::visitFREM(SDNode *N) { 8647 SDValue N0 = N->getOperand(0); 8648 SDValue N1 = N->getOperand(1); 8649 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8650 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8651 EVT VT = N->getValueType(0); 8652 8653 // fold (frem c1, c2) -> fmod(c1,c2) 8654 if (N0CFP && N1CFP) 8655 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8656 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8657 8658 return SDValue(); 8659 } 8660 8661 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8662 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8663 return SDValue(); 8664 8665 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8666 // For now, create a Flags object for use with all unsafe math transforms. 8667 SDNodeFlags Flags; 8668 Flags.setUnsafeAlgebra(true); 8669 8670 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8671 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags); 8672 if (!RV) 8673 return SDValue(); 8674 8675 EVT VT = RV.getValueType(); 8676 SDLoc DL(N); 8677 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags); 8678 AddToWorklist(RV.getNode()); 8679 8680 // Unfortunately, RV is now NaN if the input was exactly 0. 8681 // Select out this case and force the answer to 0. 8682 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8683 EVT CCVT = getSetCCResultType(VT); 8684 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ); 8685 AddToWorklist(ZeroCmp.getNode()); 8686 AddToWorklist(RV.getNode()); 8687 8688 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 8689 ZeroCmp, Zero, RV); 8690 } 8691 8692 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8693 SDValue N0 = N->getOperand(0); 8694 SDValue N1 = N->getOperand(1); 8695 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8696 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8697 EVT VT = N->getValueType(0); 8698 8699 if (N0CFP && N1CFP) // Constant fold 8700 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8701 8702 if (N1CFP) { 8703 const APFloat& V = N1CFP->getValueAPF(); 8704 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8705 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8706 if (!V.isNegative()) { 8707 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8708 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8709 } else { 8710 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8711 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8712 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8713 } 8714 } 8715 8716 // copysign(fabs(x), y) -> copysign(x, y) 8717 // copysign(fneg(x), y) -> copysign(x, y) 8718 // copysign(copysign(x,z), y) -> copysign(x, y) 8719 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8720 N0.getOpcode() == ISD::FCOPYSIGN) 8721 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8722 N0.getOperand(0), N1); 8723 8724 // copysign(x, abs(y)) -> abs(x) 8725 if (N1.getOpcode() == ISD::FABS) 8726 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8727 8728 // copysign(x, copysign(y,z)) -> copysign(x, z) 8729 if (N1.getOpcode() == ISD::FCOPYSIGN) 8730 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8731 N0, N1.getOperand(1)); 8732 8733 // copysign(x, fp_extend(y)) -> copysign(x, y) 8734 // copysign(x, fp_round(y)) -> copysign(x, y) 8735 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 8736 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8737 N0, N1.getOperand(0)); 8738 8739 return SDValue(); 8740 } 8741 8742 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8743 SDValue N0 = N->getOperand(0); 8744 EVT VT = N->getValueType(0); 8745 EVT OpVT = N0.getValueType(); 8746 8747 // fold (sint_to_fp c1) -> c1fp 8748 if (isConstantIntBuildVectorOrConstantInt(N0) && 8749 // ...but only if the target supports immediate floating-point values 8750 (!LegalOperations || 8751 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8752 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8753 8754 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8755 // but UINT_TO_FP is legal on this target, try to convert. 8756 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8757 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8758 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8759 if (DAG.SignBitIsZero(N0)) 8760 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8761 } 8762 8763 // The next optimizations are desirable only if SELECT_CC can be lowered. 8764 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8765 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8766 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8767 !VT.isVector() && 8768 (!LegalOperations || 8769 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8770 SDLoc DL(N); 8771 SDValue Ops[] = 8772 { N0.getOperand(0), N0.getOperand(1), 8773 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8774 N0.getOperand(2) }; 8775 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8776 } 8777 8778 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8779 // (select_cc x, y, 1.0, 0.0,, cc) 8780 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8781 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8782 (!LegalOperations || 8783 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8784 SDLoc DL(N); 8785 SDValue Ops[] = 8786 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8787 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8788 N0.getOperand(0).getOperand(2) }; 8789 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8790 } 8791 } 8792 8793 return SDValue(); 8794 } 8795 8796 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8797 SDValue N0 = N->getOperand(0); 8798 EVT VT = N->getValueType(0); 8799 EVT OpVT = N0.getValueType(); 8800 8801 // fold (uint_to_fp c1) -> c1fp 8802 if (isConstantIntBuildVectorOrConstantInt(N0) && 8803 // ...but only if the target supports immediate floating-point values 8804 (!LegalOperations || 8805 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8806 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8807 8808 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8809 // but SINT_TO_FP is legal on this target, try to convert. 8810 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8811 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8812 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8813 if (DAG.SignBitIsZero(N0)) 8814 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8815 } 8816 8817 // The next optimizations are desirable only if SELECT_CC can be lowered. 8818 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8819 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8820 8821 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8822 (!LegalOperations || 8823 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8824 SDLoc DL(N); 8825 SDValue Ops[] = 8826 { N0.getOperand(0), N0.getOperand(1), 8827 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8828 N0.getOperand(2) }; 8829 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8830 } 8831 } 8832 8833 return SDValue(); 8834 } 8835 8836 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8837 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8838 SDValue N0 = N->getOperand(0); 8839 EVT VT = N->getValueType(0); 8840 8841 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8842 return SDValue(); 8843 8844 SDValue Src = N0.getOperand(0); 8845 EVT SrcVT = Src.getValueType(); 8846 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8847 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8848 8849 // We can safely assume the conversion won't overflow the output range, 8850 // because (for example) (uint8_t)18293.f is undefined behavior. 8851 8852 // Since we can assume the conversion won't overflow, our decision as to 8853 // whether the input will fit in the float should depend on the minimum 8854 // of the input range and output range. 8855 8856 // This means this is also safe for a signed input and unsigned output, since 8857 // a negative input would lead to undefined behavior. 8858 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8859 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8860 unsigned ActualSize = std::min(InputSize, OutputSize); 8861 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8862 8863 // We can only fold away the float conversion if the input range can be 8864 // represented exactly in the float range. 8865 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8866 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8867 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8868 : ISD::ZERO_EXTEND; 8869 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8870 } 8871 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8872 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8873 if (SrcVT == VT) 8874 return Src; 8875 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 8876 } 8877 return SDValue(); 8878 } 8879 8880 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8881 SDValue N0 = N->getOperand(0); 8882 EVT VT = N->getValueType(0); 8883 8884 // fold (fp_to_sint c1fp) -> c1 8885 if (isConstantFPBuildVectorOrConstantFP(N0)) 8886 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8887 8888 return FoldIntToFPToInt(N, DAG); 8889 } 8890 8891 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 8892 SDValue N0 = N->getOperand(0); 8893 EVT VT = N->getValueType(0); 8894 8895 // fold (fp_to_uint c1fp) -> c1 8896 if (isConstantFPBuildVectorOrConstantFP(N0)) 8897 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 8898 8899 return FoldIntToFPToInt(N, DAG); 8900 } 8901 8902 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 8903 SDValue N0 = N->getOperand(0); 8904 SDValue N1 = N->getOperand(1); 8905 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8906 EVT VT = N->getValueType(0); 8907 8908 // fold (fp_round c1fp) -> c1fp 8909 if (N0CFP) 8910 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 8911 8912 // fold (fp_round (fp_extend x)) -> x 8913 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 8914 return N0.getOperand(0); 8915 8916 // fold (fp_round (fp_round x)) -> (fp_round x) 8917 if (N0.getOpcode() == ISD::FP_ROUND) { 8918 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 8919 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 8920 // If the first fp_round isn't a value preserving truncation, it might 8921 // introduce a tie in the second fp_round, that wouldn't occur in the 8922 // single-step fp_round we want to fold to. 8923 // In other words, double rounding isn't the same as rounding. 8924 // Also, this is a value preserving truncation iff both fp_round's are. 8925 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 8926 SDLoc DL(N); 8927 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 8928 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 8929 } 8930 } 8931 8932 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 8933 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 8934 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 8935 N0.getOperand(0), N1); 8936 AddToWorklist(Tmp.getNode()); 8937 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8938 Tmp, N0.getOperand(1)); 8939 } 8940 8941 return SDValue(); 8942 } 8943 8944 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 8945 SDValue N0 = N->getOperand(0); 8946 EVT VT = N->getValueType(0); 8947 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8948 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8949 8950 // fold (fp_round_inreg c1fp) -> c1fp 8951 if (N0CFP && isTypeLegal(EVT)) { 8952 SDLoc DL(N); 8953 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 8954 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 8955 } 8956 8957 return SDValue(); 8958 } 8959 8960 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 8961 SDValue N0 = N->getOperand(0); 8962 EVT VT = N->getValueType(0); 8963 8964 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 8965 if (N->hasOneUse() && 8966 N->use_begin()->getOpcode() == ISD::FP_ROUND) 8967 return SDValue(); 8968 8969 // fold (fp_extend c1fp) -> c1fp 8970 if (isConstantFPBuildVectorOrConstantFP(N0)) 8971 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 8972 8973 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 8974 if (N0.getOpcode() == ISD::FP16_TO_FP && 8975 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 8976 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 8977 8978 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 8979 // value of X. 8980 if (N0.getOpcode() == ISD::FP_ROUND 8981 && N0.getNode()->getConstantOperandVal(1) == 1) { 8982 SDValue In = N0.getOperand(0); 8983 if (In.getValueType() == VT) return In; 8984 if (VT.bitsLT(In.getValueType())) 8985 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 8986 In, N0.getOperand(1)); 8987 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 8988 } 8989 8990 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 8991 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8992 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8993 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8994 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8995 LN0->getChain(), 8996 LN0->getBasePtr(), N0.getValueType(), 8997 LN0->getMemOperand()); 8998 CombineTo(N, ExtLoad); 8999 CombineTo(N0.getNode(), 9000 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9001 N0.getValueType(), ExtLoad, 9002 DAG.getIntPtrConstant(1, SDLoc(N0))), 9003 ExtLoad.getValue(1)); 9004 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9005 } 9006 9007 return SDValue(); 9008 } 9009 9010 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9011 SDValue N0 = N->getOperand(0); 9012 EVT VT = N->getValueType(0); 9013 9014 // fold (fceil c1) -> fceil(c1) 9015 if (isConstantFPBuildVectorOrConstantFP(N0)) 9016 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9017 9018 return SDValue(); 9019 } 9020 9021 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9022 SDValue N0 = N->getOperand(0); 9023 EVT VT = N->getValueType(0); 9024 9025 // fold (ftrunc c1) -> ftrunc(c1) 9026 if (isConstantFPBuildVectorOrConstantFP(N0)) 9027 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9028 9029 return SDValue(); 9030 } 9031 9032 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9033 SDValue N0 = N->getOperand(0); 9034 EVT VT = N->getValueType(0); 9035 9036 // fold (ffloor c1) -> ffloor(c1) 9037 if (isConstantFPBuildVectorOrConstantFP(N0)) 9038 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9039 9040 return SDValue(); 9041 } 9042 9043 // FIXME: FNEG and FABS have a lot in common; refactor. 9044 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9045 SDValue N0 = N->getOperand(0); 9046 EVT VT = N->getValueType(0); 9047 9048 // Constant fold FNEG. 9049 if (isConstantFPBuildVectorOrConstantFP(N0)) 9050 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9051 9052 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9053 &DAG.getTarget().Options)) 9054 return GetNegatedExpression(N0, DAG, LegalOperations); 9055 9056 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9057 // constant pool values. 9058 if (!TLI.isFNegFree(VT) && 9059 N0.getOpcode() == ISD::BITCAST && 9060 N0.getNode()->hasOneUse()) { 9061 SDValue Int = N0.getOperand(0); 9062 EVT IntVT = Int.getValueType(); 9063 if (IntVT.isInteger() && !IntVT.isVector()) { 9064 APInt SignMask; 9065 if (N0.getValueType().isVector()) { 9066 // For a vector, get a mask such as 0x80... per scalar element 9067 // and splat it. 9068 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9069 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9070 } else { 9071 // For a scalar, just generate 0x80... 9072 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9073 } 9074 SDLoc DL0(N0); 9075 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9076 DAG.getConstant(SignMask, DL0, IntVT)); 9077 AddToWorklist(Int.getNode()); 9078 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 9079 } 9080 } 9081 9082 // (fneg (fmul c, x)) -> (fmul -c, x) 9083 if (N0.getOpcode() == ISD::FMUL && 9084 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9085 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9086 if (CFP1) { 9087 APFloat CVal = CFP1->getValueAPF(); 9088 CVal.changeSign(); 9089 if (Level >= AfterLegalizeDAG && 9090 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 9091 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 9092 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9093 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9094 N0.getOperand(1)), 9095 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9096 } 9097 } 9098 9099 return SDValue(); 9100 } 9101 9102 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9103 SDValue N0 = N->getOperand(0); 9104 SDValue N1 = N->getOperand(1); 9105 EVT VT = N->getValueType(0); 9106 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9107 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9108 9109 if (N0CFP && N1CFP) { 9110 const APFloat &C0 = N0CFP->getValueAPF(); 9111 const APFloat &C1 = N1CFP->getValueAPF(); 9112 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9113 } 9114 9115 // Canonicalize to constant on RHS. 9116 if (isConstantFPBuildVectorOrConstantFP(N0) && 9117 !isConstantFPBuildVectorOrConstantFP(N1)) 9118 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9119 9120 return SDValue(); 9121 } 9122 9123 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9124 SDValue N0 = N->getOperand(0); 9125 SDValue N1 = N->getOperand(1); 9126 EVT VT = N->getValueType(0); 9127 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9128 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9129 9130 if (N0CFP && N1CFP) { 9131 const APFloat &C0 = N0CFP->getValueAPF(); 9132 const APFloat &C1 = N1CFP->getValueAPF(); 9133 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9134 } 9135 9136 // Canonicalize to constant on RHS. 9137 if (isConstantFPBuildVectorOrConstantFP(N0) && 9138 !isConstantFPBuildVectorOrConstantFP(N1)) 9139 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9140 9141 return SDValue(); 9142 } 9143 9144 SDValue DAGCombiner::visitFABS(SDNode *N) { 9145 SDValue N0 = N->getOperand(0); 9146 EVT VT = N->getValueType(0); 9147 9148 // fold (fabs c1) -> fabs(c1) 9149 if (isConstantFPBuildVectorOrConstantFP(N0)) 9150 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9151 9152 // fold (fabs (fabs x)) -> (fabs x) 9153 if (N0.getOpcode() == ISD::FABS) 9154 return N->getOperand(0); 9155 9156 // fold (fabs (fneg x)) -> (fabs x) 9157 // fold (fabs (fcopysign x, y)) -> (fabs x) 9158 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9159 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9160 9161 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9162 // constant pool values. 9163 if (!TLI.isFAbsFree(VT) && 9164 N0.getOpcode() == ISD::BITCAST && 9165 N0.getNode()->hasOneUse()) { 9166 SDValue Int = N0.getOperand(0); 9167 EVT IntVT = Int.getValueType(); 9168 if (IntVT.isInteger() && !IntVT.isVector()) { 9169 APInt SignMask; 9170 if (N0.getValueType().isVector()) { 9171 // For a vector, get a mask such as 0x7f... per scalar element 9172 // and splat it. 9173 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9174 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9175 } else { 9176 // For a scalar, just generate 0x7f... 9177 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9178 } 9179 SDLoc DL(N0); 9180 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9181 DAG.getConstant(SignMask, DL, IntVT)); 9182 AddToWorklist(Int.getNode()); 9183 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 9184 } 9185 } 9186 9187 return SDValue(); 9188 } 9189 9190 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9191 SDValue Chain = N->getOperand(0); 9192 SDValue N1 = N->getOperand(1); 9193 SDValue N2 = N->getOperand(2); 9194 9195 // If N is a constant we could fold this into a fallthrough or unconditional 9196 // branch. However that doesn't happen very often in normal code, because 9197 // Instcombine/SimplifyCFG should have handled the available opportunities. 9198 // If we did this folding here, it would be necessary to update the 9199 // MachineBasicBlock CFG, which is awkward. 9200 9201 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9202 // on the target. 9203 if (N1.getOpcode() == ISD::SETCC && 9204 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9205 N1.getOperand(0).getValueType())) { 9206 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9207 Chain, N1.getOperand(2), 9208 N1.getOperand(0), N1.getOperand(1), N2); 9209 } 9210 9211 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9212 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9213 (N1.getOperand(0).hasOneUse() && 9214 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9215 SDNode *Trunc = nullptr; 9216 if (N1.getOpcode() == ISD::TRUNCATE) { 9217 // Look pass the truncate. 9218 Trunc = N1.getNode(); 9219 N1 = N1.getOperand(0); 9220 } 9221 9222 // Match this pattern so that we can generate simpler code: 9223 // 9224 // %a = ... 9225 // %b = and i32 %a, 2 9226 // %c = srl i32 %b, 1 9227 // brcond i32 %c ... 9228 // 9229 // into 9230 // 9231 // %a = ... 9232 // %b = and i32 %a, 2 9233 // %c = setcc eq %b, 0 9234 // brcond %c ... 9235 // 9236 // This applies only when the AND constant value has one bit set and the 9237 // SRL constant is equal to the log2 of the AND constant. The back-end is 9238 // smart enough to convert the result into a TEST/JMP sequence. 9239 SDValue Op0 = N1.getOperand(0); 9240 SDValue Op1 = N1.getOperand(1); 9241 9242 if (Op0.getOpcode() == ISD::AND && 9243 Op1.getOpcode() == ISD::Constant) { 9244 SDValue AndOp1 = Op0.getOperand(1); 9245 9246 if (AndOp1.getOpcode() == ISD::Constant) { 9247 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9248 9249 if (AndConst.isPowerOf2() && 9250 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9251 SDLoc DL(N); 9252 SDValue SetCC = 9253 DAG.getSetCC(DL, 9254 getSetCCResultType(Op0.getValueType()), 9255 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9256 ISD::SETNE); 9257 9258 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9259 MVT::Other, Chain, SetCC, N2); 9260 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9261 // will convert it back to (X & C1) >> C2. 9262 CombineTo(N, NewBRCond, false); 9263 // Truncate is dead. 9264 if (Trunc) 9265 deleteAndRecombine(Trunc); 9266 // Replace the uses of SRL with SETCC 9267 WorklistRemover DeadNodes(*this); 9268 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9269 deleteAndRecombine(N1.getNode()); 9270 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9271 } 9272 } 9273 } 9274 9275 if (Trunc) 9276 // Restore N1 if the above transformation doesn't match. 9277 N1 = N->getOperand(1); 9278 } 9279 9280 // Transform br(xor(x, y)) -> br(x != y) 9281 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9282 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9283 SDNode *TheXor = N1.getNode(); 9284 SDValue Op0 = TheXor->getOperand(0); 9285 SDValue Op1 = TheXor->getOperand(1); 9286 if (Op0.getOpcode() == Op1.getOpcode()) { 9287 // Avoid missing important xor optimizations. 9288 if (SDValue Tmp = visitXOR(TheXor)) { 9289 if (Tmp.getNode() != TheXor) { 9290 DEBUG(dbgs() << "\nReplacing.8 "; 9291 TheXor->dump(&DAG); 9292 dbgs() << "\nWith: "; 9293 Tmp.getNode()->dump(&DAG); 9294 dbgs() << '\n'); 9295 WorklistRemover DeadNodes(*this); 9296 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9297 deleteAndRecombine(TheXor); 9298 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9299 MVT::Other, Chain, Tmp, N2); 9300 } 9301 9302 // visitXOR has changed XOR's operands or replaced the XOR completely, 9303 // bail out. 9304 return SDValue(N, 0); 9305 } 9306 } 9307 9308 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9309 bool Equal = false; 9310 if (isOneConstant(Op0) && Op0.hasOneUse() && 9311 Op0.getOpcode() == ISD::XOR) { 9312 TheXor = Op0.getNode(); 9313 Equal = true; 9314 } 9315 9316 EVT SetCCVT = N1.getValueType(); 9317 if (LegalTypes) 9318 SetCCVT = getSetCCResultType(SetCCVT); 9319 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9320 SetCCVT, 9321 Op0, Op1, 9322 Equal ? ISD::SETEQ : ISD::SETNE); 9323 // Replace the uses of XOR with SETCC 9324 WorklistRemover DeadNodes(*this); 9325 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9326 deleteAndRecombine(N1.getNode()); 9327 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9328 MVT::Other, Chain, SetCC, N2); 9329 } 9330 } 9331 9332 return SDValue(); 9333 } 9334 9335 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9336 // 9337 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9338 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9339 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9340 9341 // If N is a constant we could fold this into a fallthrough or unconditional 9342 // branch. However that doesn't happen very often in normal code, because 9343 // Instcombine/SimplifyCFG should have handled the available opportunities. 9344 // If we did this folding here, it would be necessary to update the 9345 // MachineBasicBlock CFG, which is awkward. 9346 9347 // Use SimplifySetCC to simplify SETCC's. 9348 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9349 CondLHS, CondRHS, CC->get(), SDLoc(N), 9350 false); 9351 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9352 9353 // fold to a simpler setcc 9354 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9355 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9356 N->getOperand(0), Simp.getOperand(2), 9357 Simp.getOperand(0), Simp.getOperand(1), 9358 N->getOperand(4)); 9359 9360 return SDValue(); 9361 } 9362 9363 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9364 /// and that N may be folded in the load / store addressing mode. 9365 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9366 SelectionDAG &DAG, 9367 const TargetLowering &TLI) { 9368 EVT VT; 9369 unsigned AS; 9370 9371 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9372 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9373 return false; 9374 VT = LD->getMemoryVT(); 9375 AS = LD->getAddressSpace(); 9376 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9377 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9378 return false; 9379 VT = ST->getMemoryVT(); 9380 AS = ST->getAddressSpace(); 9381 } else 9382 return false; 9383 9384 TargetLowering::AddrMode AM; 9385 if (N->getOpcode() == ISD::ADD) { 9386 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9387 if (Offset) 9388 // [reg +/- imm] 9389 AM.BaseOffs = Offset->getSExtValue(); 9390 else 9391 // [reg +/- reg] 9392 AM.Scale = 1; 9393 } else if (N->getOpcode() == ISD::SUB) { 9394 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9395 if (Offset) 9396 // [reg +/- imm] 9397 AM.BaseOffs = -Offset->getSExtValue(); 9398 else 9399 // [reg +/- reg] 9400 AM.Scale = 1; 9401 } else 9402 return false; 9403 9404 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9405 VT.getTypeForEVT(*DAG.getContext()), AS); 9406 } 9407 9408 /// Try turning a load/store into a pre-indexed load/store when the base 9409 /// pointer is an add or subtract and it has other uses besides the load/store. 9410 /// After the transformation, the new indexed load/store has effectively folded 9411 /// the add/subtract in and all of its other uses are redirected to the 9412 /// new load/store. 9413 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9414 if (Level < AfterLegalizeDAG) 9415 return false; 9416 9417 bool isLoad = true; 9418 SDValue Ptr; 9419 EVT VT; 9420 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9421 if (LD->isIndexed()) 9422 return false; 9423 VT = LD->getMemoryVT(); 9424 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9425 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9426 return false; 9427 Ptr = LD->getBasePtr(); 9428 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9429 if (ST->isIndexed()) 9430 return false; 9431 VT = ST->getMemoryVT(); 9432 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9433 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9434 return false; 9435 Ptr = ST->getBasePtr(); 9436 isLoad = false; 9437 } else { 9438 return false; 9439 } 9440 9441 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9442 // out. There is no reason to make this a preinc/predec. 9443 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9444 Ptr.getNode()->hasOneUse()) 9445 return false; 9446 9447 // Ask the target to do addressing mode selection. 9448 SDValue BasePtr; 9449 SDValue Offset; 9450 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9451 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9452 return false; 9453 9454 // Backends without true r+i pre-indexed forms may need to pass a 9455 // constant base with a variable offset so that constant coercion 9456 // will work with the patterns in canonical form. 9457 bool Swapped = false; 9458 if (isa<ConstantSDNode>(BasePtr)) { 9459 std::swap(BasePtr, Offset); 9460 Swapped = true; 9461 } 9462 9463 // Don't create a indexed load / store with zero offset. 9464 if (isNullConstant(Offset)) 9465 return false; 9466 9467 // Try turning it into a pre-indexed load / store except when: 9468 // 1) The new base ptr is a frame index. 9469 // 2) If N is a store and the new base ptr is either the same as or is a 9470 // predecessor of the value being stored. 9471 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9472 // that would create a cycle. 9473 // 4) All uses are load / store ops that use it as old base ptr. 9474 9475 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9476 // (plus the implicit offset) to a register to preinc anyway. 9477 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9478 return false; 9479 9480 // Check #2. 9481 if (!isLoad) { 9482 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9483 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9484 return false; 9485 } 9486 9487 // If the offset is a constant, there may be other adds of constants that 9488 // can be folded with this one. We should do this to avoid having to keep 9489 // a copy of the original base pointer. 9490 SmallVector<SDNode *, 16> OtherUses; 9491 if (isa<ConstantSDNode>(Offset)) 9492 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9493 UE = BasePtr.getNode()->use_end(); 9494 UI != UE; ++UI) { 9495 SDUse &Use = UI.getUse(); 9496 // Skip the use that is Ptr and uses of other results from BasePtr's 9497 // node (important for nodes that return multiple results). 9498 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9499 continue; 9500 9501 if (Use.getUser()->isPredecessorOf(N)) 9502 continue; 9503 9504 if (Use.getUser()->getOpcode() != ISD::ADD && 9505 Use.getUser()->getOpcode() != ISD::SUB) { 9506 OtherUses.clear(); 9507 break; 9508 } 9509 9510 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9511 if (!isa<ConstantSDNode>(Op1)) { 9512 OtherUses.clear(); 9513 break; 9514 } 9515 9516 // FIXME: In some cases, we can be smarter about this. 9517 if (Op1.getValueType() != Offset.getValueType()) { 9518 OtherUses.clear(); 9519 break; 9520 } 9521 9522 OtherUses.push_back(Use.getUser()); 9523 } 9524 9525 if (Swapped) 9526 std::swap(BasePtr, Offset); 9527 9528 // Now check for #3 and #4. 9529 bool RealUse = false; 9530 9531 // Caches for hasPredecessorHelper 9532 SmallPtrSet<const SDNode *, 32> Visited; 9533 SmallVector<const SDNode *, 16> Worklist; 9534 9535 for (SDNode *Use : Ptr.getNode()->uses()) { 9536 if (Use == N) 9537 continue; 9538 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 9539 return false; 9540 9541 // If Ptr may be folded in addressing mode of other use, then it's 9542 // not profitable to do this transformation. 9543 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9544 RealUse = true; 9545 } 9546 9547 if (!RealUse) 9548 return false; 9549 9550 SDValue Result; 9551 if (isLoad) 9552 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9553 BasePtr, Offset, AM); 9554 else 9555 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9556 BasePtr, Offset, AM); 9557 ++PreIndexedNodes; 9558 ++NodesCombined; 9559 DEBUG(dbgs() << "\nReplacing.4 "; 9560 N->dump(&DAG); 9561 dbgs() << "\nWith: "; 9562 Result.getNode()->dump(&DAG); 9563 dbgs() << '\n'); 9564 WorklistRemover DeadNodes(*this); 9565 if (isLoad) { 9566 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9567 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9568 } else { 9569 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9570 } 9571 9572 // Finally, since the node is now dead, remove it from the graph. 9573 deleteAndRecombine(N); 9574 9575 if (Swapped) 9576 std::swap(BasePtr, Offset); 9577 9578 // Replace other uses of BasePtr that can be updated to use Ptr 9579 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9580 unsigned OffsetIdx = 1; 9581 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9582 OffsetIdx = 0; 9583 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9584 BasePtr.getNode() && "Expected BasePtr operand"); 9585 9586 // We need to replace ptr0 in the following expression: 9587 // x0 * offset0 + y0 * ptr0 = t0 9588 // knowing that 9589 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9590 // 9591 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9592 // indexed load/store and the expresion that needs to be re-written. 9593 // 9594 // Therefore, we have: 9595 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9596 9597 ConstantSDNode *CN = 9598 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9599 int X0, X1, Y0, Y1; 9600 APInt Offset0 = CN->getAPIntValue(); 9601 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9602 9603 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9604 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9605 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9606 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9607 9608 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9609 9610 APInt CNV = Offset0; 9611 if (X0 < 0) CNV = -CNV; 9612 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9613 else CNV = CNV - Offset1; 9614 9615 SDLoc DL(OtherUses[i]); 9616 9617 // We can now generate the new expression. 9618 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9619 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9620 9621 SDValue NewUse = DAG.getNode(Opcode, 9622 DL, 9623 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9624 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9625 deleteAndRecombine(OtherUses[i]); 9626 } 9627 9628 // Replace the uses of Ptr with uses of the updated base value. 9629 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9630 deleteAndRecombine(Ptr.getNode()); 9631 9632 return true; 9633 } 9634 9635 /// Try to combine a load/store with a add/sub of the base pointer node into a 9636 /// post-indexed load/store. The transformation folded the add/subtract into the 9637 /// new indexed load/store effectively and all of its uses are redirected to the 9638 /// new load/store. 9639 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9640 if (Level < AfterLegalizeDAG) 9641 return false; 9642 9643 bool isLoad = true; 9644 SDValue Ptr; 9645 EVT VT; 9646 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9647 if (LD->isIndexed()) 9648 return false; 9649 VT = LD->getMemoryVT(); 9650 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9651 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9652 return false; 9653 Ptr = LD->getBasePtr(); 9654 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9655 if (ST->isIndexed()) 9656 return false; 9657 VT = ST->getMemoryVT(); 9658 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9659 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9660 return false; 9661 Ptr = ST->getBasePtr(); 9662 isLoad = false; 9663 } else { 9664 return false; 9665 } 9666 9667 if (Ptr.getNode()->hasOneUse()) 9668 return false; 9669 9670 for (SDNode *Op : Ptr.getNode()->uses()) { 9671 if (Op == N || 9672 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9673 continue; 9674 9675 SDValue BasePtr; 9676 SDValue Offset; 9677 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9678 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9679 // Don't create a indexed load / store with zero offset. 9680 if (isNullConstant(Offset)) 9681 continue; 9682 9683 // Try turning it into a post-indexed load / store except when 9684 // 1) All uses are load / store ops that use it as base ptr (and 9685 // it may be folded as addressing mmode). 9686 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9687 // nor a successor of N. Otherwise, if Op is folded that would 9688 // create a cycle. 9689 9690 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9691 continue; 9692 9693 // Check for #1. 9694 bool TryNext = false; 9695 for (SDNode *Use : BasePtr.getNode()->uses()) { 9696 if (Use == Ptr.getNode()) 9697 continue; 9698 9699 // If all the uses are load / store addresses, then don't do the 9700 // transformation. 9701 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9702 bool RealUse = false; 9703 for (SDNode *UseUse : Use->uses()) { 9704 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9705 RealUse = true; 9706 } 9707 9708 if (!RealUse) { 9709 TryNext = true; 9710 break; 9711 } 9712 } 9713 } 9714 9715 if (TryNext) 9716 continue; 9717 9718 // Check for #2 9719 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9720 SDValue Result = isLoad 9721 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9722 BasePtr, Offset, AM) 9723 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9724 BasePtr, Offset, AM); 9725 ++PostIndexedNodes; 9726 ++NodesCombined; 9727 DEBUG(dbgs() << "\nReplacing.5 "; 9728 N->dump(&DAG); 9729 dbgs() << "\nWith: "; 9730 Result.getNode()->dump(&DAG); 9731 dbgs() << '\n'); 9732 WorklistRemover DeadNodes(*this); 9733 if (isLoad) { 9734 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9735 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9736 } else { 9737 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9738 } 9739 9740 // Finally, since the node is now dead, remove it from the graph. 9741 deleteAndRecombine(N); 9742 9743 // Replace the uses of Use with uses of the updated base value. 9744 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9745 Result.getValue(isLoad ? 1 : 0)); 9746 deleteAndRecombine(Op); 9747 return true; 9748 } 9749 } 9750 } 9751 9752 return false; 9753 } 9754 9755 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9756 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9757 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9758 assert(AM != ISD::UNINDEXED); 9759 SDValue BP = LD->getOperand(1); 9760 SDValue Inc = LD->getOperand(2); 9761 9762 // Some backends use TargetConstants for load offsets, but don't expect 9763 // TargetConstants in general ADD nodes. We can convert these constants into 9764 // regular Constants (if the constant is not opaque). 9765 assert((Inc.getOpcode() != ISD::TargetConstant || 9766 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9767 "Cannot split out indexing using opaque target constants"); 9768 if (Inc.getOpcode() == ISD::TargetConstant) { 9769 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9770 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9771 ConstInc->getValueType(0)); 9772 } 9773 9774 unsigned Opc = 9775 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9776 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9777 } 9778 9779 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9780 LoadSDNode *LD = cast<LoadSDNode>(N); 9781 SDValue Chain = LD->getChain(); 9782 SDValue Ptr = LD->getBasePtr(); 9783 9784 // If load is not volatile and there are no uses of the loaded value (and 9785 // the updated indexed value in case of indexed loads), change uses of the 9786 // chain value into uses of the chain input (i.e. delete the dead load). 9787 if (!LD->isVolatile()) { 9788 if (N->getValueType(1) == MVT::Other) { 9789 // Unindexed loads. 9790 if (!N->hasAnyUseOfValue(0)) { 9791 // It's not safe to use the two value CombineTo variant here. e.g. 9792 // v1, chain2 = load chain1, loc 9793 // v2, chain3 = load chain2, loc 9794 // v3 = add v2, c 9795 // Now we replace use of chain2 with chain1. This makes the second load 9796 // isomorphic to the one we are deleting, and thus makes this load live. 9797 DEBUG(dbgs() << "\nReplacing.6 "; 9798 N->dump(&DAG); 9799 dbgs() << "\nWith chain: "; 9800 Chain.getNode()->dump(&DAG); 9801 dbgs() << "\n"); 9802 WorklistRemover DeadNodes(*this); 9803 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9804 9805 if (N->use_empty()) 9806 deleteAndRecombine(N); 9807 9808 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9809 } 9810 } else { 9811 // Indexed loads. 9812 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9813 9814 // If this load has an opaque TargetConstant offset, then we cannot split 9815 // the indexing into an add/sub directly (that TargetConstant may not be 9816 // valid for a different type of node, and we cannot convert an opaque 9817 // target constant into a regular constant). 9818 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9819 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9820 9821 if (!N->hasAnyUseOfValue(0) && 9822 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9823 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9824 SDValue Index; 9825 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9826 Index = SplitIndexingFromLoad(LD); 9827 // Try to fold the base pointer arithmetic into subsequent loads and 9828 // stores. 9829 AddUsersToWorklist(N); 9830 } else 9831 Index = DAG.getUNDEF(N->getValueType(1)); 9832 DEBUG(dbgs() << "\nReplacing.7 "; 9833 N->dump(&DAG); 9834 dbgs() << "\nWith: "; 9835 Undef.getNode()->dump(&DAG); 9836 dbgs() << " and 2 other values\n"); 9837 WorklistRemover DeadNodes(*this); 9838 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9839 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9840 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9841 deleteAndRecombine(N); 9842 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9843 } 9844 } 9845 } 9846 9847 // If this load is directly stored, replace the load value with the stored 9848 // value. 9849 // TODO: Handle store large -> read small portion. 9850 // TODO: Handle TRUNCSTORE/LOADEXT 9851 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9852 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9853 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9854 if (PrevST->getBasePtr() == Ptr && 9855 PrevST->getValue().getValueType() == N->getValueType(0)) 9856 return CombineTo(N, Chain.getOperand(1), Chain); 9857 } 9858 } 9859 9860 // Try to infer better alignment information than the load already has. 9861 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9862 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9863 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9864 SDValue NewLoad = 9865 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9866 LD->getValueType(0), 9867 Chain, Ptr, LD->getPointerInfo(), 9868 LD->getMemoryVT(), 9869 LD->isVolatile(), LD->isNonTemporal(), 9870 LD->isInvariant(), Align, LD->getAAInfo()); 9871 if (NewLoad.getNode() != N) 9872 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9873 } 9874 } 9875 } 9876 9877 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 9878 : DAG.getSubtarget().useAA(); 9879 #ifndef NDEBUG 9880 if (CombinerAAOnlyFunc.getNumOccurrences() && 9881 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9882 UseAA = false; 9883 #endif 9884 if (UseAA && LD->isUnindexed()) { 9885 // Walk up chain skipping non-aliasing memory nodes. 9886 SDValue BetterChain = FindBetterChain(N, Chain); 9887 9888 // If there is a better chain. 9889 if (Chain != BetterChain) { 9890 SDValue ReplLoad; 9891 9892 // Replace the chain to void dependency. 9893 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 9894 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 9895 BetterChain, Ptr, LD->getMemOperand()); 9896 } else { 9897 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 9898 LD->getValueType(0), 9899 BetterChain, Ptr, LD->getMemoryVT(), 9900 LD->getMemOperand()); 9901 } 9902 9903 // Create token factor to keep old chain connected. 9904 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9905 MVT::Other, Chain, ReplLoad.getValue(1)); 9906 9907 // Make sure the new and old chains are cleaned up. 9908 AddToWorklist(Token.getNode()); 9909 9910 // Replace uses with load result and token factor. Don't add users 9911 // to work list. 9912 return CombineTo(N, ReplLoad.getValue(0), Token, false); 9913 } 9914 } 9915 9916 // Try transforming N to an indexed load. 9917 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9918 return SDValue(N, 0); 9919 9920 // Try to slice up N to more direct loads if the slices are mapped to 9921 // different register banks or pairing can take place. 9922 if (SliceUpLoad(N)) 9923 return SDValue(N, 0); 9924 9925 return SDValue(); 9926 } 9927 9928 namespace { 9929 /// \brief Helper structure used to slice a load in smaller loads. 9930 /// Basically a slice is obtained from the following sequence: 9931 /// Origin = load Ty1, Base 9932 /// Shift = srl Ty1 Origin, CstTy Amount 9933 /// Inst = trunc Shift to Ty2 9934 /// 9935 /// Then, it will be rewriten into: 9936 /// Slice = load SliceTy, Base + SliceOffset 9937 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 9938 /// 9939 /// SliceTy is deduced from the number of bits that are actually used to 9940 /// build Inst. 9941 struct LoadedSlice { 9942 /// \brief Helper structure used to compute the cost of a slice. 9943 struct Cost { 9944 /// Are we optimizing for code size. 9945 bool ForCodeSize; 9946 /// Various cost. 9947 unsigned Loads; 9948 unsigned Truncates; 9949 unsigned CrossRegisterBanksCopies; 9950 unsigned ZExts; 9951 unsigned Shift; 9952 9953 Cost(bool ForCodeSize = false) 9954 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 9955 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 9956 9957 /// \brief Get the cost of one isolated slice. 9958 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 9959 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 9960 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 9961 EVT TruncType = LS.Inst->getValueType(0); 9962 EVT LoadedType = LS.getLoadedType(); 9963 if (TruncType != LoadedType && 9964 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 9965 ZExts = 1; 9966 } 9967 9968 /// \brief Account for slicing gain in the current cost. 9969 /// Slicing provide a few gains like removing a shift or a 9970 /// truncate. This method allows to grow the cost of the original 9971 /// load with the gain from this slice. 9972 void addSliceGain(const LoadedSlice &LS) { 9973 // Each slice saves a truncate. 9974 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 9975 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 9976 LS.Inst->getValueType(0))) 9977 ++Truncates; 9978 // If there is a shift amount, this slice gets rid of it. 9979 if (LS.Shift) 9980 ++Shift; 9981 // If this slice can merge a cross register bank copy, account for it. 9982 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 9983 ++CrossRegisterBanksCopies; 9984 } 9985 9986 Cost &operator+=(const Cost &RHS) { 9987 Loads += RHS.Loads; 9988 Truncates += RHS.Truncates; 9989 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 9990 ZExts += RHS.ZExts; 9991 Shift += RHS.Shift; 9992 return *this; 9993 } 9994 9995 bool operator==(const Cost &RHS) const { 9996 return Loads == RHS.Loads && Truncates == RHS.Truncates && 9997 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 9998 ZExts == RHS.ZExts && Shift == RHS.Shift; 9999 } 10000 10001 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10002 10003 bool operator<(const Cost &RHS) const { 10004 // Assume cross register banks copies are as expensive as loads. 10005 // FIXME: Do we want some more target hooks? 10006 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10007 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10008 // Unless we are optimizing for code size, consider the 10009 // expensive operation first. 10010 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10011 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10012 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10013 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10014 } 10015 10016 bool operator>(const Cost &RHS) const { return RHS < *this; } 10017 10018 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10019 10020 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10021 }; 10022 // The last instruction that represent the slice. This should be a 10023 // truncate instruction. 10024 SDNode *Inst; 10025 // The original load instruction. 10026 LoadSDNode *Origin; 10027 // The right shift amount in bits from the original load. 10028 unsigned Shift; 10029 // The DAG from which Origin came from. 10030 // This is used to get some contextual information about legal types, etc. 10031 SelectionDAG *DAG; 10032 10033 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10034 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10035 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10036 10037 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10038 /// \return Result is \p BitWidth and has used bits set to 1 and 10039 /// not used bits set to 0. 10040 APInt getUsedBits() const { 10041 // Reproduce the trunc(lshr) sequence: 10042 // - Start from the truncated value. 10043 // - Zero extend to the desired bit width. 10044 // - Shift left. 10045 assert(Origin && "No original load to compare against."); 10046 unsigned BitWidth = Origin->getValueSizeInBits(0); 10047 assert(Inst && "This slice is not bound to an instruction"); 10048 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10049 "Extracted slice is bigger than the whole type!"); 10050 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10051 UsedBits.setAllBits(); 10052 UsedBits = UsedBits.zext(BitWidth); 10053 UsedBits <<= Shift; 10054 return UsedBits; 10055 } 10056 10057 /// \brief Get the size of the slice to be loaded in bytes. 10058 unsigned getLoadedSize() const { 10059 unsigned SliceSize = getUsedBits().countPopulation(); 10060 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10061 return SliceSize / 8; 10062 } 10063 10064 /// \brief Get the type that will be loaded for this slice. 10065 /// Note: This may not be the final type for the slice. 10066 EVT getLoadedType() const { 10067 assert(DAG && "Missing context"); 10068 LLVMContext &Ctxt = *DAG->getContext(); 10069 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10070 } 10071 10072 /// \brief Get the alignment of the load used for this slice. 10073 unsigned getAlignment() const { 10074 unsigned Alignment = Origin->getAlignment(); 10075 unsigned Offset = getOffsetFromBase(); 10076 if (Offset != 0) 10077 Alignment = MinAlign(Alignment, Alignment + Offset); 10078 return Alignment; 10079 } 10080 10081 /// \brief Check if this slice can be rewritten with legal operations. 10082 bool isLegal() const { 10083 // An invalid slice is not legal. 10084 if (!Origin || !Inst || !DAG) 10085 return false; 10086 10087 // Offsets are for indexed load only, we do not handle that. 10088 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 10089 return false; 10090 10091 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10092 10093 // Check that the type is legal. 10094 EVT SliceType = getLoadedType(); 10095 if (!TLI.isTypeLegal(SliceType)) 10096 return false; 10097 10098 // Check that the load is legal for this type. 10099 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10100 return false; 10101 10102 // Check that the offset can be computed. 10103 // 1. Check its type. 10104 EVT PtrType = Origin->getBasePtr().getValueType(); 10105 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10106 return false; 10107 10108 // 2. Check that it fits in the immediate. 10109 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10110 return false; 10111 10112 // 3. Check that the computation is legal. 10113 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10114 return false; 10115 10116 // Check that the zext is legal if it needs one. 10117 EVT TruncateType = Inst->getValueType(0); 10118 if (TruncateType != SliceType && 10119 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10120 return false; 10121 10122 return true; 10123 } 10124 10125 /// \brief Get the offset in bytes of this slice in the original chunk of 10126 /// bits. 10127 /// \pre DAG != nullptr. 10128 uint64_t getOffsetFromBase() const { 10129 assert(DAG && "Missing context."); 10130 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10131 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10132 uint64_t Offset = Shift / 8; 10133 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10134 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10135 "The size of the original loaded type is not a multiple of a" 10136 " byte."); 10137 // If Offset is bigger than TySizeInBytes, it means we are loading all 10138 // zeros. This should have been optimized before in the process. 10139 assert(TySizeInBytes > Offset && 10140 "Invalid shift amount for given loaded size"); 10141 if (IsBigEndian) 10142 Offset = TySizeInBytes - Offset - getLoadedSize(); 10143 return Offset; 10144 } 10145 10146 /// \brief Generate the sequence of instructions to load the slice 10147 /// represented by this object and redirect the uses of this slice to 10148 /// this new sequence of instructions. 10149 /// \pre this->Inst && this->Origin are valid Instructions and this 10150 /// object passed the legal check: LoadedSlice::isLegal returned true. 10151 /// \return The last instruction of the sequence used to load the slice. 10152 SDValue loadSlice() const { 10153 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10154 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10155 SDValue BaseAddr = OldBaseAddr; 10156 // Get the offset in that chunk of bytes w.r.t. the endianess. 10157 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10158 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10159 if (Offset) { 10160 // BaseAddr = BaseAddr + Offset. 10161 EVT ArithType = BaseAddr.getValueType(); 10162 SDLoc DL(Origin); 10163 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10164 DAG->getConstant(Offset, DL, ArithType)); 10165 } 10166 10167 // Create the type of the loaded slice according to its size. 10168 EVT SliceType = getLoadedType(); 10169 10170 // Create the load for the slice. 10171 SDValue LastInst = DAG->getLoad( 10172 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10173 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 10174 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 10175 // If the final type is not the same as the loaded type, this means that 10176 // we have to pad with zero. Create a zero extend for that. 10177 EVT FinalType = Inst->getValueType(0); 10178 if (SliceType != FinalType) 10179 LastInst = 10180 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10181 return LastInst; 10182 } 10183 10184 /// \brief Check if this slice can be merged with an expensive cross register 10185 /// bank copy. E.g., 10186 /// i = load i32 10187 /// f = bitcast i32 i to float 10188 bool canMergeExpensiveCrossRegisterBankCopy() const { 10189 if (!Inst || !Inst->hasOneUse()) 10190 return false; 10191 SDNode *Use = *Inst->use_begin(); 10192 if (Use->getOpcode() != ISD::BITCAST) 10193 return false; 10194 assert(DAG && "Missing context"); 10195 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10196 EVT ResVT = Use->getValueType(0); 10197 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10198 const TargetRegisterClass *ArgRC = 10199 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10200 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10201 return false; 10202 10203 // At this point, we know that we perform a cross-register-bank copy. 10204 // Check if it is expensive. 10205 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10206 // Assume bitcasts are cheap, unless both register classes do not 10207 // explicitly share a common sub class. 10208 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10209 return false; 10210 10211 // Check if it will be merged with the load. 10212 // 1. Check the alignment constraint. 10213 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10214 ResVT.getTypeForEVT(*DAG->getContext())); 10215 10216 if (RequiredAlignment > getAlignment()) 10217 return false; 10218 10219 // 2. Check that the load is a legal operation for that type. 10220 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10221 return false; 10222 10223 // 3. Check that we do not have a zext in the way. 10224 if (Inst->getValueType(0) != getLoadedType()) 10225 return false; 10226 10227 return true; 10228 } 10229 }; 10230 } 10231 10232 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10233 /// \p UsedBits looks like 0..0 1..1 0..0. 10234 static bool areUsedBitsDense(const APInt &UsedBits) { 10235 // If all the bits are one, this is dense! 10236 if (UsedBits.isAllOnesValue()) 10237 return true; 10238 10239 // Get rid of the unused bits on the right. 10240 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10241 // Get rid of the unused bits on the left. 10242 if (NarrowedUsedBits.countLeadingZeros()) 10243 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10244 // Check that the chunk of bits is completely used. 10245 return NarrowedUsedBits.isAllOnesValue(); 10246 } 10247 10248 /// \brief Check whether or not \p First and \p Second are next to each other 10249 /// in memory. This means that there is no hole between the bits loaded 10250 /// by \p First and the bits loaded by \p Second. 10251 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10252 const LoadedSlice &Second) { 10253 assert(First.Origin == Second.Origin && First.Origin && 10254 "Unable to match different memory origins."); 10255 APInt UsedBits = First.getUsedBits(); 10256 assert((UsedBits & Second.getUsedBits()) == 0 && 10257 "Slices are not supposed to overlap."); 10258 UsedBits |= Second.getUsedBits(); 10259 return areUsedBitsDense(UsedBits); 10260 } 10261 10262 /// \brief Adjust the \p GlobalLSCost according to the target 10263 /// paring capabilities and the layout of the slices. 10264 /// \pre \p GlobalLSCost should account for at least as many loads as 10265 /// there is in the slices in \p LoadedSlices. 10266 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10267 LoadedSlice::Cost &GlobalLSCost) { 10268 unsigned NumberOfSlices = LoadedSlices.size(); 10269 // If there is less than 2 elements, no pairing is possible. 10270 if (NumberOfSlices < 2) 10271 return; 10272 10273 // Sort the slices so that elements that are likely to be next to each 10274 // other in memory are next to each other in the list. 10275 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10276 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10277 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10278 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10279 }); 10280 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10281 // First (resp. Second) is the first (resp. Second) potentially candidate 10282 // to be placed in a paired load. 10283 const LoadedSlice *First = nullptr; 10284 const LoadedSlice *Second = nullptr; 10285 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10286 // Set the beginning of the pair. 10287 First = Second) { 10288 10289 Second = &LoadedSlices[CurrSlice]; 10290 10291 // If First is NULL, it means we start a new pair. 10292 // Get to the next slice. 10293 if (!First) 10294 continue; 10295 10296 EVT LoadedType = First->getLoadedType(); 10297 10298 // If the types of the slices are different, we cannot pair them. 10299 if (LoadedType != Second->getLoadedType()) 10300 continue; 10301 10302 // Check if the target supplies paired loads for this type. 10303 unsigned RequiredAlignment = 0; 10304 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10305 // move to the next pair, this type is hopeless. 10306 Second = nullptr; 10307 continue; 10308 } 10309 // Check if we meet the alignment requirement. 10310 if (RequiredAlignment > First->getAlignment()) 10311 continue; 10312 10313 // Check that both loads are next to each other in memory. 10314 if (!areSlicesNextToEachOther(*First, *Second)) 10315 continue; 10316 10317 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10318 --GlobalLSCost.Loads; 10319 // Move to the next pair. 10320 Second = nullptr; 10321 } 10322 } 10323 10324 /// \brief Check the profitability of all involved LoadedSlice. 10325 /// Currently, it is considered profitable if there is exactly two 10326 /// involved slices (1) which are (2) next to each other in memory, and 10327 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10328 /// 10329 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10330 /// the elements themselves. 10331 /// 10332 /// FIXME: When the cost model will be mature enough, we can relax 10333 /// constraints (1) and (2). 10334 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10335 const APInt &UsedBits, bool ForCodeSize) { 10336 unsigned NumberOfSlices = LoadedSlices.size(); 10337 if (StressLoadSlicing) 10338 return NumberOfSlices > 1; 10339 10340 // Check (1). 10341 if (NumberOfSlices != 2) 10342 return false; 10343 10344 // Check (2). 10345 if (!areUsedBitsDense(UsedBits)) 10346 return false; 10347 10348 // Check (3). 10349 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10350 // The original code has one big load. 10351 OrigCost.Loads = 1; 10352 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10353 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10354 // Accumulate the cost of all the slices. 10355 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10356 GlobalSlicingCost += SliceCost; 10357 10358 // Account as cost in the original configuration the gain obtained 10359 // with the current slices. 10360 OrigCost.addSliceGain(LS); 10361 } 10362 10363 // If the target supports paired load, adjust the cost accordingly. 10364 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10365 return OrigCost > GlobalSlicingCost; 10366 } 10367 10368 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10369 /// operations, split it in the various pieces being extracted. 10370 /// 10371 /// This sort of thing is introduced by SROA. 10372 /// This slicing takes care not to insert overlapping loads. 10373 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10374 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10375 if (Level < AfterLegalizeDAG) 10376 return false; 10377 10378 LoadSDNode *LD = cast<LoadSDNode>(N); 10379 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10380 !LD->getValueType(0).isInteger()) 10381 return false; 10382 10383 // Keep track of already used bits to detect overlapping values. 10384 // In that case, we will just abort the transformation. 10385 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10386 10387 SmallVector<LoadedSlice, 4> LoadedSlices; 10388 10389 // Check if this load is used as several smaller chunks of bits. 10390 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10391 // of computation for each trunc. 10392 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10393 UI != UIEnd; ++UI) { 10394 // Skip the uses of the chain. 10395 if (UI.getUse().getResNo() != 0) 10396 continue; 10397 10398 SDNode *User = *UI; 10399 unsigned Shift = 0; 10400 10401 // Check if this is a trunc(lshr). 10402 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10403 isa<ConstantSDNode>(User->getOperand(1))) { 10404 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10405 User = *User->use_begin(); 10406 } 10407 10408 // At this point, User is a Truncate, iff we encountered, trunc or 10409 // trunc(lshr). 10410 if (User->getOpcode() != ISD::TRUNCATE) 10411 return false; 10412 10413 // The width of the type must be a power of 2 and greater than 8-bits. 10414 // Otherwise the load cannot be represented in LLVM IR. 10415 // Moreover, if we shifted with a non-8-bits multiple, the slice 10416 // will be across several bytes. We do not support that. 10417 unsigned Width = User->getValueSizeInBits(0); 10418 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10419 return 0; 10420 10421 // Build the slice for this chain of computations. 10422 LoadedSlice LS(User, LD, Shift, &DAG); 10423 APInt CurrentUsedBits = LS.getUsedBits(); 10424 10425 // Check if this slice overlaps with another. 10426 if ((CurrentUsedBits & UsedBits) != 0) 10427 return false; 10428 // Update the bits used globally. 10429 UsedBits |= CurrentUsedBits; 10430 10431 // Check if the new slice would be legal. 10432 if (!LS.isLegal()) 10433 return false; 10434 10435 // Record the slice. 10436 LoadedSlices.push_back(LS); 10437 } 10438 10439 // Abort slicing if it does not seem to be profitable. 10440 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10441 return false; 10442 10443 ++SlicedLoads; 10444 10445 // Rewrite each chain to use an independent load. 10446 // By construction, each chain can be represented by a unique load. 10447 10448 // Prepare the argument for the new token factor for all the slices. 10449 SmallVector<SDValue, 8> ArgChains; 10450 for (SmallVectorImpl<LoadedSlice>::const_iterator 10451 LSIt = LoadedSlices.begin(), 10452 LSItEnd = LoadedSlices.end(); 10453 LSIt != LSItEnd; ++LSIt) { 10454 SDValue SliceInst = LSIt->loadSlice(); 10455 CombineTo(LSIt->Inst, SliceInst, true); 10456 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10457 SliceInst = SliceInst.getOperand(0); 10458 assert(SliceInst->getOpcode() == ISD::LOAD && 10459 "It takes more than a zext to get to the loaded slice!!"); 10460 ArgChains.push_back(SliceInst.getValue(1)); 10461 } 10462 10463 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10464 ArgChains); 10465 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10466 return true; 10467 } 10468 10469 /// Check to see if V is (and load (ptr), imm), where the load is having 10470 /// specific bytes cleared out. If so, return the byte size being masked out 10471 /// and the shift amount. 10472 static std::pair<unsigned, unsigned> 10473 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10474 std::pair<unsigned, unsigned> Result(0, 0); 10475 10476 // Check for the structure we're looking for. 10477 if (V->getOpcode() != ISD::AND || 10478 !isa<ConstantSDNode>(V->getOperand(1)) || 10479 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10480 return Result; 10481 10482 // Check the chain and pointer. 10483 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10484 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10485 10486 // The store should be chained directly to the load or be an operand of a 10487 // tokenfactor. 10488 if (LD == Chain.getNode()) 10489 ; // ok. 10490 else if (Chain->getOpcode() != ISD::TokenFactor) 10491 return Result; // Fail. 10492 else { 10493 bool isOk = false; 10494 for (const SDValue &ChainOp : Chain->op_values()) 10495 if (ChainOp.getNode() == LD) { 10496 isOk = true; 10497 break; 10498 } 10499 if (!isOk) return Result; 10500 } 10501 10502 // This only handles simple types. 10503 if (V.getValueType() != MVT::i16 && 10504 V.getValueType() != MVT::i32 && 10505 V.getValueType() != MVT::i64) 10506 return Result; 10507 10508 // Check the constant mask. Invert it so that the bits being masked out are 10509 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10510 // follow the sign bit for uniformity. 10511 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10512 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10513 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10514 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10515 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10516 if (NotMaskLZ == 64) return Result; // All zero mask. 10517 10518 // See if we have a continuous run of bits. If so, we have 0*1+0* 10519 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10520 return Result; 10521 10522 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10523 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10524 NotMaskLZ -= 64-V.getValueSizeInBits(); 10525 10526 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10527 switch (MaskedBytes) { 10528 case 1: 10529 case 2: 10530 case 4: break; 10531 default: return Result; // All one mask, or 5-byte mask. 10532 } 10533 10534 // Verify that the first bit starts at a multiple of mask so that the access 10535 // is aligned the same as the access width. 10536 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10537 10538 Result.first = MaskedBytes; 10539 Result.second = NotMaskTZ/8; 10540 return Result; 10541 } 10542 10543 10544 /// Check to see if IVal is something that provides a value as specified by 10545 /// MaskInfo. If so, replace the specified store with a narrower store of 10546 /// truncated IVal. 10547 static SDNode * 10548 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10549 SDValue IVal, StoreSDNode *St, 10550 DAGCombiner *DC) { 10551 unsigned NumBytes = MaskInfo.first; 10552 unsigned ByteShift = MaskInfo.second; 10553 SelectionDAG &DAG = DC->getDAG(); 10554 10555 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10556 // that uses this. If not, this is not a replacement. 10557 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10558 ByteShift*8, (ByteShift+NumBytes)*8); 10559 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10560 10561 // Check that it is legal on the target to do this. It is legal if the new 10562 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10563 // legalization. 10564 MVT VT = MVT::getIntegerVT(NumBytes*8); 10565 if (!DC->isTypeLegal(VT)) 10566 return nullptr; 10567 10568 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10569 // shifted by ByteShift and truncated down to NumBytes. 10570 if (ByteShift) { 10571 SDLoc DL(IVal); 10572 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10573 DAG.getConstant(ByteShift*8, DL, 10574 DC->getShiftAmountTy(IVal.getValueType()))); 10575 } 10576 10577 // Figure out the offset for the store and the alignment of the access. 10578 unsigned StOffset; 10579 unsigned NewAlign = St->getAlignment(); 10580 10581 if (DAG.getDataLayout().isLittleEndian()) 10582 StOffset = ByteShift; 10583 else 10584 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10585 10586 SDValue Ptr = St->getBasePtr(); 10587 if (StOffset) { 10588 SDLoc DL(IVal); 10589 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10590 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10591 NewAlign = MinAlign(NewAlign, StOffset); 10592 } 10593 10594 // Truncate down to the new size. 10595 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10596 10597 ++OpsNarrowed; 10598 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10599 St->getPointerInfo().getWithOffset(StOffset), 10600 false, false, NewAlign).getNode(); 10601 } 10602 10603 10604 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10605 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10606 /// narrowing the load and store if it would end up being a win for performance 10607 /// or code size. 10608 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10609 StoreSDNode *ST = cast<StoreSDNode>(N); 10610 if (ST->isVolatile()) 10611 return SDValue(); 10612 10613 SDValue Chain = ST->getChain(); 10614 SDValue Value = ST->getValue(); 10615 SDValue Ptr = ST->getBasePtr(); 10616 EVT VT = Value.getValueType(); 10617 10618 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10619 return SDValue(); 10620 10621 unsigned Opc = Value.getOpcode(); 10622 10623 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10624 // is a byte mask indicating a consecutive number of bytes, check to see if 10625 // Y is known to provide just those bytes. If so, we try to replace the 10626 // load + replace + store sequence with a single (narrower) store, which makes 10627 // the load dead. 10628 if (Opc == ISD::OR) { 10629 std::pair<unsigned, unsigned> MaskedLoad; 10630 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10631 if (MaskedLoad.first) 10632 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10633 Value.getOperand(1), ST,this)) 10634 return SDValue(NewST, 0); 10635 10636 // Or is commutative, so try swapping X and Y. 10637 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10638 if (MaskedLoad.first) 10639 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10640 Value.getOperand(0), ST,this)) 10641 return SDValue(NewST, 0); 10642 } 10643 10644 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10645 Value.getOperand(1).getOpcode() != ISD::Constant) 10646 return SDValue(); 10647 10648 SDValue N0 = Value.getOperand(0); 10649 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10650 Chain == SDValue(N0.getNode(), 1)) { 10651 LoadSDNode *LD = cast<LoadSDNode>(N0); 10652 if (LD->getBasePtr() != Ptr || 10653 LD->getPointerInfo().getAddrSpace() != 10654 ST->getPointerInfo().getAddrSpace()) 10655 return SDValue(); 10656 10657 // Find the type to narrow it the load / op / store to. 10658 SDValue N1 = Value.getOperand(1); 10659 unsigned BitWidth = N1.getValueSizeInBits(); 10660 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10661 if (Opc == ISD::AND) 10662 Imm ^= APInt::getAllOnesValue(BitWidth); 10663 if (Imm == 0 || Imm.isAllOnesValue()) 10664 return SDValue(); 10665 unsigned ShAmt = Imm.countTrailingZeros(); 10666 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10667 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10668 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10669 // The narrowing should be profitable, the load/store operation should be 10670 // legal (or custom) and the store size should be equal to the NewVT width. 10671 while (NewBW < BitWidth && 10672 (NewVT.getStoreSizeInBits() != NewBW || 10673 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10674 !TLI.isNarrowingProfitable(VT, NewVT))) { 10675 NewBW = NextPowerOf2(NewBW); 10676 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10677 } 10678 if (NewBW >= BitWidth) 10679 return SDValue(); 10680 10681 // If the lsb changed does not start at the type bitwidth boundary, 10682 // start at the previous one. 10683 if (ShAmt % NewBW) 10684 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10685 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10686 std::min(BitWidth, ShAmt + NewBW)); 10687 if ((Imm & Mask) == Imm) { 10688 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10689 if (Opc == ISD::AND) 10690 NewImm ^= APInt::getAllOnesValue(NewBW); 10691 uint64_t PtrOff = ShAmt / 8; 10692 // For big endian targets, we need to adjust the offset to the pointer to 10693 // load the correct bytes. 10694 if (DAG.getDataLayout().isBigEndian()) 10695 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10696 10697 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10698 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10699 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10700 return SDValue(); 10701 10702 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10703 Ptr.getValueType(), Ptr, 10704 DAG.getConstant(PtrOff, SDLoc(LD), 10705 Ptr.getValueType())); 10706 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10707 LD->getChain(), NewPtr, 10708 LD->getPointerInfo().getWithOffset(PtrOff), 10709 LD->isVolatile(), LD->isNonTemporal(), 10710 LD->isInvariant(), NewAlign, 10711 LD->getAAInfo()); 10712 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10713 DAG.getConstant(NewImm, SDLoc(Value), 10714 NewVT)); 10715 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10716 NewVal, NewPtr, 10717 ST->getPointerInfo().getWithOffset(PtrOff), 10718 false, false, NewAlign); 10719 10720 AddToWorklist(NewPtr.getNode()); 10721 AddToWorklist(NewLD.getNode()); 10722 AddToWorklist(NewVal.getNode()); 10723 WorklistRemover DeadNodes(*this); 10724 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10725 ++OpsNarrowed; 10726 return NewST; 10727 } 10728 } 10729 10730 return SDValue(); 10731 } 10732 10733 /// For a given floating point load / store pair, if the load value isn't used 10734 /// by any other operations, then consider transforming the pair to integer 10735 /// load / store operations if the target deems the transformation profitable. 10736 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10737 StoreSDNode *ST = cast<StoreSDNode>(N); 10738 SDValue Chain = ST->getChain(); 10739 SDValue Value = ST->getValue(); 10740 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10741 Value.hasOneUse() && 10742 Chain == SDValue(Value.getNode(), 1)) { 10743 LoadSDNode *LD = cast<LoadSDNode>(Value); 10744 EVT VT = LD->getMemoryVT(); 10745 if (!VT.isFloatingPoint() || 10746 VT != ST->getMemoryVT() || 10747 LD->isNonTemporal() || 10748 ST->isNonTemporal() || 10749 LD->getPointerInfo().getAddrSpace() != 0 || 10750 ST->getPointerInfo().getAddrSpace() != 0) 10751 return SDValue(); 10752 10753 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10754 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10755 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10756 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10757 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10758 return SDValue(); 10759 10760 unsigned LDAlign = LD->getAlignment(); 10761 unsigned STAlign = ST->getAlignment(); 10762 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10763 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 10764 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10765 return SDValue(); 10766 10767 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10768 LD->getChain(), LD->getBasePtr(), 10769 LD->getPointerInfo(), 10770 false, false, false, LDAlign); 10771 10772 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10773 NewLD, ST->getBasePtr(), 10774 ST->getPointerInfo(), 10775 false, false, STAlign); 10776 10777 AddToWorklist(NewLD.getNode()); 10778 AddToWorklist(NewST.getNode()); 10779 WorklistRemover DeadNodes(*this); 10780 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10781 ++LdStFP2Int; 10782 return NewST; 10783 } 10784 10785 return SDValue(); 10786 } 10787 10788 namespace { 10789 /// Helper struct to parse and store a memory address as base + index + offset. 10790 /// We ignore sign extensions when it is safe to do so. 10791 /// The following two expressions are not equivalent. To differentiate we need 10792 /// to store whether there was a sign extension involved in the index 10793 /// computation. 10794 /// (load (i64 add (i64 copyfromreg %c) 10795 /// (i64 signextend (add (i8 load %index) 10796 /// (i8 1)))) 10797 /// vs 10798 /// 10799 /// (load (i64 add (i64 copyfromreg %c) 10800 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10801 /// (i32 1))))) 10802 struct BaseIndexOffset { 10803 SDValue Base; 10804 SDValue Index; 10805 int64_t Offset; 10806 bool IsIndexSignExt; 10807 10808 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10809 10810 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10811 bool IsIndexSignExt) : 10812 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10813 10814 bool equalBaseIndex(const BaseIndexOffset &Other) { 10815 return Other.Base == Base && Other.Index == Index && 10816 Other.IsIndexSignExt == IsIndexSignExt; 10817 } 10818 10819 /// Parses tree in Ptr for base, index, offset addresses. 10820 static BaseIndexOffset match(SDValue Ptr) { 10821 bool IsIndexSignExt = false; 10822 10823 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10824 // instruction, then it could be just the BASE or everything else we don't 10825 // know how to handle. Just use Ptr as BASE and give up. 10826 if (Ptr->getOpcode() != ISD::ADD) 10827 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10828 10829 // We know that we have at least an ADD instruction. Try to pattern match 10830 // the simple case of BASE + OFFSET. 10831 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10832 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10833 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10834 IsIndexSignExt); 10835 } 10836 10837 // Inside a loop the current BASE pointer is calculated using an ADD and a 10838 // MUL instruction. In this case Ptr is the actual BASE pointer. 10839 // (i64 add (i64 %array_ptr) 10840 // (i64 mul (i64 %induction_var) 10841 // (i64 %element_size))) 10842 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10843 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10844 10845 // Look at Base + Index + Offset cases. 10846 SDValue Base = Ptr->getOperand(0); 10847 SDValue IndexOffset = Ptr->getOperand(1); 10848 10849 // Skip signextends. 10850 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10851 IndexOffset = IndexOffset->getOperand(0); 10852 IsIndexSignExt = true; 10853 } 10854 10855 // Either the case of Base + Index (no offset) or something else. 10856 if (IndexOffset->getOpcode() != ISD::ADD) 10857 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10858 10859 // Now we have the case of Base + Index + offset. 10860 SDValue Index = IndexOffset->getOperand(0); 10861 SDValue Offset = IndexOffset->getOperand(1); 10862 10863 if (!isa<ConstantSDNode>(Offset)) 10864 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10865 10866 // Ignore signextends. 10867 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 10868 Index = Index->getOperand(0); 10869 IsIndexSignExt = true; 10870 } else IsIndexSignExt = false; 10871 10872 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 10873 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 10874 } 10875 }; 10876 } // namespace 10877 10878 // This is a helper function for visitMUL to check the profitability 10879 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 10880 // MulNode is the original multiply, AddNode is (add x, c1), 10881 // and ConstNode is c2. 10882 // 10883 // If the (add x, c1) has multiple uses, we could increase 10884 // the number of adds if we make this transformation. 10885 // It would only be worth doing this if we can remove a 10886 // multiply in the process. Check for that here. 10887 // To illustrate: 10888 // (A + c1) * c3 10889 // (A + c2) * c3 10890 // We're checking for cases where we have common "c3 * A" expressions. 10891 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 10892 SDValue &AddNode, 10893 SDValue &ConstNode) { 10894 APInt Val; 10895 10896 // If the add only has one use, this would be OK to do. 10897 if (AddNode.getNode()->hasOneUse()) 10898 return true; 10899 10900 // Walk all the users of the constant with which we're multiplying. 10901 for (SDNode *Use : ConstNode->uses()) { 10902 10903 if (Use == MulNode) // This use is the one we're on right now. Skip it. 10904 continue; 10905 10906 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 10907 SDNode *OtherOp; 10908 SDNode *MulVar = AddNode.getOperand(0).getNode(); 10909 10910 // OtherOp is what we're multiplying against the constant. 10911 if (Use->getOperand(0) == ConstNode) 10912 OtherOp = Use->getOperand(1).getNode(); 10913 else 10914 OtherOp = Use->getOperand(0).getNode(); 10915 10916 // Check to see if multiply is with the same operand of our "add". 10917 // 10918 // ConstNode = CONST 10919 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 10920 // ... 10921 // AddNode = (A + c1) <-- MulVar is A. 10922 // = AddNode * ConstNode <-- current visiting instruction. 10923 // 10924 // If we make this transformation, we will have a common 10925 // multiply (ConstNode * A) that we can save. 10926 if (OtherOp == MulVar) 10927 return true; 10928 10929 // Now check to see if a future expansion will give us a common 10930 // multiply. 10931 // 10932 // ConstNode = CONST 10933 // AddNode = (A + c1) 10934 // ... = AddNode * ConstNode <-- current visiting instruction. 10935 // ... 10936 // OtherOp = (A + c2) 10937 // Use = OtherOp * ConstNode <-- visiting Use. 10938 // 10939 // If we make this transformation, we will have a common 10940 // multiply (CONST * A) after we also do the same transformation 10941 // to the "t2" instruction. 10942 if (OtherOp->getOpcode() == ISD::ADD && 10943 isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 10944 OtherOp->getOperand(0).getNode() == MulVar) 10945 return true; 10946 } 10947 } 10948 10949 // Didn't find a case where this would be profitable. 10950 return false; 10951 } 10952 10953 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG, 10954 SDLoc SL, 10955 ArrayRef<MemOpLink> Stores, 10956 SmallVectorImpl<SDValue> &Chains, 10957 EVT Ty) const { 10958 SmallVector<SDValue, 8> BuildVector; 10959 10960 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 10961 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 10962 Chains.push_back(St->getChain()); 10963 BuildVector.push_back(St->getValue()); 10964 } 10965 10966 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector); 10967 } 10968 10969 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 10970 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 10971 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 10972 // Make sure we have something to merge. 10973 if (NumStores < 2) 10974 return false; 10975 10976 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 10977 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10978 unsigned LatestNodeUsed = 0; 10979 10980 for (unsigned i=0; i < NumStores; ++i) { 10981 // Find a chain for the new wide-store operand. Notice that some 10982 // of the store nodes that we found may not be selected for inclusion 10983 // in the wide store. The chain we use needs to be the chain of the 10984 // latest store node which is *used* and replaced by the wide store. 10985 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 10986 LatestNodeUsed = i; 10987 } 10988 10989 SmallVector<SDValue, 8> Chains; 10990 10991 // The latest Node in the DAG. 10992 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 10993 SDLoc DL(StoreNodes[0].MemNode); 10994 10995 SDValue StoredVal; 10996 if (UseVector) { 10997 bool IsVec = MemVT.isVector(); 10998 unsigned Elts = NumStores; 10999 if (IsVec) { 11000 // When merging vector stores, get the total number of elements. 11001 Elts *= MemVT.getVectorNumElements(); 11002 } 11003 // Get the type for the merged vector store. 11004 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11005 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11006 11007 if (IsConstantSrc) { 11008 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11009 } else { 11010 SmallVector<SDValue, 8> Ops; 11011 for (unsigned i = 0; i < NumStores; ++i) { 11012 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11013 SDValue Val = St->getValue(); 11014 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11015 if (Val.getValueType() != MemVT) 11016 return false; 11017 Ops.push_back(Val); 11018 Chains.push_back(St->getChain()); 11019 } 11020 11021 // Build the extracted vector elements back into a vector. 11022 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11023 DL, Ty, Ops); } 11024 } else { 11025 // We should always use a vector store when merging extracted vector 11026 // elements, so this path implies a store of constants. 11027 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11028 11029 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11030 APInt StoreInt(SizeInBits, 0); 11031 11032 // Construct a single integer constant which is made of the smaller 11033 // constant inputs. 11034 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11035 for (unsigned i = 0; i < NumStores; ++i) { 11036 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11037 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11038 Chains.push_back(St->getChain()); 11039 11040 SDValue Val = St->getValue(); 11041 StoreInt <<= ElementSizeBytes * 8; 11042 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11043 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11044 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11045 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11046 } else { 11047 llvm_unreachable("Invalid constant element type"); 11048 } 11049 } 11050 11051 // Create the new Load and Store operations. 11052 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11053 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11054 } 11055 11056 assert(!Chains.empty()); 11057 11058 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11059 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11060 FirstInChain->getBasePtr(), 11061 FirstInChain->getPointerInfo(), 11062 false, false, 11063 FirstInChain->getAlignment()); 11064 11065 // Replace the last store with the new store 11066 CombineTo(LatestOp, NewStore); 11067 // Erase all other stores. 11068 for (unsigned i = 0; i < NumStores; ++i) { 11069 if (StoreNodes[i].MemNode == LatestOp) 11070 continue; 11071 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11072 // ReplaceAllUsesWith will replace all uses that existed when it was 11073 // called, but graph optimizations may cause new ones to appear. For 11074 // example, the case in pr14333 looks like 11075 // 11076 // St's chain -> St -> another store -> X 11077 // 11078 // And the only difference from St to the other store is the chain. 11079 // When we change it's chain to be St's chain they become identical, 11080 // get CSEed and the net result is that X is now a use of St. 11081 // Since we know that St is redundant, just iterate. 11082 while (!St->use_empty()) 11083 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11084 deleteAndRecombine(St); 11085 } 11086 11087 return true; 11088 } 11089 11090 void DAGCombiner::getStoreMergeAndAliasCandidates( 11091 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11092 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11093 // This holds the base pointer, index, and the offset in bytes from the base 11094 // pointer. 11095 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 11096 11097 // We must have a base and an offset. 11098 if (!BasePtr.Base.getNode()) 11099 return; 11100 11101 // Do not handle stores to undef base pointers. 11102 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 11103 return; 11104 11105 // Walk up the chain and look for nodes with offsets from the same 11106 // base pointer. Stop when reaching an instruction with a different kind 11107 // or instruction which has a different base pointer. 11108 EVT MemVT = St->getMemoryVT(); 11109 unsigned Seq = 0; 11110 StoreSDNode *Index = St; 11111 11112 11113 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11114 : DAG.getSubtarget().useAA(); 11115 11116 if (UseAA) { 11117 // Look at other users of the same chain. Stores on the same chain do not 11118 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11119 // to be on the same chain, so don't bother looking at adjacent chains. 11120 11121 SDValue Chain = St->getChain(); 11122 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11123 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11124 if (I.getOperandNo() != 0) 11125 continue; 11126 11127 if (OtherST->isVolatile() || OtherST->isIndexed()) 11128 continue; 11129 11130 if (OtherST->getMemoryVT() != MemVT) 11131 continue; 11132 11133 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr()); 11134 11135 if (Ptr.equalBaseIndex(BasePtr)) 11136 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11137 } 11138 } 11139 11140 return; 11141 } 11142 11143 while (Index) { 11144 // If the chain has more than one use, then we can't reorder the mem ops. 11145 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11146 break; 11147 11148 // Find the base pointer and offset for this memory node. 11149 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 11150 11151 // Check that the base pointer is the same as the original one. 11152 if (!Ptr.equalBaseIndex(BasePtr)) 11153 break; 11154 11155 // The memory operands must not be volatile. 11156 if (Index->isVolatile() || Index->isIndexed()) 11157 break; 11158 11159 // No truncation. 11160 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 11161 if (St->isTruncatingStore()) 11162 break; 11163 11164 // The stored memory type must be the same. 11165 if (Index->getMemoryVT() != MemVT) 11166 break; 11167 11168 // We do not allow under-aligned stores in order to prevent 11169 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11170 // be irrelevant here; what MATTERS is that we not move memory 11171 // operations that potentially overlap past each-other. 11172 if (Index->getAlignment() < MemVT.getStoreSize()) 11173 break; 11174 11175 // We found a potential memory operand to merge. 11176 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11177 11178 // Find the next memory operand in the chain. If the next operand in the 11179 // chain is a store then move up and continue the scan with the next 11180 // memory operand. If the next operand is a load save it and use alias 11181 // information to check if it interferes with anything. 11182 SDNode *NextInChain = Index->getChain().getNode(); 11183 while (1) { 11184 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11185 // We found a store node. Use it for the next iteration. 11186 Index = STn; 11187 break; 11188 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11189 if (Ldn->isVolatile()) { 11190 Index = nullptr; 11191 break; 11192 } 11193 11194 // Save the load node for later. Continue the scan. 11195 AliasLoadNodes.push_back(Ldn); 11196 NextInChain = Ldn->getChain().getNode(); 11197 continue; 11198 } else { 11199 Index = nullptr; 11200 break; 11201 } 11202 } 11203 } 11204 } 11205 11206 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11207 if (OptLevel == CodeGenOpt::None) 11208 return false; 11209 11210 EVT MemVT = St->getMemoryVT(); 11211 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11212 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11213 Attribute::NoImplicitFloat); 11214 11215 // This function cannot currently deal with non-byte-sized memory sizes. 11216 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11217 return false; 11218 11219 if (!MemVT.isSimple()) 11220 return false; 11221 11222 // Perform an early exit check. Do not bother looking at stored values that 11223 // are not constants, loads, or extracted vector elements. 11224 SDValue StoredVal = St->getValue(); 11225 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11226 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11227 isa<ConstantFPSDNode>(StoredVal); 11228 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11229 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11230 11231 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11232 return false; 11233 11234 // Don't merge vectors into wider vectors if the source data comes from loads. 11235 // TODO: This restriction can be lifted by using logic similar to the 11236 // ExtractVecSrc case. 11237 if (MemVT.isVector() && IsLoadSrc) 11238 return false; 11239 11240 // Only look at ends of store sequences. 11241 SDValue Chain = SDValue(St, 0); 11242 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11243 return false; 11244 11245 // Save the LoadSDNodes that we find in the chain. 11246 // We need to make sure that these nodes do not interfere with 11247 // any of the store nodes. 11248 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11249 11250 // Save the StoreSDNodes that we find in the chain. 11251 SmallVector<MemOpLink, 8> StoreNodes; 11252 11253 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11254 11255 // Check if there is anything to merge. 11256 if (StoreNodes.size() < 2) 11257 return false; 11258 11259 // Sort the memory operands according to their distance from the 11260 // base pointer. As a secondary criteria: make sure stores coming 11261 // later in the code come first in the list. This is important for 11262 // the non-UseAA case, because we're merging stores into the FINAL 11263 // store along a chain which potentially contains aliasing stores. 11264 // Thus, if there are multiple stores to the same address, the last 11265 // one can be considered for merging but not the others. 11266 std::sort(StoreNodes.begin(), StoreNodes.end(), 11267 [](MemOpLink LHS, MemOpLink RHS) { 11268 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11269 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11270 LHS.SequenceNum < RHS.SequenceNum); 11271 }); 11272 11273 // Scan the memory operations on the chain and find the first non-consecutive 11274 // store memory address. 11275 unsigned LastConsecutiveStore = 0; 11276 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11277 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11278 11279 // Check that the addresses are consecutive starting from the second 11280 // element in the list of stores. 11281 if (i > 0) { 11282 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11283 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11284 break; 11285 } 11286 11287 bool Alias = false; 11288 // Check if this store interferes with any of the loads that we found. 11289 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 11290 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 11291 Alias = true; 11292 break; 11293 } 11294 // We found a load that alias with this store. Stop the sequence. 11295 if (Alias) 11296 break; 11297 11298 // Mark this node as useful. 11299 LastConsecutiveStore = i; 11300 } 11301 11302 // The node with the lowest store address. 11303 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11304 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11305 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11306 LLVMContext &Context = *DAG.getContext(); 11307 const DataLayout &DL = DAG.getDataLayout(); 11308 11309 // Store the constants into memory as one consecutive store. 11310 if (IsConstantSrc) { 11311 unsigned LastLegalType = 0; 11312 unsigned LastLegalVectorType = 0; 11313 bool NonZero = false; 11314 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11315 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11316 SDValue StoredVal = St->getValue(); 11317 11318 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11319 NonZero |= !C->isNullValue(); 11320 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11321 NonZero |= !C->getConstantFPValue()->isNullValue(); 11322 } else { 11323 // Non-constant. 11324 break; 11325 } 11326 11327 // Find a legal type for the constant store. 11328 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11329 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11330 bool IsFast; 11331 if (TLI.isTypeLegal(StoreTy) && 11332 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11333 FirstStoreAlign, &IsFast) && IsFast) { 11334 LastLegalType = i+1; 11335 // Or check whether a truncstore is legal. 11336 } else if (TLI.getTypeAction(Context, StoreTy) == 11337 TargetLowering::TypePromoteInteger) { 11338 EVT LegalizedStoredValueTy = 11339 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11340 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11341 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11342 FirstStoreAS, FirstStoreAlign, &IsFast) && 11343 IsFast) { 11344 LastLegalType = i + 1; 11345 } 11346 } 11347 11348 // We only use vectors if the constant is known to be zero or the target 11349 // allows it and the function is not marked with the noimplicitfloat 11350 // attribute. 11351 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11352 FirstStoreAS)) && 11353 !NoVectors) { 11354 // Find a legal type for the vector store. 11355 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11356 if (TLI.isTypeLegal(Ty) && 11357 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11358 FirstStoreAlign, &IsFast) && IsFast) 11359 LastLegalVectorType = i + 1; 11360 } 11361 } 11362 11363 // Check if we found a legal integer type to store. 11364 if (LastLegalType == 0 && LastLegalVectorType == 0) 11365 return false; 11366 11367 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11368 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11369 11370 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11371 true, UseVector); 11372 } 11373 11374 // When extracting multiple vector elements, try to store them 11375 // in one vector store rather than a sequence of scalar stores. 11376 if (IsExtractVecSrc) { 11377 unsigned NumStoresToMerge = 0; 11378 bool IsVec = MemVT.isVector(); 11379 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11380 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11381 unsigned StoreValOpcode = St->getValue().getOpcode(); 11382 // This restriction could be loosened. 11383 // Bail out if any stored values are not elements extracted from a vector. 11384 // It should be possible to handle mixed sources, but load sources need 11385 // more careful handling (see the block of code below that handles 11386 // consecutive loads). 11387 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11388 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11389 return false; 11390 11391 // Find a legal type for the vector store. 11392 unsigned Elts = i + 1; 11393 if (IsVec) { 11394 // When merging vector stores, get the total number of elements. 11395 Elts *= MemVT.getVectorNumElements(); 11396 } 11397 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11398 bool IsFast; 11399 if (TLI.isTypeLegal(Ty) && 11400 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11401 FirstStoreAlign, &IsFast) && IsFast) 11402 NumStoresToMerge = i + 1; 11403 } 11404 11405 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11406 false, true); 11407 } 11408 11409 // Below we handle the case of multiple consecutive stores that 11410 // come from multiple consecutive loads. We merge them into a single 11411 // wide load and a single wide store. 11412 11413 // Look for load nodes which are used by the stored values. 11414 SmallVector<MemOpLink, 8> LoadNodes; 11415 11416 // Find acceptable loads. Loads need to have the same chain (token factor), 11417 // must not be zext, volatile, indexed, and they must be consecutive. 11418 BaseIndexOffset LdBasePtr; 11419 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11420 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11421 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11422 if (!Ld) break; 11423 11424 // Loads must only have one use. 11425 if (!Ld->hasNUsesOfValue(1, 0)) 11426 break; 11427 11428 // The memory operands must not be volatile. 11429 if (Ld->isVolatile() || Ld->isIndexed()) 11430 break; 11431 11432 // We do not accept ext loads. 11433 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11434 break; 11435 11436 // The stored memory type must be the same. 11437 if (Ld->getMemoryVT() != MemVT) 11438 break; 11439 11440 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 11441 // If this is not the first ptr that we check. 11442 if (LdBasePtr.Base.getNode()) { 11443 // The base ptr must be the same. 11444 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11445 break; 11446 } else { 11447 // Check that all other base pointers are the same as this one. 11448 LdBasePtr = LdPtr; 11449 } 11450 11451 // We found a potential memory operand to merge. 11452 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11453 } 11454 11455 if (LoadNodes.size() < 2) 11456 return false; 11457 11458 // If we have load/store pair instructions and we only have two values, 11459 // don't bother. 11460 unsigned RequiredAlignment; 11461 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11462 St->getAlignment() >= RequiredAlignment) 11463 return false; 11464 11465 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11466 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11467 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11468 11469 // Scan the memory operations on the chain and find the first non-consecutive 11470 // load memory address. These variables hold the index in the store node 11471 // array. 11472 unsigned LastConsecutiveLoad = 0; 11473 // This variable refers to the size and not index in the array. 11474 unsigned LastLegalVectorType = 0; 11475 unsigned LastLegalIntegerType = 0; 11476 StartAddress = LoadNodes[0].OffsetFromBase; 11477 SDValue FirstChain = FirstLoad->getChain(); 11478 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11479 // All loads much share the same chain. 11480 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11481 break; 11482 11483 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11484 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11485 break; 11486 LastConsecutiveLoad = i; 11487 // Find a legal type for the vector store. 11488 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11489 bool IsFastSt, IsFastLd; 11490 if (TLI.isTypeLegal(StoreTy) && 11491 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11492 FirstStoreAlign, &IsFastSt) && IsFastSt && 11493 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11494 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11495 LastLegalVectorType = i + 1; 11496 } 11497 11498 // Find a legal type for the integer store. 11499 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11500 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11501 if (TLI.isTypeLegal(StoreTy) && 11502 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11503 FirstStoreAlign, &IsFastSt) && IsFastSt && 11504 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11505 FirstLoadAlign, &IsFastLd) && IsFastLd) 11506 LastLegalIntegerType = i + 1; 11507 // Or check whether a truncstore and extload is legal. 11508 else if (TLI.getTypeAction(Context, StoreTy) == 11509 TargetLowering::TypePromoteInteger) { 11510 EVT LegalizedStoredValueTy = 11511 TLI.getTypeToTransformTo(Context, StoreTy); 11512 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11513 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11514 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11515 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11516 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11517 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11518 IsFastSt && 11519 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11520 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11521 IsFastLd) 11522 LastLegalIntegerType = i+1; 11523 } 11524 } 11525 11526 // Only use vector types if the vector type is larger than the integer type. 11527 // If they are the same, use integers. 11528 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11529 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11530 11531 // We add +1 here because the LastXXX variables refer to location while 11532 // the NumElem refers to array/index size. 11533 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11534 NumElem = std::min(LastLegalType, NumElem); 11535 11536 if (NumElem < 2) 11537 return false; 11538 11539 // Collect the chains from all merged stores. 11540 SmallVector<SDValue, 8> MergeStoreChains; 11541 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11542 11543 // The latest Node in the DAG. 11544 unsigned LatestNodeUsed = 0; 11545 for (unsigned i=1; i<NumElem; ++i) { 11546 // Find a chain for the new wide-store operand. Notice that some 11547 // of the store nodes that we found may not be selected for inclusion 11548 // in the wide store. The chain we use needs to be the chain of the 11549 // latest store node which is *used* and replaced by the wide store. 11550 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11551 LatestNodeUsed = i; 11552 11553 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11554 } 11555 11556 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11557 11558 // Find if it is better to use vectors or integers to load and store 11559 // to memory. 11560 EVT JointMemOpVT; 11561 if (UseVectorTy) { 11562 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11563 } else { 11564 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11565 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11566 } 11567 11568 SDLoc LoadDL(LoadNodes[0].MemNode); 11569 SDLoc StoreDL(StoreNodes[0].MemNode); 11570 11571 // The merged loads are required to have the same chain, so using the first's 11572 // chain is acceptable. 11573 SDValue NewLoad = DAG.getLoad( 11574 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11575 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11576 11577 SDValue NewStoreChain = 11578 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11579 11580 SDValue NewStore = DAG.getStore( 11581 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11582 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11583 11584 // Replace one of the loads with the new load. 11585 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 11586 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11587 SDValue(NewLoad.getNode(), 1)); 11588 11589 // Remove the rest of the load chains. 11590 for (unsigned i = 1; i < NumElem ; ++i) { 11591 // Replace all chain users of the old load nodes with the chain of the new 11592 // load node. 11593 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11594 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 11595 } 11596 11597 // Replace the last store with the new store. 11598 CombineTo(LatestOp, NewStore); 11599 // Erase all other stores. 11600 for (unsigned i = 0; i < NumElem ; ++i) { 11601 // Remove all Store nodes. 11602 if (StoreNodes[i].MemNode == LatestOp) 11603 continue; 11604 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11605 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11606 deleteAndRecombine(St); 11607 } 11608 11609 return true; 11610 } 11611 11612 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11613 SDLoc SL(ST); 11614 SDValue ReplStore; 11615 11616 // Replace the chain to avoid dependency. 11617 if (ST->isTruncatingStore()) { 11618 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11619 ST->getBasePtr(), ST->getMemoryVT(), 11620 ST->getMemOperand()); 11621 } else { 11622 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11623 ST->getMemOperand()); 11624 } 11625 11626 // Create token to keep both nodes around. 11627 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11628 MVT::Other, ST->getChain(), ReplStore); 11629 11630 // Make sure the new and old chains are cleaned up. 11631 AddToWorklist(Token.getNode()); 11632 11633 // Don't add users to work list. 11634 return CombineTo(ST, Token, false); 11635 } 11636 11637 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11638 SDValue Value = ST->getValue(); 11639 if (Value.getOpcode() == ISD::TargetConstantFP) 11640 return SDValue(); 11641 11642 SDLoc DL(ST); 11643 11644 SDValue Chain = ST->getChain(); 11645 SDValue Ptr = ST->getBasePtr(); 11646 11647 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11648 11649 // NOTE: If the original store is volatile, this transform must not increase 11650 // the number of stores. For example, on x86-32 an f64 can be stored in one 11651 // processor operation but an i64 (which is not legal) requires two. So the 11652 // transform should not be done in this case. 11653 11654 SDValue Tmp; 11655 switch (CFP->getSimpleValueType(0).SimpleTy) { 11656 default: 11657 llvm_unreachable("Unknown FP type"); 11658 case MVT::f16: // We don't do this for these yet. 11659 case MVT::f80: 11660 case MVT::f128: 11661 case MVT::ppcf128: 11662 return SDValue(); 11663 case MVT::f32: 11664 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11665 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11666 ; 11667 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11668 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11669 MVT::i32); 11670 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11671 } 11672 11673 return SDValue(); 11674 case MVT::f64: 11675 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11676 !ST->isVolatile()) || 11677 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11678 ; 11679 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11680 getZExtValue(), SDLoc(CFP), MVT::i64); 11681 return DAG.getStore(Chain, DL, Tmp, 11682 Ptr, ST->getMemOperand()); 11683 } 11684 11685 if (!ST->isVolatile() && 11686 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11687 // Many FP stores are not made apparent until after legalize, e.g. for 11688 // argument passing. Since this is so common, custom legalize the 11689 // 64-bit integer store into two 32-bit stores. 11690 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11691 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11692 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11693 if (DAG.getDataLayout().isBigEndian()) 11694 std::swap(Lo, Hi); 11695 11696 unsigned Alignment = ST->getAlignment(); 11697 bool isVolatile = ST->isVolatile(); 11698 bool isNonTemporal = ST->isNonTemporal(); 11699 AAMDNodes AAInfo = ST->getAAInfo(); 11700 11701 SDValue St0 = DAG.getStore(Chain, DL, Lo, 11702 Ptr, ST->getPointerInfo(), 11703 isVolatile, isNonTemporal, 11704 ST->getAlignment(), AAInfo); 11705 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11706 DAG.getConstant(4, DL, Ptr.getValueType())); 11707 Alignment = MinAlign(Alignment, 4U); 11708 SDValue St1 = DAG.getStore(Chain, DL, Hi, 11709 Ptr, ST->getPointerInfo().getWithOffset(4), 11710 isVolatile, isNonTemporal, 11711 Alignment, AAInfo); 11712 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11713 St0, St1); 11714 } 11715 11716 return SDValue(); 11717 } 11718 } 11719 11720 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11721 StoreSDNode *ST = cast<StoreSDNode>(N); 11722 SDValue Chain = ST->getChain(); 11723 SDValue Value = ST->getValue(); 11724 SDValue Ptr = ST->getBasePtr(); 11725 11726 // If this is a store of a bit convert, store the input value if the 11727 // resultant store does not need a higher alignment than the original. 11728 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11729 ST->isUnindexed()) { 11730 unsigned OrigAlign = ST->getAlignment(); 11731 EVT SVT = Value.getOperand(0).getValueType(); 11732 unsigned Align = DAG.getDataLayout().getABITypeAlignment( 11733 SVT.getTypeForEVT(*DAG.getContext())); 11734 if (Align <= OrigAlign && 11735 ((!LegalOperations && !ST->isVolatile()) || 11736 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 11737 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11738 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11739 ST->isNonTemporal(), OrigAlign, 11740 ST->getAAInfo()); 11741 } 11742 11743 // Turn 'store undef, Ptr' -> nothing. 11744 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 11745 return Chain; 11746 11747 // Try to infer better alignment information than the store already has. 11748 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 11749 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11750 if (Align > ST->getAlignment()) { 11751 SDValue NewStore = 11752 DAG.getTruncStore(Chain, SDLoc(N), Value, 11753 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 11754 ST->isVolatile(), ST->isNonTemporal(), Align, 11755 ST->getAAInfo()); 11756 if (NewStore.getNode() != N) 11757 return CombineTo(ST, NewStore, true); 11758 } 11759 } 11760 } 11761 11762 // Try transforming a pair floating point load / store ops to integer 11763 // load / store ops. 11764 if (SDValue NewST = TransformFPLoadStorePair(N)) 11765 return NewST; 11766 11767 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11768 : DAG.getSubtarget().useAA(); 11769 #ifndef NDEBUG 11770 if (CombinerAAOnlyFunc.getNumOccurrences() && 11771 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11772 UseAA = false; 11773 #endif 11774 if (UseAA && ST->isUnindexed()) { 11775 // FIXME: We should do this even without AA enabled. AA will just allow 11776 // FindBetterChain to work in more situations. The problem with this is that 11777 // any combine that expects memory operations to be on consecutive chains 11778 // first needs to be updated to look for users of the same chain. 11779 11780 // Walk up chain skipping non-aliasing memory nodes, on this store and any 11781 // adjacent stores. 11782 if (findBetterNeighborChains(ST)) { 11783 // replaceStoreChain uses CombineTo, which handled all of the worklist 11784 // manipulation. Return the original node to not do anything else. 11785 return SDValue(ST, 0); 11786 } 11787 } 11788 11789 // Try transforming N to an indexed store. 11790 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11791 return SDValue(N, 0); 11792 11793 // FIXME: is there such a thing as a truncating indexed store? 11794 if (ST->isTruncatingStore() && ST->isUnindexed() && 11795 Value.getValueType().isInteger()) { 11796 // See if we can simplify the input to this truncstore with knowledge that 11797 // only the low bits are being used. For example: 11798 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 11799 SDValue Shorter = 11800 GetDemandedBits(Value, 11801 APInt::getLowBitsSet( 11802 Value.getValueType().getScalarType().getSizeInBits(), 11803 ST->getMemoryVT().getScalarType().getSizeInBits())); 11804 AddToWorklist(Value.getNode()); 11805 if (Shorter.getNode()) 11806 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 11807 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11808 11809 // Otherwise, see if we can simplify the operation with 11810 // SimplifyDemandedBits, which only works if the value has a single use. 11811 if (SimplifyDemandedBits(Value, 11812 APInt::getLowBitsSet( 11813 Value.getValueType().getScalarType().getSizeInBits(), 11814 ST->getMemoryVT().getScalarType().getSizeInBits()))) 11815 return SDValue(N, 0); 11816 } 11817 11818 // If this is a load followed by a store to the same location, then the store 11819 // is dead/noop. 11820 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 11821 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 11822 ST->isUnindexed() && !ST->isVolatile() && 11823 // There can't be any side effects between the load and store, such as 11824 // a call or store. 11825 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 11826 // The store is dead, remove it. 11827 return Chain; 11828 } 11829 } 11830 11831 // If this is a store followed by a store with the same value to the same 11832 // location, then the store is dead/noop. 11833 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 11834 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 11835 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 11836 ST1->isUnindexed() && !ST1->isVolatile()) { 11837 // The store is dead, remove it. 11838 return Chain; 11839 } 11840 } 11841 11842 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 11843 // truncating store. We can do this even if this is already a truncstore. 11844 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 11845 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 11846 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 11847 ST->getMemoryVT())) { 11848 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 11849 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11850 } 11851 11852 // Only perform this optimization before the types are legal, because we 11853 // don't want to perform this optimization on every DAGCombine invocation. 11854 if (!LegalTypes) { 11855 bool EverChanged = false; 11856 11857 do { 11858 // There can be multiple store sequences on the same chain. 11859 // Keep trying to merge store sequences until we are unable to do so 11860 // or until we merge the last store on the chain. 11861 bool Changed = MergeConsecutiveStores(ST); 11862 EverChanged |= Changed; 11863 if (!Changed) break; 11864 } while (ST->getOpcode() != ISD::DELETED_NODE); 11865 11866 if (EverChanged) 11867 return SDValue(N, 0); 11868 } 11869 11870 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 11871 // 11872 // Make sure to do this only after attempting to merge stores in order to 11873 // avoid changing the types of some subset of stores due to visit order, 11874 // preventing their merging. 11875 if (isa<ConstantFPSDNode>(Value)) { 11876 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 11877 return NewSt; 11878 } 11879 11880 return ReduceLoadOpStoreWidth(N); 11881 } 11882 11883 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 11884 SDValue InVec = N->getOperand(0); 11885 SDValue InVal = N->getOperand(1); 11886 SDValue EltNo = N->getOperand(2); 11887 SDLoc dl(N); 11888 11889 // If the inserted element is an UNDEF, just use the input vector. 11890 if (InVal.getOpcode() == ISD::UNDEF) 11891 return InVec; 11892 11893 EVT VT = InVec.getValueType(); 11894 11895 // If we can't generate a legal BUILD_VECTOR, exit 11896 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 11897 return SDValue(); 11898 11899 // Check that we know which element is being inserted 11900 if (!isa<ConstantSDNode>(EltNo)) 11901 return SDValue(); 11902 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11903 11904 // Canonicalize insert_vector_elt dag nodes. 11905 // Example: 11906 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 11907 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 11908 // 11909 // Do this only if the child insert_vector node has one use; also 11910 // do this only if indices are both constants and Idx1 < Idx0. 11911 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 11912 && isa<ConstantSDNode>(InVec.getOperand(2))) { 11913 unsigned OtherElt = 11914 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 11915 if (Elt < OtherElt) { 11916 // Swap nodes. 11917 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 11918 InVec.getOperand(0), InVal, EltNo); 11919 AddToWorklist(NewOp.getNode()); 11920 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 11921 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 11922 } 11923 } 11924 11925 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 11926 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 11927 // vector elements. 11928 SmallVector<SDValue, 8> Ops; 11929 // Do not combine these two vectors if the output vector will not replace 11930 // the input vector. 11931 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 11932 Ops.append(InVec.getNode()->op_begin(), 11933 InVec.getNode()->op_end()); 11934 } else if (InVec.getOpcode() == ISD::UNDEF) { 11935 unsigned NElts = VT.getVectorNumElements(); 11936 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 11937 } else { 11938 return SDValue(); 11939 } 11940 11941 // Insert the element 11942 if (Elt < Ops.size()) { 11943 // All the operands of BUILD_VECTOR must have the same type; 11944 // we enforce that here. 11945 EVT OpVT = Ops[0].getValueType(); 11946 if (InVal.getValueType() != OpVT) 11947 InVal = OpVT.bitsGT(InVal.getValueType()) ? 11948 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 11949 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 11950 Ops[Elt] = InVal; 11951 } 11952 11953 // Return the new vector 11954 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 11955 } 11956 11957 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 11958 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 11959 EVT ResultVT = EVE->getValueType(0); 11960 EVT VecEltVT = InVecVT.getVectorElementType(); 11961 unsigned Align = OriginalLoad->getAlignment(); 11962 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 11963 VecEltVT.getTypeForEVT(*DAG.getContext())); 11964 11965 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 11966 return SDValue(); 11967 11968 Align = NewAlign; 11969 11970 SDValue NewPtr = OriginalLoad->getBasePtr(); 11971 SDValue Offset; 11972 EVT PtrType = NewPtr.getValueType(); 11973 MachinePointerInfo MPI; 11974 SDLoc DL(EVE); 11975 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 11976 int Elt = ConstEltNo->getZExtValue(); 11977 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 11978 Offset = DAG.getConstant(PtrOff, DL, PtrType); 11979 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 11980 } else { 11981 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 11982 Offset = DAG.getNode( 11983 ISD::MUL, DL, PtrType, Offset, 11984 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 11985 MPI = OriginalLoad->getPointerInfo(); 11986 } 11987 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 11988 11989 // The replacement we need to do here is a little tricky: we need to 11990 // replace an extractelement of a load with a load. 11991 // Use ReplaceAllUsesOfValuesWith to do the replacement. 11992 // Note that this replacement assumes that the extractvalue is the only 11993 // use of the load; that's okay because we don't want to perform this 11994 // transformation in other cases anyway. 11995 SDValue Load; 11996 SDValue Chain; 11997 if (ResultVT.bitsGT(VecEltVT)) { 11998 // If the result type of vextract is wider than the load, then issue an 11999 // extending load instead. 12000 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12001 VecEltVT) 12002 ? ISD::ZEXTLOAD 12003 : ISD::EXTLOAD; 12004 Load = DAG.getExtLoad( 12005 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 12006 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12007 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12008 Chain = Load.getValue(1); 12009 } else { 12010 Load = DAG.getLoad( 12011 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 12012 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12013 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12014 Chain = Load.getValue(1); 12015 if (ResultVT.bitsLT(VecEltVT)) 12016 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12017 else 12018 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 12019 } 12020 WorklistRemover DeadNodes(*this); 12021 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12022 SDValue To[] = { Load, Chain }; 12023 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12024 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12025 // worklist explicitly as well. 12026 AddToWorklist(Load.getNode()); 12027 AddUsersToWorklist(Load.getNode()); // Add users too 12028 // Make sure to revisit this node to clean it up; it will usually be dead. 12029 AddToWorklist(EVE); 12030 ++OpsNarrowed; 12031 return SDValue(EVE, 0); 12032 } 12033 12034 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12035 // (vextract (scalar_to_vector val, 0) -> val 12036 SDValue InVec = N->getOperand(0); 12037 EVT VT = InVec.getValueType(); 12038 EVT NVT = N->getValueType(0); 12039 12040 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12041 // Check if the result type doesn't match the inserted element type. A 12042 // SCALAR_TO_VECTOR may truncate the inserted element and the 12043 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12044 SDValue InOp = InVec.getOperand(0); 12045 if (InOp.getValueType() != NVT) { 12046 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12047 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12048 } 12049 return InOp; 12050 } 12051 12052 SDValue EltNo = N->getOperand(1); 12053 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12054 12055 // extract_vector_elt (build_vector x, y), 1 -> y 12056 if (ConstEltNo && 12057 InVec.getOpcode() == ISD::BUILD_VECTOR && 12058 TLI.isTypeLegal(VT) && 12059 (InVec.hasOneUse() || 12060 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12061 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12062 EVT InEltVT = Elt.getValueType(); 12063 12064 // Sometimes build_vector's scalar input types do not match result type. 12065 if (NVT == InEltVT) 12066 return Elt; 12067 12068 // TODO: It may be useful to truncate if free if the build_vector implicitly 12069 // converts. 12070 } 12071 12072 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12073 // We only perform this optimization before the op legalization phase because 12074 // we may introduce new vector instructions which are not backed by TD 12075 // patterns. For example on AVX, extracting elements from a wide vector 12076 // without using extract_subvector. However, if we can find an underlying 12077 // scalar value, then we can always use that. 12078 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12079 int NumElem = VT.getVectorNumElements(); 12080 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12081 // Find the new index to extract from. 12082 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12083 12084 // Extracting an undef index is undef. 12085 if (OrigElt == -1) 12086 return DAG.getUNDEF(NVT); 12087 12088 // Select the right vector half to extract from. 12089 SDValue SVInVec; 12090 if (OrigElt < NumElem) { 12091 SVInVec = InVec->getOperand(0); 12092 } else { 12093 SVInVec = InVec->getOperand(1); 12094 OrigElt -= NumElem; 12095 } 12096 12097 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12098 SDValue InOp = SVInVec.getOperand(OrigElt); 12099 if (InOp.getValueType() != NVT) { 12100 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12101 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12102 } 12103 12104 return InOp; 12105 } 12106 12107 // FIXME: We should handle recursing on other vector shuffles and 12108 // scalar_to_vector here as well. 12109 12110 if (!LegalOperations) { 12111 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12112 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12113 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12114 } 12115 } 12116 12117 bool BCNumEltsChanged = false; 12118 EVT ExtVT = VT.getVectorElementType(); 12119 EVT LVT = ExtVT; 12120 12121 // If the result of load has to be truncated, then it's not necessarily 12122 // profitable. 12123 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12124 return SDValue(); 12125 12126 if (InVec.getOpcode() == ISD::BITCAST) { 12127 // Don't duplicate a load with other uses. 12128 if (!InVec.hasOneUse()) 12129 return SDValue(); 12130 12131 EVT BCVT = InVec.getOperand(0).getValueType(); 12132 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12133 return SDValue(); 12134 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12135 BCNumEltsChanged = true; 12136 InVec = InVec.getOperand(0); 12137 ExtVT = BCVT.getVectorElementType(); 12138 } 12139 12140 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12141 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12142 ISD::isNormalLoad(InVec.getNode()) && 12143 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12144 SDValue Index = N->getOperand(1); 12145 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 12146 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12147 OrigLoad); 12148 } 12149 12150 // Perform only after legalization to ensure build_vector / vector_shuffle 12151 // optimizations have already been done. 12152 if (!LegalOperations) return SDValue(); 12153 12154 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12155 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12156 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12157 12158 if (ConstEltNo) { 12159 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12160 12161 LoadSDNode *LN0 = nullptr; 12162 const ShuffleVectorSDNode *SVN = nullptr; 12163 if (ISD::isNormalLoad(InVec.getNode())) { 12164 LN0 = cast<LoadSDNode>(InVec); 12165 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12166 InVec.getOperand(0).getValueType() == ExtVT && 12167 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12168 // Don't duplicate a load with other uses. 12169 if (!InVec.hasOneUse()) 12170 return SDValue(); 12171 12172 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12173 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12174 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12175 // => 12176 // (load $addr+1*size) 12177 12178 // Don't duplicate a load with other uses. 12179 if (!InVec.hasOneUse()) 12180 return SDValue(); 12181 12182 // If the bit convert changed the number of elements, it is unsafe 12183 // to examine the mask. 12184 if (BCNumEltsChanged) 12185 return SDValue(); 12186 12187 // Select the input vector, guarding against out of range extract vector. 12188 unsigned NumElems = VT.getVectorNumElements(); 12189 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12190 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12191 12192 if (InVec.getOpcode() == ISD::BITCAST) { 12193 // Don't duplicate a load with other uses. 12194 if (!InVec.hasOneUse()) 12195 return SDValue(); 12196 12197 InVec = InVec.getOperand(0); 12198 } 12199 if (ISD::isNormalLoad(InVec.getNode())) { 12200 LN0 = cast<LoadSDNode>(InVec); 12201 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12202 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12203 } 12204 } 12205 12206 // Make sure we found a non-volatile load and the extractelement is 12207 // the only use. 12208 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12209 return SDValue(); 12210 12211 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12212 if (Elt == -1) 12213 return DAG.getUNDEF(LVT); 12214 12215 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12216 } 12217 12218 return SDValue(); 12219 } 12220 12221 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12222 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12223 // We perform this optimization post type-legalization because 12224 // the type-legalizer often scalarizes integer-promoted vectors. 12225 // Performing this optimization before may create bit-casts which 12226 // will be type-legalized to complex code sequences. 12227 // We perform this optimization only before the operation legalizer because we 12228 // may introduce illegal operations. 12229 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12230 return SDValue(); 12231 12232 unsigned NumInScalars = N->getNumOperands(); 12233 SDLoc dl(N); 12234 EVT VT = N->getValueType(0); 12235 12236 // Check to see if this is a BUILD_VECTOR of a bunch of values 12237 // which come from any_extend or zero_extend nodes. If so, we can create 12238 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12239 // optimizations. We do not handle sign-extend because we can't fill the sign 12240 // using shuffles. 12241 EVT SourceType = MVT::Other; 12242 bool AllAnyExt = true; 12243 12244 for (unsigned i = 0; i != NumInScalars; ++i) { 12245 SDValue In = N->getOperand(i); 12246 // Ignore undef inputs. 12247 if (In.getOpcode() == ISD::UNDEF) continue; 12248 12249 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12250 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12251 12252 // Abort if the element is not an extension. 12253 if (!ZeroExt && !AnyExt) { 12254 SourceType = MVT::Other; 12255 break; 12256 } 12257 12258 // The input is a ZeroExt or AnyExt. Check the original type. 12259 EVT InTy = In.getOperand(0).getValueType(); 12260 12261 // Check that all of the widened source types are the same. 12262 if (SourceType == MVT::Other) 12263 // First time. 12264 SourceType = InTy; 12265 else if (InTy != SourceType) { 12266 // Multiple income types. Abort. 12267 SourceType = MVT::Other; 12268 break; 12269 } 12270 12271 // Check if all of the extends are ANY_EXTENDs. 12272 AllAnyExt &= AnyExt; 12273 } 12274 12275 // In order to have valid types, all of the inputs must be extended from the 12276 // same source type and all of the inputs must be any or zero extend. 12277 // Scalar sizes must be a power of two. 12278 EVT OutScalarTy = VT.getScalarType(); 12279 bool ValidTypes = SourceType != MVT::Other && 12280 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12281 isPowerOf2_32(SourceType.getSizeInBits()); 12282 12283 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12284 // turn into a single shuffle instruction. 12285 if (!ValidTypes) 12286 return SDValue(); 12287 12288 bool isLE = DAG.getDataLayout().isLittleEndian(); 12289 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12290 assert(ElemRatio > 1 && "Invalid element size ratio"); 12291 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12292 DAG.getConstant(0, SDLoc(N), SourceType); 12293 12294 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12295 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12296 12297 // Populate the new build_vector 12298 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12299 SDValue Cast = N->getOperand(i); 12300 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12301 Cast.getOpcode() == ISD::ZERO_EXTEND || 12302 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 12303 SDValue In; 12304 if (Cast.getOpcode() == ISD::UNDEF) 12305 In = DAG.getUNDEF(SourceType); 12306 else 12307 In = Cast->getOperand(0); 12308 unsigned Index = isLE ? (i * ElemRatio) : 12309 (i * ElemRatio + (ElemRatio - 1)); 12310 12311 assert(Index < Ops.size() && "Invalid index"); 12312 Ops[Index] = In; 12313 } 12314 12315 // The type of the new BUILD_VECTOR node. 12316 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12317 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12318 "Invalid vector size"); 12319 // Check if the new vector type is legal. 12320 if (!isTypeLegal(VecVT)) return SDValue(); 12321 12322 // Make the new BUILD_VECTOR. 12323 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 12324 12325 // The new BUILD_VECTOR node has the potential to be further optimized. 12326 AddToWorklist(BV.getNode()); 12327 // Bitcast to the desired type. 12328 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12329 } 12330 12331 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12332 EVT VT = N->getValueType(0); 12333 12334 unsigned NumInScalars = N->getNumOperands(); 12335 SDLoc dl(N); 12336 12337 EVT SrcVT = MVT::Other; 12338 unsigned Opcode = ISD::DELETED_NODE; 12339 unsigned NumDefs = 0; 12340 12341 for (unsigned i = 0; i != NumInScalars; ++i) { 12342 SDValue In = N->getOperand(i); 12343 unsigned Opc = In.getOpcode(); 12344 12345 if (Opc == ISD::UNDEF) 12346 continue; 12347 12348 // If all scalar values are floats and converted from integers. 12349 if (Opcode == ISD::DELETED_NODE && 12350 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12351 Opcode = Opc; 12352 } 12353 12354 if (Opc != Opcode) 12355 return SDValue(); 12356 12357 EVT InVT = In.getOperand(0).getValueType(); 12358 12359 // If all scalar values are typed differently, bail out. It's chosen to 12360 // simplify BUILD_VECTOR of integer types. 12361 if (SrcVT == MVT::Other) 12362 SrcVT = InVT; 12363 if (SrcVT != InVT) 12364 return SDValue(); 12365 NumDefs++; 12366 } 12367 12368 // If the vector has just one element defined, it's not worth to fold it into 12369 // a vectorized one. 12370 if (NumDefs < 2) 12371 return SDValue(); 12372 12373 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12374 && "Should only handle conversion from integer to float."); 12375 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12376 12377 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12378 12379 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12380 return SDValue(); 12381 12382 // Just because the floating-point vector type is legal does not necessarily 12383 // mean that the corresponding integer vector type is. 12384 if (!isTypeLegal(NVT)) 12385 return SDValue(); 12386 12387 SmallVector<SDValue, 8> Opnds; 12388 for (unsigned i = 0; i != NumInScalars; ++i) { 12389 SDValue In = N->getOperand(i); 12390 12391 if (In.getOpcode() == ISD::UNDEF) 12392 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12393 else 12394 Opnds.push_back(In.getOperand(0)); 12395 } 12396 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 12397 AddToWorklist(BV.getNode()); 12398 12399 return DAG.getNode(Opcode, dl, VT, BV); 12400 } 12401 12402 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12403 unsigned NumInScalars = N->getNumOperands(); 12404 SDLoc dl(N); 12405 EVT VT = N->getValueType(0); 12406 12407 // A vector built entirely of undefs is undef. 12408 if (ISD::allOperandsUndef(N)) 12409 return DAG.getUNDEF(VT); 12410 12411 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12412 return V; 12413 12414 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12415 return V; 12416 12417 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12418 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12419 // at most two distinct vectors, turn this into a shuffle node. 12420 12421 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12422 if (!isTypeLegal(VT)) 12423 return SDValue(); 12424 12425 // May only combine to shuffle after legalize if shuffle is legal. 12426 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12427 return SDValue(); 12428 12429 SDValue VecIn1, VecIn2; 12430 bool UsesZeroVector = false; 12431 for (unsigned i = 0; i != NumInScalars; ++i) { 12432 SDValue Op = N->getOperand(i); 12433 // Ignore undef inputs. 12434 if (Op.getOpcode() == ISD::UNDEF) continue; 12435 12436 // See if we can combine this build_vector into a blend with a zero vector. 12437 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12438 UsesZeroVector = true; 12439 continue; 12440 } 12441 12442 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12443 // constant index, bail out. 12444 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12445 !isa<ConstantSDNode>(Op.getOperand(1))) { 12446 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12447 break; 12448 } 12449 12450 // We allow up to two distinct input vectors. 12451 SDValue ExtractedFromVec = Op.getOperand(0); 12452 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12453 continue; 12454 12455 if (!VecIn1.getNode()) { 12456 VecIn1 = ExtractedFromVec; 12457 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12458 VecIn2 = ExtractedFromVec; 12459 } else { 12460 // Too many inputs. 12461 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12462 break; 12463 } 12464 } 12465 12466 // If everything is good, we can make a shuffle operation. 12467 if (VecIn1.getNode()) { 12468 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12469 SmallVector<int, 8> Mask; 12470 for (unsigned i = 0; i != NumInScalars; ++i) { 12471 unsigned Opcode = N->getOperand(i).getOpcode(); 12472 if (Opcode == ISD::UNDEF) { 12473 Mask.push_back(-1); 12474 continue; 12475 } 12476 12477 // Operands can also be zero. 12478 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12479 assert(UsesZeroVector && 12480 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12481 "Unexpected node found!"); 12482 Mask.push_back(NumInScalars+i); 12483 continue; 12484 } 12485 12486 // If extracting from the first vector, just use the index directly. 12487 SDValue Extract = N->getOperand(i); 12488 SDValue ExtVal = Extract.getOperand(1); 12489 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12490 if (Extract.getOperand(0) == VecIn1) { 12491 Mask.push_back(ExtIndex); 12492 continue; 12493 } 12494 12495 // Otherwise, use InIdx + InputVecSize 12496 Mask.push_back(InNumElements + ExtIndex); 12497 } 12498 12499 // Avoid introducing illegal shuffles with zero. 12500 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12501 return SDValue(); 12502 12503 // We can't generate a shuffle node with mismatched input and output types. 12504 // Attempt to transform a single input vector to the correct type. 12505 if ((VT != VecIn1.getValueType())) { 12506 // If the input vector type has a different base type to the output 12507 // vector type, bail out. 12508 EVT VTElemType = VT.getVectorElementType(); 12509 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12510 (VecIn2.getNode() && 12511 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12512 return SDValue(); 12513 12514 // If the input vector is too small, widen it. 12515 // We only support widening of vectors which are half the size of the 12516 // output registers. For example XMM->YMM widening on X86 with AVX. 12517 EVT VecInT = VecIn1.getValueType(); 12518 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12519 // If we only have one small input, widen it by adding undef values. 12520 if (!VecIn2.getNode()) 12521 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12522 DAG.getUNDEF(VecIn1.getValueType())); 12523 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12524 // If we have two small inputs of the same type, try to concat them. 12525 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12526 VecIn2 = SDValue(nullptr, 0); 12527 } else 12528 return SDValue(); 12529 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12530 // If the input vector is too large, try to split it. 12531 // We don't support having two input vectors that are too large. 12532 // If the zero vector was used, we can not split the vector, 12533 // since we'd need 3 inputs. 12534 if (UsesZeroVector || VecIn2.getNode()) 12535 return SDValue(); 12536 12537 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12538 return SDValue(); 12539 12540 // Try to replace VecIn1 with two extract_subvectors 12541 // No need to update the masks, they should still be correct. 12542 VecIn2 = DAG.getNode( 12543 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12544 DAG.getConstant(VT.getVectorNumElements(), dl, 12545 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12546 VecIn1 = DAG.getNode( 12547 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12548 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12549 } else 12550 return SDValue(); 12551 } 12552 12553 if (UsesZeroVector) 12554 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12555 DAG.getConstantFP(0.0, dl, VT); 12556 else 12557 // If VecIn2 is unused then change it to undef. 12558 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12559 12560 // Check that we were able to transform all incoming values to the same 12561 // type. 12562 if (VecIn2.getValueType() != VecIn1.getValueType() || 12563 VecIn1.getValueType() != VT) 12564 return SDValue(); 12565 12566 // Return the new VECTOR_SHUFFLE node. 12567 SDValue Ops[2]; 12568 Ops[0] = VecIn1; 12569 Ops[1] = VecIn2; 12570 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12571 } 12572 12573 return SDValue(); 12574 } 12575 12576 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12577 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12578 EVT OpVT = N->getOperand(0).getValueType(); 12579 12580 // If the operands are legal vectors, leave them alone. 12581 if (TLI.isTypeLegal(OpVT)) 12582 return SDValue(); 12583 12584 SDLoc DL(N); 12585 EVT VT = N->getValueType(0); 12586 SmallVector<SDValue, 8> Ops; 12587 12588 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12589 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12590 12591 // Keep track of what we encounter. 12592 bool AnyInteger = false; 12593 bool AnyFP = false; 12594 for (const SDValue &Op : N->ops()) { 12595 if (ISD::BITCAST == Op.getOpcode() && 12596 !Op.getOperand(0).getValueType().isVector()) 12597 Ops.push_back(Op.getOperand(0)); 12598 else if (ISD::UNDEF == Op.getOpcode()) 12599 Ops.push_back(ScalarUndef); 12600 else 12601 return SDValue(); 12602 12603 // Note whether we encounter an integer or floating point scalar. 12604 // If it's neither, bail out, it could be something weird like x86mmx. 12605 EVT LastOpVT = Ops.back().getValueType(); 12606 if (LastOpVT.isFloatingPoint()) 12607 AnyFP = true; 12608 else if (LastOpVT.isInteger()) 12609 AnyInteger = true; 12610 else 12611 return SDValue(); 12612 } 12613 12614 // If any of the operands is a floating point scalar bitcast to a vector, 12615 // use floating point types throughout, and bitcast everything. 12616 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12617 if (AnyFP) { 12618 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12619 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12620 if (AnyInteger) { 12621 for (SDValue &Op : Ops) { 12622 if (Op.getValueType() == SVT) 12623 continue; 12624 if (Op.getOpcode() == ISD::UNDEF) 12625 Op = ScalarUndef; 12626 else 12627 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12628 } 12629 } 12630 } 12631 12632 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12633 VT.getSizeInBits() / SVT.getSizeInBits()); 12634 return DAG.getNode(ISD::BITCAST, DL, VT, 12635 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 12636 } 12637 12638 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12639 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12640 // most two distinct vectors the same size as the result, attempt to turn this 12641 // into a legal shuffle. 12642 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12643 EVT VT = N->getValueType(0); 12644 EVT OpVT = N->getOperand(0).getValueType(); 12645 int NumElts = VT.getVectorNumElements(); 12646 int NumOpElts = OpVT.getVectorNumElements(); 12647 12648 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12649 SmallVector<int, 8> Mask; 12650 12651 for (SDValue Op : N->ops()) { 12652 // Peek through any bitcast. 12653 while (Op.getOpcode() == ISD::BITCAST) 12654 Op = Op.getOperand(0); 12655 12656 // UNDEF nodes convert to UNDEF shuffle mask values. 12657 if (Op.getOpcode() == ISD::UNDEF) { 12658 Mask.append((unsigned)NumOpElts, -1); 12659 continue; 12660 } 12661 12662 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12663 return SDValue(); 12664 12665 // What vector are we extracting the subvector from and at what index? 12666 SDValue ExtVec = Op.getOperand(0); 12667 12668 // We want the EVT of the original extraction to correctly scale the 12669 // extraction index. 12670 EVT ExtVT = ExtVec.getValueType(); 12671 12672 // Peek through any bitcast. 12673 while (ExtVec.getOpcode() == ISD::BITCAST) 12674 ExtVec = ExtVec.getOperand(0); 12675 12676 // UNDEF nodes convert to UNDEF shuffle mask values. 12677 if (ExtVec.getOpcode() == ISD::UNDEF) { 12678 Mask.append((unsigned)NumOpElts, -1); 12679 continue; 12680 } 12681 12682 if (!isa<ConstantSDNode>(Op.getOperand(1))) 12683 return SDValue(); 12684 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 12685 12686 // Ensure that we are extracting a subvector from a vector the same 12687 // size as the result. 12688 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 12689 return SDValue(); 12690 12691 // Scale the subvector index to account for any bitcast. 12692 int NumExtElts = ExtVT.getVectorNumElements(); 12693 if (0 == (NumExtElts % NumElts)) 12694 ExtIdx /= (NumExtElts / NumElts); 12695 else if (0 == (NumElts % NumExtElts)) 12696 ExtIdx *= (NumElts / NumExtElts); 12697 else 12698 return SDValue(); 12699 12700 // At most we can reference 2 inputs in the final shuffle. 12701 if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) { 12702 SV0 = ExtVec; 12703 for (int i = 0; i != NumOpElts; ++i) 12704 Mask.push_back(i + ExtIdx); 12705 } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) { 12706 SV1 = ExtVec; 12707 for (int i = 0; i != NumOpElts; ++i) 12708 Mask.push_back(i + ExtIdx + NumElts); 12709 } else { 12710 return SDValue(); 12711 } 12712 } 12713 12714 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 12715 return SDValue(); 12716 12717 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 12718 DAG.getBitcast(VT, SV1), Mask); 12719 } 12720 12721 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12722 // If we only have one input vector, we don't need to do any concatenation. 12723 if (N->getNumOperands() == 1) 12724 return N->getOperand(0); 12725 12726 // Check if all of the operands are undefs. 12727 EVT VT = N->getValueType(0); 12728 if (ISD::allOperandsUndef(N)) 12729 return DAG.getUNDEF(VT); 12730 12731 // Optimize concat_vectors where all but the first of the vectors are undef. 12732 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 12733 return Op.getOpcode() == ISD::UNDEF; 12734 })) { 12735 SDValue In = N->getOperand(0); 12736 assert(In.getValueType().isVector() && "Must concat vectors"); 12737 12738 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 12739 if (In->getOpcode() == ISD::BITCAST && 12740 !In->getOperand(0)->getValueType(0).isVector()) { 12741 SDValue Scalar = In->getOperand(0); 12742 12743 // If the bitcast type isn't legal, it might be a trunc of a legal type; 12744 // look through the trunc so we can still do the transform: 12745 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 12746 if (Scalar->getOpcode() == ISD::TRUNCATE && 12747 !TLI.isTypeLegal(Scalar.getValueType()) && 12748 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 12749 Scalar = Scalar->getOperand(0); 12750 12751 EVT SclTy = Scalar->getValueType(0); 12752 12753 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 12754 return SDValue(); 12755 12756 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 12757 VT.getSizeInBits() / SclTy.getSizeInBits()); 12758 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 12759 return SDValue(); 12760 12761 SDLoc dl = SDLoc(N); 12762 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 12763 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 12764 } 12765 } 12766 12767 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 12768 // We have already tested above for an UNDEF only concatenation. 12769 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 12770 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 12771 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 12772 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 12773 }; 12774 bool AllBuildVectorsOrUndefs = 12775 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 12776 if (AllBuildVectorsOrUndefs) { 12777 SmallVector<SDValue, 8> Opnds; 12778 EVT SVT = VT.getScalarType(); 12779 12780 EVT MinVT = SVT; 12781 if (!SVT.isFloatingPoint()) { 12782 // If BUILD_VECTOR are from built from integer, they may have different 12783 // operand types. Get the smallest type and truncate all operands to it. 12784 bool FoundMinVT = false; 12785 for (const SDValue &Op : N->ops()) 12786 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12787 EVT OpSVT = Op.getOperand(0)->getValueType(0); 12788 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 12789 FoundMinVT = true; 12790 } 12791 assert(FoundMinVT && "Concat vector type mismatch"); 12792 } 12793 12794 for (const SDValue &Op : N->ops()) { 12795 EVT OpVT = Op.getValueType(); 12796 unsigned NumElts = OpVT.getVectorNumElements(); 12797 12798 if (ISD::UNDEF == Op.getOpcode()) 12799 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 12800 12801 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12802 if (SVT.isFloatingPoint()) { 12803 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 12804 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 12805 } else { 12806 for (unsigned i = 0; i != NumElts; ++i) 12807 Opnds.push_back( 12808 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 12809 } 12810 } 12811 } 12812 12813 assert(VT.getVectorNumElements() == Opnds.size() && 12814 "Concat vector type mismatch"); 12815 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 12816 } 12817 12818 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 12819 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 12820 return V; 12821 12822 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 12823 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 12824 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 12825 return V; 12826 12827 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 12828 // nodes often generate nop CONCAT_VECTOR nodes. 12829 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 12830 // place the incoming vectors at the exact same location. 12831 SDValue SingleSource = SDValue(); 12832 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 12833 12834 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12835 SDValue Op = N->getOperand(i); 12836 12837 if (Op.getOpcode() == ISD::UNDEF) 12838 continue; 12839 12840 // Check if this is the identity extract: 12841 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12842 return SDValue(); 12843 12844 // Find the single incoming vector for the extract_subvector. 12845 if (SingleSource.getNode()) { 12846 if (Op.getOperand(0) != SingleSource) 12847 return SDValue(); 12848 } else { 12849 SingleSource = Op.getOperand(0); 12850 12851 // Check the source type is the same as the type of the result. 12852 // If not, this concat may extend the vector, so we can not 12853 // optimize it away. 12854 if (SingleSource.getValueType() != N->getValueType(0)) 12855 return SDValue(); 12856 } 12857 12858 unsigned IdentityIndex = i * PartNumElem; 12859 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 12860 // The extract index must be constant. 12861 if (!CS) 12862 return SDValue(); 12863 12864 // Check that we are reading from the identity index. 12865 if (CS->getZExtValue() != IdentityIndex) 12866 return SDValue(); 12867 } 12868 12869 if (SingleSource.getNode()) 12870 return SingleSource; 12871 12872 return SDValue(); 12873 } 12874 12875 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 12876 EVT NVT = N->getValueType(0); 12877 SDValue V = N->getOperand(0); 12878 12879 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 12880 // Combine: 12881 // (extract_subvec (concat V1, V2, ...), i) 12882 // Into: 12883 // Vi if possible 12884 // Only operand 0 is checked as 'concat' assumes all inputs of the same 12885 // type. 12886 if (V->getOperand(0).getValueType() != NVT) 12887 return SDValue(); 12888 unsigned Idx = N->getConstantOperandVal(1); 12889 unsigned NumElems = NVT.getVectorNumElements(); 12890 assert((Idx % NumElems) == 0 && 12891 "IDX in concat is not a multiple of the result vector length."); 12892 return V->getOperand(Idx / NumElems); 12893 } 12894 12895 // Skip bitcasting 12896 if (V->getOpcode() == ISD::BITCAST) 12897 V = V.getOperand(0); 12898 12899 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 12900 SDLoc dl(N); 12901 // Handle only simple case where vector being inserted and vector 12902 // being extracted are of same type, and are half size of larger vectors. 12903 EVT BigVT = V->getOperand(0).getValueType(); 12904 EVT SmallVT = V->getOperand(1).getValueType(); 12905 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 12906 return SDValue(); 12907 12908 // Only handle cases where both indexes are constants with the same type. 12909 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12910 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12911 12912 if (InsIdx && ExtIdx && 12913 InsIdx->getValueType(0).getSizeInBits() <= 64 && 12914 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 12915 // Combine: 12916 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 12917 // Into: 12918 // indices are equal or bit offsets are equal => V1 12919 // otherwise => (extract_subvec V1, ExtIdx) 12920 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 12921 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 12922 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 12923 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 12924 DAG.getNode(ISD::BITCAST, dl, 12925 N->getOperand(0).getValueType(), 12926 V->getOperand(0)), N->getOperand(1)); 12927 } 12928 } 12929 12930 return SDValue(); 12931 } 12932 12933 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 12934 SDValue V, SelectionDAG &DAG) { 12935 SDLoc DL(V); 12936 EVT VT = V.getValueType(); 12937 12938 switch (V.getOpcode()) { 12939 default: 12940 return V; 12941 12942 case ISD::CONCAT_VECTORS: { 12943 EVT OpVT = V->getOperand(0).getValueType(); 12944 int OpSize = OpVT.getVectorNumElements(); 12945 SmallBitVector OpUsedElements(OpSize, false); 12946 bool FoundSimplification = false; 12947 SmallVector<SDValue, 4> NewOps; 12948 NewOps.reserve(V->getNumOperands()); 12949 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 12950 SDValue Op = V->getOperand(i); 12951 bool OpUsed = false; 12952 for (int j = 0; j < OpSize; ++j) 12953 if (UsedElements[i * OpSize + j]) { 12954 OpUsedElements[j] = true; 12955 OpUsed = true; 12956 } 12957 NewOps.push_back( 12958 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 12959 : DAG.getUNDEF(OpVT)); 12960 FoundSimplification |= Op == NewOps.back(); 12961 OpUsedElements.reset(); 12962 } 12963 if (FoundSimplification) 12964 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 12965 return V; 12966 } 12967 12968 case ISD::INSERT_SUBVECTOR: { 12969 SDValue BaseV = V->getOperand(0); 12970 SDValue SubV = V->getOperand(1); 12971 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12972 if (!IdxN) 12973 return V; 12974 12975 int SubSize = SubV.getValueType().getVectorNumElements(); 12976 int Idx = IdxN->getZExtValue(); 12977 bool SubVectorUsed = false; 12978 SmallBitVector SubUsedElements(SubSize, false); 12979 for (int i = 0; i < SubSize; ++i) 12980 if (UsedElements[i + Idx]) { 12981 SubVectorUsed = true; 12982 SubUsedElements[i] = true; 12983 UsedElements[i + Idx] = false; 12984 } 12985 12986 // Now recurse on both the base and sub vectors. 12987 SDValue SimplifiedSubV = 12988 SubVectorUsed 12989 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 12990 : DAG.getUNDEF(SubV.getValueType()); 12991 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 12992 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 12993 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 12994 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 12995 return V; 12996 } 12997 } 12998 } 12999 13000 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13001 SDValue N1, SelectionDAG &DAG) { 13002 EVT VT = SVN->getValueType(0); 13003 int NumElts = VT.getVectorNumElements(); 13004 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13005 for (int M : SVN->getMask()) 13006 if (M >= 0 && M < NumElts) 13007 N0UsedElements[M] = true; 13008 else if (M >= NumElts) 13009 N1UsedElements[M - NumElts] = true; 13010 13011 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13012 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13013 if (S0 == N0 && S1 == N1) 13014 return SDValue(); 13015 13016 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13017 } 13018 13019 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13020 // or turn a shuffle of a single concat into simpler shuffle then concat. 13021 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13022 EVT VT = N->getValueType(0); 13023 unsigned NumElts = VT.getVectorNumElements(); 13024 13025 SDValue N0 = N->getOperand(0); 13026 SDValue N1 = N->getOperand(1); 13027 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13028 13029 SmallVector<SDValue, 4> Ops; 13030 EVT ConcatVT = N0.getOperand(0).getValueType(); 13031 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13032 unsigned NumConcats = NumElts / NumElemsPerConcat; 13033 13034 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13035 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13036 // half vector elements. 13037 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 13038 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13039 SVN->getMask().end(), [](int i) { return i == -1; })) { 13040 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13041 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13042 N1 = DAG.getUNDEF(ConcatVT); 13043 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13044 } 13045 13046 // Look at every vector that's inserted. We're looking for exact 13047 // subvector-sized copies from a concatenated vector 13048 for (unsigned I = 0; I != NumConcats; ++I) { 13049 // Make sure we're dealing with a copy. 13050 unsigned Begin = I * NumElemsPerConcat; 13051 bool AllUndef = true, NoUndef = true; 13052 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13053 if (SVN->getMaskElt(J) >= 0) 13054 AllUndef = false; 13055 else 13056 NoUndef = false; 13057 } 13058 13059 if (NoUndef) { 13060 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13061 return SDValue(); 13062 13063 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13064 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13065 return SDValue(); 13066 13067 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13068 if (FirstElt < N0.getNumOperands()) 13069 Ops.push_back(N0.getOperand(FirstElt)); 13070 else 13071 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13072 13073 } else if (AllUndef) { 13074 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13075 } else { // Mixed with general masks and undefs, can't do optimization. 13076 return SDValue(); 13077 } 13078 } 13079 13080 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13081 } 13082 13083 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13084 EVT VT = N->getValueType(0); 13085 unsigned NumElts = VT.getVectorNumElements(); 13086 13087 SDValue N0 = N->getOperand(0); 13088 SDValue N1 = N->getOperand(1); 13089 13090 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13091 13092 // Canonicalize shuffle undef, undef -> undef 13093 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 13094 return DAG.getUNDEF(VT); 13095 13096 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13097 13098 // Canonicalize shuffle v, v -> v, undef 13099 if (N0 == N1) { 13100 SmallVector<int, 8> NewMask; 13101 for (unsigned i = 0; i != NumElts; ++i) { 13102 int Idx = SVN->getMaskElt(i); 13103 if (Idx >= (int)NumElts) Idx -= NumElts; 13104 NewMask.push_back(Idx); 13105 } 13106 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 13107 &NewMask[0]); 13108 } 13109 13110 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13111 if (N0.getOpcode() == ISD::UNDEF) { 13112 SmallVector<int, 8> NewMask; 13113 for (unsigned i = 0; i != NumElts; ++i) { 13114 int Idx = SVN->getMaskElt(i); 13115 if (Idx >= 0) { 13116 if (Idx >= (int)NumElts) 13117 Idx -= NumElts; 13118 else 13119 Idx = -1; // remove reference to lhs 13120 } 13121 NewMask.push_back(Idx); 13122 } 13123 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 13124 &NewMask[0]); 13125 } 13126 13127 // Remove references to rhs if it is undef 13128 if (N1.getOpcode() == ISD::UNDEF) { 13129 bool Changed = false; 13130 SmallVector<int, 8> NewMask; 13131 for (unsigned i = 0; i != NumElts; ++i) { 13132 int Idx = SVN->getMaskElt(i); 13133 if (Idx >= (int)NumElts) { 13134 Idx = -1; 13135 Changed = true; 13136 } 13137 NewMask.push_back(Idx); 13138 } 13139 if (Changed) 13140 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 13141 } 13142 13143 // If it is a splat, check if the argument vector is another splat or a 13144 // build_vector. 13145 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13146 SDNode *V = N0.getNode(); 13147 13148 // If this is a bit convert that changes the element type of the vector but 13149 // not the number of vector elements, look through it. Be careful not to 13150 // look though conversions that change things like v4f32 to v2f64. 13151 if (V->getOpcode() == ISD::BITCAST) { 13152 SDValue ConvInput = V->getOperand(0); 13153 if (ConvInput.getValueType().isVector() && 13154 ConvInput.getValueType().getVectorNumElements() == NumElts) 13155 V = ConvInput.getNode(); 13156 } 13157 13158 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13159 assert(V->getNumOperands() == NumElts && 13160 "BUILD_VECTOR has wrong number of operands"); 13161 SDValue Base; 13162 bool AllSame = true; 13163 for (unsigned i = 0; i != NumElts; ++i) { 13164 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 13165 Base = V->getOperand(i); 13166 break; 13167 } 13168 } 13169 // Splat of <u, u, u, u>, return <u, u, u, u> 13170 if (!Base.getNode()) 13171 return N0; 13172 for (unsigned i = 0; i != NumElts; ++i) { 13173 if (V->getOperand(i) != Base) { 13174 AllSame = false; 13175 break; 13176 } 13177 } 13178 // Splat of <x, x, x, x>, return <x, x, x, x> 13179 if (AllSame) 13180 return N0; 13181 13182 // Canonicalize any other splat as a build_vector. 13183 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13184 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13185 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 13186 V->getValueType(0), Ops); 13187 13188 // We may have jumped through bitcasts, so the type of the 13189 // BUILD_VECTOR may not match the type of the shuffle. 13190 if (V->getValueType(0) != VT) 13191 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 13192 return NewBV; 13193 } 13194 } 13195 13196 // There are various patterns used to build up a vector from smaller vectors, 13197 // subvectors, or elements. Scan chains of these and replace unused insertions 13198 // or components with undef. 13199 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13200 return S; 13201 13202 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13203 Level < AfterLegalizeVectorOps && 13204 (N1.getOpcode() == ISD::UNDEF || 13205 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13206 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13207 SDValue V = partitionShuffleOfConcats(N, DAG); 13208 13209 if (V.getNode()) 13210 return V; 13211 } 13212 13213 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13214 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13215 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13216 SmallVector<SDValue, 8> Ops; 13217 for (int M : SVN->getMask()) { 13218 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13219 if (M >= 0) { 13220 int Idx = M % NumElts; 13221 SDValue &S = (M < (int)NumElts ? N0 : N1); 13222 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13223 Op = S.getOperand(Idx); 13224 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13225 if (Idx == 0) 13226 Op = S.getOperand(0); 13227 } else { 13228 // Operand can't be combined - bail out. 13229 break; 13230 } 13231 } 13232 Ops.push_back(Op); 13233 } 13234 if (Ops.size() == VT.getVectorNumElements()) { 13235 // BUILD_VECTOR requires all inputs to be of the same type, find the 13236 // maximum type and extend them all. 13237 EVT SVT = VT.getScalarType(); 13238 if (SVT.isInteger()) 13239 for (SDValue &Op : Ops) 13240 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13241 if (SVT != VT.getScalarType()) 13242 for (SDValue &Op : Ops) 13243 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13244 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13245 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13246 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 13247 } 13248 } 13249 13250 // If this shuffle only has a single input that is a bitcasted shuffle, 13251 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13252 // back to their original types. 13253 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13254 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 13255 TLI.isTypeLegal(VT)) { 13256 13257 // Peek through the bitcast only if there is one user. 13258 SDValue BC0 = N0; 13259 while (BC0.getOpcode() == ISD::BITCAST) { 13260 if (!BC0.hasOneUse()) 13261 break; 13262 BC0 = BC0.getOperand(0); 13263 } 13264 13265 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13266 if (Scale == 1) 13267 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13268 13269 SmallVector<int, 8> NewMask; 13270 for (int M : Mask) 13271 for (int s = 0; s != Scale; ++s) 13272 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13273 return NewMask; 13274 }; 13275 13276 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13277 EVT SVT = VT.getScalarType(); 13278 EVT InnerVT = BC0->getValueType(0); 13279 EVT InnerSVT = InnerVT.getScalarType(); 13280 13281 // Determine which shuffle works with the smaller scalar type. 13282 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13283 EVT ScaleSVT = ScaleVT.getScalarType(); 13284 13285 if (TLI.isTypeLegal(ScaleVT) && 13286 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13287 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13288 13289 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13290 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13291 13292 // Scale the shuffle masks to the smaller scalar type. 13293 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13294 SmallVector<int, 8> InnerMask = 13295 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13296 SmallVector<int, 8> OuterMask = 13297 ScaleShuffleMask(SVN->getMask(), OuterScale); 13298 13299 // Merge the shuffle masks. 13300 SmallVector<int, 8> NewMask; 13301 for (int M : OuterMask) 13302 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13303 13304 // Test for shuffle mask legality over both commutations. 13305 SDValue SV0 = BC0->getOperand(0); 13306 SDValue SV1 = BC0->getOperand(1); 13307 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13308 if (!LegalMask) { 13309 std::swap(SV0, SV1); 13310 ShuffleVectorSDNode::commuteMask(NewMask); 13311 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13312 } 13313 13314 if (LegalMask) { 13315 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 13316 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 13317 return DAG.getNode( 13318 ISD::BITCAST, SDLoc(N), VT, 13319 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13320 } 13321 } 13322 } 13323 } 13324 13325 // Canonicalize shuffles according to rules: 13326 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13327 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13328 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13329 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13330 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13331 TLI.isTypeLegal(VT)) { 13332 // The incoming shuffle must be of the same type as the result of the 13333 // current shuffle. 13334 assert(N1->getOperand(0).getValueType() == VT && 13335 "Shuffle types don't match"); 13336 13337 SDValue SV0 = N1->getOperand(0); 13338 SDValue SV1 = N1->getOperand(1); 13339 bool HasSameOp0 = N0 == SV0; 13340 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 13341 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13342 // Commute the operands of this shuffle so that next rule 13343 // will trigger. 13344 return DAG.getCommutedVectorShuffle(*SVN); 13345 } 13346 13347 // Try to fold according to rules: 13348 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13349 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13350 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13351 // Don't try to fold shuffles with illegal type. 13352 // Only fold if this shuffle is the only user of the other shuffle. 13353 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13354 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13355 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13356 13357 // The incoming shuffle must be of the same type as the result of the 13358 // current shuffle. 13359 assert(OtherSV->getOperand(0).getValueType() == VT && 13360 "Shuffle types don't match"); 13361 13362 SDValue SV0, SV1; 13363 SmallVector<int, 4> Mask; 13364 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13365 // operand, and SV1 as the second operand. 13366 for (unsigned i = 0; i != NumElts; ++i) { 13367 int Idx = SVN->getMaskElt(i); 13368 if (Idx < 0) { 13369 // Propagate Undef. 13370 Mask.push_back(Idx); 13371 continue; 13372 } 13373 13374 SDValue CurrentVec; 13375 if (Idx < (int)NumElts) { 13376 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13377 // shuffle mask to identify which vector is actually referenced. 13378 Idx = OtherSV->getMaskElt(Idx); 13379 if (Idx < 0) { 13380 // Propagate Undef. 13381 Mask.push_back(Idx); 13382 continue; 13383 } 13384 13385 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13386 : OtherSV->getOperand(1); 13387 } else { 13388 // This shuffle index references an element within N1. 13389 CurrentVec = N1; 13390 } 13391 13392 // Simple case where 'CurrentVec' is UNDEF. 13393 if (CurrentVec.getOpcode() == ISD::UNDEF) { 13394 Mask.push_back(-1); 13395 continue; 13396 } 13397 13398 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13399 // will be the first or second operand of the combined shuffle. 13400 Idx = Idx % NumElts; 13401 if (!SV0.getNode() || SV0 == CurrentVec) { 13402 // Ok. CurrentVec is the left hand side. 13403 // Update the mask accordingly. 13404 SV0 = CurrentVec; 13405 Mask.push_back(Idx); 13406 continue; 13407 } 13408 13409 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13410 if (SV1.getNode() && SV1 != CurrentVec) 13411 return SDValue(); 13412 13413 // Ok. CurrentVec is the right hand side. 13414 // Update the mask accordingly. 13415 SV1 = CurrentVec; 13416 Mask.push_back(Idx + NumElts); 13417 } 13418 13419 // Check if all indices in Mask are Undef. In case, propagate Undef. 13420 bool isUndefMask = true; 13421 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13422 isUndefMask &= Mask[i] < 0; 13423 13424 if (isUndefMask) 13425 return DAG.getUNDEF(VT); 13426 13427 if (!SV0.getNode()) 13428 SV0 = DAG.getUNDEF(VT); 13429 if (!SV1.getNode()) 13430 SV1 = DAG.getUNDEF(VT); 13431 13432 // Avoid introducing shuffles with illegal mask. 13433 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13434 ShuffleVectorSDNode::commuteMask(Mask); 13435 13436 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13437 return SDValue(); 13438 13439 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13440 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13441 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13442 std::swap(SV0, SV1); 13443 } 13444 13445 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13446 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13447 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13448 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 13449 } 13450 13451 return SDValue(); 13452 } 13453 13454 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13455 SDValue InVal = N->getOperand(0); 13456 EVT VT = N->getValueType(0); 13457 13458 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13459 // with a VECTOR_SHUFFLE. 13460 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13461 SDValue InVec = InVal->getOperand(0); 13462 SDValue EltNo = InVal->getOperand(1); 13463 13464 // FIXME: We could support implicit truncation if the shuffle can be 13465 // scaled to a smaller vector scalar type. 13466 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13467 if (C0 && VT == InVec.getValueType() && 13468 VT.getScalarType() == InVal.getValueType()) { 13469 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13470 int Elt = C0->getZExtValue(); 13471 NewMask[0] = Elt; 13472 13473 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13474 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13475 NewMask); 13476 } 13477 } 13478 13479 return SDValue(); 13480 } 13481 13482 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13483 SDValue N0 = N->getOperand(0); 13484 SDValue N2 = N->getOperand(2); 13485 13486 // If the input vector is a concatenation, and the insert replaces 13487 // one of the halves, we can optimize into a single concat_vectors. 13488 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13489 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 13490 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13491 EVT VT = N->getValueType(0); 13492 13493 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13494 // (concat_vectors Z, Y) 13495 if (InsIdx == 0) 13496 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13497 N->getOperand(1), N0.getOperand(1)); 13498 13499 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13500 // (concat_vectors X, Z) 13501 if (InsIdx == VT.getVectorNumElements()/2) 13502 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13503 N0.getOperand(0), N->getOperand(1)); 13504 } 13505 13506 return SDValue(); 13507 } 13508 13509 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13510 SDValue N0 = N->getOperand(0); 13511 13512 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13513 if (N0->getOpcode() == ISD::FP16_TO_FP) 13514 return N0->getOperand(0); 13515 13516 return SDValue(); 13517 } 13518 13519 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13520 SDValue N0 = N->getOperand(0); 13521 13522 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13523 if (N0->getOpcode() == ISD::AND) { 13524 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13525 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13526 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13527 N0.getOperand(0)); 13528 } 13529 } 13530 13531 return SDValue(); 13532 } 13533 13534 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13535 /// with the destination vector and a zero vector. 13536 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13537 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13538 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13539 EVT VT = N->getValueType(0); 13540 SDValue LHS = N->getOperand(0); 13541 SDValue RHS = N->getOperand(1); 13542 SDLoc dl(N); 13543 13544 // Make sure we're not running after operation legalization where it 13545 // may have custom lowered the vector shuffles. 13546 if (LegalOperations) 13547 return SDValue(); 13548 13549 if (N->getOpcode() != ISD::AND) 13550 return SDValue(); 13551 13552 if (RHS.getOpcode() == ISD::BITCAST) 13553 RHS = RHS.getOperand(0); 13554 13555 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13556 return SDValue(); 13557 13558 EVT RVT = RHS.getValueType(); 13559 unsigned NumElts = RHS.getNumOperands(); 13560 13561 // Attempt to create a valid clear mask, splitting the mask into 13562 // sub elements and checking to see if each is 13563 // all zeros or all ones - suitable for shuffle masking. 13564 auto BuildClearMask = [&](int Split) { 13565 int NumSubElts = NumElts * Split; 13566 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13567 13568 SmallVector<int, 8> Indices; 13569 for (int i = 0; i != NumSubElts; ++i) { 13570 int EltIdx = i / Split; 13571 int SubIdx = i % Split; 13572 SDValue Elt = RHS.getOperand(EltIdx); 13573 if (Elt.getOpcode() == ISD::UNDEF) { 13574 Indices.push_back(-1); 13575 continue; 13576 } 13577 13578 APInt Bits; 13579 if (isa<ConstantSDNode>(Elt)) 13580 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13581 else if (isa<ConstantFPSDNode>(Elt)) 13582 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13583 else 13584 return SDValue(); 13585 13586 // Extract the sub element from the constant bit mask. 13587 if (DAG.getDataLayout().isBigEndian()) { 13588 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13589 } else { 13590 Bits = Bits.lshr(SubIdx * NumSubBits); 13591 } 13592 13593 if (Split > 1) 13594 Bits = Bits.trunc(NumSubBits); 13595 13596 if (Bits.isAllOnesValue()) 13597 Indices.push_back(i); 13598 else if (Bits == 0) 13599 Indices.push_back(i + NumSubElts); 13600 else 13601 return SDValue(); 13602 } 13603 13604 // Let's see if the target supports this vector_shuffle. 13605 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13606 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13607 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13608 return SDValue(); 13609 13610 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13611 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13612 DAG.getBitcast(ClearVT, LHS), 13613 Zero, &Indices[0])); 13614 }; 13615 13616 // Determine maximum split level (byte level masking). 13617 int MaxSplit = 1; 13618 if (RVT.getScalarSizeInBits() % 8 == 0) 13619 MaxSplit = RVT.getScalarSizeInBits() / 8; 13620 13621 for (int Split = 1; Split <= MaxSplit; ++Split) 13622 if (RVT.getScalarSizeInBits() % Split == 0) 13623 if (SDValue S = BuildClearMask(Split)) 13624 return S; 13625 13626 return SDValue(); 13627 } 13628 13629 /// Visit a binary vector operation, like ADD. 13630 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13631 assert(N->getValueType(0).isVector() && 13632 "SimplifyVBinOp only works on vectors!"); 13633 13634 SDValue LHS = N->getOperand(0); 13635 SDValue RHS = N->getOperand(1); 13636 SDValue Ops[] = {LHS, RHS}; 13637 13638 // See if we can constant fold the vector operation. 13639 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 13640 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 13641 return Fold; 13642 13643 // Try to convert a constant mask AND into a shuffle clear mask. 13644 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13645 return Shuffle; 13646 13647 // Type legalization might introduce new shuffles in the DAG. 13648 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13649 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13650 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13651 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13652 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 13653 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 13654 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13655 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13656 13657 if (SVN0->getMask().equals(SVN1->getMask())) { 13658 EVT VT = N->getValueType(0); 13659 SDValue UndefVector = LHS.getOperand(1); 13660 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13661 LHS.getOperand(0), RHS.getOperand(0), 13662 N->getFlags()); 13663 AddUsersToWorklist(N); 13664 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13665 &SVN0->getMask()[0]); 13666 } 13667 } 13668 13669 return SDValue(); 13670 } 13671 13672 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13673 SDValue N1, SDValue N2){ 13674 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13675 13676 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13677 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13678 13679 // If we got a simplified select_cc node back from SimplifySelectCC, then 13680 // break it down into a new SETCC node, and a new SELECT node, and then return 13681 // the SELECT node, since we were called with a SELECT node. 13682 if (SCC.getNode()) { 13683 // Check to see if we got a select_cc back (to turn into setcc/select). 13684 // Otherwise, just return whatever node we got back, like fabs. 13685 if (SCC.getOpcode() == ISD::SELECT_CC) { 13686 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13687 N0.getValueType(), 13688 SCC.getOperand(0), SCC.getOperand(1), 13689 SCC.getOperand(4)); 13690 AddToWorklist(SETCC.getNode()); 13691 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13692 SCC.getOperand(2), SCC.getOperand(3)); 13693 } 13694 13695 return SCC; 13696 } 13697 return SDValue(); 13698 } 13699 13700 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13701 /// being selected between, see if we can simplify the select. Callers of this 13702 /// should assume that TheSelect is deleted if this returns true. As such, they 13703 /// should return the appropriate thing (e.g. the node) back to the top-level of 13704 /// the DAG combiner loop to avoid it being looked at. 13705 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13706 SDValue RHS) { 13707 13708 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13709 // The select + setcc is redundant, because fsqrt returns NaN for X < -0. 13710 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13711 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13712 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13713 SDValue Sqrt = RHS; 13714 ISD::CondCode CC; 13715 SDValue CmpLHS; 13716 const ConstantFPSDNode *NegZero = nullptr; 13717 13718 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13719 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13720 CmpLHS = TheSelect->getOperand(0); 13721 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13722 } else { 13723 // SELECT or VSELECT 13724 SDValue Cmp = TheSelect->getOperand(0); 13725 if (Cmp.getOpcode() == ISD::SETCC) { 13726 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13727 CmpLHS = Cmp.getOperand(0); 13728 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13729 } 13730 } 13731 if (NegZero && NegZero->isNegative() && NegZero->isZero() && 13732 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13733 CC == ISD::SETULT || CC == ISD::SETLT)) { 13734 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13735 CombineTo(TheSelect, Sqrt); 13736 return true; 13737 } 13738 } 13739 } 13740 // Cannot simplify select with vector condition 13741 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 13742 13743 // If this is a select from two identical things, try to pull the operation 13744 // through the select. 13745 if (LHS.getOpcode() != RHS.getOpcode() || 13746 !LHS.hasOneUse() || !RHS.hasOneUse()) 13747 return false; 13748 13749 // If this is a load and the token chain is identical, replace the select 13750 // of two loads with a load through a select of the address to load from. 13751 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 13752 // constants have been dropped into the constant pool. 13753 if (LHS.getOpcode() == ISD::LOAD) { 13754 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 13755 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 13756 13757 // Token chains must be identical. 13758 if (LHS.getOperand(0) != RHS.getOperand(0) || 13759 // Do not let this transformation reduce the number of volatile loads. 13760 LLD->isVolatile() || RLD->isVolatile() || 13761 // FIXME: If either is a pre/post inc/dec load, 13762 // we'd need to split out the address adjustment. 13763 LLD->isIndexed() || RLD->isIndexed() || 13764 // If this is an EXTLOAD, the VT's must match. 13765 LLD->getMemoryVT() != RLD->getMemoryVT() || 13766 // If this is an EXTLOAD, the kind of extension must match. 13767 (LLD->getExtensionType() != RLD->getExtensionType() && 13768 // The only exception is if one of the extensions is anyext. 13769 LLD->getExtensionType() != ISD::EXTLOAD && 13770 RLD->getExtensionType() != ISD::EXTLOAD) || 13771 // FIXME: this discards src value information. This is 13772 // over-conservative. It would be beneficial to be able to remember 13773 // both potential memory locations. Since we are discarding 13774 // src value info, don't do the transformation if the memory 13775 // locations are not in the default address space. 13776 LLD->getPointerInfo().getAddrSpace() != 0 || 13777 RLD->getPointerInfo().getAddrSpace() != 0 || 13778 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 13779 LLD->getBasePtr().getValueType())) 13780 return false; 13781 13782 // Check that the select condition doesn't reach either load. If so, 13783 // folding this will induce a cycle into the DAG. If not, this is safe to 13784 // xform, so create a select of the addresses. 13785 SDValue Addr; 13786 if (TheSelect->getOpcode() == ISD::SELECT) { 13787 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 13788 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 13789 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 13790 return false; 13791 // The loads must not depend on one another. 13792 if (LLD->isPredecessorOf(RLD) || 13793 RLD->isPredecessorOf(LLD)) 13794 return false; 13795 Addr = DAG.getSelect(SDLoc(TheSelect), 13796 LLD->getBasePtr().getValueType(), 13797 TheSelect->getOperand(0), LLD->getBasePtr(), 13798 RLD->getBasePtr()); 13799 } else { // Otherwise SELECT_CC 13800 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 13801 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 13802 13803 if ((LLD->hasAnyUseOfValue(1) && 13804 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 13805 (RLD->hasAnyUseOfValue(1) && 13806 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 13807 return false; 13808 13809 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 13810 LLD->getBasePtr().getValueType(), 13811 TheSelect->getOperand(0), 13812 TheSelect->getOperand(1), 13813 LLD->getBasePtr(), RLD->getBasePtr(), 13814 TheSelect->getOperand(4)); 13815 } 13816 13817 SDValue Load; 13818 // It is safe to replace the two loads if they have different alignments, 13819 // but the new load must be the minimum (most restrictive) alignment of the 13820 // inputs. 13821 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 13822 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 13823 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 13824 Load = DAG.getLoad(TheSelect->getValueType(0), 13825 SDLoc(TheSelect), 13826 // FIXME: Discards pointer and AA info. 13827 LLD->getChain(), Addr, MachinePointerInfo(), 13828 LLD->isVolatile(), LLD->isNonTemporal(), 13829 isInvariant, Alignment); 13830 } else { 13831 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 13832 RLD->getExtensionType() : LLD->getExtensionType(), 13833 SDLoc(TheSelect), 13834 TheSelect->getValueType(0), 13835 // FIXME: Discards pointer and AA info. 13836 LLD->getChain(), Addr, MachinePointerInfo(), 13837 LLD->getMemoryVT(), LLD->isVolatile(), 13838 LLD->isNonTemporal(), isInvariant, Alignment); 13839 } 13840 13841 // Users of the select now use the result of the load. 13842 CombineTo(TheSelect, Load); 13843 13844 // Users of the old loads now use the new load's chain. We know the 13845 // old-load value is dead now. 13846 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 13847 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 13848 return true; 13849 } 13850 13851 return false; 13852 } 13853 13854 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 13855 /// where 'cond' is the comparison specified by CC. 13856 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 13857 SDValue N2, SDValue N3, 13858 ISD::CondCode CC, bool NotExtCompare) { 13859 // (x ? y : y) -> y. 13860 if (N2 == N3) return N2; 13861 13862 EVT VT = N2.getValueType(); 13863 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 13864 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 13865 13866 // Determine if the condition we're dealing with is constant 13867 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 13868 N0, N1, CC, DL, false); 13869 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 13870 13871 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 13872 // fold select_cc true, x, y -> x 13873 // fold select_cc false, x, y -> y 13874 return !SCCC->isNullValue() ? N2 : N3; 13875 } 13876 13877 // Check to see if we can simplify the select into an fabs node 13878 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 13879 // Allow either -0.0 or 0.0 13880 if (CFP->isZero()) { 13881 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 13882 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 13883 N0 == N2 && N3.getOpcode() == ISD::FNEG && 13884 N2 == N3.getOperand(0)) 13885 return DAG.getNode(ISD::FABS, DL, VT, N0); 13886 13887 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 13888 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 13889 N0 == N3 && N2.getOpcode() == ISD::FNEG && 13890 N2.getOperand(0) == N3) 13891 return DAG.getNode(ISD::FABS, DL, VT, N3); 13892 } 13893 } 13894 13895 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 13896 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 13897 // in it. This is a win when the constant is not otherwise available because 13898 // it replaces two constant pool loads with one. We only do this if the FP 13899 // type is known to be legal, because if it isn't, then we are before legalize 13900 // types an we want the other legalization to happen first (e.g. to avoid 13901 // messing with soft float) and if the ConstantFP is not legal, because if 13902 // it is legal, we may not need to store the FP constant in a constant pool. 13903 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 13904 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 13905 if (TLI.isTypeLegal(N2.getValueType()) && 13906 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 13907 TargetLowering::Legal && 13908 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 13909 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 13910 // If both constants have multiple uses, then we won't need to do an 13911 // extra load, they are likely around in registers for other users. 13912 (TV->hasOneUse() || FV->hasOneUse())) { 13913 Constant *Elts[] = { 13914 const_cast<ConstantFP*>(FV->getConstantFPValue()), 13915 const_cast<ConstantFP*>(TV->getConstantFPValue()) 13916 }; 13917 Type *FPTy = Elts[0]->getType(); 13918 const DataLayout &TD = DAG.getDataLayout(); 13919 13920 // Create a ConstantArray of the two constants. 13921 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 13922 SDValue CPIdx = 13923 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 13924 TD.getPrefTypeAlignment(FPTy)); 13925 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 13926 13927 // Get the offsets to the 0 and 1 element of the array so that we can 13928 // select between them. 13929 SDValue Zero = DAG.getIntPtrConstant(0, DL); 13930 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 13931 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 13932 13933 SDValue Cond = DAG.getSetCC(DL, 13934 getSetCCResultType(N0.getValueType()), 13935 N0, N1, CC); 13936 AddToWorklist(Cond.getNode()); 13937 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 13938 Cond, One, Zero); 13939 AddToWorklist(CstOffset.getNode()); 13940 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 13941 CstOffset); 13942 AddToWorklist(CPIdx.getNode()); 13943 return DAG.getLoad( 13944 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 13945 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 13946 false, false, false, Alignment); 13947 } 13948 } 13949 13950 // Check to see if we can perform the "gzip trick", transforming 13951 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 13952 if (isNullConstant(N3) && CC == ISD::SETLT && 13953 (isNullConstant(N1) || // (a < 0) ? b : 0 13954 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 13955 EVT XType = N0.getValueType(); 13956 EVT AType = N2.getValueType(); 13957 if (XType.bitsGE(AType)) { 13958 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 13959 // single-bit constant. 13960 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 13961 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 13962 ShCtV = XType.getSizeInBits() - ShCtV - 1; 13963 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 13964 getShiftAmountTy(N0.getValueType())); 13965 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 13966 XType, N0, ShCt); 13967 AddToWorklist(Shift.getNode()); 13968 13969 if (XType.bitsGT(AType)) { 13970 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13971 AddToWorklist(Shift.getNode()); 13972 } 13973 13974 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13975 } 13976 13977 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 13978 XType, N0, 13979 DAG.getConstant(XType.getSizeInBits() - 1, 13980 SDLoc(N0), 13981 getShiftAmountTy(N0.getValueType()))); 13982 AddToWorklist(Shift.getNode()); 13983 13984 if (XType.bitsGT(AType)) { 13985 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13986 AddToWorklist(Shift.getNode()); 13987 } 13988 13989 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13990 } 13991 } 13992 13993 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 13994 // where y is has a single bit set. 13995 // A plaintext description would be, we can turn the SELECT_CC into an AND 13996 // when the condition can be materialized as an all-ones register. Any 13997 // single bit-test can be materialized as an all-ones register with 13998 // shift-left and shift-right-arith. 13999 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14000 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14001 SDValue AndLHS = N0->getOperand(0); 14002 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14003 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14004 // Shift the tested bit over the sign bit. 14005 APInt AndMask = ConstAndRHS->getAPIntValue(); 14006 SDValue ShlAmt = 14007 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14008 getShiftAmountTy(AndLHS.getValueType())); 14009 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14010 14011 // Now arithmetic right shift it all the way over, so the result is either 14012 // all-ones, or zero. 14013 SDValue ShrAmt = 14014 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14015 getShiftAmountTy(Shl.getValueType())); 14016 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14017 14018 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14019 } 14020 } 14021 14022 // fold select C, 16, 0 -> shl C, 4 14023 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14024 TLI.getBooleanContents(N0.getValueType()) == 14025 TargetLowering::ZeroOrOneBooleanContent) { 14026 14027 // If the caller doesn't want us to simplify this into a zext of a compare, 14028 // don't do it. 14029 if (NotExtCompare && N2C->isOne()) 14030 return SDValue(); 14031 14032 // Get a SetCC of the condition 14033 // NOTE: Don't create a SETCC if it's not legal on this target. 14034 if (!LegalOperations || 14035 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14036 SDValue Temp, SCC; 14037 // cast from setcc result type to select result type 14038 if (LegalTypes) { 14039 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14040 N0, N1, CC); 14041 if (N2.getValueType().bitsLT(SCC.getValueType())) 14042 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14043 N2.getValueType()); 14044 else 14045 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14046 N2.getValueType(), SCC); 14047 } else { 14048 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14049 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14050 N2.getValueType(), SCC); 14051 } 14052 14053 AddToWorklist(SCC.getNode()); 14054 AddToWorklist(Temp.getNode()); 14055 14056 if (N2C->isOne()) 14057 return Temp; 14058 14059 // shl setcc result by log2 n2c 14060 return DAG.getNode( 14061 ISD::SHL, DL, N2.getValueType(), Temp, 14062 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14063 getShiftAmountTy(Temp.getValueType()))); 14064 } 14065 } 14066 14067 // Check to see if this is an integer abs. 14068 // select_cc setg[te] X, 0, X, -X -> 14069 // select_cc setgt X, -1, X, -X -> 14070 // select_cc setl[te] X, 0, -X, X -> 14071 // select_cc setlt X, 1, -X, X -> 14072 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14073 if (N1C) { 14074 ConstantSDNode *SubC = nullptr; 14075 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14076 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14077 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14078 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14079 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14080 (N1C->isOne() && CC == ISD::SETLT)) && 14081 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14082 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14083 14084 EVT XType = N0.getValueType(); 14085 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14086 SDLoc DL(N0); 14087 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14088 N0, 14089 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14090 getShiftAmountTy(N0.getValueType()))); 14091 SDValue Add = DAG.getNode(ISD::ADD, DL, 14092 XType, N0, Shift); 14093 AddToWorklist(Shift.getNode()); 14094 AddToWorklist(Add.getNode()); 14095 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14096 } 14097 } 14098 14099 return SDValue(); 14100 } 14101 14102 /// This is a stub for TargetLowering::SimplifySetCC. 14103 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 14104 SDValue N1, ISD::CondCode Cond, 14105 SDLoc DL, bool foldBooleans) { 14106 TargetLowering::DAGCombinerInfo 14107 DagCombineInfo(DAG, Level, false, this); 14108 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14109 } 14110 14111 /// Given an ISD::SDIV node expressing a divide by constant, return 14112 /// a DAG expression to select that will generate the same value by multiplying 14113 /// by a magic number. 14114 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14115 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14116 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14117 if (!C) 14118 return SDValue(); 14119 14120 // Avoid division by zero. 14121 if (C->isNullValue()) 14122 return SDValue(); 14123 14124 std::vector<SDNode*> Built; 14125 SDValue S = 14126 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14127 14128 for (SDNode *N : Built) 14129 AddToWorklist(N); 14130 return S; 14131 } 14132 14133 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14134 /// DAG expression that will generate the same value by right shifting. 14135 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14136 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14137 if (!C) 14138 return SDValue(); 14139 14140 // Avoid division by zero. 14141 if (C->isNullValue()) 14142 return SDValue(); 14143 14144 std::vector<SDNode *> Built; 14145 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14146 14147 for (SDNode *N : Built) 14148 AddToWorklist(N); 14149 return S; 14150 } 14151 14152 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14153 /// expression that will generate the same value by multiplying by a magic 14154 /// number. 14155 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14156 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14157 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14158 if (!C) 14159 return SDValue(); 14160 14161 // Avoid division by zero. 14162 if (C->isNullValue()) 14163 return SDValue(); 14164 14165 std::vector<SDNode*> Built; 14166 SDValue S = 14167 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14168 14169 for (SDNode *N : Built) 14170 AddToWorklist(N); 14171 return S; 14172 } 14173 14174 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14175 if (Level >= AfterLegalizeDAG) 14176 return SDValue(); 14177 14178 // Expose the DAG combiner to the target combiner implementations. 14179 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14180 14181 unsigned Iterations = 0; 14182 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14183 if (Iterations) { 14184 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14185 // For the reciprocal, we need to find the zero of the function: 14186 // F(X) = A X - 1 [which has a zero at X = 1/A] 14187 // => 14188 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14189 // does not require additional intermediate precision] 14190 EVT VT = Op.getValueType(); 14191 SDLoc DL(Op); 14192 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14193 14194 AddToWorklist(Est.getNode()); 14195 14196 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14197 for (unsigned i = 0; i < Iterations; ++i) { 14198 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14199 AddToWorklist(NewEst.getNode()); 14200 14201 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14202 AddToWorklist(NewEst.getNode()); 14203 14204 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14205 AddToWorklist(NewEst.getNode()); 14206 14207 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14208 AddToWorklist(Est.getNode()); 14209 } 14210 } 14211 return Est; 14212 } 14213 14214 return SDValue(); 14215 } 14216 14217 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14218 /// For the reciprocal sqrt, we need to find the zero of the function: 14219 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14220 /// => 14221 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14222 /// As a result, we precompute A/2 prior to the iteration loop. 14223 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 14224 unsigned Iterations, 14225 SDNodeFlags *Flags) { 14226 EVT VT = Arg.getValueType(); 14227 SDLoc DL(Arg); 14228 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14229 14230 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14231 // this entire sequence requires only one FP constant. 14232 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14233 AddToWorklist(HalfArg.getNode()); 14234 14235 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14236 AddToWorklist(HalfArg.getNode()); 14237 14238 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14239 for (unsigned i = 0; i < Iterations; ++i) { 14240 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14241 AddToWorklist(NewEst.getNode()); 14242 14243 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14244 AddToWorklist(NewEst.getNode()); 14245 14246 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14247 AddToWorklist(NewEst.getNode()); 14248 14249 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14250 AddToWorklist(Est.getNode()); 14251 } 14252 return Est; 14253 } 14254 14255 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14256 /// For the reciprocal sqrt, we need to find the zero of the function: 14257 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14258 /// => 14259 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14260 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 14261 unsigned Iterations, 14262 SDNodeFlags *Flags) { 14263 EVT VT = Arg.getValueType(); 14264 SDLoc DL(Arg); 14265 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14266 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14267 14268 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 14269 for (unsigned i = 0; i < Iterations; ++i) { 14270 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14271 AddToWorklist(HalfEst.getNode()); 14272 14273 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14274 AddToWorklist(Est.getNode()); 14275 14276 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14277 AddToWorklist(Est.getNode()); 14278 14279 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags); 14280 AddToWorklist(Est.getNode()); 14281 14282 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags); 14283 AddToWorklist(Est.getNode()); 14284 } 14285 return Est; 14286 } 14287 14288 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14289 if (Level >= AfterLegalizeDAG) 14290 return SDValue(); 14291 14292 // Expose the DAG combiner to the target combiner implementations. 14293 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14294 unsigned Iterations = 0; 14295 bool UseOneConstNR = false; 14296 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14297 AddToWorklist(Est.getNode()); 14298 if (Iterations) { 14299 Est = UseOneConstNR ? 14300 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) : 14301 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags); 14302 } 14303 return Est; 14304 } 14305 14306 return SDValue(); 14307 } 14308 14309 /// Return true if base is a frame index, which is known not to alias with 14310 /// anything but itself. Provides base object and offset as results. 14311 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14312 const GlobalValue *&GV, const void *&CV) { 14313 // Assume it is a primitive operation. 14314 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14315 14316 // If it's an adding a simple constant then integrate the offset. 14317 if (Base.getOpcode() == ISD::ADD) { 14318 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14319 Base = Base.getOperand(0); 14320 Offset += C->getZExtValue(); 14321 } 14322 } 14323 14324 // Return the underlying GlobalValue, and update the Offset. Return false 14325 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14326 // by multiple nodes with different offsets. 14327 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14328 GV = G->getGlobal(); 14329 Offset += G->getOffset(); 14330 return false; 14331 } 14332 14333 // Return the underlying Constant value, and update the Offset. Return false 14334 // for ConstantSDNodes since the same constant pool entry may be represented 14335 // by multiple nodes with different offsets. 14336 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14337 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14338 : (const void *)C->getConstVal(); 14339 Offset += C->getOffset(); 14340 return false; 14341 } 14342 // If it's any of the following then it can't alias with anything but itself. 14343 return isa<FrameIndexSDNode>(Base); 14344 } 14345 14346 /// Return true if there is any possibility that the two addresses overlap. 14347 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14348 // If they are the same then they must be aliases. 14349 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14350 14351 // If they are both volatile then they cannot be reordered. 14352 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14353 14354 // If one operation reads from invariant memory, and the other may store, they 14355 // cannot alias. These should really be checking the equivalent of mayWrite, 14356 // but it only matters for memory nodes other than load /store. 14357 if (Op0->isInvariant() && Op1->writeMem()) 14358 return false; 14359 14360 if (Op1->isInvariant() && Op0->writeMem()) 14361 return false; 14362 14363 // Gather base node and offset information. 14364 SDValue Base1, Base2; 14365 int64_t Offset1, Offset2; 14366 const GlobalValue *GV1, *GV2; 14367 const void *CV1, *CV2; 14368 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14369 Base1, Offset1, GV1, CV1); 14370 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14371 Base2, Offset2, GV2, CV2); 14372 14373 // If they have a same base address then check to see if they overlap. 14374 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14375 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14376 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14377 14378 // It is possible for different frame indices to alias each other, mostly 14379 // when tail call optimization reuses return address slots for arguments. 14380 // To catch this case, look up the actual index of frame indices to compute 14381 // the real alias relationship. 14382 if (isFrameIndex1 && isFrameIndex2) { 14383 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 14384 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14385 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14386 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14387 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14388 } 14389 14390 // Otherwise, if we know what the bases are, and they aren't identical, then 14391 // we know they cannot alias. 14392 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14393 return false; 14394 14395 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14396 // compared to the size and offset of the access, we may be able to prove they 14397 // do not alias. This check is conservative for now to catch cases created by 14398 // splitting vector types. 14399 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14400 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14401 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14402 Op1->getMemoryVT().getSizeInBits() >> 3) && 14403 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 14404 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14405 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14406 14407 // There is no overlap between these relatively aligned accesses of similar 14408 // size, return no alias. 14409 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14410 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14411 return false; 14412 } 14413 14414 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14415 ? CombinerGlobalAA 14416 : DAG.getSubtarget().useAA(); 14417 #ifndef NDEBUG 14418 if (CombinerAAOnlyFunc.getNumOccurrences() && 14419 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14420 UseAA = false; 14421 #endif 14422 if (UseAA && 14423 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14424 // Use alias analysis information. 14425 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14426 Op1->getSrcValueOffset()); 14427 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14428 Op0->getSrcValueOffset() - MinOffset; 14429 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14430 Op1->getSrcValueOffset() - MinOffset; 14431 AliasResult AAResult = 14432 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14433 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14434 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14435 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14436 if (AAResult == NoAlias) 14437 return false; 14438 } 14439 14440 // Otherwise we have to assume they alias. 14441 return true; 14442 } 14443 14444 /// Walk up chain skipping non-aliasing memory nodes, 14445 /// looking for aliasing nodes and adding them to the Aliases vector. 14446 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14447 SmallVectorImpl<SDValue> &Aliases) { 14448 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14449 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14450 14451 // Get alias information for node. 14452 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14453 14454 // Starting off. 14455 Chains.push_back(OriginalChain); 14456 unsigned Depth = 0; 14457 14458 // Look at each chain and determine if it is an alias. If so, add it to the 14459 // aliases list. If not, then continue up the chain looking for the next 14460 // candidate. 14461 while (!Chains.empty()) { 14462 SDValue Chain = Chains.pop_back_val(); 14463 14464 // For TokenFactor nodes, look at each operand and only continue up the 14465 // chain until we reach the depth limit. 14466 // 14467 // FIXME: The depth check could be made to return the last non-aliasing 14468 // chain we found before we hit a tokenfactor rather than the original 14469 // chain. 14470 if (Depth > 6) { 14471 Aliases.clear(); 14472 Aliases.push_back(OriginalChain); 14473 return; 14474 } 14475 14476 // Don't bother if we've been before. 14477 if (!Visited.insert(Chain.getNode()).second) 14478 continue; 14479 14480 switch (Chain.getOpcode()) { 14481 case ISD::EntryToken: 14482 // Entry token is ideal chain operand, but handled in FindBetterChain. 14483 break; 14484 14485 case ISD::LOAD: 14486 case ISD::STORE: { 14487 // Get alias information for Chain. 14488 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14489 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14490 14491 // If chain is alias then stop here. 14492 if (!(IsLoad && IsOpLoad) && 14493 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14494 Aliases.push_back(Chain); 14495 } else { 14496 // Look further up the chain. 14497 Chains.push_back(Chain.getOperand(0)); 14498 ++Depth; 14499 } 14500 break; 14501 } 14502 14503 case ISD::TokenFactor: 14504 // We have to check each of the operands of the token factor for "small" 14505 // token factors, so we queue them up. Adding the operands to the queue 14506 // (stack) in reverse order maintains the original order and increases the 14507 // likelihood that getNode will find a matching token factor (CSE.) 14508 if (Chain.getNumOperands() > 16) { 14509 Aliases.push_back(Chain); 14510 break; 14511 } 14512 for (unsigned n = Chain.getNumOperands(); n;) 14513 Chains.push_back(Chain.getOperand(--n)); 14514 ++Depth; 14515 break; 14516 14517 default: 14518 // For all other instructions we will just have to take what we can get. 14519 Aliases.push_back(Chain); 14520 break; 14521 } 14522 } 14523 14524 // We need to be careful here to also search for aliases through the 14525 // value operand of a store, etc. Consider the following situation: 14526 // Token1 = ... 14527 // L1 = load Token1, %52 14528 // S1 = store Token1, L1, %51 14529 // L2 = load Token1, %52+8 14530 // S2 = store Token1, L2, %51+8 14531 // Token2 = Token(S1, S2) 14532 // L3 = load Token2, %53 14533 // S3 = store Token2, L3, %52 14534 // L4 = load Token2, %53+8 14535 // S4 = store Token2, L4, %52+8 14536 // If we search for aliases of S3 (which loads address %52), and we look 14537 // only through the chain, then we'll miss the trivial dependence on L1 14538 // (which also loads from %52). We then might change all loads and 14539 // stores to use Token1 as their chain operand, which could result in 14540 // copying %53 into %52 before copying %52 into %51 (which should 14541 // happen first). 14542 // 14543 // The problem is, however, that searching for such data dependencies 14544 // can become expensive, and the cost is not directly related to the 14545 // chain depth. Instead, we'll rule out such configurations here by 14546 // insisting that we've visited all chain users (except for users 14547 // of the original chain, which is not necessary). When doing this, 14548 // we need to look through nodes we don't care about (otherwise, things 14549 // like register copies will interfere with trivial cases). 14550 14551 SmallVector<const SDNode *, 16> Worklist; 14552 for (const SDNode *N : Visited) 14553 if (N != OriginalChain.getNode()) 14554 Worklist.push_back(N); 14555 14556 while (!Worklist.empty()) { 14557 const SDNode *M = Worklist.pop_back_val(); 14558 14559 // We have already visited M, and want to make sure we've visited any uses 14560 // of M that we care about. For uses that we've not visisted, and don't 14561 // care about, queue them to the worklist. 14562 14563 for (SDNode::use_iterator UI = M->use_begin(), 14564 UIE = M->use_end(); UI != UIE; ++UI) 14565 if (UI.getUse().getValueType() == MVT::Other && 14566 Visited.insert(*UI).second) { 14567 if (isa<MemSDNode>(*UI)) { 14568 // We've not visited this use, and we care about it (it could have an 14569 // ordering dependency with the original node). 14570 Aliases.clear(); 14571 Aliases.push_back(OriginalChain); 14572 return; 14573 } 14574 14575 // We've not visited this use, but we don't care about it. Mark it as 14576 // visited and enqueue it to the worklist. 14577 Worklist.push_back(*UI); 14578 } 14579 } 14580 } 14581 14582 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14583 /// (aliasing node.) 14584 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14585 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14586 14587 // Accumulate all the aliases to this node. 14588 GatherAllAliases(N, OldChain, Aliases); 14589 14590 // If no operands then chain to entry token. 14591 if (Aliases.size() == 0) 14592 return DAG.getEntryNode(); 14593 14594 // If a single operand then chain to it. We don't need to revisit it. 14595 if (Aliases.size() == 1) 14596 return Aliases[0]; 14597 14598 // Construct a custom tailored token factor. 14599 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14600 } 14601 14602 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) { 14603 // This holds the base pointer, index, and the offset in bytes from the base 14604 // pointer. 14605 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 14606 14607 // We must have a base and an offset. 14608 if (!BasePtr.Base.getNode()) 14609 return false; 14610 14611 // Do not handle stores to undef base pointers. 14612 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 14613 return false; 14614 14615 SmallVector<StoreSDNode *, 8> ChainedStores; 14616 ChainedStores.push_back(St); 14617 14618 // Walk up the chain and look for nodes with offsets from the same 14619 // base pointer. Stop when reaching an instruction with a different kind 14620 // or instruction which has a different base pointer. 14621 StoreSDNode *Index = St; 14622 while (Index) { 14623 // If the chain has more than one use, then we can't reorder the mem ops. 14624 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14625 break; 14626 14627 if (Index->isVolatile() || Index->isIndexed()) 14628 break; 14629 14630 // Find the base pointer and offset for this memory node. 14631 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 14632 14633 // Check that the base pointer is the same as the original one. 14634 if (!Ptr.equalBaseIndex(BasePtr)) 14635 break; 14636 14637 // Find the next memory operand in the chain. If the next operand in the 14638 // chain is a store then move up and continue the scan with the next 14639 // memory operand. If the next operand is a load save it and use alias 14640 // information to check if it interferes with anything. 14641 SDNode *NextInChain = Index->getChain().getNode(); 14642 while (true) { 14643 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14644 // We found a store node. Use it for the next iteration. 14645 ChainedStores.push_back(STn); 14646 Index = STn; 14647 break; 14648 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14649 NextInChain = Ldn->getChain().getNode(); 14650 continue; 14651 } else { 14652 Index = nullptr; 14653 break; 14654 } 14655 } 14656 } 14657 14658 bool MadeChange = false; 14659 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 14660 14661 for (StoreSDNode *ChainedStore : ChainedStores) { 14662 SDValue Chain = ChainedStore->getChain(); 14663 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 14664 14665 if (Chain != BetterChain) { 14666 MadeChange = true; 14667 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 14668 } 14669 } 14670 14671 // Do all replacements after finding the replacements to make to avoid making 14672 // the chains more complicated by introducing new TokenFactors. 14673 for (auto Replacement : BetterChains) 14674 replaceStoreChain(Replacement.first, Replacement.second); 14675 14676 return MadeChange; 14677 } 14678 14679 /// This is the entry point for the file. 14680 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 14681 CodeGenOpt::Level OptLevel) { 14682 /// This is the main entry point to this class. 14683 DAGCombiner(*this, AA, OptLevel).Run(Level); 14684 } 14685