1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/SelectionDAG.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DerivedTypes.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/LLVMContext.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/MathExtras.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Target/TargetLowering.h" 38 #include "llvm/Target/TargetOptions.h" 39 #include "llvm/Target/TargetRegisterInfo.h" 40 #include "llvm/Target/TargetSubtargetInfo.h" 41 #include <algorithm> 42 using namespace llvm; 43 44 #define DEBUG_TYPE "dagcombine" 45 46 STATISTIC(NodesCombined , "Number of dag nodes combined"); 47 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 48 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 49 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 50 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 51 STATISTIC(SlicedLoads, "Number of load sliced"); 52 53 namespace { 54 static cl::opt<bool> 55 CombinerAA("combiner-alias-analysis", cl::Hidden, 56 cl::desc("Enable DAG combiner alias-analysis heuristics")); 57 58 static cl::opt<bool> 59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 60 cl::desc("Enable DAG combiner's use of IR alias analysis")); 61 62 static cl::opt<bool> 63 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 64 cl::desc("Enable DAG combiner's use of TBAA")); 65 66 #ifndef NDEBUG 67 static cl::opt<std::string> 68 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 69 cl::desc("Only use DAG-combiner alias analysis in this" 70 " function")); 71 #endif 72 73 /// Hidden option to stress test load slicing, i.e., when this option 74 /// is enabled, load slicing bypasses most of its profitability guards. 75 static cl::opt<bool> 76 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 77 cl::desc("Bypass the profitability model of load " 78 "slicing"), 79 cl::init(false)); 80 81 static cl::opt<bool> 82 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 83 cl::desc("DAG combiner may split indexing from loads")); 84 85 //------------------------------ DAGCombiner ---------------------------------// 86 87 class DAGCombiner { 88 SelectionDAG &DAG; 89 const TargetLowering &TLI; 90 CombineLevel Level; 91 CodeGenOpt::Level OptLevel; 92 bool LegalOperations; 93 bool LegalTypes; 94 bool ForCodeSize; 95 96 /// \brief Worklist of all of the nodes that need to be simplified. 97 /// 98 /// This must behave as a stack -- new nodes to process are pushed onto the 99 /// back and when processing we pop off of the back. 100 /// 101 /// The worklist will not contain duplicates but may contain null entries 102 /// due to nodes being deleted from the underlying DAG. 103 SmallVector<SDNode *, 64> Worklist; 104 105 /// \brief Mapping from an SDNode to its position on the worklist. 106 /// 107 /// This is used to find and remove nodes from the worklist (by nulling 108 /// them) when they are deleted from the underlying DAG. It relies on 109 /// stable indices of nodes within the worklist. 110 DenseMap<SDNode *, unsigned> WorklistMap; 111 112 /// \brief Set of nodes which have been combined (at least once). 113 /// 114 /// This is used to allow us to reliably add any operands of a DAG node 115 /// which have not yet been combined to the worklist. 116 SmallPtrSet<SDNode *, 32> CombinedNodes; 117 118 // AA - Used for DAG load/store alias analysis. 119 AliasAnalysis &AA; 120 121 /// When an instruction is simplified, add all users of the instruction to 122 /// the work lists because they might get more simplified now. 123 void AddUsersToWorklist(SDNode *N) { 124 for (SDNode *Node : N->uses()) 125 AddToWorklist(Node); 126 } 127 128 /// Call the node-specific routine that folds each particular type of node. 129 SDValue visit(SDNode *N); 130 131 public: 132 /// Add to the worklist making sure its instance is at the back (next to be 133 /// processed.) 134 void AddToWorklist(SDNode *N) { 135 // Skip handle nodes as they can't usefully be combined and confuse the 136 // zero-use deletion strategy. 137 if (N->getOpcode() == ISD::HANDLENODE) 138 return; 139 140 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 141 Worklist.push_back(N); 142 } 143 144 /// Remove all instances of N from the worklist. 145 void removeFromWorklist(SDNode *N) { 146 CombinedNodes.erase(N); 147 148 auto It = WorklistMap.find(N); 149 if (It == WorklistMap.end()) 150 return; // Not in the worklist. 151 152 // Null out the entry rather than erasing it to avoid a linear operation. 153 Worklist[It->second] = nullptr; 154 WorklistMap.erase(It); 155 } 156 157 void deleteAndRecombine(SDNode *N); 158 bool recursivelyDeleteUnusedNodes(SDNode *N); 159 160 /// Replaces all uses of the results of one DAG node with new values. 161 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 162 bool AddTo = true); 163 164 /// Replaces all uses of the results of one DAG node with new values. 165 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 166 return CombineTo(N, &Res, 1, AddTo); 167 } 168 169 /// Replaces all uses of the results of one DAG node with new values. 170 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 171 bool AddTo = true) { 172 SDValue To[] = { Res0, Res1 }; 173 return CombineTo(N, To, 2, AddTo); 174 } 175 176 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 177 178 private: 179 180 /// Check the specified integer node value to see if it can be simplified or 181 /// if things it uses can be simplified by bit propagation. 182 /// If so, return true. 183 bool SimplifyDemandedBits(SDValue Op) { 184 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 185 APInt Demanded = APInt::getAllOnesValue(BitWidth); 186 return SimplifyDemandedBits(Op, Demanded); 187 } 188 189 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 190 191 bool CombineToPreIndexedLoadStore(SDNode *N); 192 bool CombineToPostIndexedLoadStore(SDNode *N); 193 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 194 bool SliceUpLoad(SDNode *N); 195 196 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 197 /// load. 198 /// 199 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 200 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 201 /// \param EltNo index of the vector element to load. 202 /// \param OriginalLoad load that EVE came from to be replaced. 203 /// \returns EVE on success SDValue() on failure. 204 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 205 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 206 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 207 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 208 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 209 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 210 SDValue PromoteIntBinOp(SDValue Op); 211 SDValue PromoteIntShiftOp(SDValue Op); 212 SDValue PromoteExtend(SDValue Op); 213 bool PromoteLoad(SDValue Op); 214 215 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc, 216 SDValue ExtLoad, const SDLoc &DL, 217 ISD::NodeType ExtType); 218 219 /// Call the node-specific routine that knows how to fold each 220 /// particular type of node. If that doesn't do anything, try the 221 /// target-specific DAG combines. 222 SDValue combine(SDNode *N); 223 224 // Visitation implementation - Implement dag node combining for different 225 // node types. The semantics are as follows: 226 // Return Value: 227 // SDValue.getNode() == 0 - No change was made 228 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 229 // otherwise - N should be replaced by the returned Operand. 230 // 231 SDValue visitTokenFactor(SDNode *N); 232 SDValue visitMERGE_VALUES(SDNode *N); 233 SDValue visitADD(SDNode *N); 234 SDValue visitSUB(SDNode *N); 235 SDValue visitADDC(SDNode *N); 236 SDValue visitSUBC(SDNode *N); 237 SDValue visitADDE(SDNode *N); 238 SDValue visitSUBE(SDNode *N); 239 SDValue visitMUL(SDNode *N); 240 SDValue useDivRem(SDNode *N); 241 SDValue visitSDIV(SDNode *N); 242 SDValue visitUDIV(SDNode *N); 243 SDValue visitREM(SDNode *N); 244 SDValue visitMULHU(SDNode *N); 245 SDValue visitMULHS(SDNode *N); 246 SDValue visitSMUL_LOHI(SDNode *N); 247 SDValue visitUMUL_LOHI(SDNode *N); 248 SDValue visitSMULO(SDNode *N); 249 SDValue visitUMULO(SDNode *N); 250 SDValue visitIMINMAX(SDNode *N); 251 SDValue visitAND(SDNode *N); 252 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 253 SDValue visitOR(SDNode *N); 254 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 255 SDValue visitXOR(SDNode *N); 256 SDValue SimplifyVBinOp(SDNode *N); 257 SDValue visitSHL(SDNode *N); 258 SDValue visitSRA(SDNode *N); 259 SDValue visitSRL(SDNode *N); 260 SDValue visitRotate(SDNode *N); 261 SDValue visitBSWAP(SDNode *N); 262 SDValue visitBITREVERSE(SDNode *N); 263 SDValue visitCTLZ(SDNode *N); 264 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 265 SDValue visitCTTZ(SDNode *N); 266 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 267 SDValue visitCTPOP(SDNode *N); 268 SDValue visitSELECT(SDNode *N); 269 SDValue visitVSELECT(SDNode *N); 270 SDValue visitSELECT_CC(SDNode *N); 271 SDValue visitSETCC(SDNode *N); 272 SDValue visitSETCCE(SDNode *N); 273 SDValue visitSIGN_EXTEND(SDNode *N); 274 SDValue visitZERO_EXTEND(SDNode *N); 275 SDValue visitANY_EXTEND(SDNode *N); 276 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 277 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 278 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 279 SDValue visitTRUNCATE(SDNode *N); 280 SDValue visitBITCAST(SDNode *N); 281 SDValue visitBUILD_PAIR(SDNode *N); 282 SDValue visitFADD(SDNode *N); 283 SDValue visitFSUB(SDNode *N); 284 SDValue visitFMUL(SDNode *N); 285 SDValue visitFMA(SDNode *N); 286 SDValue visitFDIV(SDNode *N); 287 SDValue visitFREM(SDNode *N); 288 SDValue visitFSQRT(SDNode *N); 289 SDValue visitFCOPYSIGN(SDNode *N); 290 SDValue visitSINT_TO_FP(SDNode *N); 291 SDValue visitUINT_TO_FP(SDNode *N); 292 SDValue visitFP_TO_SINT(SDNode *N); 293 SDValue visitFP_TO_UINT(SDNode *N); 294 SDValue visitFP_ROUND(SDNode *N); 295 SDValue visitFP_ROUND_INREG(SDNode *N); 296 SDValue visitFP_EXTEND(SDNode *N); 297 SDValue visitFNEG(SDNode *N); 298 SDValue visitFABS(SDNode *N); 299 SDValue visitFCEIL(SDNode *N); 300 SDValue visitFTRUNC(SDNode *N); 301 SDValue visitFFLOOR(SDNode *N); 302 SDValue visitFMINNUM(SDNode *N); 303 SDValue visitFMAXNUM(SDNode *N); 304 SDValue visitBRCOND(SDNode *N); 305 SDValue visitBR_CC(SDNode *N); 306 SDValue visitLOAD(SDNode *N); 307 308 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 309 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 310 311 SDValue visitSTORE(SDNode *N); 312 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 313 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 314 SDValue visitBUILD_VECTOR(SDNode *N); 315 SDValue visitCONCAT_VECTORS(SDNode *N); 316 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 317 SDValue visitVECTOR_SHUFFLE(SDNode *N); 318 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 319 SDValue visitINSERT_SUBVECTOR(SDNode *N); 320 SDValue visitMLOAD(SDNode *N); 321 SDValue visitMSTORE(SDNode *N); 322 SDValue visitMGATHER(SDNode *N); 323 SDValue visitMSCATTER(SDNode *N); 324 SDValue visitFP_TO_FP16(SDNode *N); 325 SDValue visitFP16_TO_FP(SDNode *N); 326 327 SDValue visitFADDForFMACombine(SDNode *N); 328 SDValue visitFSUBForFMACombine(SDNode *N); 329 SDValue visitFMULForFMACombine(SDNode *N); 330 331 SDValue XformToShuffleWithZero(SDNode *N); 332 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS, 333 SDValue RHS); 334 335 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 336 337 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 338 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 339 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 340 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 341 SDValue N2, SDValue N3, ISD::CondCode CC, 342 bool NotExtCompare = false); 343 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 344 const SDLoc &DL, bool foldBooleans = true); 345 346 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 347 SDValue &CC) const; 348 bool isOneUseSetCC(SDValue N) const; 349 350 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 351 unsigned HiOp); 352 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 353 SDValue CombineExtLoad(SDNode *N); 354 SDValue combineRepeatedFPDivisors(SDNode *N); 355 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 356 SDValue BuildSDIV(SDNode *N); 357 SDValue BuildSDIVPow2(SDNode *N); 358 SDValue BuildUDIV(SDNode *N); 359 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 360 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 361 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags); 362 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip); 363 SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 364 SDNodeFlags *Flags, bool Reciprocal); 365 SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 366 SDNodeFlags *Flags, bool Reciprocal); 367 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 368 bool DemandHighBits = true); 369 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 370 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 371 SDValue InnerPos, SDValue InnerNeg, 372 unsigned PosOpcode, unsigned NegOpcode, 373 const SDLoc &DL); 374 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 375 SDValue ReduceLoadWidth(SDNode *N); 376 SDValue ReduceLoadOpStoreWidth(SDNode *N); 377 SDValue TransformFPLoadStorePair(SDNode *N); 378 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 379 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 380 381 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 382 383 /// Walk up chain skipping non-aliasing memory nodes, 384 /// looking for aliasing nodes and adding them to the Aliases vector. 385 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 386 SmallVectorImpl<SDValue> &Aliases); 387 388 /// Return true if there is any possibility that the two addresses overlap. 389 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 390 391 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 392 /// chain (aliasing node.) 393 SDValue FindBetterChain(SDNode *N, SDValue Chain); 394 395 /// Try to replace a store and any possibly adjacent stores on 396 /// consecutive chains with better chains. Return true only if St is 397 /// replaced. 398 /// 399 /// Notice that other chains may still be replaced even if the function 400 /// returns false. 401 bool findBetterNeighborChains(StoreSDNode *St); 402 403 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 404 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 405 406 /// Holds a pointer to an LSBaseSDNode as well as information on where it 407 /// is located in a sequence of memory operations connected by a chain. 408 struct MemOpLink { 409 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 410 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 411 // Ptr to the mem node. 412 LSBaseSDNode *MemNode; 413 // Offset from the base ptr. 414 int64_t OffsetFromBase; 415 // What is the sequence number of this mem node. 416 // Lowest mem operand in the DAG starts at zero. 417 unsigned SequenceNum; 418 }; 419 420 /// This is a helper function for visitMUL to check the profitability 421 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 422 /// MulNode is the original multiply, AddNode is (add x, c1), 423 /// and ConstNode is c2. 424 bool isMulAddWithConstProfitable(SDNode *MulNode, 425 SDValue &AddNode, 426 SDValue &ConstNode); 427 428 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 429 /// constant build_vector of the stored constant values in Stores. 430 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, const SDLoc &SL, 431 ArrayRef<MemOpLink> Stores, 432 SmallVectorImpl<SDValue> &Chains, 433 EVT Ty) const; 434 435 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 436 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 437 /// the type of the loaded value to be extended. LoadedVT returns the type 438 /// of the original loaded value. NarrowLoad returns whether the load would 439 /// need to be narrowed in order to match. 440 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 441 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 442 bool &NarrowLoad); 443 444 /// This is a helper function for MergeConsecutiveStores. When the source 445 /// elements of the consecutive stores are all constants or all extracted 446 /// vector elements, try to merge them into one larger store. 447 /// \return True if a merged store was created. 448 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 449 EVT MemVT, unsigned NumStores, 450 bool IsConstantSrc, bool UseVector); 451 452 /// This is a helper function for MergeConsecutiveStores. 453 /// Stores that may be merged are placed in StoreNodes. 454 /// Loads that may alias with those stores are placed in AliasLoadNodes. 455 void getStoreMergeAndAliasCandidates( 456 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 457 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 458 459 /// Helper function for MergeConsecutiveStores. Checks if 460 /// Candidate stores have indirect dependency through their 461 /// operands. \return True if safe to merge 462 bool checkMergeStoreCandidatesForDependencies( 463 SmallVectorImpl<MemOpLink> &StoreNodes); 464 465 /// Merge consecutive store operations into a wide store. 466 /// This optimization uses wide integers or vectors when possible. 467 /// \return True if some memory operations were changed. 468 bool MergeConsecutiveStores(StoreSDNode *N); 469 470 /// \brief Try to transform a truncation where C is a constant: 471 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 472 /// 473 /// \p N needs to be a truncation and its first operand an AND. Other 474 /// requirements are checked by the function (e.g. that trunc is 475 /// single-use) and if missed an empty SDValue is returned. 476 SDValue distributeTruncateThroughAnd(SDNode *N); 477 478 public: 479 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 480 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 481 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 482 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 483 } 484 485 /// Runs the dag combiner on all nodes in the work list 486 void Run(CombineLevel AtLevel); 487 488 SelectionDAG &getDAG() const { return DAG; } 489 490 /// Returns a type large enough to hold any valid shift amount - before type 491 /// legalization these can be huge. 492 EVT getShiftAmountTy(EVT LHSTy) { 493 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 494 if (LHSTy.isVector()) 495 return LHSTy; 496 auto &DL = DAG.getDataLayout(); 497 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 498 : TLI.getPointerTy(DL); 499 } 500 501 /// This method returns true if we are running before type legalization or 502 /// if the specified VT is legal. 503 bool isTypeLegal(const EVT &VT) { 504 if (!LegalTypes) return true; 505 return TLI.isTypeLegal(VT); 506 } 507 508 /// Convenience wrapper around TargetLowering::getSetCCResultType 509 EVT getSetCCResultType(EVT VT) const { 510 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 511 } 512 }; 513 } 514 515 516 namespace { 517 /// This class is a DAGUpdateListener that removes any deleted 518 /// nodes from the worklist. 519 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 520 DAGCombiner &DC; 521 public: 522 explicit WorklistRemover(DAGCombiner &dc) 523 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 524 525 void NodeDeleted(SDNode *N, SDNode *E) override { 526 DC.removeFromWorklist(N); 527 } 528 }; 529 } 530 531 //===----------------------------------------------------------------------===// 532 // TargetLowering::DAGCombinerInfo implementation 533 //===----------------------------------------------------------------------===// 534 535 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 536 ((DAGCombiner*)DC)->AddToWorklist(N); 537 } 538 539 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 540 ((DAGCombiner*)DC)->removeFromWorklist(N); 541 } 542 543 SDValue TargetLowering::DAGCombinerInfo:: 544 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 545 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 546 } 547 548 SDValue TargetLowering::DAGCombinerInfo:: 549 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 550 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 551 } 552 553 554 SDValue TargetLowering::DAGCombinerInfo:: 555 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 556 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 557 } 558 559 void TargetLowering::DAGCombinerInfo:: 560 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 561 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 562 } 563 564 //===----------------------------------------------------------------------===// 565 // Helper Functions 566 //===----------------------------------------------------------------------===// 567 568 void DAGCombiner::deleteAndRecombine(SDNode *N) { 569 removeFromWorklist(N); 570 571 // If the operands of this node are only used by the node, they will now be 572 // dead. Make sure to re-visit them and recursively delete dead nodes. 573 for (const SDValue &Op : N->ops()) 574 // For an operand generating multiple values, one of the values may 575 // become dead allowing further simplification (e.g. split index 576 // arithmetic from an indexed load). 577 if (Op->hasOneUse() || Op->getNumValues() > 1) 578 AddToWorklist(Op.getNode()); 579 580 DAG.DeleteNode(N); 581 } 582 583 /// Return 1 if we can compute the negated form of the specified expression for 584 /// the same cost as the expression itself, or 2 if we can compute the negated 585 /// form more cheaply than the expression itself. 586 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 587 const TargetLowering &TLI, 588 const TargetOptions *Options, 589 unsigned Depth = 0) { 590 // fneg is removable even if it has multiple uses. 591 if (Op.getOpcode() == ISD::FNEG) return 2; 592 593 // Don't allow anything with multiple uses. 594 if (!Op.hasOneUse()) return 0; 595 596 // Don't recurse exponentially. 597 if (Depth > 6) return 0; 598 599 switch (Op.getOpcode()) { 600 default: return false; 601 case ISD::ConstantFP: 602 // Don't invert constant FP values after legalize. The negated constant 603 // isn't necessarily legal. 604 return LegalOperations ? 0 : 1; 605 case ISD::FADD: 606 // FIXME: determine better conditions for this xform. 607 if (!Options->UnsafeFPMath) return 0; 608 609 // After operation legalization, it might not be legal to create new FSUBs. 610 if (LegalOperations && 611 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 612 return 0; 613 614 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 615 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 616 Options, Depth + 1)) 617 return V; 618 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 619 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 620 Depth + 1); 621 case ISD::FSUB: 622 // We can't turn -(A-B) into B-A when we honor signed zeros. 623 if (!Options->UnsafeFPMath) return 0; 624 625 // fold (fneg (fsub A, B)) -> (fsub B, A) 626 return 1; 627 628 case ISD::FMUL: 629 case ISD::FDIV: 630 if (Options->HonorSignDependentRoundingFPMath()) return 0; 631 632 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 633 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 634 Options, Depth + 1)) 635 return V; 636 637 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 638 Depth + 1); 639 640 case ISD::FP_EXTEND: 641 case ISD::FP_ROUND: 642 case ISD::FSIN: 643 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 644 Depth + 1); 645 } 646 } 647 648 /// If isNegatibleForFree returns true, return the newly negated expression. 649 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 650 bool LegalOperations, unsigned Depth = 0) { 651 const TargetOptions &Options = DAG.getTarget().Options; 652 // fneg is removable even if it has multiple uses. 653 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 654 655 // Don't allow anything with multiple uses. 656 assert(Op.hasOneUse() && "Unknown reuse!"); 657 658 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 659 660 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 661 662 switch (Op.getOpcode()) { 663 default: llvm_unreachable("Unknown code"); 664 case ISD::ConstantFP: { 665 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 666 V.changeSign(); 667 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 668 } 669 case ISD::FADD: 670 // FIXME: determine better conditions for this xform. 671 assert(Options.UnsafeFPMath); 672 673 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 674 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 675 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 676 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 677 GetNegatedExpression(Op.getOperand(0), DAG, 678 LegalOperations, Depth+1), 679 Op.getOperand(1), Flags); 680 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 681 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 682 GetNegatedExpression(Op.getOperand(1), DAG, 683 LegalOperations, Depth+1), 684 Op.getOperand(0), Flags); 685 case ISD::FSUB: 686 // We can't turn -(A-B) into B-A when we honor signed zeros. 687 assert(Options.UnsafeFPMath); 688 689 // fold (fneg (fsub 0, B)) -> B 690 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 691 if (N0CFP->isZero()) 692 return Op.getOperand(1); 693 694 // fold (fneg (fsub A, B)) -> (fsub B, A) 695 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 696 Op.getOperand(1), Op.getOperand(0), Flags); 697 698 case ISD::FMUL: 699 case ISD::FDIV: 700 assert(!Options.HonorSignDependentRoundingFPMath()); 701 702 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 703 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 704 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 705 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 706 GetNegatedExpression(Op.getOperand(0), DAG, 707 LegalOperations, Depth+1), 708 Op.getOperand(1), Flags); 709 710 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 711 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 712 Op.getOperand(0), 713 GetNegatedExpression(Op.getOperand(1), DAG, 714 LegalOperations, Depth+1), Flags); 715 716 case ISD::FP_EXTEND: 717 case ISD::FSIN: 718 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 719 GetNegatedExpression(Op.getOperand(0), DAG, 720 LegalOperations, Depth+1)); 721 case ISD::FP_ROUND: 722 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 723 GetNegatedExpression(Op.getOperand(0), DAG, 724 LegalOperations, Depth+1), 725 Op.getOperand(1)); 726 } 727 } 728 729 // APInts must be the same size for most operations, this helper 730 // function zero extends the shorter of the pair so that they match. 731 // We provide an Offset so that we can create bitwidths that won't overflow. 732 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 733 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 734 LHS = LHS.zextOrSelf(Bits); 735 RHS = RHS.zextOrSelf(Bits); 736 } 737 738 // Return true if this node is a setcc, or is a select_cc 739 // that selects between the target values used for true and false, making it 740 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 741 // the appropriate nodes based on the type of node we are checking. This 742 // simplifies life a bit for the callers. 743 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 744 SDValue &CC) const { 745 if (N.getOpcode() == ISD::SETCC) { 746 LHS = N.getOperand(0); 747 RHS = N.getOperand(1); 748 CC = N.getOperand(2); 749 return true; 750 } 751 752 if (N.getOpcode() != ISD::SELECT_CC || 753 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 754 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 755 return false; 756 757 if (TLI.getBooleanContents(N.getValueType()) == 758 TargetLowering::UndefinedBooleanContent) 759 return false; 760 761 LHS = N.getOperand(0); 762 RHS = N.getOperand(1); 763 CC = N.getOperand(4); 764 return true; 765 } 766 767 /// Return true if this is a SetCC-equivalent operation with only one use. 768 /// If this is true, it allows the users to invert the operation for free when 769 /// it is profitable to do so. 770 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 771 SDValue N0, N1, N2; 772 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 773 return true; 774 return false; 775 } 776 777 // \brief Returns the SDNode if it is a constant float BuildVector 778 // or constant float. 779 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 780 if (isa<ConstantFPSDNode>(N)) 781 return N.getNode(); 782 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 783 return N.getNode(); 784 return nullptr; 785 } 786 787 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 788 // int. 789 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 790 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 791 return CN; 792 793 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 794 BitVector UndefElements; 795 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 796 797 // BuildVectors can truncate their operands. Ignore that case here. 798 // FIXME: We blindly ignore splats which include undef which is overly 799 // pessimistic. 800 if (CN && UndefElements.none() && 801 CN->getValueType(0) == N.getValueType().getScalarType()) 802 return CN; 803 } 804 805 return nullptr; 806 } 807 808 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 809 // float. 810 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 811 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 812 return CN; 813 814 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 815 BitVector UndefElements; 816 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 817 818 if (CN && UndefElements.none()) 819 return CN; 820 } 821 822 return nullptr; 823 } 824 825 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 826 SDValue N1) { 827 EVT VT = N0.getValueType(); 828 if (N0.getOpcode() == Opc) { 829 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 830 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 831 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 832 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 833 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 834 return SDValue(); 835 } 836 if (N0.hasOneUse()) { 837 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 838 // use 839 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 840 if (!OpNode.getNode()) 841 return SDValue(); 842 AddToWorklist(OpNode.getNode()); 843 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 844 } 845 } 846 } 847 848 if (N1.getOpcode() == Opc) { 849 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 850 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 851 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 852 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 853 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 854 return SDValue(); 855 } 856 if (N1.hasOneUse()) { 857 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 858 // use 859 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 860 if (!OpNode.getNode()) 861 return SDValue(); 862 AddToWorklist(OpNode.getNode()); 863 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 864 } 865 } 866 } 867 868 return SDValue(); 869 } 870 871 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 872 bool AddTo) { 873 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 874 ++NodesCombined; 875 DEBUG(dbgs() << "\nReplacing.1 "; 876 N->dump(&DAG); 877 dbgs() << "\nWith: "; 878 To[0].getNode()->dump(&DAG); 879 dbgs() << " and " << NumTo-1 << " other values\n"); 880 for (unsigned i = 0, e = NumTo; i != e; ++i) 881 assert((!To[i].getNode() || 882 N->getValueType(i) == To[i].getValueType()) && 883 "Cannot combine value to value of different type!"); 884 885 WorklistRemover DeadNodes(*this); 886 DAG.ReplaceAllUsesWith(N, To); 887 if (AddTo) { 888 // Push the new nodes and any users onto the worklist 889 for (unsigned i = 0, e = NumTo; i != e; ++i) { 890 if (To[i].getNode()) { 891 AddToWorklist(To[i].getNode()); 892 AddUsersToWorklist(To[i].getNode()); 893 } 894 } 895 } 896 897 // Finally, if the node is now dead, remove it from the graph. The node 898 // may not be dead if the replacement process recursively simplified to 899 // something else needing this node. 900 if (N->use_empty()) 901 deleteAndRecombine(N); 902 return SDValue(N, 0); 903 } 904 905 void DAGCombiner:: 906 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 907 // Replace all uses. If any nodes become isomorphic to other nodes and 908 // are deleted, make sure to remove them from our worklist. 909 WorklistRemover DeadNodes(*this); 910 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 911 912 // Push the new node and any (possibly new) users onto the worklist. 913 AddToWorklist(TLO.New.getNode()); 914 AddUsersToWorklist(TLO.New.getNode()); 915 916 // Finally, if the node is now dead, remove it from the graph. The node 917 // may not be dead if the replacement process recursively simplified to 918 // something else needing this node. 919 if (TLO.Old.getNode()->use_empty()) 920 deleteAndRecombine(TLO.Old.getNode()); 921 } 922 923 /// Check the specified integer node value to see if it can be simplified or if 924 /// things it uses can be simplified by bit propagation. If so, return true. 925 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 926 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 927 APInt KnownZero, KnownOne; 928 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 929 return false; 930 931 // Revisit the node. 932 AddToWorklist(Op.getNode()); 933 934 // Replace the old value with the new one. 935 ++NodesCombined; 936 DEBUG(dbgs() << "\nReplacing.2 "; 937 TLO.Old.getNode()->dump(&DAG); 938 dbgs() << "\nWith: "; 939 TLO.New.getNode()->dump(&DAG); 940 dbgs() << '\n'); 941 942 CommitTargetLoweringOpt(TLO); 943 return true; 944 } 945 946 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 947 SDLoc dl(Load); 948 EVT VT = Load->getValueType(0); 949 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 950 951 DEBUG(dbgs() << "\nReplacing.9 "; 952 Load->dump(&DAG); 953 dbgs() << "\nWith: "; 954 Trunc.getNode()->dump(&DAG); 955 dbgs() << '\n'); 956 WorklistRemover DeadNodes(*this); 957 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 958 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 959 deleteAndRecombine(Load); 960 AddToWorklist(Trunc.getNode()); 961 } 962 963 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 964 Replace = false; 965 SDLoc dl(Op); 966 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 967 LoadSDNode *LD = cast<LoadSDNode>(Op); 968 EVT MemVT = LD->getMemoryVT(); 969 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 970 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 971 : ISD::EXTLOAD) 972 : LD->getExtensionType(); 973 Replace = true; 974 return DAG.getExtLoad(ExtType, dl, PVT, 975 LD->getChain(), LD->getBasePtr(), 976 MemVT, LD->getMemOperand()); 977 } 978 979 unsigned Opc = Op.getOpcode(); 980 switch (Opc) { 981 default: break; 982 case ISD::AssertSext: 983 return DAG.getNode(ISD::AssertSext, dl, PVT, 984 SExtPromoteOperand(Op.getOperand(0), PVT), 985 Op.getOperand(1)); 986 case ISD::AssertZext: 987 return DAG.getNode(ISD::AssertZext, dl, PVT, 988 ZExtPromoteOperand(Op.getOperand(0), PVT), 989 Op.getOperand(1)); 990 case ISD::Constant: { 991 unsigned ExtOpc = 992 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 993 return DAG.getNode(ExtOpc, dl, PVT, Op); 994 } 995 } 996 997 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 998 return SDValue(); 999 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 1000 } 1001 1002 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1003 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1004 return SDValue(); 1005 EVT OldVT = Op.getValueType(); 1006 SDLoc dl(Op); 1007 bool Replace = false; 1008 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1009 if (!NewOp.getNode()) 1010 return SDValue(); 1011 AddToWorklist(NewOp.getNode()); 1012 1013 if (Replace) 1014 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1015 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 1016 DAG.getValueType(OldVT)); 1017 } 1018 1019 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1020 EVT OldVT = Op.getValueType(); 1021 SDLoc dl(Op); 1022 bool Replace = false; 1023 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1024 if (!NewOp.getNode()) 1025 return SDValue(); 1026 AddToWorklist(NewOp.getNode()); 1027 1028 if (Replace) 1029 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1030 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1031 } 1032 1033 /// Promote the specified integer binary operation if the target indicates it is 1034 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1035 /// i32 since i16 instructions are longer. 1036 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1037 if (!LegalOperations) 1038 return SDValue(); 1039 1040 EVT VT = Op.getValueType(); 1041 if (VT.isVector() || !VT.isInteger()) 1042 return SDValue(); 1043 1044 // If operation type is 'undesirable', e.g. i16 on x86, consider 1045 // promoting it. 1046 unsigned Opc = Op.getOpcode(); 1047 if (TLI.isTypeDesirableForOp(Opc, VT)) 1048 return SDValue(); 1049 1050 EVT PVT = VT; 1051 // Consult target whether it is a good idea to promote this operation and 1052 // what's the right type to promote it to. 1053 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1054 assert(PVT != VT && "Don't know what type to promote to!"); 1055 1056 bool Replace0 = false; 1057 SDValue N0 = Op.getOperand(0); 1058 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1059 if (!NN0.getNode()) 1060 return SDValue(); 1061 1062 bool Replace1 = false; 1063 SDValue N1 = Op.getOperand(1); 1064 SDValue NN1; 1065 if (N0 == N1) 1066 NN1 = NN0; 1067 else { 1068 NN1 = PromoteOperand(N1, PVT, Replace1); 1069 if (!NN1.getNode()) 1070 return SDValue(); 1071 } 1072 1073 AddToWorklist(NN0.getNode()); 1074 if (NN1.getNode()) 1075 AddToWorklist(NN1.getNode()); 1076 1077 if (Replace0) 1078 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1079 if (Replace1) 1080 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1081 1082 DEBUG(dbgs() << "\nPromoting "; 1083 Op.getNode()->dump(&DAG)); 1084 SDLoc dl(Op); 1085 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1086 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1087 } 1088 return SDValue(); 1089 } 1090 1091 /// Promote the specified integer shift operation if the target indicates it is 1092 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1093 /// i32 since i16 instructions are longer. 1094 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1095 if (!LegalOperations) 1096 return SDValue(); 1097 1098 EVT VT = Op.getValueType(); 1099 if (VT.isVector() || !VT.isInteger()) 1100 return SDValue(); 1101 1102 // If operation type is 'undesirable', e.g. i16 on x86, consider 1103 // promoting it. 1104 unsigned Opc = Op.getOpcode(); 1105 if (TLI.isTypeDesirableForOp(Opc, VT)) 1106 return SDValue(); 1107 1108 EVT PVT = VT; 1109 // Consult target whether it is a good idea to promote this operation and 1110 // what's the right type to promote it to. 1111 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1112 assert(PVT != VT && "Don't know what type to promote to!"); 1113 1114 bool Replace = false; 1115 SDValue N0 = Op.getOperand(0); 1116 if (Opc == ISD::SRA) 1117 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1118 else if (Opc == ISD::SRL) 1119 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1120 else 1121 N0 = PromoteOperand(N0, PVT, Replace); 1122 if (!N0.getNode()) 1123 return SDValue(); 1124 1125 AddToWorklist(N0.getNode()); 1126 if (Replace) 1127 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1128 1129 DEBUG(dbgs() << "\nPromoting "; 1130 Op.getNode()->dump(&DAG)); 1131 SDLoc dl(Op); 1132 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1133 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1134 } 1135 return SDValue(); 1136 } 1137 1138 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1139 if (!LegalOperations) 1140 return SDValue(); 1141 1142 EVT VT = Op.getValueType(); 1143 if (VT.isVector() || !VT.isInteger()) 1144 return SDValue(); 1145 1146 // If operation type is 'undesirable', e.g. i16 on x86, consider 1147 // promoting it. 1148 unsigned Opc = Op.getOpcode(); 1149 if (TLI.isTypeDesirableForOp(Opc, VT)) 1150 return SDValue(); 1151 1152 EVT PVT = VT; 1153 // Consult target whether it is a good idea to promote this operation and 1154 // what's the right type to promote it to. 1155 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1156 assert(PVT != VT && "Don't know what type to promote to!"); 1157 // fold (aext (aext x)) -> (aext x) 1158 // fold (aext (zext x)) -> (zext x) 1159 // fold (aext (sext x)) -> (sext x) 1160 DEBUG(dbgs() << "\nPromoting "; 1161 Op.getNode()->dump(&DAG)); 1162 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1163 } 1164 return SDValue(); 1165 } 1166 1167 bool DAGCombiner::PromoteLoad(SDValue Op) { 1168 if (!LegalOperations) 1169 return false; 1170 1171 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1172 return false; 1173 1174 EVT VT = Op.getValueType(); 1175 if (VT.isVector() || !VT.isInteger()) 1176 return false; 1177 1178 // If operation type is 'undesirable', e.g. i16 on x86, consider 1179 // promoting it. 1180 unsigned Opc = Op.getOpcode(); 1181 if (TLI.isTypeDesirableForOp(Opc, VT)) 1182 return false; 1183 1184 EVT PVT = VT; 1185 // Consult target whether it is a good idea to promote this operation and 1186 // what's the right type to promote it to. 1187 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1188 assert(PVT != VT && "Don't know what type to promote to!"); 1189 1190 SDLoc dl(Op); 1191 SDNode *N = Op.getNode(); 1192 LoadSDNode *LD = cast<LoadSDNode>(N); 1193 EVT MemVT = LD->getMemoryVT(); 1194 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1195 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1196 : ISD::EXTLOAD) 1197 : LD->getExtensionType(); 1198 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1199 LD->getChain(), LD->getBasePtr(), 1200 MemVT, LD->getMemOperand()); 1201 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1202 1203 DEBUG(dbgs() << "\nPromoting "; 1204 N->dump(&DAG); 1205 dbgs() << "\nTo: "; 1206 Result.getNode()->dump(&DAG); 1207 dbgs() << '\n'); 1208 WorklistRemover DeadNodes(*this); 1209 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1210 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1211 deleteAndRecombine(N); 1212 AddToWorklist(Result.getNode()); 1213 return true; 1214 } 1215 return false; 1216 } 1217 1218 /// \brief Recursively delete a node which has no uses and any operands for 1219 /// which it is the only use. 1220 /// 1221 /// Note that this both deletes the nodes and removes them from the worklist. 1222 /// It also adds any nodes who have had a user deleted to the worklist as they 1223 /// may now have only one use and subject to other combines. 1224 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1225 if (!N->use_empty()) 1226 return false; 1227 1228 SmallSetVector<SDNode *, 16> Nodes; 1229 Nodes.insert(N); 1230 do { 1231 N = Nodes.pop_back_val(); 1232 if (!N) 1233 continue; 1234 1235 if (N->use_empty()) { 1236 for (const SDValue &ChildN : N->op_values()) 1237 Nodes.insert(ChildN.getNode()); 1238 1239 removeFromWorklist(N); 1240 DAG.DeleteNode(N); 1241 } else { 1242 AddToWorklist(N); 1243 } 1244 } while (!Nodes.empty()); 1245 return true; 1246 } 1247 1248 //===----------------------------------------------------------------------===// 1249 // Main DAG Combiner implementation 1250 //===----------------------------------------------------------------------===// 1251 1252 void DAGCombiner::Run(CombineLevel AtLevel) { 1253 // set the instance variables, so that the various visit routines may use it. 1254 Level = AtLevel; 1255 LegalOperations = Level >= AfterLegalizeVectorOps; 1256 LegalTypes = Level >= AfterLegalizeTypes; 1257 1258 // Add all the dag nodes to the worklist. 1259 for (SDNode &Node : DAG.allnodes()) 1260 AddToWorklist(&Node); 1261 1262 // Create a dummy node (which is not added to allnodes), that adds a reference 1263 // to the root node, preventing it from being deleted, and tracking any 1264 // changes of the root. 1265 HandleSDNode Dummy(DAG.getRoot()); 1266 1267 // While the worklist isn't empty, find a node and try to combine it. 1268 while (!WorklistMap.empty()) { 1269 SDNode *N; 1270 // The Worklist holds the SDNodes in order, but it may contain null entries. 1271 do { 1272 N = Worklist.pop_back_val(); 1273 } while (!N); 1274 1275 bool GoodWorklistEntry = WorklistMap.erase(N); 1276 (void)GoodWorklistEntry; 1277 assert(GoodWorklistEntry && 1278 "Found a worklist entry without a corresponding map entry!"); 1279 1280 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1281 // N is deleted from the DAG, since they too may now be dead or may have a 1282 // reduced number of uses, allowing other xforms. 1283 if (recursivelyDeleteUnusedNodes(N)) 1284 continue; 1285 1286 WorklistRemover DeadNodes(*this); 1287 1288 // If this combine is running after legalizing the DAG, re-legalize any 1289 // nodes pulled off the worklist. 1290 if (Level == AfterLegalizeDAG) { 1291 SmallSetVector<SDNode *, 16> UpdatedNodes; 1292 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1293 1294 for (SDNode *LN : UpdatedNodes) { 1295 AddToWorklist(LN); 1296 AddUsersToWorklist(LN); 1297 } 1298 if (!NIsValid) 1299 continue; 1300 } 1301 1302 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1303 1304 // Add any operands of the new node which have not yet been combined to the 1305 // worklist as well. Because the worklist uniques things already, this 1306 // won't repeatedly process the same operand. 1307 CombinedNodes.insert(N); 1308 for (const SDValue &ChildN : N->op_values()) 1309 if (!CombinedNodes.count(ChildN.getNode())) 1310 AddToWorklist(ChildN.getNode()); 1311 1312 SDValue RV = combine(N); 1313 1314 if (!RV.getNode()) 1315 continue; 1316 1317 ++NodesCombined; 1318 1319 // If we get back the same node we passed in, rather than a new node or 1320 // zero, we know that the node must have defined multiple values and 1321 // CombineTo was used. Since CombineTo takes care of the worklist 1322 // mechanics for us, we have no work to do in this case. 1323 if (RV.getNode() == N) 1324 continue; 1325 1326 assert(N->getOpcode() != ISD::DELETED_NODE && 1327 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1328 "Node was deleted but visit returned new node!"); 1329 1330 DEBUG(dbgs() << " ... into: "; 1331 RV.getNode()->dump(&DAG)); 1332 1333 if (N->getNumValues() == RV.getNode()->getNumValues()) 1334 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1335 else { 1336 assert(N->getValueType(0) == RV.getValueType() && 1337 N->getNumValues() == 1 && "Type mismatch"); 1338 SDValue OpV = RV; 1339 DAG.ReplaceAllUsesWith(N, &OpV); 1340 } 1341 1342 // Push the new node and any users onto the worklist 1343 AddToWorklist(RV.getNode()); 1344 AddUsersToWorklist(RV.getNode()); 1345 1346 // Finally, if the node is now dead, remove it from the graph. The node 1347 // may not be dead if the replacement process recursively simplified to 1348 // something else needing this node. This will also take care of adding any 1349 // operands which have lost a user to the worklist. 1350 recursivelyDeleteUnusedNodes(N); 1351 } 1352 1353 // If the root changed (e.g. it was a dead load, update the root). 1354 DAG.setRoot(Dummy.getValue()); 1355 DAG.RemoveDeadNodes(); 1356 } 1357 1358 SDValue DAGCombiner::visit(SDNode *N) { 1359 switch (N->getOpcode()) { 1360 default: break; 1361 case ISD::TokenFactor: return visitTokenFactor(N); 1362 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1363 case ISD::ADD: return visitADD(N); 1364 case ISD::SUB: return visitSUB(N); 1365 case ISD::ADDC: return visitADDC(N); 1366 case ISD::SUBC: return visitSUBC(N); 1367 case ISD::ADDE: return visitADDE(N); 1368 case ISD::SUBE: return visitSUBE(N); 1369 case ISD::MUL: return visitMUL(N); 1370 case ISD::SDIV: return visitSDIV(N); 1371 case ISD::UDIV: return visitUDIV(N); 1372 case ISD::SREM: 1373 case ISD::UREM: return visitREM(N); 1374 case ISD::MULHU: return visitMULHU(N); 1375 case ISD::MULHS: return visitMULHS(N); 1376 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1377 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1378 case ISD::SMULO: return visitSMULO(N); 1379 case ISD::UMULO: return visitUMULO(N); 1380 case ISD::SMIN: 1381 case ISD::SMAX: 1382 case ISD::UMIN: 1383 case ISD::UMAX: return visitIMINMAX(N); 1384 case ISD::AND: return visitAND(N); 1385 case ISD::OR: return visitOR(N); 1386 case ISD::XOR: return visitXOR(N); 1387 case ISD::SHL: return visitSHL(N); 1388 case ISD::SRA: return visitSRA(N); 1389 case ISD::SRL: return visitSRL(N); 1390 case ISD::ROTR: 1391 case ISD::ROTL: return visitRotate(N); 1392 case ISD::BSWAP: return visitBSWAP(N); 1393 case ISD::BITREVERSE: return visitBITREVERSE(N); 1394 case ISD::CTLZ: return visitCTLZ(N); 1395 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1396 case ISD::CTTZ: return visitCTTZ(N); 1397 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1398 case ISD::CTPOP: return visitCTPOP(N); 1399 case ISD::SELECT: return visitSELECT(N); 1400 case ISD::VSELECT: return visitVSELECT(N); 1401 case ISD::SELECT_CC: return visitSELECT_CC(N); 1402 case ISD::SETCC: return visitSETCC(N); 1403 case ISD::SETCCE: return visitSETCCE(N); 1404 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1405 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1406 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1407 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1408 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1409 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1410 case ISD::TRUNCATE: return visitTRUNCATE(N); 1411 case ISD::BITCAST: return visitBITCAST(N); 1412 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1413 case ISD::FADD: return visitFADD(N); 1414 case ISD::FSUB: return visitFSUB(N); 1415 case ISD::FMUL: return visitFMUL(N); 1416 case ISD::FMA: return visitFMA(N); 1417 case ISD::FDIV: return visitFDIV(N); 1418 case ISD::FREM: return visitFREM(N); 1419 case ISD::FSQRT: return visitFSQRT(N); 1420 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1421 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1422 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1423 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1424 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1425 case ISD::FP_ROUND: return visitFP_ROUND(N); 1426 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1427 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1428 case ISD::FNEG: return visitFNEG(N); 1429 case ISD::FABS: return visitFABS(N); 1430 case ISD::FFLOOR: return visitFFLOOR(N); 1431 case ISD::FMINNUM: return visitFMINNUM(N); 1432 case ISD::FMAXNUM: return visitFMAXNUM(N); 1433 case ISD::FCEIL: return visitFCEIL(N); 1434 case ISD::FTRUNC: return visitFTRUNC(N); 1435 case ISD::BRCOND: return visitBRCOND(N); 1436 case ISD::BR_CC: return visitBR_CC(N); 1437 case ISD::LOAD: return visitLOAD(N); 1438 case ISD::STORE: return visitSTORE(N); 1439 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1440 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1441 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1442 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1443 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1444 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1445 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1446 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1447 case ISD::MGATHER: return visitMGATHER(N); 1448 case ISD::MLOAD: return visitMLOAD(N); 1449 case ISD::MSCATTER: return visitMSCATTER(N); 1450 case ISD::MSTORE: return visitMSTORE(N); 1451 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1452 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1453 } 1454 return SDValue(); 1455 } 1456 1457 SDValue DAGCombiner::combine(SDNode *N) { 1458 SDValue RV = visit(N); 1459 1460 // If nothing happened, try a target-specific DAG combine. 1461 if (!RV.getNode()) { 1462 assert(N->getOpcode() != ISD::DELETED_NODE && 1463 "Node was deleted but visit returned NULL!"); 1464 1465 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1466 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1467 1468 // Expose the DAG combiner to the target combiner impls. 1469 TargetLowering::DAGCombinerInfo 1470 DagCombineInfo(DAG, Level, false, this); 1471 1472 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1473 } 1474 } 1475 1476 // If nothing happened still, try promoting the operation. 1477 if (!RV.getNode()) { 1478 switch (N->getOpcode()) { 1479 default: break; 1480 case ISD::ADD: 1481 case ISD::SUB: 1482 case ISD::MUL: 1483 case ISD::AND: 1484 case ISD::OR: 1485 case ISD::XOR: 1486 RV = PromoteIntBinOp(SDValue(N, 0)); 1487 break; 1488 case ISD::SHL: 1489 case ISD::SRA: 1490 case ISD::SRL: 1491 RV = PromoteIntShiftOp(SDValue(N, 0)); 1492 break; 1493 case ISD::SIGN_EXTEND: 1494 case ISD::ZERO_EXTEND: 1495 case ISD::ANY_EXTEND: 1496 RV = PromoteExtend(SDValue(N, 0)); 1497 break; 1498 case ISD::LOAD: 1499 if (PromoteLoad(SDValue(N, 0))) 1500 RV = SDValue(N, 0); 1501 break; 1502 } 1503 } 1504 1505 // If N is a commutative binary node, try commuting it to enable more 1506 // sdisel CSE. 1507 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1508 N->getNumValues() == 1) { 1509 SDValue N0 = N->getOperand(0); 1510 SDValue N1 = N->getOperand(1); 1511 1512 // Constant operands are canonicalized to RHS. 1513 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1514 SDValue Ops[] = {N1, N0}; 1515 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1516 N->getFlags()); 1517 if (CSENode) 1518 return SDValue(CSENode, 0); 1519 } 1520 } 1521 1522 return RV; 1523 } 1524 1525 /// Given a node, return its input chain if it has one, otherwise return a null 1526 /// sd operand. 1527 static SDValue getInputChainForNode(SDNode *N) { 1528 if (unsigned NumOps = N->getNumOperands()) { 1529 if (N->getOperand(0).getValueType() == MVT::Other) 1530 return N->getOperand(0); 1531 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1532 return N->getOperand(NumOps-1); 1533 for (unsigned i = 1; i < NumOps-1; ++i) 1534 if (N->getOperand(i).getValueType() == MVT::Other) 1535 return N->getOperand(i); 1536 } 1537 return SDValue(); 1538 } 1539 1540 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1541 // If N has two operands, where one has an input chain equal to the other, 1542 // the 'other' chain is redundant. 1543 if (N->getNumOperands() == 2) { 1544 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1545 return N->getOperand(0); 1546 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1547 return N->getOperand(1); 1548 } 1549 1550 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1551 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1552 SmallPtrSet<SDNode*, 16> SeenOps; 1553 bool Changed = false; // If we should replace this token factor. 1554 1555 // Start out with this token factor. 1556 TFs.push_back(N); 1557 1558 // Iterate through token factors. The TFs grows when new token factors are 1559 // encountered. 1560 for (unsigned i = 0; i < TFs.size(); ++i) { 1561 SDNode *TF = TFs[i]; 1562 1563 // Check each of the operands. 1564 for (const SDValue &Op : TF->op_values()) { 1565 1566 switch (Op.getOpcode()) { 1567 case ISD::EntryToken: 1568 // Entry tokens don't need to be added to the list. They are 1569 // redundant. 1570 Changed = true; 1571 break; 1572 1573 case ISD::TokenFactor: 1574 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1575 // Queue up for processing. 1576 TFs.push_back(Op.getNode()); 1577 // Clean up in case the token factor is removed. 1578 AddToWorklist(Op.getNode()); 1579 Changed = true; 1580 break; 1581 } 1582 LLVM_FALLTHROUGH; 1583 1584 default: 1585 // Only add if it isn't already in the list. 1586 if (SeenOps.insert(Op.getNode()).second) 1587 Ops.push_back(Op); 1588 else 1589 Changed = true; 1590 break; 1591 } 1592 } 1593 } 1594 1595 SDValue Result; 1596 1597 // If we've changed things around then replace token factor. 1598 if (Changed) { 1599 if (Ops.empty()) { 1600 // The entry token is the only possible outcome. 1601 Result = DAG.getEntryNode(); 1602 } else { 1603 // New and improved token factor. 1604 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1605 } 1606 1607 // Add users to worklist if AA is enabled, since it may introduce 1608 // a lot of new chained token factors while removing memory deps. 1609 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1610 : DAG.getSubtarget().useAA(); 1611 return CombineTo(N, Result, UseAA /*add to worklist*/); 1612 } 1613 1614 return Result; 1615 } 1616 1617 /// MERGE_VALUES can always be eliminated. 1618 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1619 WorklistRemover DeadNodes(*this); 1620 // Replacing results may cause a different MERGE_VALUES to suddenly 1621 // be CSE'd with N, and carry its uses with it. Iterate until no 1622 // uses remain, to ensure that the node can be safely deleted. 1623 // First add the users of this node to the work list so that they 1624 // can be tried again once they have new operands. 1625 AddUsersToWorklist(N); 1626 do { 1627 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1628 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1629 } while (!N->use_empty()); 1630 deleteAndRecombine(N); 1631 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1632 } 1633 1634 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1635 /// ConstantSDNode pointer else nullptr. 1636 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1637 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1638 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1639 } 1640 1641 SDValue DAGCombiner::visitADD(SDNode *N) { 1642 SDValue N0 = N->getOperand(0); 1643 SDValue N1 = N->getOperand(1); 1644 EVT VT = N0.getValueType(); 1645 1646 // fold vector ops 1647 if (VT.isVector()) { 1648 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1649 return FoldedVOp; 1650 1651 // fold (add x, 0) -> x, vector edition 1652 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1653 return N0; 1654 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1655 return N1; 1656 } 1657 1658 // fold (add x, undef) -> undef 1659 if (N0.isUndef()) 1660 return N0; 1661 if (N1.isUndef()) 1662 return N1; 1663 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1664 // canonicalize constant to RHS 1665 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1666 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1667 // fold (add c1, c2) -> c1+c2 1668 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, 1669 N0.getNode(), N1.getNode()); 1670 } 1671 // fold (add x, 0) -> x 1672 if (isNullConstant(N1)) 1673 return N0; 1674 // fold ((c1-A)+c2) -> (c1+c2)-A 1675 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) { 1676 if (N0.getOpcode() == ISD::SUB) 1677 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1678 SDLoc DL(N); 1679 return DAG.getNode(ISD::SUB, DL, VT, 1680 DAG.getConstant(N1C->getAPIntValue()+ 1681 N0C->getAPIntValue(), DL, VT), 1682 N0.getOperand(1)); 1683 } 1684 } 1685 // reassociate add 1686 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1687 return RADD; 1688 // fold ((0-A) + B) -> B-A 1689 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1690 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1691 // fold (A + (0-B)) -> A-B 1692 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1693 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1694 // fold (A+(B-A)) -> B 1695 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1696 return N1.getOperand(0); 1697 // fold ((B-A)+A) -> B 1698 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1699 return N0.getOperand(0); 1700 // fold (A+(B-(A+C))) to (B-C) 1701 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1702 N0 == N1.getOperand(1).getOperand(0)) 1703 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1704 N1.getOperand(1).getOperand(1)); 1705 // fold (A+(B-(C+A))) to (B-C) 1706 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1707 N0 == N1.getOperand(1).getOperand(1)) 1708 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1709 N1.getOperand(1).getOperand(0)); 1710 // fold (A+((B-A)+or-C)) to (B+or-C) 1711 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1712 N1.getOperand(0).getOpcode() == ISD::SUB && 1713 N0 == N1.getOperand(0).getOperand(1)) 1714 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1715 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1716 1717 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1718 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1719 SDValue N00 = N0.getOperand(0); 1720 SDValue N01 = N0.getOperand(1); 1721 SDValue N10 = N1.getOperand(0); 1722 SDValue N11 = N1.getOperand(1); 1723 1724 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1725 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1726 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1727 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1728 } 1729 1730 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1731 return SDValue(N, 0); 1732 1733 // fold (a+b) -> (a|b) iff a and b share no bits. 1734 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1735 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1)) 1736 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1737 1738 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1739 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1740 isNullConstant(N1.getOperand(0).getOperand(0))) 1741 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1742 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1743 N1.getOperand(0).getOperand(1), 1744 N1.getOperand(1))); 1745 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1746 isNullConstant(N0.getOperand(0).getOperand(0))) 1747 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1748 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1749 N0.getOperand(0).getOperand(1), 1750 N0.getOperand(1))); 1751 1752 if (N1.getOpcode() == ISD::AND) { 1753 SDValue AndOp0 = N1.getOperand(0); 1754 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1755 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1756 1757 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1758 // and similar xforms where the inner op is either ~0 or 0. 1759 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1760 SDLoc DL(N); 1761 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1762 } 1763 } 1764 1765 // add (sext i1), X -> sub X, (zext i1) 1766 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1767 N0.getOperand(0).getValueType() == MVT::i1 && 1768 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1769 SDLoc DL(N); 1770 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1771 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1772 } 1773 1774 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1775 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1776 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1777 if (TN->getVT() == MVT::i1) { 1778 SDLoc DL(N); 1779 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1780 DAG.getConstant(1, DL, VT)); 1781 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1782 } 1783 } 1784 1785 return SDValue(); 1786 } 1787 1788 SDValue DAGCombiner::visitADDC(SDNode *N) { 1789 SDValue N0 = N->getOperand(0); 1790 SDValue N1 = N->getOperand(1); 1791 EVT VT = N0.getValueType(); 1792 1793 // If the flag result is dead, turn this into an ADD. 1794 if (!N->hasAnyUseOfValue(1)) 1795 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1796 DAG.getNode(ISD::CARRY_FALSE, 1797 SDLoc(N), MVT::Glue)); 1798 1799 // canonicalize constant to RHS. 1800 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1801 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1802 if (N0C && !N1C) 1803 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1804 1805 // fold (addc x, 0) -> x + no carry out 1806 if (isNullConstant(N1)) 1807 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1808 SDLoc(N), MVT::Glue)); 1809 1810 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1811 APInt LHSZero, LHSOne; 1812 APInt RHSZero, RHSOne; 1813 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1814 1815 if (LHSZero.getBoolValue()) { 1816 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1817 1818 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1819 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1820 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1821 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1822 DAG.getNode(ISD::CARRY_FALSE, 1823 SDLoc(N), MVT::Glue)); 1824 } 1825 1826 return SDValue(); 1827 } 1828 1829 SDValue DAGCombiner::visitADDE(SDNode *N) { 1830 SDValue N0 = N->getOperand(0); 1831 SDValue N1 = N->getOperand(1); 1832 SDValue CarryIn = N->getOperand(2); 1833 1834 // canonicalize constant to RHS 1835 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1836 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1837 if (N0C && !N1C) 1838 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1839 N1, N0, CarryIn); 1840 1841 // fold (adde x, y, false) -> (addc x, y) 1842 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1843 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1844 1845 return SDValue(); 1846 } 1847 1848 // Since it may not be valid to emit a fold to zero for vector initializers 1849 // check if we can before folding. 1850 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 1851 SelectionDAG &DAG, bool LegalOperations, 1852 bool LegalTypes) { 1853 if (!VT.isVector()) 1854 return DAG.getConstant(0, DL, VT); 1855 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1856 return DAG.getConstant(0, DL, VT); 1857 return SDValue(); 1858 } 1859 1860 SDValue DAGCombiner::visitSUB(SDNode *N) { 1861 SDValue N0 = N->getOperand(0); 1862 SDValue N1 = N->getOperand(1); 1863 EVT VT = N0.getValueType(); 1864 1865 // fold vector ops 1866 if (VT.isVector()) { 1867 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1868 return FoldedVOp; 1869 1870 // fold (sub x, 0) -> x, vector edition 1871 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1872 return N0; 1873 } 1874 1875 // fold (sub x, x) -> 0 1876 // FIXME: Refactor this and xor and other similar operations together. 1877 if (N0 == N1) 1878 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1879 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1880 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1881 // fold (sub c1, c2) -> c1-c2 1882 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, 1883 N0.getNode(), N1.getNode()); 1884 } 1885 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1886 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1887 // fold (sub x, c) -> (add x, -c) 1888 if (N1C) { 1889 SDLoc DL(N); 1890 return DAG.getNode(ISD::ADD, DL, VT, N0, 1891 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1892 } 1893 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1894 if (isAllOnesConstant(N0)) 1895 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1896 // fold A-(A-B) -> B 1897 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1898 return N1.getOperand(1); 1899 // fold (A+B)-A -> B 1900 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1901 return N0.getOperand(1); 1902 // fold (A+B)-B -> A 1903 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1904 return N0.getOperand(0); 1905 // fold C2-(A+C1) -> (C2-C1)-A 1906 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1907 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1908 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1909 SDLoc DL(N); 1910 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1911 DL, VT); 1912 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1913 N1.getOperand(0)); 1914 } 1915 // fold ((A+(B+or-C))-B) -> A+or-C 1916 if (N0.getOpcode() == ISD::ADD && 1917 (N0.getOperand(1).getOpcode() == ISD::SUB || 1918 N0.getOperand(1).getOpcode() == ISD::ADD) && 1919 N0.getOperand(1).getOperand(0) == N1) 1920 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1921 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1922 // fold ((A+(C+B))-B) -> A+C 1923 if (N0.getOpcode() == ISD::ADD && 1924 N0.getOperand(1).getOpcode() == ISD::ADD && 1925 N0.getOperand(1).getOperand(1) == N1) 1926 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1927 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1928 // fold ((A-(B-C))-C) -> A-B 1929 if (N0.getOpcode() == ISD::SUB && 1930 N0.getOperand(1).getOpcode() == ISD::SUB && 1931 N0.getOperand(1).getOperand(1) == N1) 1932 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1933 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1934 1935 // If either operand of a sub is undef, the result is undef 1936 if (N0.isUndef()) 1937 return N0; 1938 if (N1.isUndef()) 1939 return N1; 1940 1941 // If the relocation model supports it, consider symbol offsets. 1942 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1943 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1944 // fold (sub Sym, c) -> Sym-c 1945 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1946 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1947 GA->getOffset() - 1948 (uint64_t)N1C->getSExtValue()); 1949 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1950 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1951 if (GA->getGlobal() == GB->getGlobal()) 1952 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1953 SDLoc(N), VT); 1954 } 1955 1956 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1957 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1958 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1959 if (TN->getVT() == MVT::i1) { 1960 SDLoc DL(N); 1961 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1962 DAG.getConstant(1, DL, VT)); 1963 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1964 } 1965 } 1966 1967 return SDValue(); 1968 } 1969 1970 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1971 SDValue N0 = N->getOperand(0); 1972 SDValue N1 = N->getOperand(1); 1973 EVT VT = N0.getValueType(); 1974 SDLoc DL(N); 1975 1976 // If the flag result is dead, turn this into an SUB. 1977 if (!N->hasAnyUseOfValue(1)) 1978 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 1979 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1980 1981 // fold (subc x, x) -> 0 + no borrow 1982 if (N0 == N1) 1983 return CombineTo(N, DAG.getConstant(0, DL, VT), 1984 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1985 1986 // fold (subc x, 0) -> x + no borrow 1987 if (isNullConstant(N1)) 1988 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1989 1990 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1991 if (isAllOnesConstant(N0)) 1992 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 1993 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1994 1995 return SDValue(); 1996 } 1997 1998 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1999 SDValue N0 = N->getOperand(0); 2000 SDValue N1 = N->getOperand(1); 2001 SDValue CarryIn = N->getOperand(2); 2002 2003 // fold (sube x, y, false) -> (subc x, y) 2004 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2005 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2006 2007 return SDValue(); 2008 } 2009 2010 SDValue DAGCombiner::visitMUL(SDNode *N) { 2011 SDValue N0 = N->getOperand(0); 2012 SDValue N1 = N->getOperand(1); 2013 EVT VT = N0.getValueType(); 2014 2015 // fold (mul x, undef) -> 0 2016 if (N0.isUndef() || N1.isUndef()) 2017 return DAG.getConstant(0, SDLoc(N), VT); 2018 2019 bool N0IsConst = false; 2020 bool N1IsConst = false; 2021 bool N1IsOpaqueConst = false; 2022 bool N0IsOpaqueConst = false; 2023 APInt ConstValue0, ConstValue1; 2024 // fold vector ops 2025 if (VT.isVector()) { 2026 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2027 return FoldedVOp; 2028 2029 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2030 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2031 } else { 2032 N0IsConst = isa<ConstantSDNode>(N0); 2033 if (N0IsConst) { 2034 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2035 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2036 } 2037 N1IsConst = isa<ConstantSDNode>(N1); 2038 if (N1IsConst) { 2039 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2040 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2041 } 2042 } 2043 2044 // fold (mul c1, c2) -> c1*c2 2045 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2046 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2047 N0.getNode(), N1.getNode()); 2048 2049 // canonicalize constant to RHS (vector doesn't have to splat) 2050 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2051 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2052 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2053 // fold (mul x, 0) -> 0 2054 if (N1IsConst && ConstValue1 == 0) 2055 return N1; 2056 // We require a splat of the entire scalar bit width for non-contiguous 2057 // bit patterns. 2058 bool IsFullSplat = 2059 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2060 // fold (mul x, 1) -> x 2061 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2062 return N0; 2063 // fold (mul x, -1) -> 0-x 2064 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2065 SDLoc DL(N); 2066 return DAG.getNode(ISD::SUB, DL, VT, 2067 DAG.getConstant(0, DL, VT), N0); 2068 } 2069 // fold (mul x, (1 << c)) -> x << c 2070 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2071 IsFullSplat) { 2072 SDLoc DL(N); 2073 return DAG.getNode(ISD::SHL, DL, VT, N0, 2074 DAG.getConstant(ConstValue1.logBase2(), DL, 2075 getShiftAmountTy(N0.getValueType()))); 2076 } 2077 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2078 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2079 IsFullSplat) { 2080 unsigned Log2Val = (-ConstValue1).logBase2(); 2081 SDLoc DL(N); 2082 // FIXME: If the input is something that is easily negated (e.g. a 2083 // single-use add), we should put the negate there. 2084 return DAG.getNode(ISD::SUB, DL, VT, 2085 DAG.getConstant(0, DL, VT), 2086 DAG.getNode(ISD::SHL, DL, VT, N0, 2087 DAG.getConstant(Log2Val, DL, 2088 getShiftAmountTy(N0.getValueType())))); 2089 } 2090 2091 APInt Val; 2092 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2093 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2094 (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2095 isa<ConstantSDNode>(N0.getOperand(1)))) { 2096 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2097 AddToWorklist(C3.getNode()); 2098 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2099 } 2100 2101 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2102 // use. 2103 { 2104 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2105 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2106 if (N0.getOpcode() == ISD::SHL && 2107 (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2108 isa<ConstantSDNode>(N0.getOperand(1))) && 2109 N0.getNode()->hasOneUse()) { 2110 Sh = N0; Y = N1; 2111 } else if (N1.getOpcode() == ISD::SHL && 2112 isa<ConstantSDNode>(N1.getOperand(1)) && 2113 N1.getNode()->hasOneUse()) { 2114 Sh = N1; Y = N0; 2115 } 2116 2117 if (Sh.getNode()) { 2118 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2119 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2120 } 2121 } 2122 2123 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2124 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2125 N0.getOpcode() == ISD::ADD && 2126 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2127 isMulAddWithConstProfitable(N, N0, N1)) 2128 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2129 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2130 N0.getOperand(0), N1), 2131 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2132 N0.getOperand(1), N1)); 2133 2134 // reassociate mul 2135 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2136 return RMUL; 2137 2138 return SDValue(); 2139 } 2140 2141 /// Return true if divmod libcall is available. 2142 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2143 const TargetLowering &TLI) { 2144 RTLIB::Libcall LC; 2145 EVT NodeType = Node->getValueType(0); 2146 if (!NodeType.isSimple()) 2147 return false; 2148 switch (NodeType.getSimpleVT().SimpleTy) { 2149 default: return false; // No libcall for vector types. 2150 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2151 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2152 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2153 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2154 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2155 } 2156 2157 return TLI.getLibcallName(LC) != nullptr; 2158 } 2159 2160 /// Issue divrem if both quotient and remainder are needed. 2161 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2162 if (Node->use_empty()) 2163 return SDValue(); // This is a dead node, leave it alone. 2164 2165 unsigned Opcode = Node->getOpcode(); 2166 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2167 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2168 2169 // DivMod lib calls can still work on non-legal types if using lib-calls. 2170 EVT VT = Node->getValueType(0); 2171 if (VT.isVector() || !VT.isInteger()) 2172 return SDValue(); 2173 2174 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2175 return SDValue(); 2176 2177 // If DIVREM is going to get expanded into a libcall, 2178 // but there is no libcall available, then don't combine. 2179 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2180 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2181 return SDValue(); 2182 2183 // If div is legal, it's better to do the normal expansion 2184 unsigned OtherOpcode = 0; 2185 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2186 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2187 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2188 return SDValue(); 2189 } else { 2190 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2191 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2192 return SDValue(); 2193 } 2194 2195 SDValue Op0 = Node->getOperand(0); 2196 SDValue Op1 = Node->getOperand(1); 2197 SDValue combined; 2198 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2199 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2200 SDNode *User = *UI; 2201 if (User == Node || User->use_empty()) 2202 continue; 2203 // Convert the other matching node(s), too; 2204 // otherwise, the DIVREM may get target-legalized into something 2205 // target-specific that we won't be able to recognize. 2206 unsigned UserOpc = User->getOpcode(); 2207 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2208 User->getOperand(0) == Op0 && 2209 User->getOperand(1) == Op1) { 2210 if (!combined) { 2211 if (UserOpc == OtherOpcode) { 2212 SDVTList VTs = DAG.getVTList(VT, VT); 2213 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2214 } else if (UserOpc == DivRemOpc) { 2215 combined = SDValue(User, 0); 2216 } else { 2217 assert(UserOpc == Opcode); 2218 continue; 2219 } 2220 } 2221 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2222 CombineTo(User, combined); 2223 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2224 CombineTo(User, combined.getValue(1)); 2225 } 2226 } 2227 return combined; 2228 } 2229 2230 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2231 SDValue N0 = N->getOperand(0); 2232 SDValue N1 = N->getOperand(1); 2233 EVT VT = N->getValueType(0); 2234 2235 // fold vector ops 2236 if (VT.isVector()) 2237 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2238 return FoldedVOp; 2239 2240 SDLoc DL(N); 2241 2242 // fold (sdiv c1, c2) -> c1/c2 2243 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2244 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2245 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2246 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2247 // fold (sdiv X, 1) -> X 2248 if (N1C && N1C->isOne()) 2249 return N0; 2250 // fold (sdiv X, -1) -> 0-X 2251 if (N1C && N1C->isAllOnesValue()) 2252 return DAG.getNode(ISD::SUB, DL, VT, 2253 DAG.getConstant(0, DL, VT), N0); 2254 2255 // If we know the sign bits of both operands are zero, strength reduce to a 2256 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2257 if (!VT.isVector()) { 2258 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2259 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2260 } 2261 2262 // fold (sdiv X, pow2) -> simple ops after legalize 2263 // FIXME: We check for the exact bit here because the generic lowering gives 2264 // better results in that case. The target-specific lowering should learn how 2265 // to handle exact sdivs efficiently. 2266 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2267 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2268 (N1C->getAPIntValue().isPowerOf2() || 2269 (-N1C->getAPIntValue()).isPowerOf2())) { 2270 // Target-specific implementation of sdiv x, pow2. 2271 if (SDValue Res = BuildSDIVPow2(N)) 2272 return Res; 2273 2274 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2275 2276 // Splat the sign bit into the register 2277 SDValue SGN = 2278 DAG.getNode(ISD::SRA, DL, VT, N0, 2279 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2280 getShiftAmountTy(N0.getValueType()))); 2281 AddToWorklist(SGN.getNode()); 2282 2283 // Add (N0 < 0) ? abs2 - 1 : 0; 2284 SDValue SRL = 2285 DAG.getNode(ISD::SRL, DL, VT, SGN, 2286 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2287 getShiftAmountTy(SGN.getValueType()))); 2288 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2289 AddToWorklist(SRL.getNode()); 2290 AddToWorklist(ADD.getNode()); // Divide by pow2 2291 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2292 DAG.getConstant(lg2, DL, 2293 getShiftAmountTy(ADD.getValueType()))); 2294 2295 // If we're dividing by a positive value, we're done. Otherwise, we must 2296 // negate the result. 2297 if (N1C->getAPIntValue().isNonNegative()) 2298 return SRA; 2299 2300 AddToWorklist(SRA.getNode()); 2301 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2302 } 2303 2304 // If integer divide is expensive and we satisfy the requirements, emit an 2305 // alternate sequence. Targets may check function attributes for size/speed 2306 // trade-offs. 2307 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2308 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2309 if (SDValue Op = BuildSDIV(N)) 2310 return Op; 2311 2312 // sdiv, srem -> sdivrem 2313 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2314 // Otherwise, we break the simplification logic in visitREM(). 2315 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2316 if (SDValue DivRem = useDivRem(N)) 2317 return DivRem; 2318 2319 // undef / X -> 0 2320 if (N0.isUndef()) 2321 return DAG.getConstant(0, DL, VT); 2322 // X / undef -> undef 2323 if (N1.isUndef()) 2324 return N1; 2325 2326 return SDValue(); 2327 } 2328 2329 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2330 SDValue N0 = N->getOperand(0); 2331 SDValue N1 = N->getOperand(1); 2332 EVT VT = N->getValueType(0); 2333 2334 // fold vector ops 2335 if (VT.isVector()) 2336 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2337 return FoldedVOp; 2338 2339 SDLoc DL(N); 2340 2341 // fold (udiv c1, c2) -> c1/c2 2342 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2343 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2344 if (N0C && N1C) 2345 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2346 N0C, N1C)) 2347 return Folded; 2348 // fold (udiv x, (1 << c)) -> x >>u c 2349 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2350 return DAG.getNode(ISD::SRL, DL, VT, N0, 2351 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2352 getShiftAmountTy(N0.getValueType()))); 2353 2354 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2355 if (N1.getOpcode() == ISD::SHL) { 2356 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2357 if (SHC->getAPIntValue().isPowerOf2()) { 2358 EVT ADDVT = N1.getOperand(1).getValueType(); 2359 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2360 N1.getOperand(1), 2361 DAG.getConstant(SHC->getAPIntValue() 2362 .logBase2(), 2363 DL, ADDVT)); 2364 AddToWorklist(Add.getNode()); 2365 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2366 } 2367 } 2368 } 2369 2370 // fold (udiv x, c) -> alternate 2371 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2372 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2373 if (SDValue Op = BuildUDIV(N)) 2374 return Op; 2375 2376 // sdiv, srem -> sdivrem 2377 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2378 // Otherwise, we break the simplification logic in visitREM(). 2379 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2380 if (SDValue DivRem = useDivRem(N)) 2381 return DivRem; 2382 2383 // undef / X -> 0 2384 if (N0.isUndef()) 2385 return DAG.getConstant(0, DL, VT); 2386 // X / undef -> undef 2387 if (N1.isUndef()) 2388 return N1; 2389 2390 return SDValue(); 2391 } 2392 2393 // handles ISD::SREM and ISD::UREM 2394 SDValue DAGCombiner::visitREM(SDNode *N) { 2395 unsigned Opcode = N->getOpcode(); 2396 SDValue N0 = N->getOperand(0); 2397 SDValue N1 = N->getOperand(1); 2398 EVT VT = N->getValueType(0); 2399 bool isSigned = (Opcode == ISD::SREM); 2400 SDLoc DL(N); 2401 2402 // fold (rem c1, c2) -> c1%c2 2403 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2404 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2405 if (N0C && N1C) 2406 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2407 return Folded; 2408 2409 if (isSigned) { 2410 // If we know the sign bits of both operands are zero, strength reduce to a 2411 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2412 if (!VT.isVector()) { 2413 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2414 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2415 } 2416 } else { 2417 // fold (urem x, pow2) -> (and x, pow2-1) 2418 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2419 N1C->getAPIntValue().isPowerOf2()) { 2420 return DAG.getNode(ISD::AND, DL, VT, N0, 2421 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2422 } 2423 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2424 if (N1.getOpcode() == ISD::SHL) { 2425 ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0)); 2426 if (SHC && SHC->getAPIntValue().isPowerOf2()) { 2427 APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits()); 2428 SDValue Add = 2429 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT)); 2430 AddToWorklist(Add.getNode()); 2431 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2432 } 2433 } 2434 } 2435 2436 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2437 2438 // If X/C can be simplified by the division-by-constant logic, lower 2439 // X%C to the equivalent of X-X/C*C. 2440 // To avoid mangling nodes, this simplification requires that the combine() 2441 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2442 // against this by skipping the simplification if isIntDivCheap(). When 2443 // div is not cheap, combine will not return a DIVREM. Regardless, 2444 // checking cheapness here makes sense since the simplification results in 2445 // fatter code. 2446 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2447 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2448 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2449 AddToWorklist(Div.getNode()); 2450 SDValue OptimizedDiv = combine(Div.getNode()); 2451 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2452 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2453 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2454 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2455 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2456 AddToWorklist(Mul.getNode()); 2457 return Sub; 2458 } 2459 } 2460 2461 // sdiv, srem -> sdivrem 2462 if (SDValue DivRem = useDivRem(N)) 2463 return DivRem.getValue(1); 2464 2465 // undef % X -> 0 2466 if (N0.isUndef()) 2467 return DAG.getConstant(0, DL, VT); 2468 // X % undef -> undef 2469 if (N1.isUndef()) 2470 return N1; 2471 2472 return SDValue(); 2473 } 2474 2475 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2476 SDValue N0 = N->getOperand(0); 2477 SDValue N1 = N->getOperand(1); 2478 EVT VT = N->getValueType(0); 2479 SDLoc DL(N); 2480 2481 // fold (mulhs x, 0) -> 0 2482 if (isNullConstant(N1)) 2483 return N1; 2484 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2485 if (isOneConstant(N1)) { 2486 SDLoc DL(N); 2487 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2488 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2489 DL, 2490 getShiftAmountTy(N0.getValueType()))); 2491 } 2492 // fold (mulhs x, undef) -> 0 2493 if (N0.isUndef() || N1.isUndef()) 2494 return DAG.getConstant(0, SDLoc(N), VT); 2495 2496 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2497 // plus a shift. 2498 if (VT.isSimple() && !VT.isVector()) { 2499 MVT Simple = VT.getSimpleVT(); 2500 unsigned SimpleSize = Simple.getSizeInBits(); 2501 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2502 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2503 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2504 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2505 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2506 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2507 DAG.getConstant(SimpleSize, DL, 2508 getShiftAmountTy(N1.getValueType()))); 2509 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2510 } 2511 } 2512 2513 return SDValue(); 2514 } 2515 2516 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2517 SDValue N0 = N->getOperand(0); 2518 SDValue N1 = N->getOperand(1); 2519 EVT VT = N->getValueType(0); 2520 SDLoc DL(N); 2521 2522 // fold (mulhu x, 0) -> 0 2523 if (isNullConstant(N1)) 2524 return N1; 2525 // fold (mulhu x, 1) -> 0 2526 if (isOneConstant(N1)) 2527 return DAG.getConstant(0, DL, N0.getValueType()); 2528 // fold (mulhu x, undef) -> 0 2529 if (N0.isUndef() || N1.isUndef()) 2530 return DAG.getConstant(0, DL, VT); 2531 2532 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2533 // plus a shift. 2534 if (VT.isSimple() && !VT.isVector()) { 2535 MVT Simple = VT.getSimpleVT(); 2536 unsigned SimpleSize = Simple.getSizeInBits(); 2537 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2538 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2539 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2540 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2541 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2542 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2543 DAG.getConstant(SimpleSize, DL, 2544 getShiftAmountTy(N1.getValueType()))); 2545 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2546 } 2547 } 2548 2549 return SDValue(); 2550 } 2551 2552 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2553 /// give the opcodes for the two computations that are being performed. Return 2554 /// true if a simplification was made. 2555 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2556 unsigned HiOp) { 2557 // If the high half is not needed, just compute the low half. 2558 bool HiExists = N->hasAnyUseOfValue(1); 2559 if (!HiExists && 2560 (!LegalOperations || 2561 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2562 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2563 return CombineTo(N, Res, Res); 2564 } 2565 2566 // If the low half is not needed, just compute the high half. 2567 bool LoExists = N->hasAnyUseOfValue(0); 2568 if (!LoExists && 2569 (!LegalOperations || 2570 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2571 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2572 return CombineTo(N, Res, Res); 2573 } 2574 2575 // If both halves are used, return as it is. 2576 if (LoExists && HiExists) 2577 return SDValue(); 2578 2579 // If the two computed results can be simplified separately, separate them. 2580 if (LoExists) { 2581 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2582 AddToWorklist(Lo.getNode()); 2583 SDValue LoOpt = combine(Lo.getNode()); 2584 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2585 (!LegalOperations || 2586 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2587 return CombineTo(N, LoOpt, LoOpt); 2588 } 2589 2590 if (HiExists) { 2591 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2592 AddToWorklist(Hi.getNode()); 2593 SDValue HiOpt = combine(Hi.getNode()); 2594 if (HiOpt.getNode() && HiOpt != Hi && 2595 (!LegalOperations || 2596 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2597 return CombineTo(N, HiOpt, HiOpt); 2598 } 2599 2600 return SDValue(); 2601 } 2602 2603 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2604 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2605 return Res; 2606 2607 EVT VT = N->getValueType(0); 2608 SDLoc DL(N); 2609 2610 // If the type is twice as wide is legal, transform the mulhu to a wider 2611 // multiply plus a shift. 2612 if (VT.isSimple() && !VT.isVector()) { 2613 MVT Simple = VT.getSimpleVT(); 2614 unsigned SimpleSize = Simple.getSizeInBits(); 2615 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2616 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2617 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2618 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2619 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2620 // Compute the high part as N1. 2621 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2622 DAG.getConstant(SimpleSize, DL, 2623 getShiftAmountTy(Lo.getValueType()))); 2624 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2625 // Compute the low part as N0. 2626 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2627 return CombineTo(N, Lo, Hi); 2628 } 2629 } 2630 2631 return SDValue(); 2632 } 2633 2634 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2635 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2636 return Res; 2637 2638 EVT VT = N->getValueType(0); 2639 SDLoc DL(N); 2640 2641 // If the type is twice as wide is legal, transform the mulhu to a wider 2642 // multiply plus a shift. 2643 if (VT.isSimple() && !VT.isVector()) { 2644 MVT Simple = VT.getSimpleVT(); 2645 unsigned SimpleSize = Simple.getSizeInBits(); 2646 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2647 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2648 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2649 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2650 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2651 // Compute the high part as N1. 2652 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2653 DAG.getConstant(SimpleSize, DL, 2654 getShiftAmountTy(Lo.getValueType()))); 2655 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2656 // Compute the low part as N0. 2657 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2658 return CombineTo(N, Lo, Hi); 2659 } 2660 } 2661 2662 return SDValue(); 2663 } 2664 2665 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2666 // (smulo x, 2) -> (saddo x, x) 2667 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2668 if (C2->getAPIntValue() == 2) 2669 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2670 N->getOperand(0), N->getOperand(0)); 2671 2672 return SDValue(); 2673 } 2674 2675 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2676 // (umulo x, 2) -> (uaddo x, x) 2677 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2678 if (C2->getAPIntValue() == 2) 2679 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2680 N->getOperand(0), N->getOperand(0)); 2681 2682 return SDValue(); 2683 } 2684 2685 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2686 SDValue N0 = N->getOperand(0); 2687 SDValue N1 = N->getOperand(1); 2688 EVT VT = N0.getValueType(); 2689 2690 // fold vector ops 2691 if (VT.isVector()) 2692 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2693 return FoldedVOp; 2694 2695 // fold (add c1, c2) -> c1+c2 2696 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2697 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2698 if (N0C && N1C) 2699 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2700 2701 // canonicalize constant to RHS 2702 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2703 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2704 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2705 2706 return SDValue(); 2707 } 2708 2709 /// If this is a binary operator with two operands of the same opcode, try to 2710 /// simplify it. 2711 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2712 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2713 EVT VT = N0.getValueType(); 2714 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2715 2716 // Bail early if none of these transforms apply. 2717 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2718 2719 // For each of OP in AND/OR/XOR: 2720 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2721 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2722 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2723 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2724 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2725 // 2726 // do not sink logical op inside of a vector extend, since it may combine 2727 // into a vsetcc. 2728 EVT Op0VT = N0.getOperand(0).getValueType(); 2729 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2730 N0.getOpcode() == ISD::SIGN_EXTEND || 2731 N0.getOpcode() == ISD::BSWAP || 2732 // Avoid infinite looping with PromoteIntBinOp. 2733 (N0.getOpcode() == ISD::ANY_EXTEND && 2734 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2735 (N0.getOpcode() == ISD::TRUNCATE && 2736 (!TLI.isZExtFree(VT, Op0VT) || 2737 !TLI.isTruncateFree(Op0VT, VT)) && 2738 TLI.isTypeLegal(Op0VT))) && 2739 !VT.isVector() && 2740 Op0VT == N1.getOperand(0).getValueType() && 2741 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2742 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2743 N0.getOperand(0).getValueType(), 2744 N0.getOperand(0), N1.getOperand(0)); 2745 AddToWorklist(ORNode.getNode()); 2746 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2747 } 2748 2749 // For each of OP in SHL/SRL/SRA/AND... 2750 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2751 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2752 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2753 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2754 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2755 N0.getOperand(1) == N1.getOperand(1)) { 2756 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2757 N0.getOperand(0).getValueType(), 2758 N0.getOperand(0), N1.getOperand(0)); 2759 AddToWorklist(ORNode.getNode()); 2760 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2761 ORNode, N0.getOperand(1)); 2762 } 2763 2764 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2765 // Only perform this optimization up until type legalization, before 2766 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2767 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2768 // we don't want to undo this promotion. 2769 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2770 // on scalars. 2771 if ((N0.getOpcode() == ISD::BITCAST || 2772 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2773 Level <= AfterLegalizeTypes) { 2774 SDValue In0 = N0.getOperand(0); 2775 SDValue In1 = N1.getOperand(0); 2776 EVT In0Ty = In0.getValueType(); 2777 EVT In1Ty = In1.getValueType(); 2778 SDLoc DL(N); 2779 // If both incoming values are integers, and the original types are the 2780 // same. 2781 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2782 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2783 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2784 AddToWorklist(Op.getNode()); 2785 return BC; 2786 } 2787 } 2788 2789 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2790 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2791 // If both shuffles use the same mask, and both shuffle within a single 2792 // vector, then it is worthwhile to move the swizzle after the operation. 2793 // The type-legalizer generates this pattern when loading illegal 2794 // vector types from memory. In many cases this allows additional shuffle 2795 // optimizations. 2796 // There are other cases where moving the shuffle after the xor/and/or 2797 // is profitable even if shuffles don't perform a swizzle. 2798 // If both shuffles use the same mask, and both shuffles have the same first 2799 // or second operand, then it might still be profitable to move the shuffle 2800 // after the xor/and/or operation. 2801 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2802 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2803 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2804 2805 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2806 "Inputs to shuffles are not the same type"); 2807 2808 // Check that both shuffles use the same mask. The masks are known to be of 2809 // the same length because the result vector type is the same. 2810 // Check also that shuffles have only one use to avoid introducing extra 2811 // instructions. 2812 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2813 SVN0->getMask().equals(SVN1->getMask())) { 2814 SDValue ShOp = N0->getOperand(1); 2815 2816 // Don't try to fold this node if it requires introducing a 2817 // build vector of all zeros that might be illegal at this stage. 2818 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2819 if (!LegalTypes) 2820 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2821 else 2822 ShOp = SDValue(); 2823 } 2824 2825 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2826 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2827 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2828 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2829 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2830 N0->getOperand(0), N1->getOperand(0)); 2831 AddToWorklist(NewNode.getNode()); 2832 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2833 SVN0->getMask()); 2834 } 2835 2836 // Don't try to fold this node if it requires introducing a 2837 // build vector of all zeros that might be illegal at this stage. 2838 ShOp = N0->getOperand(0); 2839 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2840 if (!LegalTypes) 2841 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2842 else 2843 ShOp = SDValue(); 2844 } 2845 2846 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2847 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2848 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2849 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2850 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2851 N0->getOperand(1), N1->getOperand(1)); 2852 AddToWorklist(NewNode.getNode()); 2853 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2854 SVN0->getMask()); 2855 } 2856 } 2857 } 2858 2859 return SDValue(); 2860 } 2861 2862 /// This contains all DAGCombine rules which reduce two values combined by 2863 /// an And operation to a single value. This makes them reusable in the context 2864 /// of visitSELECT(). Rules involving constants are not included as 2865 /// visitSELECT() already handles those cases. 2866 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2867 SDNode *LocReference) { 2868 EVT VT = N1.getValueType(); 2869 2870 // fold (and x, undef) -> 0 2871 if (N0.isUndef() || N1.isUndef()) 2872 return DAG.getConstant(0, SDLoc(LocReference), VT); 2873 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2874 SDValue LL, LR, RL, RR, CC0, CC1; 2875 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2876 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2877 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2878 2879 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2880 LL.getValueType().isInteger()) { 2881 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2882 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2883 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2884 LR.getValueType(), LL, RL); 2885 AddToWorklist(ORNode.getNode()); 2886 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2887 } 2888 if (isAllOnesConstant(LR)) { 2889 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2890 if (Op1 == ISD::SETEQ) { 2891 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2892 LR.getValueType(), LL, RL); 2893 AddToWorklist(ANDNode.getNode()); 2894 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2895 } 2896 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2897 if (Op1 == ISD::SETGT) { 2898 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2899 LR.getValueType(), LL, RL); 2900 AddToWorklist(ORNode.getNode()); 2901 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2902 } 2903 } 2904 } 2905 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2906 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2907 Op0 == Op1 && LL.getValueType().isInteger() && 2908 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2909 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2910 SDLoc DL(N0); 2911 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2912 LL, DAG.getConstant(1, DL, 2913 LL.getValueType())); 2914 AddToWorklist(ADDNode.getNode()); 2915 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2916 DAG.getConstant(2, DL, LL.getValueType()), 2917 ISD::SETUGE); 2918 } 2919 // canonicalize equivalent to ll == rl 2920 if (LL == RR && LR == RL) { 2921 Op1 = ISD::getSetCCSwappedOperands(Op1); 2922 std::swap(RL, RR); 2923 } 2924 if (LL == RL && LR == RR) { 2925 bool isInteger = LL.getValueType().isInteger(); 2926 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2927 if (Result != ISD::SETCC_INVALID && 2928 (!LegalOperations || 2929 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2930 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2931 EVT CCVT = getSetCCResultType(LL.getValueType()); 2932 if (N0.getValueType() == CCVT || 2933 (!LegalOperations && N0.getValueType() == MVT::i1)) 2934 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2935 LL, LR, Result); 2936 } 2937 } 2938 } 2939 2940 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2941 VT.getSizeInBits() <= 64) { 2942 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2943 APInt ADDC = ADDI->getAPIntValue(); 2944 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2945 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2946 // immediate for an add, but it is legal if its top c2 bits are set, 2947 // transform the ADD so the immediate doesn't need to be materialized 2948 // in a register. 2949 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2950 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2951 SRLI->getZExtValue()); 2952 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2953 ADDC |= Mask; 2954 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2955 SDLoc DL(N0); 2956 SDValue NewAdd = 2957 DAG.getNode(ISD::ADD, DL, VT, 2958 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2959 CombineTo(N0.getNode(), NewAdd); 2960 // Return N so it doesn't get rechecked! 2961 return SDValue(LocReference, 0); 2962 } 2963 } 2964 } 2965 } 2966 } 2967 } 2968 2969 // Reduce bit extract of low half of an integer to the narrower type. 2970 // (and (srl i64:x, K), KMask) -> 2971 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 2972 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 2973 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 2974 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2975 unsigned Size = VT.getSizeInBits(); 2976 const APInt &AndMask = CAnd->getAPIntValue(); 2977 unsigned ShiftBits = CShift->getZExtValue(); 2978 unsigned MaskBits = AndMask.countTrailingOnes(); 2979 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 2980 2981 if (APIntOps::isMask(AndMask) && 2982 // Required bits must not span the two halves of the integer and 2983 // must fit in the half size type. 2984 (ShiftBits + MaskBits <= Size / 2) && 2985 TLI.isNarrowingProfitable(VT, HalfVT) && 2986 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 2987 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 2988 TLI.isTruncateFree(VT, HalfVT) && 2989 TLI.isZExtFree(HalfVT, VT)) { 2990 // The isNarrowingProfitable is to avoid regressions on PPC and 2991 // AArch64 which match a few 64-bit bit insert / bit extract patterns 2992 // on downstream users of this. Those patterns could probably be 2993 // extended to handle extensions mixed in. 2994 2995 SDValue SL(N0); 2996 assert(ShiftBits != 0 && MaskBits <= Size); 2997 2998 // Extracting the highest bit of the low half. 2999 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3000 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3001 N0.getOperand(0)); 3002 3003 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3004 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3005 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3006 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3007 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3008 } 3009 } 3010 } 3011 } 3012 3013 return SDValue(); 3014 } 3015 3016 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3017 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3018 bool &NarrowLoad) { 3019 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3020 3021 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 3022 return false; 3023 3024 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3025 LoadedVT = LoadN->getMemoryVT(); 3026 3027 if (ExtVT == LoadedVT && 3028 (!LegalOperations || 3029 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3030 // ZEXTLOAD will match without needing to change the size of the value being 3031 // loaded. 3032 NarrowLoad = false; 3033 return true; 3034 } 3035 3036 // Do not change the width of a volatile load. 3037 if (LoadN->isVolatile()) 3038 return false; 3039 3040 // Do not generate loads of non-round integer types since these can 3041 // be expensive (and would be wrong if the type is not byte sized). 3042 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3043 return false; 3044 3045 if (LegalOperations && 3046 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3047 return false; 3048 3049 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3050 return false; 3051 3052 NarrowLoad = true; 3053 return true; 3054 } 3055 3056 SDValue DAGCombiner::visitAND(SDNode *N) { 3057 SDValue N0 = N->getOperand(0); 3058 SDValue N1 = N->getOperand(1); 3059 EVT VT = N1.getValueType(); 3060 3061 // fold vector ops 3062 if (VT.isVector()) { 3063 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3064 return FoldedVOp; 3065 3066 // fold (and x, 0) -> 0, vector edition 3067 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3068 // do not return N0, because undef node may exist in N0 3069 return DAG.getConstant( 3070 APInt::getNullValue( 3071 N0.getValueType().getScalarType().getSizeInBits()), 3072 SDLoc(N), N0.getValueType()); 3073 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3074 // do not return N1, because undef node may exist in N1 3075 return DAG.getConstant( 3076 APInt::getNullValue( 3077 N1.getValueType().getScalarType().getSizeInBits()), 3078 SDLoc(N), N1.getValueType()); 3079 3080 // fold (and x, -1) -> x, vector edition 3081 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3082 return N1; 3083 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3084 return N0; 3085 } 3086 3087 // fold (and c1, c2) -> c1&c2 3088 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3089 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3090 if (N0C && N1C && !N1C->isOpaque()) 3091 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3092 // canonicalize constant to RHS 3093 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3094 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3095 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3096 // fold (and x, -1) -> x 3097 if (isAllOnesConstant(N1)) 3098 return N0; 3099 // if (and x, c) is known to be zero, return 0 3100 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3101 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3102 APInt::getAllOnesValue(BitWidth))) 3103 return DAG.getConstant(0, SDLoc(N), VT); 3104 // reassociate and 3105 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3106 return RAND; 3107 // fold (and (or x, C), D) -> D if (C & D) == D 3108 if (N1C && N0.getOpcode() == ISD::OR) 3109 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3110 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3111 return N1; 3112 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3113 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3114 SDValue N0Op0 = N0.getOperand(0); 3115 APInt Mask = ~N1C->getAPIntValue(); 3116 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 3117 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3118 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3119 N0.getValueType(), N0Op0); 3120 3121 // Replace uses of the AND with uses of the Zero extend node. 3122 CombineTo(N, Zext); 3123 3124 // We actually want to replace all uses of the any_extend with the 3125 // zero_extend, to avoid duplicating things. This will later cause this 3126 // AND to be folded. 3127 CombineTo(N0.getNode(), Zext); 3128 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3129 } 3130 } 3131 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3132 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3133 // already be zero by virtue of the width of the base type of the load. 3134 // 3135 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3136 // more cases. 3137 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3138 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3139 N0.getOperand(0).getOpcode() == ISD::LOAD && 3140 N0.getOperand(0).getResNo() == 0) || 3141 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3142 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3143 N0 : N0.getOperand(0) ); 3144 3145 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3146 // This can be a pure constant or a vector splat, in which case we treat the 3147 // vector as a scalar and use the splat value. 3148 APInt Constant = APInt::getNullValue(1); 3149 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3150 Constant = C->getAPIntValue(); 3151 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3152 APInt SplatValue, SplatUndef; 3153 unsigned SplatBitSize; 3154 bool HasAnyUndefs; 3155 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3156 SplatBitSize, HasAnyUndefs); 3157 if (IsSplat) { 3158 // Undef bits can contribute to a possible optimisation if set, so 3159 // set them. 3160 SplatValue |= SplatUndef; 3161 3162 // The splat value may be something like "0x00FFFFFF", which means 0 for 3163 // the first vector value and FF for the rest, repeating. We need a mask 3164 // that will apply equally to all members of the vector, so AND all the 3165 // lanes of the constant together. 3166 EVT VT = Vector->getValueType(0); 3167 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3168 3169 // If the splat value has been compressed to a bitlength lower 3170 // than the size of the vector lane, we need to re-expand it to 3171 // the lane size. 3172 if (BitWidth > SplatBitSize) 3173 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3174 SplatBitSize < BitWidth; 3175 SplatBitSize = SplatBitSize * 2) 3176 SplatValue |= SplatValue.shl(SplatBitSize); 3177 3178 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3179 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3180 if (SplatBitSize % BitWidth == 0) { 3181 Constant = APInt::getAllOnesValue(BitWidth); 3182 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3183 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3184 } 3185 } 3186 } 3187 3188 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3189 // actually legal and isn't going to get expanded, else this is a false 3190 // optimisation. 3191 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3192 Load->getValueType(0), 3193 Load->getMemoryVT()); 3194 3195 // Resize the constant to the same size as the original memory access before 3196 // extension. If it is still the AllOnesValue then this AND is completely 3197 // unneeded. 3198 Constant = 3199 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3200 3201 bool B; 3202 switch (Load->getExtensionType()) { 3203 default: B = false; break; 3204 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3205 case ISD::ZEXTLOAD: 3206 case ISD::NON_EXTLOAD: B = true; break; 3207 } 3208 3209 if (B && Constant.isAllOnesValue()) { 3210 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3211 // preserve semantics once we get rid of the AND. 3212 SDValue NewLoad(Load, 0); 3213 if (Load->getExtensionType() == ISD::EXTLOAD) { 3214 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3215 Load->getValueType(0), SDLoc(Load), 3216 Load->getChain(), Load->getBasePtr(), 3217 Load->getOffset(), Load->getMemoryVT(), 3218 Load->getMemOperand()); 3219 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3220 if (Load->getNumValues() == 3) { 3221 // PRE/POST_INC loads have 3 values. 3222 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3223 NewLoad.getValue(2) }; 3224 CombineTo(Load, To, 3, true); 3225 } else { 3226 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3227 } 3228 } 3229 3230 // Fold the AND away, taking care not to fold to the old load node if we 3231 // replaced it. 3232 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3233 3234 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3235 } 3236 } 3237 3238 // fold (and (load x), 255) -> (zextload x, i8) 3239 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3240 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3241 if (N1C && (N0.getOpcode() == ISD::LOAD || 3242 (N0.getOpcode() == ISD::ANY_EXTEND && 3243 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3244 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3245 LoadSDNode *LN0 = HasAnyExt 3246 ? cast<LoadSDNode>(N0.getOperand(0)) 3247 : cast<LoadSDNode>(N0); 3248 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3249 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3250 auto NarrowLoad = false; 3251 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3252 EVT ExtVT, LoadedVT; 3253 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3254 NarrowLoad)) { 3255 if (!NarrowLoad) { 3256 SDValue NewLoad = 3257 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3258 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3259 LN0->getMemOperand()); 3260 AddToWorklist(N); 3261 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3262 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3263 } else { 3264 EVT PtrType = LN0->getOperand(1).getValueType(); 3265 3266 unsigned Alignment = LN0->getAlignment(); 3267 SDValue NewPtr = LN0->getBasePtr(); 3268 3269 // For big endian targets, we need to add an offset to the pointer 3270 // to load the correct bytes. For little endian systems, we merely 3271 // need to read fewer bytes from the same pointer. 3272 if (DAG.getDataLayout().isBigEndian()) { 3273 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3274 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3275 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3276 SDLoc DL(LN0); 3277 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3278 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3279 Alignment = MinAlign(Alignment, PtrOff); 3280 } 3281 3282 AddToWorklist(NewPtr.getNode()); 3283 3284 SDValue Load = DAG.getExtLoad( 3285 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3286 LN0->getPointerInfo(), ExtVT, Alignment, 3287 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3288 AddToWorklist(N); 3289 CombineTo(LN0, Load, Load.getValue(1)); 3290 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3291 } 3292 } 3293 } 3294 } 3295 3296 if (SDValue Combined = visitANDLike(N0, N1, N)) 3297 return Combined; 3298 3299 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3300 if (N0.getOpcode() == N1.getOpcode()) 3301 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3302 return Tmp; 3303 3304 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3305 // fold (and (sra)) -> (and (srl)) when possible. 3306 if (!VT.isVector() && 3307 SimplifyDemandedBits(SDValue(N, 0))) 3308 return SDValue(N, 0); 3309 3310 // fold (zext_inreg (extload x)) -> (zextload x) 3311 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3312 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3313 EVT MemVT = LN0->getMemoryVT(); 3314 // If we zero all the possible extended bits, then we can turn this into 3315 // a zextload if we are running before legalize or the operation is legal. 3316 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3317 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3318 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3319 ((!LegalOperations && !LN0->isVolatile()) || 3320 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3321 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3322 LN0->getChain(), LN0->getBasePtr(), 3323 MemVT, LN0->getMemOperand()); 3324 AddToWorklist(N); 3325 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3326 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3327 } 3328 } 3329 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3330 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3331 N0.hasOneUse()) { 3332 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3333 EVT MemVT = LN0->getMemoryVT(); 3334 // If we zero all the possible extended bits, then we can turn this into 3335 // a zextload if we are running before legalize or the operation is legal. 3336 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3337 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3338 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3339 ((!LegalOperations && !LN0->isVolatile()) || 3340 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3341 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3342 LN0->getChain(), LN0->getBasePtr(), 3343 MemVT, LN0->getMemOperand()); 3344 AddToWorklist(N); 3345 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3346 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3347 } 3348 } 3349 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3350 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3351 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3352 N0.getOperand(1), false)) 3353 return BSwap; 3354 } 3355 3356 return SDValue(); 3357 } 3358 3359 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3360 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3361 bool DemandHighBits) { 3362 if (!LegalOperations) 3363 return SDValue(); 3364 3365 EVT VT = N->getValueType(0); 3366 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3367 return SDValue(); 3368 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3369 return SDValue(); 3370 3371 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3372 bool LookPassAnd0 = false; 3373 bool LookPassAnd1 = false; 3374 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3375 std::swap(N0, N1); 3376 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3377 std::swap(N0, N1); 3378 if (N0.getOpcode() == ISD::AND) { 3379 if (!N0.getNode()->hasOneUse()) 3380 return SDValue(); 3381 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3382 if (!N01C || N01C->getZExtValue() != 0xFF00) 3383 return SDValue(); 3384 N0 = N0.getOperand(0); 3385 LookPassAnd0 = true; 3386 } 3387 3388 if (N1.getOpcode() == ISD::AND) { 3389 if (!N1.getNode()->hasOneUse()) 3390 return SDValue(); 3391 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3392 if (!N11C || N11C->getZExtValue() != 0xFF) 3393 return SDValue(); 3394 N1 = N1.getOperand(0); 3395 LookPassAnd1 = true; 3396 } 3397 3398 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3399 std::swap(N0, N1); 3400 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3401 return SDValue(); 3402 if (!N0.getNode()->hasOneUse() || 3403 !N1.getNode()->hasOneUse()) 3404 return SDValue(); 3405 3406 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3407 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3408 if (!N01C || !N11C) 3409 return SDValue(); 3410 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3411 return SDValue(); 3412 3413 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3414 SDValue N00 = N0->getOperand(0); 3415 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3416 if (!N00.getNode()->hasOneUse()) 3417 return SDValue(); 3418 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3419 if (!N001C || N001C->getZExtValue() != 0xFF) 3420 return SDValue(); 3421 N00 = N00.getOperand(0); 3422 LookPassAnd0 = true; 3423 } 3424 3425 SDValue N10 = N1->getOperand(0); 3426 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3427 if (!N10.getNode()->hasOneUse()) 3428 return SDValue(); 3429 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3430 if (!N101C || N101C->getZExtValue() != 0xFF00) 3431 return SDValue(); 3432 N10 = N10.getOperand(0); 3433 LookPassAnd1 = true; 3434 } 3435 3436 if (N00 != N10) 3437 return SDValue(); 3438 3439 // Make sure everything beyond the low halfword gets set to zero since the SRL 3440 // 16 will clear the top bits. 3441 unsigned OpSizeInBits = VT.getSizeInBits(); 3442 if (DemandHighBits && OpSizeInBits > 16) { 3443 // If the left-shift isn't masked out then the only way this is a bswap is 3444 // if all bits beyond the low 8 are 0. In that case the entire pattern 3445 // reduces to a left shift anyway: leave it for other parts of the combiner. 3446 if (!LookPassAnd0) 3447 return SDValue(); 3448 3449 // However, if the right shift isn't masked out then it might be because 3450 // it's not needed. See if we can spot that too. 3451 if (!LookPassAnd1 && 3452 !DAG.MaskedValueIsZero( 3453 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3454 return SDValue(); 3455 } 3456 3457 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3458 if (OpSizeInBits > 16) { 3459 SDLoc DL(N); 3460 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3461 DAG.getConstant(OpSizeInBits - 16, DL, 3462 getShiftAmountTy(VT))); 3463 } 3464 return Res; 3465 } 3466 3467 /// Return true if the specified node is an element that makes up a 32-bit 3468 /// packed halfword byteswap. 3469 /// ((x & 0x000000ff) << 8) | 3470 /// ((x & 0x0000ff00) >> 8) | 3471 /// ((x & 0x00ff0000) << 8) | 3472 /// ((x & 0xff000000) >> 8) 3473 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3474 if (!N.getNode()->hasOneUse()) 3475 return false; 3476 3477 unsigned Opc = N.getOpcode(); 3478 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3479 return false; 3480 3481 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3482 if (!N1C) 3483 return false; 3484 3485 unsigned Num; 3486 switch (N1C->getZExtValue()) { 3487 default: 3488 return false; 3489 case 0xFF: Num = 0; break; 3490 case 0xFF00: Num = 1; break; 3491 case 0xFF0000: Num = 2; break; 3492 case 0xFF000000: Num = 3; break; 3493 } 3494 3495 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3496 SDValue N0 = N.getOperand(0); 3497 if (Opc == ISD::AND) { 3498 if (Num == 0 || Num == 2) { 3499 // (x >> 8) & 0xff 3500 // (x >> 8) & 0xff0000 3501 if (N0.getOpcode() != ISD::SRL) 3502 return false; 3503 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3504 if (!C || C->getZExtValue() != 8) 3505 return false; 3506 } else { 3507 // (x << 8) & 0xff00 3508 // (x << 8) & 0xff000000 3509 if (N0.getOpcode() != ISD::SHL) 3510 return false; 3511 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3512 if (!C || C->getZExtValue() != 8) 3513 return false; 3514 } 3515 } else if (Opc == ISD::SHL) { 3516 // (x & 0xff) << 8 3517 // (x & 0xff0000) << 8 3518 if (Num != 0 && Num != 2) 3519 return false; 3520 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3521 if (!C || C->getZExtValue() != 8) 3522 return false; 3523 } else { // Opc == ISD::SRL 3524 // (x & 0xff00) >> 8 3525 // (x & 0xff000000) >> 8 3526 if (Num != 1 && Num != 3) 3527 return false; 3528 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3529 if (!C || C->getZExtValue() != 8) 3530 return false; 3531 } 3532 3533 if (Parts[Num]) 3534 return false; 3535 3536 Parts[Num] = N0.getOperand(0).getNode(); 3537 return true; 3538 } 3539 3540 /// Match a 32-bit packed halfword bswap. That is 3541 /// ((x & 0x000000ff) << 8) | 3542 /// ((x & 0x0000ff00) >> 8) | 3543 /// ((x & 0x00ff0000) << 8) | 3544 /// ((x & 0xff000000) >> 8) 3545 /// => (rotl (bswap x), 16) 3546 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3547 if (!LegalOperations) 3548 return SDValue(); 3549 3550 EVT VT = N->getValueType(0); 3551 if (VT != MVT::i32) 3552 return SDValue(); 3553 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3554 return SDValue(); 3555 3556 // Look for either 3557 // (or (or (and), (and)), (or (and), (and))) 3558 // (or (or (or (and), (and)), (and)), (and)) 3559 if (N0.getOpcode() != ISD::OR) 3560 return SDValue(); 3561 SDValue N00 = N0.getOperand(0); 3562 SDValue N01 = N0.getOperand(1); 3563 SDNode *Parts[4] = {}; 3564 3565 if (N1.getOpcode() == ISD::OR && 3566 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3567 // (or (or (and), (and)), (or (and), (and))) 3568 SDValue N000 = N00.getOperand(0); 3569 if (!isBSwapHWordElement(N000, Parts)) 3570 return SDValue(); 3571 3572 SDValue N001 = N00.getOperand(1); 3573 if (!isBSwapHWordElement(N001, Parts)) 3574 return SDValue(); 3575 SDValue N010 = N01.getOperand(0); 3576 if (!isBSwapHWordElement(N010, Parts)) 3577 return SDValue(); 3578 SDValue N011 = N01.getOperand(1); 3579 if (!isBSwapHWordElement(N011, Parts)) 3580 return SDValue(); 3581 } else { 3582 // (or (or (or (and), (and)), (and)), (and)) 3583 if (!isBSwapHWordElement(N1, Parts)) 3584 return SDValue(); 3585 if (!isBSwapHWordElement(N01, Parts)) 3586 return SDValue(); 3587 if (N00.getOpcode() != ISD::OR) 3588 return SDValue(); 3589 SDValue N000 = N00.getOperand(0); 3590 if (!isBSwapHWordElement(N000, Parts)) 3591 return SDValue(); 3592 SDValue N001 = N00.getOperand(1); 3593 if (!isBSwapHWordElement(N001, Parts)) 3594 return SDValue(); 3595 } 3596 3597 // Make sure the parts are all coming from the same node. 3598 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3599 return SDValue(); 3600 3601 SDLoc DL(N); 3602 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3603 SDValue(Parts[0], 0)); 3604 3605 // Result of the bswap should be rotated by 16. If it's not legal, then 3606 // do (x << 16) | (x >> 16). 3607 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3608 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3609 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3610 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3611 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3612 return DAG.getNode(ISD::OR, DL, VT, 3613 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3614 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3615 } 3616 3617 /// This contains all DAGCombine rules which reduce two values combined by 3618 /// an Or operation to a single value \see visitANDLike(). 3619 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3620 EVT VT = N1.getValueType(); 3621 // fold (or x, undef) -> -1 3622 if (!LegalOperations && 3623 (N0.isUndef() || N1.isUndef())) { 3624 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3625 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3626 SDLoc(LocReference), VT); 3627 } 3628 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3629 SDValue LL, LR, RL, RR, CC0, CC1; 3630 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3631 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3632 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3633 3634 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3635 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3636 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3637 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3638 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3639 LR.getValueType(), LL, RL); 3640 AddToWorklist(ORNode.getNode()); 3641 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3642 } 3643 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3644 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3645 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3646 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3647 LR.getValueType(), LL, RL); 3648 AddToWorklist(ANDNode.getNode()); 3649 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3650 } 3651 } 3652 // canonicalize equivalent to ll == rl 3653 if (LL == RR && LR == RL) { 3654 Op1 = ISD::getSetCCSwappedOperands(Op1); 3655 std::swap(RL, RR); 3656 } 3657 if (LL == RL && LR == RR) { 3658 bool isInteger = LL.getValueType().isInteger(); 3659 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3660 if (Result != ISD::SETCC_INVALID && 3661 (!LegalOperations || 3662 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3663 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3664 EVT CCVT = getSetCCResultType(LL.getValueType()); 3665 if (N0.getValueType() == CCVT || 3666 (!LegalOperations && N0.getValueType() == MVT::i1)) 3667 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3668 LL, LR, Result); 3669 } 3670 } 3671 } 3672 3673 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3674 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3675 // Don't increase # computations. 3676 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3677 // We can only do this xform if we know that bits from X that are set in C2 3678 // but not in C1 are already zero. Likewise for Y. 3679 if (const ConstantSDNode *N0O1C = 3680 getAsNonOpaqueConstant(N0.getOperand(1))) { 3681 if (const ConstantSDNode *N1O1C = 3682 getAsNonOpaqueConstant(N1.getOperand(1))) { 3683 // We can only do this xform if we know that bits from X that are set in 3684 // C2 but not in C1 are already zero. Likewise for Y. 3685 const APInt &LHSMask = N0O1C->getAPIntValue(); 3686 const APInt &RHSMask = N1O1C->getAPIntValue(); 3687 3688 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3689 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3690 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3691 N0.getOperand(0), N1.getOperand(0)); 3692 SDLoc DL(LocReference); 3693 return DAG.getNode(ISD::AND, DL, VT, X, 3694 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3695 } 3696 } 3697 } 3698 } 3699 3700 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3701 if (N0.getOpcode() == ISD::AND && 3702 N1.getOpcode() == ISD::AND && 3703 N0.getOperand(0) == N1.getOperand(0) && 3704 // Don't increase # computations. 3705 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3706 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3707 N0.getOperand(1), N1.getOperand(1)); 3708 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3709 } 3710 3711 return SDValue(); 3712 } 3713 3714 SDValue DAGCombiner::visitOR(SDNode *N) { 3715 SDValue N0 = N->getOperand(0); 3716 SDValue N1 = N->getOperand(1); 3717 EVT VT = N1.getValueType(); 3718 3719 // fold vector ops 3720 if (VT.isVector()) { 3721 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3722 return FoldedVOp; 3723 3724 // fold (or x, 0) -> x, vector edition 3725 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3726 return N1; 3727 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3728 return N0; 3729 3730 // fold (or x, -1) -> -1, vector edition 3731 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3732 // do not return N0, because undef node may exist in N0 3733 return DAG.getConstant( 3734 APInt::getAllOnesValue( 3735 N0.getValueType().getScalarType().getSizeInBits()), 3736 SDLoc(N), N0.getValueType()); 3737 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3738 // do not return N1, because undef node may exist in N1 3739 return DAG.getConstant( 3740 APInt::getAllOnesValue( 3741 N1.getValueType().getScalarType().getSizeInBits()), 3742 SDLoc(N), N1.getValueType()); 3743 3744 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 3745 // Do this only if the resulting shuffle is legal. 3746 if (isa<ShuffleVectorSDNode>(N0) && 3747 isa<ShuffleVectorSDNode>(N1) && 3748 // Avoid folding a node with illegal type. 3749 TLI.isTypeLegal(VT)) { 3750 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 3751 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 3752 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 3753 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 3754 // Ensure both shuffles have a zero input. 3755 if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) { 3756 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 3757 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 3758 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3759 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3760 bool CanFold = true; 3761 int NumElts = VT.getVectorNumElements(); 3762 SmallVector<int, 4> Mask(NumElts); 3763 3764 for (int i = 0; i != NumElts; ++i) { 3765 int M0 = SV0->getMaskElt(i); 3766 int M1 = SV1->getMaskElt(i); 3767 3768 // Determine if either index is pointing to a zero vector. 3769 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 3770 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 3771 3772 // If one element is zero and the otherside is undef, keep undef. 3773 // This also handles the case that both are undef. 3774 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 3775 Mask[i] = -1; 3776 continue; 3777 } 3778 3779 // Make sure only one of the elements is zero. 3780 if (M0Zero == M1Zero) { 3781 CanFold = false; 3782 break; 3783 } 3784 3785 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 3786 3787 // We have a zero and non-zero element. If the non-zero came from 3788 // SV0 make the index a LHS index. If it came from SV1, make it 3789 // a RHS index. We need to mod by NumElts because we don't care 3790 // which operand it came from in the original shuffles. 3791 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 3792 } 3793 3794 if (CanFold) { 3795 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 3796 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 3797 3798 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3799 if (!LegalMask) { 3800 std::swap(NewLHS, NewRHS); 3801 ShuffleVectorSDNode::commuteMask(Mask); 3802 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3803 } 3804 3805 if (LegalMask) 3806 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 3807 } 3808 } 3809 } 3810 } 3811 3812 // fold (or c1, c2) -> c1|c2 3813 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3814 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3815 if (N0C && N1C && !N1C->isOpaque()) 3816 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3817 // canonicalize constant to RHS 3818 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3819 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3820 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3821 // fold (or x, 0) -> x 3822 if (isNullConstant(N1)) 3823 return N0; 3824 // fold (or x, -1) -> -1 3825 if (isAllOnesConstant(N1)) 3826 return N1; 3827 // fold (or x, c) -> c iff (x & ~c) == 0 3828 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3829 return N1; 3830 3831 if (SDValue Combined = visitORLike(N0, N1, N)) 3832 return Combined; 3833 3834 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3835 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3836 return BSwap; 3837 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3838 return BSwap; 3839 3840 // reassociate or 3841 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3842 return ROR; 3843 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3844 // iff (c1 & c2) == 0. 3845 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3846 isa<ConstantSDNode>(N0.getOperand(1))) { 3847 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3848 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3849 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3850 N1C, C1)) 3851 return DAG.getNode( 3852 ISD::AND, SDLoc(N), VT, 3853 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3854 return SDValue(); 3855 } 3856 } 3857 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3858 if (N0.getOpcode() == N1.getOpcode()) 3859 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3860 return Tmp; 3861 3862 // See if this is some rotate idiom. 3863 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3864 return SDValue(Rot, 0); 3865 3866 // Simplify the operands using demanded-bits information. 3867 if (!VT.isVector() && 3868 SimplifyDemandedBits(SDValue(N, 0))) 3869 return SDValue(N, 0); 3870 3871 return SDValue(); 3872 } 3873 3874 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3875 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3876 if (Op.getOpcode() == ISD::AND) { 3877 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3878 Mask = Op.getOperand(1); 3879 Op = Op.getOperand(0); 3880 } else { 3881 return false; 3882 } 3883 } 3884 3885 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3886 Shift = Op; 3887 return true; 3888 } 3889 3890 return false; 3891 } 3892 3893 // Return true if we can prove that, whenever Neg and Pos are both in the 3894 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 3895 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3896 // 3897 // (or (shift1 X, Neg), (shift2 X, Pos)) 3898 // 3899 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3900 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 3901 // to consider shift amounts with defined behavior. 3902 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 3903 // If EltSize is a power of 2 then: 3904 // 3905 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 3906 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 3907 // 3908 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 3909 // for the stronger condition: 3910 // 3911 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 3912 // 3913 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 3914 // we can just replace Neg with Neg' for the rest of the function. 3915 // 3916 // In other cases we check for the even stronger condition: 3917 // 3918 // Neg == EltSize - Pos [B] 3919 // 3920 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3921 // behavior if Pos == 0 (and consequently Neg == EltSize). 3922 // 3923 // We could actually use [A] whenever EltSize is a power of 2, but the 3924 // only extra cases that it would match are those uninteresting ones 3925 // where Neg and Pos are never in range at the same time. E.g. for 3926 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3927 // as well as (sub 32, Pos), but: 3928 // 3929 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3930 // 3931 // always invokes undefined behavior for 32-bit X. 3932 // 3933 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 3934 unsigned MaskLoBits = 0; 3935 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 3936 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 3937 if (NegC->getAPIntValue() == EltSize - 1) { 3938 Neg = Neg.getOperand(0); 3939 MaskLoBits = Log2_64(EltSize); 3940 } 3941 } 3942 } 3943 3944 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3945 if (Neg.getOpcode() != ISD::SUB) 3946 return false; 3947 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 3948 if (!NegC) 3949 return false; 3950 SDValue NegOp1 = Neg.getOperand(1); 3951 3952 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 3953 // Pos'. The truncation is redundant for the purpose of the equality. 3954 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 3955 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3956 if (PosC->getAPIntValue() == EltSize - 1) 3957 Pos = Pos.getOperand(0); 3958 3959 // The condition we need is now: 3960 // 3961 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 3962 // 3963 // If NegOp1 == Pos then we need: 3964 // 3965 // EltSize & Mask == NegC & Mask 3966 // 3967 // (because "x & Mask" is a truncation and distributes through subtraction). 3968 APInt Width; 3969 if (Pos == NegOp1) 3970 Width = NegC->getAPIntValue(); 3971 3972 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3973 // Then the condition we want to prove becomes: 3974 // 3975 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 3976 // 3977 // which, again because "x & Mask" is a truncation, becomes: 3978 // 3979 // NegC & Mask == (EltSize - PosC) & Mask 3980 // EltSize & Mask == (NegC + PosC) & Mask 3981 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 3982 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3983 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 3984 else 3985 return false; 3986 } else 3987 return false; 3988 3989 // Now we just need to check that EltSize & Mask == Width & Mask. 3990 if (MaskLoBits) 3991 // EltSize & Mask is 0 since Mask is EltSize - 1. 3992 return Width.getLoBits(MaskLoBits) == 0; 3993 return Width == EltSize; 3994 } 3995 3996 // A subroutine of MatchRotate used once we have found an OR of two opposite 3997 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3998 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3999 // former being preferred if supported. InnerPos and InnerNeg are Pos and 4000 // Neg with outer conversions stripped away. 4001 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4002 SDValue Neg, SDValue InnerPos, 4003 SDValue InnerNeg, unsigned PosOpcode, 4004 unsigned NegOpcode, const SDLoc &DL) { 4005 // fold (or (shl x, (*ext y)), 4006 // (srl x, (*ext (sub 32, y)))) -> 4007 // (rotl x, y) or (rotr x, (sub 32, y)) 4008 // 4009 // fold (or (shl x, (*ext (sub 32, y))), 4010 // (srl x, (*ext y))) -> 4011 // (rotr x, y) or (rotl x, (sub 32, y)) 4012 EVT VT = Shifted.getValueType(); 4013 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4014 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4015 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4016 HasPos ? Pos : Neg).getNode(); 4017 } 4018 4019 return nullptr; 4020 } 4021 4022 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4023 // idioms for rotate, and if the target supports rotation instructions, generate 4024 // a rot[lr]. 4025 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4026 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4027 EVT VT = LHS.getValueType(); 4028 if (!TLI.isTypeLegal(VT)) return nullptr; 4029 4030 // The target must have at least one rotate flavor. 4031 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4032 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4033 if (!HasROTL && !HasROTR) return nullptr; 4034 4035 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4036 SDValue LHSShift; // The shift. 4037 SDValue LHSMask; // AND value if any. 4038 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4039 return nullptr; // Not part of a rotate. 4040 4041 SDValue RHSShift; // The shift. 4042 SDValue RHSMask; // AND value if any. 4043 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4044 return nullptr; // Not part of a rotate. 4045 4046 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4047 return nullptr; // Not shifting the same value. 4048 4049 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4050 return nullptr; // Shifts must disagree. 4051 4052 // Canonicalize shl to left side in a shl/srl pair. 4053 if (RHSShift.getOpcode() == ISD::SHL) { 4054 std::swap(LHS, RHS); 4055 std::swap(LHSShift, RHSShift); 4056 std::swap(LHSMask, RHSMask); 4057 } 4058 4059 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4060 SDValue LHSShiftArg = LHSShift.getOperand(0); 4061 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4062 SDValue RHSShiftArg = RHSShift.getOperand(0); 4063 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4064 4065 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4066 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4067 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4068 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4069 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4070 if ((LShVal + RShVal) != EltSizeInBits) 4071 return nullptr; 4072 4073 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4074 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4075 4076 // If there is an AND of either shifted operand, apply it to the result. 4077 if (LHSMask.getNode() || RHSMask.getNode()) { 4078 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4079 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4080 4081 if (LHSMask.getNode()) { 4082 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4083 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4084 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4085 DAG.getConstant(RHSBits, DL, VT))); 4086 } 4087 if (RHSMask.getNode()) { 4088 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4089 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4090 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4091 DAG.getConstant(LHSBits, DL, VT))); 4092 } 4093 4094 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4095 } 4096 4097 return Rot.getNode(); 4098 } 4099 4100 // If there is a mask here, and we have a variable shift, we can't be sure 4101 // that we're masking out the right stuff. 4102 if (LHSMask.getNode() || RHSMask.getNode()) 4103 return nullptr; 4104 4105 // If the shift amount is sign/zext/any-extended just peel it off. 4106 SDValue LExtOp0 = LHSShiftAmt; 4107 SDValue RExtOp0 = RHSShiftAmt; 4108 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4109 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4110 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4111 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4112 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4113 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4114 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4115 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4116 LExtOp0 = LHSShiftAmt.getOperand(0); 4117 RExtOp0 = RHSShiftAmt.getOperand(0); 4118 } 4119 4120 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4121 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4122 if (TryL) 4123 return TryL; 4124 4125 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4126 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4127 if (TryR) 4128 return TryR; 4129 4130 return nullptr; 4131 } 4132 4133 SDValue DAGCombiner::visitXOR(SDNode *N) { 4134 SDValue N0 = N->getOperand(0); 4135 SDValue N1 = N->getOperand(1); 4136 EVT VT = N0.getValueType(); 4137 4138 // fold vector ops 4139 if (VT.isVector()) { 4140 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4141 return FoldedVOp; 4142 4143 // fold (xor x, 0) -> x, vector edition 4144 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4145 return N1; 4146 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4147 return N0; 4148 } 4149 4150 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4151 if (N0.isUndef() && N1.isUndef()) 4152 return DAG.getConstant(0, SDLoc(N), VT); 4153 // fold (xor x, undef) -> undef 4154 if (N0.isUndef()) 4155 return N0; 4156 if (N1.isUndef()) 4157 return N1; 4158 // fold (xor c1, c2) -> c1^c2 4159 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4160 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4161 if (N0C && N1C) 4162 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4163 // canonicalize constant to RHS 4164 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4165 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4166 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4167 // fold (xor x, 0) -> x 4168 if (isNullConstant(N1)) 4169 return N0; 4170 // reassociate xor 4171 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4172 return RXOR; 4173 4174 // fold !(x cc y) -> (x !cc y) 4175 SDValue LHS, RHS, CC; 4176 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4177 bool isInt = LHS.getValueType().isInteger(); 4178 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4179 isInt); 4180 4181 if (!LegalOperations || 4182 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4183 switch (N0.getOpcode()) { 4184 default: 4185 llvm_unreachable("Unhandled SetCC Equivalent!"); 4186 case ISD::SETCC: 4187 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4188 case ISD::SELECT_CC: 4189 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4190 N0.getOperand(3), NotCC); 4191 } 4192 } 4193 } 4194 4195 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4196 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4197 N0.getNode()->hasOneUse() && 4198 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4199 SDValue V = N0.getOperand(0); 4200 SDLoc DL(N0); 4201 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4202 DAG.getConstant(1, DL, V.getValueType())); 4203 AddToWorklist(V.getNode()); 4204 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4205 } 4206 4207 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4208 if (isOneConstant(N1) && VT == MVT::i1 && 4209 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4210 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4211 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4212 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4213 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4214 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4215 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4216 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4217 } 4218 } 4219 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4220 if (isAllOnesConstant(N1) && 4221 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4222 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4223 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4224 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4225 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4226 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4227 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4228 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4229 } 4230 } 4231 // fold (xor (and x, y), y) -> (and (not x), y) 4232 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4233 N0->getOperand(1) == N1) { 4234 SDValue X = N0->getOperand(0); 4235 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4236 AddToWorklist(NotX.getNode()); 4237 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4238 } 4239 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4240 if (N1C && N0.getOpcode() == ISD::XOR) { 4241 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4242 SDLoc DL(N); 4243 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4244 DAG.getConstant(N1C->getAPIntValue() ^ 4245 N00C->getAPIntValue(), DL, VT)); 4246 } 4247 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4248 SDLoc DL(N); 4249 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4250 DAG.getConstant(N1C->getAPIntValue() ^ 4251 N01C->getAPIntValue(), DL, VT)); 4252 } 4253 } 4254 // fold (xor x, x) -> 0 4255 if (N0 == N1) 4256 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4257 4258 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4259 // Here is a concrete example of this equivalence: 4260 // i16 x == 14 4261 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4262 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4263 // 4264 // => 4265 // 4266 // i16 ~1 == 0b1111111111111110 4267 // i16 rol(~1, 14) == 0b1011111111111111 4268 // 4269 // Some additional tips to help conceptualize this transform: 4270 // - Try to see the operation as placing a single zero in a value of all ones. 4271 // - There exists no value for x which would allow the result to contain zero. 4272 // - Values of x larger than the bitwidth are undefined and do not require a 4273 // consistent result. 4274 // - Pushing the zero left requires shifting one bits in from the right. 4275 // A rotate left of ~1 is a nice way of achieving the desired result. 4276 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4277 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4278 SDLoc DL(N); 4279 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4280 N0.getOperand(1)); 4281 } 4282 4283 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4284 if (N0.getOpcode() == N1.getOpcode()) 4285 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4286 return Tmp; 4287 4288 // Simplify the expression using non-local knowledge. 4289 if (!VT.isVector() && 4290 SimplifyDemandedBits(SDValue(N, 0))) 4291 return SDValue(N, 0); 4292 4293 return SDValue(); 4294 } 4295 4296 /// Handle transforms common to the three shifts, when the shift amount is a 4297 /// constant. 4298 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4299 SDNode *LHS = N->getOperand(0).getNode(); 4300 if (!LHS->hasOneUse()) return SDValue(); 4301 4302 // We want to pull some binops through shifts, so that we have (and (shift)) 4303 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4304 // thing happens with address calculations, so it's important to canonicalize 4305 // it. 4306 bool HighBitSet = false; // Can we transform this if the high bit is set? 4307 4308 switch (LHS->getOpcode()) { 4309 default: return SDValue(); 4310 case ISD::OR: 4311 case ISD::XOR: 4312 HighBitSet = false; // We can only transform sra if the high bit is clear. 4313 break; 4314 case ISD::AND: 4315 HighBitSet = true; // We can only transform sra if the high bit is set. 4316 break; 4317 case ISD::ADD: 4318 if (N->getOpcode() != ISD::SHL) 4319 return SDValue(); // only shl(add) not sr[al](add). 4320 HighBitSet = false; // We can only transform sra if the high bit is clear. 4321 break; 4322 } 4323 4324 // We require the RHS of the binop to be a constant and not opaque as well. 4325 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4326 if (!BinOpCst) return SDValue(); 4327 4328 // FIXME: disable this unless the input to the binop is a shift by a constant. 4329 // If it is not a shift, it pessimizes some common cases like: 4330 // 4331 // void foo(int *X, int i) { X[i & 1235] = 1; } 4332 // int bar(int *X, int i) { return X[i & 255]; } 4333 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4334 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4335 BinOpLHSVal->getOpcode() != ISD::SRA && 4336 BinOpLHSVal->getOpcode() != ISD::SRL) || 4337 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4338 return SDValue(); 4339 4340 EVT VT = N->getValueType(0); 4341 4342 // If this is a signed shift right, and the high bit is modified by the 4343 // logical operation, do not perform the transformation. The highBitSet 4344 // boolean indicates the value of the high bit of the constant which would 4345 // cause it to be modified for this operation. 4346 if (N->getOpcode() == ISD::SRA) { 4347 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4348 if (BinOpRHSSignSet != HighBitSet) 4349 return SDValue(); 4350 } 4351 4352 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4353 return SDValue(); 4354 4355 // Fold the constants, shifting the binop RHS by the shift amount. 4356 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4357 N->getValueType(0), 4358 LHS->getOperand(1), N->getOperand(1)); 4359 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4360 4361 // Create the new shift. 4362 SDValue NewShift = DAG.getNode(N->getOpcode(), 4363 SDLoc(LHS->getOperand(0)), 4364 VT, LHS->getOperand(0), N->getOperand(1)); 4365 4366 // Create the new binop. 4367 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4368 } 4369 4370 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4371 assert(N->getOpcode() == ISD::TRUNCATE); 4372 assert(N->getOperand(0).getOpcode() == ISD::AND); 4373 4374 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4375 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4376 SDValue N01 = N->getOperand(0).getOperand(1); 4377 4378 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4379 if (!N01C->isOpaque()) { 4380 EVT TruncVT = N->getValueType(0); 4381 SDValue N00 = N->getOperand(0).getOperand(0); 4382 APInt TruncC = N01C->getAPIntValue(); 4383 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4384 SDLoc DL(N); 4385 4386 return DAG.getNode(ISD::AND, DL, TruncVT, 4387 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4388 DAG.getConstant(TruncC, DL, TruncVT)); 4389 } 4390 } 4391 } 4392 4393 return SDValue(); 4394 } 4395 4396 SDValue DAGCombiner::visitRotate(SDNode *N) { 4397 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4398 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4399 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4400 if (SDValue NewOp1 = 4401 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 4402 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4403 N->getOperand(0), NewOp1); 4404 } 4405 return SDValue(); 4406 } 4407 4408 SDValue DAGCombiner::visitSHL(SDNode *N) { 4409 SDValue N0 = N->getOperand(0); 4410 SDValue N1 = N->getOperand(1); 4411 EVT VT = N0.getValueType(); 4412 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4413 4414 // fold vector ops 4415 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4416 if (VT.isVector()) { 4417 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4418 return FoldedVOp; 4419 4420 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4421 // If setcc produces all-one true value then: 4422 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4423 if (N1CV && N1CV->isConstant()) { 4424 if (N0.getOpcode() == ISD::AND) { 4425 SDValue N00 = N0->getOperand(0); 4426 SDValue N01 = N0->getOperand(1); 4427 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4428 4429 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4430 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4431 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4432 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4433 N01CV, N1CV)) 4434 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4435 } 4436 } else { 4437 N1C = isConstOrConstSplat(N1); 4438 } 4439 } 4440 } 4441 4442 // fold (shl c1, c2) -> c1<<c2 4443 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4444 if (N0C && N1C && !N1C->isOpaque()) 4445 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4446 // fold (shl 0, x) -> 0 4447 if (isNullConstant(N0)) 4448 return N0; 4449 // fold (shl x, c >= size(x)) -> undef 4450 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4451 return DAG.getUNDEF(VT); 4452 // fold (shl x, 0) -> x 4453 if (N1C && N1C->isNullValue()) 4454 return N0; 4455 // fold (shl undef, x) -> 0 4456 if (N0.isUndef()) 4457 return DAG.getConstant(0, SDLoc(N), VT); 4458 // if (shl x, c) is known to be zero, return 0 4459 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4460 APInt::getAllOnesValue(OpSizeInBits))) 4461 return DAG.getConstant(0, SDLoc(N), VT); 4462 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4463 if (N1.getOpcode() == ISD::TRUNCATE && 4464 N1.getOperand(0).getOpcode() == ISD::AND) { 4465 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4466 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4467 } 4468 4469 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4470 return SDValue(N, 0); 4471 4472 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4473 if (N1C && N0.getOpcode() == ISD::SHL) { 4474 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4475 SDLoc DL(N); 4476 APInt c1 = N0C1->getAPIntValue(); 4477 APInt c2 = N1C->getAPIntValue(); 4478 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4479 4480 APInt Sum = c1 + c2; 4481 if (Sum.uge(OpSizeInBits)) 4482 return DAG.getConstant(0, DL, VT); 4483 4484 return DAG.getNode( 4485 ISD::SHL, DL, VT, N0.getOperand(0), 4486 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4487 } 4488 } 4489 4490 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4491 // For this to be valid, the second form must not preserve any of the bits 4492 // that are shifted out by the inner shift in the first form. This means 4493 // the outer shift size must be >= the number of bits added by the ext. 4494 // As a corollary, we don't care what kind of ext it is. 4495 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4496 N0.getOpcode() == ISD::ANY_EXTEND || 4497 N0.getOpcode() == ISD::SIGN_EXTEND) && 4498 N0.getOperand(0).getOpcode() == ISD::SHL) { 4499 SDValue N0Op0 = N0.getOperand(0); 4500 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4501 uint64_t c1 = N0Op0C1->getZExtValue(); 4502 uint64_t c2 = N1C->getZExtValue(); 4503 EVT InnerShiftVT = N0Op0.getValueType(); 4504 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4505 if (c2 >= OpSizeInBits - InnerShiftSize) { 4506 SDLoc DL(N0); 4507 if (c1 + c2 >= OpSizeInBits) 4508 return DAG.getConstant(0, DL, VT); 4509 return DAG.getNode(ISD::SHL, DL, VT, 4510 DAG.getNode(N0.getOpcode(), DL, VT, 4511 N0Op0->getOperand(0)), 4512 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4513 } 4514 } 4515 } 4516 4517 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4518 // Only fold this if the inner zext has no other uses to avoid increasing 4519 // the total number of instructions. 4520 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4521 N0.getOperand(0).getOpcode() == ISD::SRL) { 4522 SDValue N0Op0 = N0.getOperand(0); 4523 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4524 uint64_t c1 = N0Op0C1->getZExtValue(); 4525 if (c1 < VT.getScalarSizeInBits()) { 4526 uint64_t c2 = N1C->getZExtValue(); 4527 if (c1 == c2) { 4528 SDValue NewOp0 = N0.getOperand(0); 4529 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4530 SDLoc DL(N); 4531 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4532 NewOp0, 4533 DAG.getConstant(c2, DL, CountVT)); 4534 AddToWorklist(NewSHL.getNode()); 4535 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4536 } 4537 } 4538 } 4539 } 4540 4541 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4542 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4543 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4544 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4545 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4546 uint64_t C1 = N0C1->getZExtValue(); 4547 uint64_t C2 = N1C->getZExtValue(); 4548 SDLoc DL(N); 4549 if (C1 <= C2) 4550 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4551 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4552 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4553 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4554 } 4555 } 4556 4557 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4558 // (and (srl x, (sub c1, c2), MASK) 4559 // Only fold this if the inner shift has no other uses -- if it does, folding 4560 // this will increase the total number of instructions. 4561 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4562 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4563 uint64_t c1 = N0C1->getZExtValue(); 4564 if (c1 < OpSizeInBits) { 4565 uint64_t c2 = N1C->getZExtValue(); 4566 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4567 SDValue Shift; 4568 if (c2 > c1) { 4569 Mask = Mask.shl(c2 - c1); 4570 SDLoc DL(N); 4571 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4572 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4573 } else { 4574 Mask = Mask.lshr(c1 - c2); 4575 SDLoc DL(N); 4576 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4577 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4578 } 4579 SDLoc DL(N0); 4580 return DAG.getNode(ISD::AND, DL, VT, Shift, 4581 DAG.getConstant(Mask, DL, VT)); 4582 } 4583 } 4584 } 4585 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4586 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4587 unsigned BitSize = VT.getScalarSizeInBits(); 4588 SDLoc DL(N); 4589 SDValue HiBitsMask = 4590 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4591 BitSize - N1C->getZExtValue()), 4592 DL, VT); 4593 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4594 HiBitsMask); 4595 } 4596 4597 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4598 // Variant of version done on multiply, except mul by a power of 2 is turned 4599 // into a shift. 4600 APInt Val; 4601 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4602 (isa<ConstantSDNode>(N0.getOperand(1)) || 4603 ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4604 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4605 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4606 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4607 } 4608 4609 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4610 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4611 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4612 if (SDValue Folded = 4613 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4614 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4615 } 4616 } 4617 4618 if (N1C && !N1C->isOpaque()) 4619 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4620 return NewSHL; 4621 4622 return SDValue(); 4623 } 4624 4625 SDValue DAGCombiner::visitSRA(SDNode *N) { 4626 SDValue N0 = N->getOperand(0); 4627 SDValue N1 = N->getOperand(1); 4628 EVT VT = N0.getValueType(); 4629 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4630 4631 // fold vector ops 4632 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4633 if (VT.isVector()) { 4634 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4635 return FoldedVOp; 4636 4637 N1C = isConstOrConstSplat(N1); 4638 } 4639 4640 // fold (sra c1, c2) -> (sra c1, c2) 4641 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4642 if (N0C && N1C && !N1C->isOpaque()) 4643 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4644 // fold (sra 0, x) -> 0 4645 if (isNullConstant(N0)) 4646 return N0; 4647 // fold (sra -1, x) -> -1 4648 if (isAllOnesConstant(N0)) 4649 return N0; 4650 // fold (sra x, c >= size(x)) -> undef 4651 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4652 return DAG.getUNDEF(VT); 4653 // fold (sra x, 0) -> x 4654 if (N1C && N1C->isNullValue()) 4655 return N0; 4656 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4657 // sext_inreg. 4658 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4659 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4660 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4661 if (VT.isVector()) 4662 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4663 ExtVT, VT.getVectorNumElements()); 4664 if ((!LegalOperations || 4665 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4666 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4667 N0.getOperand(0), DAG.getValueType(ExtVT)); 4668 } 4669 4670 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4671 if (N1C && N0.getOpcode() == ISD::SRA) { 4672 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4673 SDLoc DL(N); 4674 APInt c1 = N0C1->getAPIntValue(); 4675 APInt c2 = N1C->getAPIntValue(); 4676 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4677 4678 APInt Sum = c1 + c2; 4679 if (Sum.uge(OpSizeInBits)) 4680 Sum = APInt(OpSizeInBits, OpSizeInBits - 1); 4681 4682 return DAG.getNode( 4683 ISD::SRA, DL, VT, N0.getOperand(0), 4684 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4685 } 4686 } 4687 4688 // fold (sra (shl X, m), (sub result_size, n)) 4689 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4690 // result_size - n != m. 4691 // If truncate is free for the target sext(shl) is likely to result in better 4692 // code. 4693 if (N0.getOpcode() == ISD::SHL && N1C) { 4694 // Get the two constanst of the shifts, CN0 = m, CN = n. 4695 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4696 if (N01C) { 4697 LLVMContext &Ctx = *DAG.getContext(); 4698 // Determine what the truncate's result bitsize and type would be. 4699 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4700 4701 if (VT.isVector()) 4702 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4703 4704 // Determine the residual right-shift amount. 4705 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4706 4707 // If the shift is not a no-op (in which case this should be just a sign 4708 // extend already), the truncated to type is legal, sign_extend is legal 4709 // on that type, and the truncate to that type is both legal and free, 4710 // perform the transform. 4711 if ((ShiftAmt > 0) && 4712 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4713 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4714 TLI.isTruncateFree(VT, TruncVT)) { 4715 4716 SDLoc DL(N); 4717 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4718 getShiftAmountTy(N0.getOperand(0).getValueType())); 4719 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4720 N0.getOperand(0), Amt); 4721 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4722 Shift); 4723 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4724 N->getValueType(0), Trunc); 4725 } 4726 } 4727 } 4728 4729 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4730 if (N1.getOpcode() == ISD::TRUNCATE && 4731 N1.getOperand(0).getOpcode() == ISD::AND) { 4732 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4733 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4734 } 4735 4736 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4737 // if c1 is equal to the number of bits the trunc removes 4738 if (N0.getOpcode() == ISD::TRUNCATE && 4739 (N0.getOperand(0).getOpcode() == ISD::SRL || 4740 N0.getOperand(0).getOpcode() == ISD::SRA) && 4741 N0.getOperand(0).hasOneUse() && 4742 N0.getOperand(0).getOperand(1).hasOneUse() && 4743 N1C) { 4744 SDValue N0Op0 = N0.getOperand(0); 4745 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4746 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4747 EVT LargeVT = N0Op0.getValueType(); 4748 4749 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4750 SDLoc DL(N); 4751 SDValue Amt = 4752 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4753 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4754 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4755 N0Op0.getOperand(0), Amt); 4756 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4757 } 4758 } 4759 } 4760 4761 // Simplify, based on bits shifted out of the LHS. 4762 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4763 return SDValue(N, 0); 4764 4765 4766 // If the sign bit is known to be zero, switch this to a SRL. 4767 if (DAG.SignBitIsZero(N0)) 4768 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4769 4770 if (N1C && !N1C->isOpaque()) 4771 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4772 return NewSRA; 4773 4774 return SDValue(); 4775 } 4776 4777 SDValue DAGCombiner::visitSRL(SDNode *N) { 4778 SDValue N0 = N->getOperand(0); 4779 SDValue N1 = N->getOperand(1); 4780 EVT VT = N0.getValueType(); 4781 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4782 4783 // fold vector ops 4784 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4785 if (VT.isVector()) { 4786 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4787 return FoldedVOp; 4788 4789 N1C = isConstOrConstSplat(N1); 4790 } 4791 4792 // fold (srl c1, c2) -> c1 >>u c2 4793 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4794 if (N0C && N1C && !N1C->isOpaque()) 4795 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4796 // fold (srl 0, x) -> 0 4797 if (isNullConstant(N0)) 4798 return N0; 4799 // fold (srl x, c >= size(x)) -> undef 4800 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4801 return DAG.getUNDEF(VT); 4802 // fold (srl x, 0) -> x 4803 if (N1C && N1C->isNullValue()) 4804 return N0; 4805 // if (srl x, c) is known to be zero, return 0 4806 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4807 APInt::getAllOnesValue(OpSizeInBits))) 4808 return DAG.getConstant(0, SDLoc(N), VT); 4809 4810 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4811 if (N1C && N0.getOpcode() == ISD::SRL) { 4812 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4813 SDLoc DL(N); 4814 APInt c1 = N0C1->getAPIntValue(); 4815 APInt c2 = N1C->getAPIntValue(); 4816 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 4817 4818 APInt Sum = c1 + c2; 4819 if (Sum.uge(OpSizeInBits)) 4820 return DAG.getConstant(0, DL, VT); 4821 4822 return DAG.getNode( 4823 ISD::SRL, DL, VT, N0.getOperand(0), 4824 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 4825 } 4826 } 4827 4828 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4829 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4830 N0.getOperand(0).getOpcode() == ISD::SRL && 4831 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4832 uint64_t c1 = 4833 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4834 uint64_t c2 = N1C->getZExtValue(); 4835 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4836 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4837 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4838 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4839 if (c1 + OpSizeInBits == InnerShiftSize) { 4840 SDLoc DL(N0); 4841 if (c1 + c2 >= InnerShiftSize) 4842 return DAG.getConstant(0, DL, VT); 4843 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4844 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4845 N0.getOperand(0)->getOperand(0), 4846 DAG.getConstant(c1 + c2, DL, 4847 ShiftCountVT))); 4848 } 4849 } 4850 4851 // fold (srl (shl x, c), c) -> (and x, cst2) 4852 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4853 unsigned BitSize = N0.getScalarValueSizeInBits(); 4854 if (BitSize <= 64) { 4855 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4856 SDLoc DL(N); 4857 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4858 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4859 } 4860 } 4861 4862 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4863 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4864 // Shifting in all undef bits? 4865 EVT SmallVT = N0.getOperand(0).getValueType(); 4866 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4867 if (N1C->getZExtValue() >= BitSize) 4868 return DAG.getUNDEF(VT); 4869 4870 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4871 uint64_t ShiftAmt = N1C->getZExtValue(); 4872 SDLoc DL0(N0); 4873 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4874 N0.getOperand(0), 4875 DAG.getConstant(ShiftAmt, DL0, 4876 getShiftAmountTy(SmallVT))); 4877 AddToWorklist(SmallShift.getNode()); 4878 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4879 SDLoc DL(N); 4880 return DAG.getNode(ISD::AND, DL, VT, 4881 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4882 DAG.getConstant(Mask, DL, VT)); 4883 } 4884 } 4885 4886 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4887 // bit, which is unmodified by sra. 4888 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4889 if (N0.getOpcode() == ISD::SRA) 4890 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4891 } 4892 4893 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4894 if (N1C && N0.getOpcode() == ISD::CTLZ && 4895 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4896 APInt KnownZero, KnownOne; 4897 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4898 4899 // If any of the input bits are KnownOne, then the input couldn't be all 4900 // zeros, thus the result of the srl will always be zero. 4901 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4902 4903 // If all of the bits input the to ctlz node are known to be zero, then 4904 // the result of the ctlz is "32" and the result of the shift is one. 4905 APInt UnknownBits = ~KnownZero; 4906 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4907 4908 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4909 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4910 // Okay, we know that only that the single bit specified by UnknownBits 4911 // could be set on input to the CTLZ node. If this bit is set, the SRL 4912 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4913 // to an SRL/XOR pair, which is likely to simplify more. 4914 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4915 SDValue Op = N0.getOperand(0); 4916 4917 if (ShAmt) { 4918 SDLoc DL(N0); 4919 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4920 DAG.getConstant(ShAmt, DL, 4921 getShiftAmountTy(Op.getValueType()))); 4922 AddToWorklist(Op.getNode()); 4923 } 4924 4925 SDLoc DL(N); 4926 return DAG.getNode(ISD::XOR, DL, VT, 4927 Op, DAG.getConstant(1, DL, VT)); 4928 } 4929 } 4930 4931 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4932 if (N1.getOpcode() == ISD::TRUNCATE && 4933 N1.getOperand(0).getOpcode() == ISD::AND) { 4934 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4935 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4936 } 4937 4938 // fold operands of srl based on knowledge that the low bits are not 4939 // demanded. 4940 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4941 return SDValue(N, 0); 4942 4943 if (N1C && !N1C->isOpaque()) 4944 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4945 return NewSRL; 4946 4947 // Attempt to convert a srl of a load into a narrower zero-extending load. 4948 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4949 return NarrowLoad; 4950 4951 // Here is a common situation. We want to optimize: 4952 // 4953 // %a = ... 4954 // %b = and i32 %a, 2 4955 // %c = srl i32 %b, 1 4956 // brcond i32 %c ... 4957 // 4958 // into 4959 // 4960 // %a = ... 4961 // %b = and %a, 2 4962 // %c = setcc eq %b, 0 4963 // brcond %c ... 4964 // 4965 // However when after the source operand of SRL is optimized into AND, the SRL 4966 // itself may not be optimized further. Look for it and add the BRCOND into 4967 // the worklist. 4968 if (N->hasOneUse()) { 4969 SDNode *Use = *N->use_begin(); 4970 if (Use->getOpcode() == ISD::BRCOND) 4971 AddToWorklist(Use); 4972 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4973 // Also look pass the truncate. 4974 Use = *Use->use_begin(); 4975 if (Use->getOpcode() == ISD::BRCOND) 4976 AddToWorklist(Use); 4977 } 4978 } 4979 4980 return SDValue(); 4981 } 4982 4983 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4984 SDValue N0 = N->getOperand(0); 4985 EVT VT = N->getValueType(0); 4986 4987 // fold (bswap c1) -> c2 4988 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4989 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4990 // fold (bswap (bswap x)) -> x 4991 if (N0.getOpcode() == ISD::BSWAP) 4992 return N0->getOperand(0); 4993 return SDValue(); 4994 } 4995 4996 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 4997 SDValue N0 = N->getOperand(0); 4998 4999 // fold (bitreverse (bitreverse x)) -> x 5000 if (N0.getOpcode() == ISD::BITREVERSE) 5001 return N0.getOperand(0); 5002 return SDValue(); 5003 } 5004 5005 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 5006 SDValue N0 = N->getOperand(0); 5007 EVT VT = N->getValueType(0); 5008 5009 // fold (ctlz c1) -> c2 5010 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5011 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 5012 return SDValue(); 5013 } 5014 5015 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 5016 SDValue N0 = N->getOperand(0); 5017 EVT VT = N->getValueType(0); 5018 5019 // fold (ctlz_zero_undef c1) -> c2 5020 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5021 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5022 return SDValue(); 5023 } 5024 5025 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5026 SDValue N0 = N->getOperand(0); 5027 EVT VT = N->getValueType(0); 5028 5029 // fold (cttz c1) -> c2 5030 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5031 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5032 return SDValue(); 5033 } 5034 5035 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5036 SDValue N0 = N->getOperand(0); 5037 EVT VT = N->getValueType(0); 5038 5039 // fold (cttz_zero_undef c1) -> c2 5040 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5041 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5042 return SDValue(); 5043 } 5044 5045 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5046 SDValue N0 = N->getOperand(0); 5047 EVT VT = N->getValueType(0); 5048 5049 // fold (ctpop c1) -> c2 5050 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5051 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5052 return SDValue(); 5053 } 5054 5055 5056 /// \brief Generate Min/Max node 5057 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 5058 SDValue RHS, SDValue True, SDValue False, 5059 ISD::CondCode CC, const TargetLowering &TLI, 5060 SelectionDAG &DAG) { 5061 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5062 return SDValue(); 5063 5064 switch (CC) { 5065 case ISD::SETOLT: 5066 case ISD::SETOLE: 5067 case ISD::SETLT: 5068 case ISD::SETLE: 5069 case ISD::SETULT: 5070 case ISD::SETULE: { 5071 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5072 if (TLI.isOperationLegal(Opcode, VT)) 5073 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5074 return SDValue(); 5075 } 5076 case ISD::SETOGT: 5077 case ISD::SETOGE: 5078 case ISD::SETGT: 5079 case ISD::SETGE: 5080 case ISD::SETUGT: 5081 case ISD::SETUGE: { 5082 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5083 if (TLI.isOperationLegal(Opcode, VT)) 5084 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5085 return SDValue(); 5086 } 5087 default: 5088 return SDValue(); 5089 } 5090 } 5091 5092 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5093 SDValue N0 = N->getOperand(0); 5094 SDValue N1 = N->getOperand(1); 5095 SDValue N2 = N->getOperand(2); 5096 EVT VT = N->getValueType(0); 5097 EVT VT0 = N0.getValueType(); 5098 5099 // fold (select C, X, X) -> X 5100 if (N1 == N2) 5101 return N1; 5102 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5103 // fold (select true, X, Y) -> X 5104 // fold (select false, X, Y) -> Y 5105 return !N0C->isNullValue() ? N1 : N2; 5106 } 5107 // fold (select C, 1, X) -> (or C, X) 5108 if (VT == MVT::i1 && isOneConstant(N1)) 5109 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5110 // fold (select C, 0, 1) -> (xor C, 1) 5111 // We can't do this reliably if integer based booleans have different contents 5112 // to floating point based booleans. This is because we can't tell whether we 5113 // have an integer-based boolean or a floating-point-based boolean unless we 5114 // can find the SETCC that produced it and inspect its operands. This is 5115 // fairly easy if C is the SETCC node, but it can potentially be 5116 // undiscoverable (or not reasonably discoverable). For example, it could be 5117 // in another basic block or it could require searching a complicated 5118 // expression. 5119 if (VT.isInteger() && 5120 (VT0 == MVT::i1 || (VT0.isInteger() && 5121 TLI.getBooleanContents(false, false) == 5122 TLI.getBooleanContents(false, true) && 5123 TLI.getBooleanContents(false, false) == 5124 TargetLowering::ZeroOrOneBooleanContent)) && 5125 isNullConstant(N1) && isOneConstant(N2)) { 5126 SDValue XORNode; 5127 if (VT == VT0) { 5128 SDLoc DL(N); 5129 return DAG.getNode(ISD::XOR, DL, VT0, 5130 N0, DAG.getConstant(1, DL, VT0)); 5131 } 5132 SDLoc DL0(N0); 5133 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5134 N0, DAG.getConstant(1, DL0, VT0)); 5135 AddToWorklist(XORNode.getNode()); 5136 if (VT.bitsGT(VT0)) 5137 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5138 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5139 } 5140 // fold (select C, 0, X) -> (and (not C), X) 5141 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5142 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5143 AddToWorklist(NOTNode.getNode()); 5144 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5145 } 5146 // fold (select C, X, 1) -> (or (not C), X) 5147 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5148 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5149 AddToWorklist(NOTNode.getNode()); 5150 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5151 } 5152 // fold (select C, X, 0) -> (and C, X) 5153 if (VT == MVT::i1 && isNullConstant(N2)) 5154 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5155 // fold (select X, X, Y) -> (or X, Y) 5156 // fold (select X, 1, Y) -> (or X, Y) 5157 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5158 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5159 // fold (select X, Y, X) -> (and X, Y) 5160 // fold (select X, Y, 0) -> (and X, Y) 5161 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5162 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5163 5164 // If we can fold this based on the true/false value, do so. 5165 if (SimplifySelectOps(N, N1, N2)) 5166 return SDValue(N, 0); // Don't revisit N. 5167 5168 if (VT0 == MVT::i1) { 5169 // The code in this block deals with the following 2 equivalences: 5170 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5171 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5172 // The target can specify its prefered form with the 5173 // shouldNormalizeToSelectSequence() callback. However we always transform 5174 // to the right anyway if we find the inner select exists in the DAG anyway 5175 // and we always transform to the left side if we know that we can further 5176 // optimize the combination of the conditions. 5177 bool normalizeToSequence 5178 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5179 // select (and Cond0, Cond1), X, Y 5180 // -> select Cond0, (select Cond1, X, Y), Y 5181 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5182 SDValue Cond0 = N0->getOperand(0); 5183 SDValue Cond1 = N0->getOperand(1); 5184 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5185 N1.getValueType(), Cond1, N1, N2); 5186 if (normalizeToSequence || !InnerSelect.use_empty()) 5187 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5188 InnerSelect, N2); 5189 } 5190 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5191 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5192 SDValue Cond0 = N0->getOperand(0); 5193 SDValue Cond1 = N0->getOperand(1); 5194 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5195 N1.getValueType(), Cond1, N1, N2); 5196 if (normalizeToSequence || !InnerSelect.use_empty()) 5197 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5198 InnerSelect); 5199 } 5200 5201 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5202 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5203 SDValue N1_0 = N1->getOperand(0); 5204 SDValue N1_1 = N1->getOperand(1); 5205 SDValue N1_2 = N1->getOperand(2); 5206 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5207 // Create the actual and node if we can generate good code for it. 5208 if (!normalizeToSequence) { 5209 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5210 N0, N1_0); 5211 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5212 N1_1, N2); 5213 } 5214 // Otherwise see if we can optimize the "and" to a better pattern. 5215 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5216 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5217 N1_1, N2); 5218 } 5219 } 5220 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5221 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5222 SDValue N2_0 = N2->getOperand(0); 5223 SDValue N2_1 = N2->getOperand(1); 5224 SDValue N2_2 = N2->getOperand(2); 5225 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5226 // Create the actual or node if we can generate good code for it. 5227 if (!normalizeToSequence) { 5228 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5229 N0, N2_0); 5230 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5231 N1, N2_2); 5232 } 5233 // Otherwise see if we can optimize to a better pattern. 5234 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5235 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5236 N1, N2_2); 5237 } 5238 } 5239 } 5240 5241 // fold selects based on a setcc into other things, such as min/max/abs 5242 if (N0.getOpcode() == ISD::SETCC) { 5243 // select x, y (fcmp lt x, y) -> fminnum x, y 5244 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5245 // 5246 // This is OK if we don't care about what happens if either operand is a 5247 // NaN. 5248 // 5249 5250 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5251 // no signed zeros as well as no nans. 5252 const TargetOptions &Options = DAG.getTarget().Options; 5253 if (Options.UnsafeFPMath && 5254 VT.isFloatingPoint() && N0.hasOneUse() && 5255 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5256 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5257 5258 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5259 N0.getOperand(1), N1, N2, CC, 5260 TLI, DAG)) 5261 return FMinMax; 5262 } 5263 5264 if ((!LegalOperations && 5265 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5266 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5267 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5268 N0.getOperand(0), N0.getOperand(1), 5269 N1, N2, N0.getOperand(2)); 5270 return SimplifySelect(SDLoc(N), N0, N1, N2); 5271 } 5272 5273 return SDValue(); 5274 } 5275 5276 static 5277 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5278 SDLoc DL(N); 5279 EVT LoVT, HiVT; 5280 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5281 5282 // Split the inputs. 5283 SDValue Lo, Hi, LL, LH, RL, RH; 5284 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5285 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5286 5287 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5288 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5289 5290 return std::make_pair(Lo, Hi); 5291 } 5292 5293 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5294 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5295 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5296 SDLoc dl(N); 5297 SDValue Cond = N->getOperand(0); 5298 SDValue LHS = N->getOperand(1); 5299 SDValue RHS = N->getOperand(2); 5300 EVT VT = N->getValueType(0); 5301 int NumElems = VT.getVectorNumElements(); 5302 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5303 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5304 Cond.getOpcode() == ISD::BUILD_VECTOR); 5305 5306 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5307 // binary ones here. 5308 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5309 return SDValue(); 5310 5311 // We're sure we have an even number of elements due to the 5312 // concat_vectors we have as arguments to vselect. 5313 // Skip BV elements until we find one that's not an UNDEF 5314 // After we find an UNDEF element, keep looping until we get to half the 5315 // length of the BV and see if all the non-undef nodes are the same. 5316 ConstantSDNode *BottomHalf = nullptr; 5317 for (int i = 0; i < NumElems / 2; ++i) { 5318 if (Cond->getOperand(i)->isUndef()) 5319 continue; 5320 5321 if (BottomHalf == nullptr) 5322 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5323 else if (Cond->getOperand(i).getNode() != BottomHalf) 5324 return SDValue(); 5325 } 5326 5327 // Do the same for the second half of the BuildVector 5328 ConstantSDNode *TopHalf = nullptr; 5329 for (int i = NumElems / 2; i < NumElems; ++i) { 5330 if (Cond->getOperand(i)->isUndef()) 5331 continue; 5332 5333 if (TopHalf == nullptr) 5334 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5335 else if (Cond->getOperand(i).getNode() != TopHalf) 5336 return SDValue(); 5337 } 5338 5339 assert(TopHalf && BottomHalf && 5340 "One half of the selector was all UNDEFs and the other was all the " 5341 "same value. This should have been addressed before this function."); 5342 return DAG.getNode( 5343 ISD::CONCAT_VECTORS, dl, VT, 5344 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5345 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5346 } 5347 5348 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5349 5350 if (Level >= AfterLegalizeTypes) 5351 return SDValue(); 5352 5353 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5354 SDValue Mask = MSC->getMask(); 5355 SDValue Data = MSC->getValue(); 5356 SDLoc DL(N); 5357 5358 // If the MSCATTER data type requires splitting and the mask is provided by a 5359 // SETCC, then split both nodes and its operands before legalization. This 5360 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5361 // and enables future optimizations (e.g. min/max pattern matching on X86). 5362 if (Mask.getOpcode() != ISD::SETCC) 5363 return SDValue(); 5364 5365 // Check if any splitting is required. 5366 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5367 TargetLowering::TypeSplitVector) 5368 return SDValue(); 5369 SDValue MaskLo, MaskHi, Lo, Hi; 5370 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5371 5372 EVT LoVT, HiVT; 5373 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5374 5375 SDValue Chain = MSC->getChain(); 5376 5377 EVT MemoryVT = MSC->getMemoryVT(); 5378 unsigned Alignment = MSC->getOriginalAlignment(); 5379 5380 EVT LoMemVT, HiMemVT; 5381 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5382 5383 SDValue DataLo, DataHi; 5384 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5385 5386 SDValue BasePtr = MSC->getBasePtr(); 5387 SDValue IndexLo, IndexHi; 5388 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5389 5390 MachineMemOperand *MMO = DAG.getMachineFunction(). 5391 getMachineMemOperand(MSC->getPointerInfo(), 5392 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5393 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5394 5395 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5396 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5397 DL, OpsLo, MMO); 5398 5399 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5400 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5401 DL, OpsHi, MMO); 5402 5403 AddToWorklist(Lo.getNode()); 5404 AddToWorklist(Hi.getNode()); 5405 5406 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5407 } 5408 5409 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5410 5411 if (Level >= AfterLegalizeTypes) 5412 return SDValue(); 5413 5414 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5415 SDValue Mask = MST->getMask(); 5416 SDValue Data = MST->getValue(); 5417 SDLoc DL(N); 5418 5419 // If the MSTORE data type requires splitting and the mask is provided by a 5420 // SETCC, then split both nodes and its operands before legalization. This 5421 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5422 // and enables future optimizations (e.g. min/max pattern matching on X86). 5423 if (Mask.getOpcode() == ISD::SETCC) { 5424 5425 // Check if any splitting is required. 5426 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5427 TargetLowering::TypeSplitVector) 5428 return SDValue(); 5429 5430 SDValue MaskLo, MaskHi, Lo, Hi; 5431 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5432 5433 EVT LoVT, HiVT; 5434 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5435 5436 SDValue Chain = MST->getChain(); 5437 SDValue Ptr = MST->getBasePtr(); 5438 5439 EVT MemoryVT = MST->getMemoryVT(); 5440 unsigned Alignment = MST->getOriginalAlignment(); 5441 5442 // if Alignment is equal to the vector size, 5443 // take the half of it for the second part 5444 unsigned SecondHalfAlignment = 5445 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5446 Alignment/2 : Alignment; 5447 5448 EVT LoMemVT, HiMemVT; 5449 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5450 5451 SDValue DataLo, DataHi; 5452 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5453 5454 MachineMemOperand *MMO = DAG.getMachineFunction(). 5455 getMachineMemOperand(MST->getPointerInfo(), 5456 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5457 Alignment, MST->getAAInfo(), MST->getRanges()); 5458 5459 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5460 MST->isTruncatingStore()); 5461 5462 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5463 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5464 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5465 5466 MMO = DAG.getMachineFunction(). 5467 getMachineMemOperand(MST->getPointerInfo(), 5468 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5469 SecondHalfAlignment, MST->getAAInfo(), 5470 MST->getRanges()); 5471 5472 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5473 MST->isTruncatingStore()); 5474 5475 AddToWorklist(Lo.getNode()); 5476 AddToWorklist(Hi.getNode()); 5477 5478 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5479 } 5480 return SDValue(); 5481 } 5482 5483 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5484 5485 if (Level >= AfterLegalizeTypes) 5486 return SDValue(); 5487 5488 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5489 SDValue Mask = MGT->getMask(); 5490 SDLoc DL(N); 5491 5492 // If the MGATHER result requires splitting and the mask is provided by a 5493 // SETCC, then split both nodes and its operands before legalization. This 5494 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5495 // and enables future optimizations (e.g. min/max pattern matching on X86). 5496 5497 if (Mask.getOpcode() != ISD::SETCC) 5498 return SDValue(); 5499 5500 EVT VT = N->getValueType(0); 5501 5502 // Check if any splitting is required. 5503 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5504 TargetLowering::TypeSplitVector) 5505 return SDValue(); 5506 5507 SDValue MaskLo, MaskHi, Lo, Hi; 5508 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5509 5510 SDValue Src0 = MGT->getValue(); 5511 SDValue Src0Lo, Src0Hi; 5512 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5513 5514 EVT LoVT, HiVT; 5515 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5516 5517 SDValue Chain = MGT->getChain(); 5518 EVT MemoryVT = MGT->getMemoryVT(); 5519 unsigned Alignment = MGT->getOriginalAlignment(); 5520 5521 EVT LoMemVT, HiMemVT; 5522 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5523 5524 SDValue BasePtr = MGT->getBasePtr(); 5525 SDValue Index = MGT->getIndex(); 5526 SDValue IndexLo, IndexHi; 5527 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5528 5529 MachineMemOperand *MMO = DAG.getMachineFunction(). 5530 getMachineMemOperand(MGT->getPointerInfo(), 5531 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5532 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5533 5534 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5535 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5536 MMO); 5537 5538 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5539 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5540 MMO); 5541 5542 AddToWorklist(Lo.getNode()); 5543 AddToWorklist(Hi.getNode()); 5544 5545 // Build a factor node to remember that this load is independent of the 5546 // other one. 5547 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5548 Hi.getValue(1)); 5549 5550 // Legalized the chain result - switch anything that used the old chain to 5551 // use the new one. 5552 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5553 5554 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5555 5556 SDValue RetOps[] = { GatherRes, Chain }; 5557 return DAG.getMergeValues(RetOps, DL); 5558 } 5559 5560 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5561 5562 if (Level >= AfterLegalizeTypes) 5563 return SDValue(); 5564 5565 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5566 SDValue Mask = MLD->getMask(); 5567 SDLoc DL(N); 5568 5569 // If the MLOAD result requires splitting and the mask is provided by a 5570 // SETCC, then split both nodes and its operands before legalization. This 5571 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5572 // and enables future optimizations (e.g. min/max pattern matching on X86). 5573 5574 if (Mask.getOpcode() == ISD::SETCC) { 5575 EVT VT = N->getValueType(0); 5576 5577 // Check if any splitting is required. 5578 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5579 TargetLowering::TypeSplitVector) 5580 return SDValue(); 5581 5582 SDValue MaskLo, MaskHi, Lo, Hi; 5583 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5584 5585 SDValue Src0 = MLD->getSrc0(); 5586 SDValue Src0Lo, Src0Hi; 5587 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5588 5589 EVT LoVT, HiVT; 5590 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5591 5592 SDValue Chain = MLD->getChain(); 5593 SDValue Ptr = MLD->getBasePtr(); 5594 EVT MemoryVT = MLD->getMemoryVT(); 5595 unsigned Alignment = MLD->getOriginalAlignment(); 5596 5597 // if Alignment is equal to the vector size, 5598 // take the half of it for the second part 5599 unsigned SecondHalfAlignment = 5600 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5601 Alignment/2 : Alignment; 5602 5603 EVT LoMemVT, HiMemVT; 5604 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5605 5606 MachineMemOperand *MMO = DAG.getMachineFunction(). 5607 getMachineMemOperand(MLD->getPointerInfo(), 5608 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5609 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5610 5611 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5612 ISD::NON_EXTLOAD); 5613 5614 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5615 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5616 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5617 5618 MMO = DAG.getMachineFunction(). 5619 getMachineMemOperand(MLD->getPointerInfo(), 5620 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5621 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5622 5623 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5624 ISD::NON_EXTLOAD); 5625 5626 AddToWorklist(Lo.getNode()); 5627 AddToWorklist(Hi.getNode()); 5628 5629 // Build a factor node to remember that this load is independent of the 5630 // other one. 5631 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5632 Hi.getValue(1)); 5633 5634 // Legalized the chain result - switch anything that used the old chain to 5635 // use the new one. 5636 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5637 5638 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5639 5640 SDValue RetOps[] = { LoadRes, Chain }; 5641 return DAG.getMergeValues(RetOps, DL); 5642 } 5643 return SDValue(); 5644 } 5645 5646 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5647 SDValue N0 = N->getOperand(0); 5648 SDValue N1 = N->getOperand(1); 5649 SDValue N2 = N->getOperand(2); 5650 SDLoc DL(N); 5651 5652 // Canonicalize integer abs. 5653 // vselect (setg[te] X, 0), X, -X -> 5654 // vselect (setgt X, -1), X, -X -> 5655 // vselect (setl[te] X, 0), -X, X -> 5656 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5657 if (N0.getOpcode() == ISD::SETCC) { 5658 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5659 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5660 bool isAbs = false; 5661 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5662 5663 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5664 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5665 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5666 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5667 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5668 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5669 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5670 5671 if (isAbs) { 5672 EVT VT = LHS.getValueType(); 5673 SDValue Shift = DAG.getNode( 5674 ISD::SRA, DL, VT, LHS, 5675 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5676 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5677 AddToWorklist(Shift.getNode()); 5678 AddToWorklist(Add.getNode()); 5679 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5680 } 5681 } 5682 5683 if (SimplifySelectOps(N, N1, N2)) 5684 return SDValue(N, 0); // Don't revisit N. 5685 5686 // If the VSELECT result requires splitting and the mask is provided by a 5687 // SETCC, then split both nodes and its operands before legalization. This 5688 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5689 // and enables future optimizations (e.g. min/max pattern matching on X86). 5690 if (N0.getOpcode() == ISD::SETCC) { 5691 EVT VT = N->getValueType(0); 5692 5693 // Check if any splitting is required. 5694 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5695 TargetLowering::TypeSplitVector) 5696 return SDValue(); 5697 5698 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5699 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5700 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5701 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5702 5703 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5704 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5705 5706 // Add the new VSELECT nodes to the work list in case they need to be split 5707 // again. 5708 AddToWorklist(Lo.getNode()); 5709 AddToWorklist(Hi.getNode()); 5710 5711 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5712 } 5713 5714 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5715 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5716 return N1; 5717 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5718 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5719 return N2; 5720 5721 // The ConvertSelectToConcatVector function is assuming both the above 5722 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5723 // and addressed. 5724 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5725 N2.getOpcode() == ISD::CONCAT_VECTORS && 5726 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5727 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5728 return CV; 5729 } 5730 5731 return SDValue(); 5732 } 5733 5734 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5735 SDValue N0 = N->getOperand(0); 5736 SDValue N1 = N->getOperand(1); 5737 SDValue N2 = N->getOperand(2); 5738 SDValue N3 = N->getOperand(3); 5739 SDValue N4 = N->getOperand(4); 5740 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5741 5742 // fold select_cc lhs, rhs, x, x, cc -> x 5743 if (N2 == N3) 5744 return N2; 5745 5746 // Determine if the condition we're dealing with is constant 5747 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 5748 CC, SDLoc(N), false)) { 5749 AddToWorklist(SCC.getNode()); 5750 5751 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5752 if (!SCCC->isNullValue()) 5753 return N2; // cond always true -> true val 5754 else 5755 return N3; // cond always false -> false val 5756 } else if (SCC->isUndef()) { 5757 // When the condition is UNDEF, just return the first operand. This is 5758 // coherent the DAG creation, no setcc node is created in this case 5759 return N2; 5760 } else if (SCC.getOpcode() == ISD::SETCC) { 5761 // Fold to a simpler select_cc 5762 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5763 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5764 SCC.getOperand(2)); 5765 } 5766 } 5767 5768 // If we can fold this based on the true/false value, do so. 5769 if (SimplifySelectOps(N, N2, N3)) 5770 return SDValue(N, 0); // Don't revisit N. 5771 5772 // fold select_cc into other things, such as min/max/abs 5773 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5774 } 5775 5776 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5777 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5778 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5779 SDLoc(N)); 5780 } 5781 5782 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5783 SDValue LHS = N->getOperand(0); 5784 SDValue RHS = N->getOperand(1); 5785 SDValue Carry = N->getOperand(2); 5786 SDValue Cond = N->getOperand(3); 5787 5788 // If Carry is false, fold to a regular SETCC. 5789 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5790 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5791 5792 return SDValue(); 5793 } 5794 5795 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5796 /// a build_vector of constants. 5797 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5798 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5799 /// Vector extends are not folded if operations are legal; this is to 5800 /// avoid introducing illegal build_vector dag nodes. 5801 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5802 SelectionDAG &DAG, bool LegalTypes, 5803 bool LegalOperations) { 5804 unsigned Opcode = N->getOpcode(); 5805 SDValue N0 = N->getOperand(0); 5806 EVT VT = N->getValueType(0); 5807 5808 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5809 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 5810 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 5811 && "Expected EXTEND dag node in input!"); 5812 5813 // fold (sext c1) -> c1 5814 // fold (zext c1) -> c1 5815 // fold (aext c1) -> c1 5816 if (isa<ConstantSDNode>(N0)) 5817 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5818 5819 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5820 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5821 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5822 EVT SVT = VT.getScalarType(); 5823 if (!(VT.isVector() && 5824 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5825 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5826 return nullptr; 5827 5828 // We can fold this node into a build_vector. 5829 unsigned VTBits = SVT.getSizeInBits(); 5830 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5831 SmallVector<SDValue, 8> Elts; 5832 unsigned NumElts = VT.getVectorNumElements(); 5833 SDLoc DL(N); 5834 5835 for (unsigned i=0; i != NumElts; ++i) { 5836 SDValue Op = N0->getOperand(i); 5837 if (Op->isUndef()) { 5838 Elts.push_back(DAG.getUNDEF(SVT)); 5839 continue; 5840 } 5841 5842 SDLoc DL(Op); 5843 // Get the constant value and if needed trunc it to the size of the type. 5844 // Nodes like build_vector might have constants wider than the scalar type. 5845 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5846 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5847 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5848 else 5849 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5850 } 5851 5852 return DAG.getBuildVector(VT, DL, Elts).getNode(); 5853 } 5854 5855 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5856 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5857 // transformation. Returns true if extension are possible and the above 5858 // mentioned transformation is profitable. 5859 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5860 unsigned ExtOpc, 5861 SmallVectorImpl<SDNode *> &ExtendNodes, 5862 const TargetLowering &TLI) { 5863 bool HasCopyToRegUses = false; 5864 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5865 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5866 UE = N0.getNode()->use_end(); 5867 UI != UE; ++UI) { 5868 SDNode *User = *UI; 5869 if (User == N) 5870 continue; 5871 if (UI.getUse().getResNo() != N0.getResNo()) 5872 continue; 5873 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5874 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5875 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5876 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5877 // Sign bits will be lost after a zext. 5878 return false; 5879 bool Add = false; 5880 for (unsigned i = 0; i != 2; ++i) { 5881 SDValue UseOp = User->getOperand(i); 5882 if (UseOp == N0) 5883 continue; 5884 if (!isa<ConstantSDNode>(UseOp)) 5885 return false; 5886 Add = true; 5887 } 5888 if (Add) 5889 ExtendNodes.push_back(User); 5890 continue; 5891 } 5892 // If truncates aren't free and there are users we can't 5893 // extend, it isn't worthwhile. 5894 if (!isTruncFree) 5895 return false; 5896 // Remember if this value is live-out. 5897 if (User->getOpcode() == ISD::CopyToReg) 5898 HasCopyToRegUses = true; 5899 } 5900 5901 if (HasCopyToRegUses) { 5902 bool BothLiveOut = false; 5903 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5904 UI != UE; ++UI) { 5905 SDUse &Use = UI.getUse(); 5906 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5907 BothLiveOut = true; 5908 break; 5909 } 5910 } 5911 if (BothLiveOut) 5912 // Both unextended and extended values are live out. There had better be 5913 // a good reason for the transformation. 5914 return ExtendNodes.size(); 5915 } 5916 return true; 5917 } 5918 5919 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5920 SDValue Trunc, SDValue ExtLoad, 5921 const SDLoc &DL, ISD::NodeType ExtType) { 5922 // Extend SetCC uses if necessary. 5923 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5924 SDNode *SetCC = SetCCs[i]; 5925 SmallVector<SDValue, 4> Ops; 5926 5927 for (unsigned j = 0; j != 2; ++j) { 5928 SDValue SOp = SetCC->getOperand(j); 5929 if (SOp == Trunc) 5930 Ops.push_back(ExtLoad); 5931 else 5932 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5933 } 5934 5935 Ops.push_back(SetCC->getOperand(2)); 5936 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5937 } 5938 } 5939 5940 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5941 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5942 SDValue N0 = N->getOperand(0); 5943 EVT DstVT = N->getValueType(0); 5944 EVT SrcVT = N0.getValueType(); 5945 5946 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5947 N->getOpcode() == ISD::ZERO_EXTEND) && 5948 "Unexpected node type (not an extend)!"); 5949 5950 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5951 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5952 // (v8i32 (sext (v8i16 (load x)))) 5953 // into: 5954 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5955 // (v4i32 (sextload (x + 16))))) 5956 // Where uses of the original load, i.e.: 5957 // (v8i16 (load x)) 5958 // are replaced with: 5959 // (v8i16 (truncate 5960 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5961 // (v4i32 (sextload (x + 16))))))) 5962 // 5963 // This combine is only applicable to illegal, but splittable, vectors. 5964 // All legal types, and illegal non-vector types, are handled elsewhere. 5965 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5966 // 5967 if (N0->getOpcode() != ISD::LOAD) 5968 return SDValue(); 5969 5970 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5971 5972 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5973 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5974 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5975 return SDValue(); 5976 5977 SmallVector<SDNode *, 4> SetCCs; 5978 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5979 return SDValue(); 5980 5981 ISD::LoadExtType ExtType = 5982 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5983 5984 // Try to split the vector types to get down to legal types. 5985 EVT SplitSrcVT = SrcVT; 5986 EVT SplitDstVT = DstVT; 5987 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5988 SplitSrcVT.getVectorNumElements() > 1) { 5989 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5990 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5991 } 5992 5993 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5994 return SDValue(); 5995 5996 SDLoc DL(N); 5997 const unsigned NumSplits = 5998 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5999 const unsigned Stride = SplitSrcVT.getStoreSize(); 6000 SmallVector<SDValue, 4> Loads; 6001 SmallVector<SDValue, 4> Chains; 6002 6003 SDValue BasePtr = LN0->getBasePtr(); 6004 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 6005 const unsigned Offset = Idx * Stride; 6006 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 6007 6008 SDValue SplitLoad = DAG.getExtLoad( 6009 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 6010 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 6011 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6012 6013 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 6014 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 6015 6016 Loads.push_back(SplitLoad.getValue(0)); 6017 Chains.push_back(SplitLoad.getValue(1)); 6018 } 6019 6020 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 6021 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 6022 6023 CombineTo(N, NewValue); 6024 6025 // Replace uses of the original load (before extension) 6026 // with a truncate of the concatenated sextloaded vectors. 6027 SDValue Trunc = 6028 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6029 CombineTo(N0.getNode(), Trunc, NewChain); 6030 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6031 (ISD::NodeType)N->getOpcode()); 6032 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6033 } 6034 6035 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 6036 SDValue N0 = N->getOperand(0); 6037 EVT VT = N->getValueType(0); 6038 6039 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6040 LegalOperations)) 6041 return SDValue(Res, 0); 6042 6043 // fold (sext (sext x)) -> (sext x) 6044 // fold (sext (aext x)) -> (sext x) 6045 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6046 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 6047 N0.getOperand(0)); 6048 6049 if (N0.getOpcode() == ISD::TRUNCATE) { 6050 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 6051 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 6052 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6053 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6054 if (NarrowLoad.getNode() != N0.getNode()) { 6055 CombineTo(N0.getNode(), NarrowLoad); 6056 // CombineTo deleted the truncate, if needed, but not what's under it. 6057 AddToWorklist(oye); 6058 } 6059 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6060 } 6061 6062 // See if the value being truncated is already sign extended. If so, just 6063 // eliminate the trunc/sext pair. 6064 SDValue Op = N0.getOperand(0); 6065 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 6066 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 6067 unsigned DestBits = VT.getScalarType().getSizeInBits(); 6068 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6069 6070 if (OpBits == DestBits) { 6071 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6072 // bits, it is already ready. 6073 if (NumSignBits > DestBits-MidBits) 6074 return Op; 6075 } else if (OpBits < DestBits) { 6076 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6077 // bits, just sext from i32. 6078 if (NumSignBits > OpBits-MidBits) 6079 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 6080 } else { 6081 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6082 // bits, just truncate to i32. 6083 if (NumSignBits > OpBits-MidBits) 6084 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6085 } 6086 6087 // fold (sext (truncate x)) -> (sextinreg x). 6088 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6089 N0.getValueType())) { 6090 if (OpBits < DestBits) 6091 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6092 else if (OpBits > DestBits) 6093 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6094 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6095 DAG.getValueType(N0.getValueType())); 6096 } 6097 } 6098 6099 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6100 // Only generate vector extloads when 1) they're legal, and 2) they are 6101 // deemed desirable by the target. 6102 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6103 ((!LegalOperations && !VT.isVector() && 6104 !cast<LoadSDNode>(N0)->isVolatile()) || 6105 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6106 bool DoXform = true; 6107 SmallVector<SDNode*, 4> SetCCs; 6108 if (!N0.hasOneUse()) 6109 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6110 if (VT.isVector()) 6111 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6112 if (DoXform) { 6113 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6114 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6115 LN0->getChain(), 6116 LN0->getBasePtr(), N0.getValueType(), 6117 LN0->getMemOperand()); 6118 CombineTo(N, ExtLoad); 6119 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6120 N0.getValueType(), ExtLoad); 6121 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6122 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6123 ISD::SIGN_EXTEND); 6124 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6125 } 6126 } 6127 6128 // fold (sext (load x)) to multiple smaller sextloads. 6129 // Only on illegal but splittable vectors. 6130 if (SDValue ExtLoad = CombineExtLoad(N)) 6131 return ExtLoad; 6132 6133 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6134 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6135 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6136 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6137 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6138 EVT MemVT = LN0->getMemoryVT(); 6139 if ((!LegalOperations && !LN0->isVolatile()) || 6140 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6141 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6142 LN0->getChain(), 6143 LN0->getBasePtr(), MemVT, 6144 LN0->getMemOperand()); 6145 CombineTo(N, ExtLoad); 6146 CombineTo(N0.getNode(), 6147 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6148 N0.getValueType(), ExtLoad), 6149 ExtLoad.getValue(1)); 6150 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6151 } 6152 } 6153 6154 // fold (sext (and/or/xor (load x), cst)) -> 6155 // (and/or/xor (sextload x), (sext cst)) 6156 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6157 N0.getOpcode() == ISD::XOR) && 6158 isa<LoadSDNode>(N0.getOperand(0)) && 6159 N0.getOperand(1).getOpcode() == ISD::Constant && 6160 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6161 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6162 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6163 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6164 bool DoXform = true; 6165 SmallVector<SDNode*, 4> SetCCs; 6166 if (!N0.hasOneUse()) 6167 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6168 SetCCs, TLI); 6169 if (DoXform) { 6170 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6171 LN0->getChain(), LN0->getBasePtr(), 6172 LN0->getMemoryVT(), 6173 LN0->getMemOperand()); 6174 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6175 Mask = Mask.sext(VT.getSizeInBits()); 6176 SDLoc DL(N); 6177 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6178 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6179 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6180 SDLoc(N0.getOperand(0)), 6181 N0.getOperand(0).getValueType(), ExtLoad); 6182 CombineTo(N, And); 6183 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6184 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6185 ISD::SIGN_EXTEND); 6186 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6187 } 6188 } 6189 } 6190 6191 if (N0.getOpcode() == ISD::SETCC) { 6192 EVT N0VT = N0.getOperand(0).getValueType(); 6193 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6194 // Only do this before legalize for now. 6195 if (VT.isVector() && !LegalOperations && 6196 TLI.getBooleanContents(N0VT) == 6197 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6198 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6199 // of the same size as the compared operands. Only optimize sext(setcc()) 6200 // if this is the case. 6201 EVT SVT = getSetCCResultType(N0VT); 6202 6203 // We know that the # elements of the results is the same as the 6204 // # elements of the compare (and the # elements of the compare result 6205 // for that matter). Check to see that they are the same size. If so, 6206 // we know that the element size of the sext'd result matches the 6207 // element size of the compare operands. 6208 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6209 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6210 N0.getOperand(1), 6211 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6212 6213 // If the desired elements are smaller or larger than the source 6214 // elements we can use a matching integer vector type and then 6215 // truncate/sign extend 6216 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6217 if (SVT == MatchingVectorType) { 6218 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6219 N0.getOperand(0), N0.getOperand(1), 6220 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6221 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6222 } 6223 } 6224 6225 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 6226 // Here, T can be 1 or -1, depending on the type of the setcc and 6227 // getBooleanContents(). 6228 unsigned SetCCWidth = N0.getValueType().getScalarSizeInBits(); 6229 6230 SDLoc DL(N); 6231 // To determine the "true" side of the select, we need to know the high bit 6232 // of the value returned by the setcc if it evaluates to true. 6233 // If the type of the setcc is i1, then the true case of the select is just 6234 // sext(i1 1), that is, -1. 6235 // If the type of the setcc is larger (say, i8) then the value of the high 6236 // bit depends on getBooleanContents(). So, ask TLI for a real "true" value 6237 // of the appropriate width. 6238 SDValue ExtTrueVal = 6239 (SetCCWidth == 1) 6240 ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()), 6241 DL, VT) 6242 : TLI.getConstTrueVal(DAG, VT, DL); 6243 6244 if (SDValue SCC = SimplifySelectCC( 6245 DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal, 6246 DAG.getConstant(0, DL, VT), 6247 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6248 return SCC; 6249 6250 if (!VT.isVector()) { 6251 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6252 if (!LegalOperations || 6253 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6254 SDLoc DL(N); 6255 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6256 SDValue SetCC = 6257 DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC); 6258 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, 6259 DAG.getConstant(0, DL, VT)); 6260 } 6261 } 6262 } 6263 6264 // fold (sext x) -> (zext x) if the sign bit is known zero. 6265 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6266 DAG.SignBitIsZero(N0)) 6267 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6268 6269 return SDValue(); 6270 } 6271 6272 // isTruncateOf - If N is a truncate of some other value, return true, record 6273 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6274 // This function computes KnownZero to avoid a duplicated call to 6275 // computeKnownBits in the caller. 6276 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6277 APInt &KnownZero) { 6278 APInt KnownOne; 6279 if (N->getOpcode() == ISD::TRUNCATE) { 6280 Op = N->getOperand(0); 6281 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6282 return true; 6283 } 6284 6285 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6286 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6287 return false; 6288 6289 SDValue Op0 = N->getOperand(0); 6290 SDValue Op1 = N->getOperand(1); 6291 assert(Op0.getValueType() == Op1.getValueType()); 6292 6293 if (isNullConstant(Op0)) 6294 Op = Op1; 6295 else if (isNullConstant(Op1)) 6296 Op = Op0; 6297 else 6298 return false; 6299 6300 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6301 6302 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6303 return false; 6304 6305 return true; 6306 } 6307 6308 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6309 SDValue N0 = N->getOperand(0); 6310 EVT VT = N->getValueType(0); 6311 6312 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6313 LegalOperations)) 6314 return SDValue(Res, 0); 6315 6316 // fold (zext (zext x)) -> (zext x) 6317 // fold (zext (aext x)) -> (zext x) 6318 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6319 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6320 N0.getOperand(0)); 6321 6322 // fold (zext (truncate x)) -> (zext x) or 6323 // (zext (truncate x)) -> (truncate x) 6324 // This is valid when the truncated bits of x are already zero. 6325 // FIXME: We should extend this to work for vectors too. 6326 SDValue Op; 6327 APInt KnownZero; 6328 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6329 APInt TruncatedBits = 6330 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6331 APInt(Op.getValueSizeInBits(), 0) : 6332 APInt::getBitsSet(Op.getValueSizeInBits(), 6333 N0.getValueSizeInBits(), 6334 std::min(Op.getValueSizeInBits(), 6335 VT.getSizeInBits())); 6336 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6337 if (VT.bitsGT(Op.getValueType())) 6338 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6339 if (VT.bitsLT(Op.getValueType())) 6340 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6341 6342 return Op; 6343 } 6344 } 6345 6346 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6347 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6348 if (N0.getOpcode() == ISD::TRUNCATE) { 6349 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6350 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6351 if (NarrowLoad.getNode() != N0.getNode()) { 6352 CombineTo(N0.getNode(), NarrowLoad); 6353 // CombineTo deleted the truncate, if needed, but not what's under it. 6354 AddToWorklist(oye); 6355 } 6356 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6357 } 6358 } 6359 6360 // fold (zext (truncate x)) -> (and x, mask) 6361 if (N0.getOpcode() == ISD::TRUNCATE) { 6362 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6363 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6364 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6365 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6366 if (NarrowLoad.getNode() != N0.getNode()) { 6367 CombineTo(N0.getNode(), NarrowLoad); 6368 // CombineTo deleted the truncate, if needed, but not what's under it. 6369 AddToWorklist(oye); 6370 } 6371 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6372 } 6373 6374 EVT SrcVT = N0.getOperand(0).getValueType(); 6375 EVT MinVT = N0.getValueType(); 6376 6377 // Try to mask before the extension to avoid having to generate a larger mask, 6378 // possibly over several sub-vectors. 6379 if (SrcVT.bitsLT(VT)) { 6380 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6381 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6382 SDValue Op = N0.getOperand(0); 6383 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6384 AddToWorklist(Op.getNode()); 6385 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6386 } 6387 } 6388 6389 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6390 SDValue Op = N0.getOperand(0); 6391 if (SrcVT.bitsLT(VT)) { 6392 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6393 AddToWorklist(Op.getNode()); 6394 } else if (SrcVT.bitsGT(VT)) { 6395 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6396 AddToWorklist(Op.getNode()); 6397 } 6398 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6399 } 6400 } 6401 6402 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6403 // if either of the casts is not free. 6404 if (N0.getOpcode() == ISD::AND && 6405 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6406 N0.getOperand(1).getOpcode() == ISD::Constant && 6407 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6408 N0.getValueType()) || 6409 !TLI.isZExtFree(N0.getValueType(), VT))) { 6410 SDValue X = N0.getOperand(0).getOperand(0); 6411 if (X.getValueType().bitsLT(VT)) { 6412 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6413 } else if (X.getValueType().bitsGT(VT)) { 6414 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6415 } 6416 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6417 Mask = Mask.zext(VT.getSizeInBits()); 6418 SDLoc DL(N); 6419 return DAG.getNode(ISD::AND, DL, VT, 6420 X, DAG.getConstant(Mask, DL, VT)); 6421 } 6422 6423 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6424 // Only generate vector extloads when 1) they're legal, and 2) they are 6425 // deemed desirable by the target. 6426 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6427 ((!LegalOperations && !VT.isVector() && 6428 !cast<LoadSDNode>(N0)->isVolatile()) || 6429 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6430 bool DoXform = true; 6431 SmallVector<SDNode*, 4> SetCCs; 6432 if (!N0.hasOneUse()) 6433 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6434 if (VT.isVector()) 6435 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6436 if (DoXform) { 6437 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6438 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6439 LN0->getChain(), 6440 LN0->getBasePtr(), N0.getValueType(), 6441 LN0->getMemOperand()); 6442 CombineTo(N, ExtLoad); 6443 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6444 N0.getValueType(), ExtLoad); 6445 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6446 6447 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6448 ISD::ZERO_EXTEND); 6449 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6450 } 6451 } 6452 6453 // fold (zext (load x)) to multiple smaller zextloads. 6454 // Only on illegal but splittable vectors. 6455 if (SDValue ExtLoad = CombineExtLoad(N)) 6456 return ExtLoad; 6457 6458 // fold (zext (and/or/xor (load x), cst)) -> 6459 // (and/or/xor (zextload x), (zext cst)) 6460 // Unless (and (load x) cst) will match as a zextload already and has 6461 // additional users. 6462 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6463 N0.getOpcode() == ISD::XOR) && 6464 isa<LoadSDNode>(N0.getOperand(0)) && 6465 N0.getOperand(1).getOpcode() == ISD::Constant && 6466 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6467 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6468 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6469 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6470 bool DoXform = true; 6471 SmallVector<SDNode*, 4> SetCCs; 6472 if (!N0.hasOneUse()) { 6473 if (N0.getOpcode() == ISD::AND) { 6474 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6475 auto NarrowLoad = false; 6476 EVT LoadResultTy = AndC->getValueType(0); 6477 EVT ExtVT, LoadedVT; 6478 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6479 NarrowLoad)) 6480 DoXform = false; 6481 } 6482 if (DoXform) 6483 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6484 ISD::ZERO_EXTEND, SetCCs, TLI); 6485 } 6486 if (DoXform) { 6487 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6488 LN0->getChain(), LN0->getBasePtr(), 6489 LN0->getMemoryVT(), 6490 LN0->getMemOperand()); 6491 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6492 Mask = Mask.zext(VT.getSizeInBits()); 6493 SDLoc DL(N); 6494 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6495 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6496 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6497 SDLoc(N0.getOperand(0)), 6498 N0.getOperand(0).getValueType(), ExtLoad); 6499 CombineTo(N, And); 6500 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6501 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6502 ISD::ZERO_EXTEND); 6503 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6504 } 6505 } 6506 } 6507 6508 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6509 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6510 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6511 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6512 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6513 EVT MemVT = LN0->getMemoryVT(); 6514 if ((!LegalOperations && !LN0->isVolatile()) || 6515 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6516 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6517 LN0->getChain(), 6518 LN0->getBasePtr(), MemVT, 6519 LN0->getMemOperand()); 6520 CombineTo(N, ExtLoad); 6521 CombineTo(N0.getNode(), 6522 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6523 ExtLoad), 6524 ExtLoad.getValue(1)); 6525 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6526 } 6527 } 6528 6529 if (N0.getOpcode() == ISD::SETCC) { 6530 // Only do this before legalize for now. 6531 if (!LegalOperations && VT.isVector() && 6532 N0.getValueType().getVectorElementType() == MVT::i1) { 6533 EVT N00VT = N0.getOperand(0).getValueType(); 6534 if (getSetCCResultType(N00VT) == N0.getValueType()) 6535 return SDValue(); 6536 6537 // We know that the # elements of the results is the same as the # 6538 // elements of the compare (and the # elements of the compare result for 6539 // that matter). Check to see that they are the same size. If so, we know 6540 // that the element size of the sext'd result matches the element size of 6541 // the compare operands. 6542 SDLoc DL(N); 6543 SDValue VecOnes = DAG.getConstant(1, DL, VT); 6544 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 6545 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6546 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 6547 N0.getOperand(1), N0.getOperand(2)); 6548 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 6549 } 6550 6551 // If the desired elements are smaller or larger than the source 6552 // elements we can use a matching integer vector type and then 6553 // truncate/sign extend. 6554 EVT MatchingElementType = EVT::getIntegerVT( 6555 *DAG.getContext(), N00VT.getScalarType().getSizeInBits()); 6556 EVT MatchingVectorType = EVT::getVectorVT( 6557 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 6558 SDValue VsetCC = 6559 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 6560 N0.getOperand(1), N0.getOperand(2)); 6561 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 6562 VecOnes); 6563 } 6564 6565 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6566 SDLoc DL(N); 6567 if (SDValue SCC = SimplifySelectCC( 6568 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6569 DAG.getConstant(0, DL, VT), 6570 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6571 return SCC; 6572 } 6573 6574 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6575 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6576 isa<ConstantSDNode>(N0.getOperand(1)) && 6577 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6578 N0.hasOneUse()) { 6579 SDValue ShAmt = N0.getOperand(1); 6580 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6581 if (N0.getOpcode() == ISD::SHL) { 6582 SDValue InnerZExt = N0.getOperand(0); 6583 // If the original shl may be shifting out bits, do not perform this 6584 // transformation. 6585 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6586 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6587 if (ShAmtVal > KnownZeroBits) 6588 return SDValue(); 6589 } 6590 6591 SDLoc DL(N); 6592 6593 // Ensure that the shift amount is wide enough for the shifted value. 6594 if (VT.getSizeInBits() >= 256) 6595 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6596 6597 return DAG.getNode(N0.getOpcode(), DL, VT, 6598 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6599 ShAmt); 6600 } 6601 6602 return SDValue(); 6603 } 6604 6605 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6606 SDValue N0 = N->getOperand(0); 6607 EVT VT = N->getValueType(0); 6608 6609 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6610 LegalOperations)) 6611 return SDValue(Res, 0); 6612 6613 // fold (aext (aext x)) -> (aext x) 6614 // fold (aext (zext x)) -> (zext x) 6615 // fold (aext (sext x)) -> (sext x) 6616 if (N0.getOpcode() == ISD::ANY_EXTEND || 6617 N0.getOpcode() == ISD::ZERO_EXTEND || 6618 N0.getOpcode() == ISD::SIGN_EXTEND) 6619 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6620 6621 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6622 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6623 if (N0.getOpcode() == ISD::TRUNCATE) { 6624 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6625 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6626 if (NarrowLoad.getNode() != N0.getNode()) { 6627 CombineTo(N0.getNode(), NarrowLoad); 6628 // CombineTo deleted the truncate, if needed, but not what's under it. 6629 AddToWorklist(oye); 6630 } 6631 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6632 } 6633 } 6634 6635 // fold (aext (truncate x)) 6636 if (N0.getOpcode() == ISD::TRUNCATE) { 6637 SDValue TruncOp = N0.getOperand(0); 6638 if (TruncOp.getValueType() == VT) 6639 return TruncOp; // x iff x size == zext size. 6640 if (TruncOp.getValueType().bitsGT(VT)) 6641 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6642 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6643 } 6644 6645 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6646 // if the trunc is not free. 6647 if (N0.getOpcode() == ISD::AND && 6648 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6649 N0.getOperand(1).getOpcode() == ISD::Constant && 6650 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6651 N0.getValueType())) { 6652 SDValue X = N0.getOperand(0).getOperand(0); 6653 if (X.getValueType().bitsLT(VT)) { 6654 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6655 } else if (X.getValueType().bitsGT(VT)) { 6656 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6657 } 6658 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6659 Mask = Mask.zext(VT.getSizeInBits()); 6660 SDLoc DL(N); 6661 return DAG.getNode(ISD::AND, DL, VT, 6662 X, DAG.getConstant(Mask, DL, VT)); 6663 } 6664 6665 // fold (aext (load x)) -> (aext (truncate (extload x))) 6666 // None of the supported targets knows how to perform load and any_ext 6667 // on vectors in one instruction. We only perform this transformation on 6668 // scalars. 6669 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6670 ISD::isUNINDEXEDLoad(N0.getNode()) && 6671 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6672 bool DoXform = true; 6673 SmallVector<SDNode*, 4> SetCCs; 6674 if (!N0.hasOneUse()) 6675 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6676 if (DoXform) { 6677 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6678 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6679 LN0->getChain(), 6680 LN0->getBasePtr(), N0.getValueType(), 6681 LN0->getMemOperand()); 6682 CombineTo(N, ExtLoad); 6683 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6684 N0.getValueType(), ExtLoad); 6685 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6686 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6687 ISD::ANY_EXTEND); 6688 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6689 } 6690 } 6691 6692 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6693 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6694 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6695 if (N0.getOpcode() == ISD::LOAD && 6696 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6697 N0.hasOneUse()) { 6698 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6699 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6700 EVT MemVT = LN0->getMemoryVT(); 6701 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6702 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6703 VT, LN0->getChain(), LN0->getBasePtr(), 6704 MemVT, LN0->getMemOperand()); 6705 CombineTo(N, ExtLoad); 6706 CombineTo(N0.getNode(), 6707 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6708 N0.getValueType(), ExtLoad), 6709 ExtLoad.getValue(1)); 6710 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6711 } 6712 } 6713 6714 if (N0.getOpcode() == ISD::SETCC) { 6715 // For vectors: 6716 // aext(setcc) -> vsetcc 6717 // aext(setcc) -> truncate(vsetcc) 6718 // aext(setcc) -> aext(vsetcc) 6719 // Only do this before legalize for now. 6720 if (VT.isVector() && !LegalOperations) { 6721 EVT N0VT = N0.getOperand(0).getValueType(); 6722 // We know that the # elements of the results is the same as the 6723 // # elements of the compare (and the # elements of the compare result 6724 // for that matter). Check to see that they are the same size. If so, 6725 // we know that the element size of the sext'd result matches the 6726 // element size of the compare operands. 6727 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6728 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6729 N0.getOperand(1), 6730 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6731 // If the desired elements are smaller or larger than the source 6732 // elements we can use a matching integer vector type and then 6733 // truncate/any extend 6734 else { 6735 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6736 SDValue VsetCC = 6737 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6738 N0.getOperand(1), 6739 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6740 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6741 } 6742 } 6743 6744 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6745 SDLoc DL(N); 6746 if (SDValue SCC = SimplifySelectCC( 6747 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6748 DAG.getConstant(0, DL, VT), 6749 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6750 return SCC; 6751 } 6752 6753 return SDValue(); 6754 } 6755 6756 /// See if the specified operand can be simplified with the knowledge that only 6757 /// the bits specified by Mask are used. If so, return the simpler operand, 6758 /// otherwise return a null SDValue. 6759 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6760 switch (V.getOpcode()) { 6761 default: break; 6762 case ISD::Constant: { 6763 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6764 assert(CV && "Const value should be ConstSDNode."); 6765 const APInt &CVal = CV->getAPIntValue(); 6766 APInt NewVal = CVal & Mask; 6767 if (NewVal != CVal) 6768 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6769 break; 6770 } 6771 case ISD::OR: 6772 case ISD::XOR: 6773 // If the LHS or RHS don't contribute bits to the or, drop them. 6774 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6775 return V.getOperand(1); 6776 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6777 return V.getOperand(0); 6778 break; 6779 case ISD::SRL: 6780 // Only look at single-use SRLs. 6781 if (!V.getNode()->hasOneUse()) 6782 break; 6783 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6784 // See if we can recursively simplify the LHS. 6785 unsigned Amt = RHSC->getZExtValue(); 6786 6787 // Watch out for shift count overflow though. 6788 if (Amt >= Mask.getBitWidth()) break; 6789 APInt NewMask = Mask << Amt; 6790 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6791 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6792 SimplifyLHS, V.getOperand(1)); 6793 } 6794 } 6795 return SDValue(); 6796 } 6797 6798 /// If the result of a wider load is shifted to right of N bits and then 6799 /// truncated to a narrower type and where N is a multiple of number of bits of 6800 /// the narrower type, transform it to a narrower load from address + N / num of 6801 /// bits of new type. If the result is to be extended, also fold the extension 6802 /// to form a extending load. 6803 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6804 unsigned Opc = N->getOpcode(); 6805 6806 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6807 SDValue N0 = N->getOperand(0); 6808 EVT VT = N->getValueType(0); 6809 EVT ExtVT = VT; 6810 6811 // This transformation isn't valid for vector loads. 6812 if (VT.isVector()) 6813 return SDValue(); 6814 6815 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6816 // extended to VT. 6817 if (Opc == ISD::SIGN_EXTEND_INREG) { 6818 ExtType = ISD::SEXTLOAD; 6819 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6820 } else if (Opc == ISD::SRL) { 6821 // Another special-case: SRL is basically zero-extending a narrower value. 6822 ExtType = ISD::ZEXTLOAD; 6823 N0 = SDValue(N, 0); 6824 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6825 if (!N01) return SDValue(); 6826 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6827 VT.getSizeInBits() - N01->getZExtValue()); 6828 } 6829 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6830 return SDValue(); 6831 6832 unsigned EVTBits = ExtVT.getSizeInBits(); 6833 6834 // Do not generate loads of non-round integer types since these can 6835 // be expensive (and would be wrong if the type is not byte sized). 6836 if (!ExtVT.isRound()) 6837 return SDValue(); 6838 6839 unsigned ShAmt = 0; 6840 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6841 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6842 ShAmt = N01->getZExtValue(); 6843 // Is the shift amount a multiple of size of VT? 6844 if ((ShAmt & (EVTBits-1)) == 0) { 6845 N0 = N0.getOperand(0); 6846 // Is the load width a multiple of size of VT? 6847 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6848 return SDValue(); 6849 } 6850 6851 // At this point, we must have a load or else we can't do the transform. 6852 if (!isa<LoadSDNode>(N0)) return SDValue(); 6853 6854 // Because a SRL must be assumed to *need* to zero-extend the high bits 6855 // (as opposed to anyext the high bits), we can't combine the zextload 6856 // lowering of SRL and an sextload. 6857 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6858 return SDValue(); 6859 6860 // If the shift amount is larger than the input type then we're not 6861 // accessing any of the loaded bytes. If the load was a zextload/extload 6862 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6863 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6864 return SDValue(); 6865 } 6866 } 6867 6868 // If the load is shifted left (and the result isn't shifted back right), 6869 // we can fold the truncate through the shift. 6870 unsigned ShLeftAmt = 0; 6871 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6872 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6873 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6874 ShLeftAmt = N01->getZExtValue(); 6875 N0 = N0.getOperand(0); 6876 } 6877 } 6878 6879 // If we haven't found a load, we can't narrow it. Don't transform one with 6880 // multiple uses, this would require adding a new load. 6881 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6882 return SDValue(); 6883 6884 // Don't change the width of a volatile load. 6885 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6886 if (LN0->isVolatile()) 6887 return SDValue(); 6888 6889 // Verify that we are actually reducing a load width here. 6890 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6891 return SDValue(); 6892 6893 // For the transform to be legal, the load must produce only two values 6894 // (the value loaded and the chain). Don't transform a pre-increment 6895 // load, for example, which produces an extra value. Otherwise the 6896 // transformation is not equivalent, and the downstream logic to replace 6897 // uses gets things wrong. 6898 if (LN0->getNumValues() > 2) 6899 return SDValue(); 6900 6901 // If the load that we're shrinking is an extload and we're not just 6902 // discarding the extension we can't simply shrink the load. Bail. 6903 // TODO: It would be possible to merge the extensions in some cases. 6904 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6905 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6906 return SDValue(); 6907 6908 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6909 return SDValue(); 6910 6911 EVT PtrType = N0.getOperand(1).getValueType(); 6912 6913 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6914 // It's not possible to generate a constant of extended or untyped type. 6915 return SDValue(); 6916 6917 // For big endian targets, we need to adjust the offset to the pointer to 6918 // load the correct bytes. 6919 if (DAG.getDataLayout().isBigEndian()) { 6920 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6921 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6922 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6923 } 6924 6925 uint64_t PtrOff = ShAmt / 8; 6926 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6927 SDLoc DL(LN0); 6928 // The original load itself didn't wrap, so an offset within it doesn't. 6929 SDNodeFlags Flags; 6930 Flags.setNoUnsignedWrap(true); 6931 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6932 PtrType, LN0->getBasePtr(), 6933 DAG.getConstant(PtrOff, DL, PtrType), 6934 &Flags); 6935 AddToWorklist(NewPtr.getNode()); 6936 6937 SDValue Load; 6938 if (ExtType == ISD::NON_EXTLOAD) 6939 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6940 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 6941 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6942 else 6943 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 6944 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 6945 NewAlign, LN0->getMemOperand()->getFlags(), 6946 LN0->getAAInfo()); 6947 6948 // Replace the old load's chain with the new load's chain. 6949 WorklistRemover DeadNodes(*this); 6950 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6951 6952 // Shift the result left, if we've swallowed a left shift. 6953 SDValue Result = Load; 6954 if (ShLeftAmt != 0) { 6955 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6956 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6957 ShImmTy = VT; 6958 // If the shift amount is as large as the result size (but, presumably, 6959 // no larger than the source) then the useful bits of the result are 6960 // zero; we can't simply return the shortened shift, because the result 6961 // of that operation is undefined. 6962 SDLoc DL(N0); 6963 if (ShLeftAmt >= VT.getSizeInBits()) 6964 Result = DAG.getConstant(0, DL, VT); 6965 else 6966 Result = DAG.getNode(ISD::SHL, DL, VT, 6967 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6968 } 6969 6970 // Return the new loaded value. 6971 return Result; 6972 } 6973 6974 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6975 SDValue N0 = N->getOperand(0); 6976 SDValue N1 = N->getOperand(1); 6977 EVT VT = N->getValueType(0); 6978 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6979 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6980 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6981 6982 if (N0.isUndef()) 6983 return DAG.getUNDEF(VT); 6984 6985 // fold (sext_in_reg c1) -> c1 6986 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6987 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6988 6989 // If the input is already sign extended, just drop the extension. 6990 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6991 return N0; 6992 6993 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6994 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6995 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6996 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6997 N0.getOperand(0), N1); 6998 6999 // fold (sext_in_reg (sext x)) -> (sext x) 7000 // fold (sext_in_reg (aext x)) -> (sext x) 7001 // if x is small enough. 7002 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 7003 SDValue N00 = N0.getOperand(0); 7004 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 7005 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 7006 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 7007 } 7008 7009 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 7010 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 7011 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 7012 7013 // fold operands of sext_in_reg based on knowledge that the top bits are not 7014 // demanded. 7015 if (SimplifyDemandedBits(SDValue(N, 0))) 7016 return SDValue(N, 0); 7017 7018 // fold (sext_in_reg (load x)) -> (smaller sextload x) 7019 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 7020 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 7021 return NarrowLoad; 7022 7023 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 7024 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 7025 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 7026 if (N0.getOpcode() == ISD::SRL) { 7027 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 7028 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 7029 // We can turn this into an SRA iff the input to the SRL is already sign 7030 // extended enough. 7031 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 7032 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 7033 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 7034 N0.getOperand(0), N0.getOperand(1)); 7035 } 7036 } 7037 7038 // fold (sext_inreg (extload x)) -> (sextload x) 7039 if (ISD::isEXTLoad(N0.getNode()) && 7040 ISD::isUNINDEXEDLoad(N0.getNode()) && 7041 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7042 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7043 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7044 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7045 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7046 LN0->getChain(), 7047 LN0->getBasePtr(), EVT, 7048 LN0->getMemOperand()); 7049 CombineTo(N, ExtLoad); 7050 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7051 AddToWorklist(ExtLoad.getNode()); 7052 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7053 } 7054 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 7055 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7056 N0.hasOneUse() && 7057 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7058 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7059 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7060 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7061 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7062 LN0->getChain(), 7063 LN0->getBasePtr(), EVT, 7064 LN0->getMemOperand()); 7065 CombineTo(N, ExtLoad); 7066 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7067 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7068 } 7069 7070 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7071 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7072 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7073 N0.getOperand(1), false)) 7074 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7075 BSwap, N1); 7076 } 7077 7078 return SDValue(); 7079 } 7080 7081 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7082 SDValue N0 = N->getOperand(0); 7083 EVT VT = N->getValueType(0); 7084 7085 if (N0.isUndef()) 7086 return DAG.getUNDEF(VT); 7087 7088 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7089 LegalOperations)) 7090 return SDValue(Res, 0); 7091 7092 return SDValue(); 7093 } 7094 7095 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7096 SDValue N0 = N->getOperand(0); 7097 EVT VT = N->getValueType(0); 7098 7099 if (N0.isUndef()) 7100 return DAG.getUNDEF(VT); 7101 7102 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7103 LegalOperations)) 7104 return SDValue(Res, 0); 7105 7106 return SDValue(); 7107 } 7108 7109 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7110 SDValue N0 = N->getOperand(0); 7111 EVT VT = N->getValueType(0); 7112 bool isLE = DAG.getDataLayout().isLittleEndian(); 7113 7114 // noop truncate 7115 if (N0.getValueType() == N->getValueType(0)) 7116 return N0; 7117 // fold (truncate c1) -> c1 7118 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7119 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7120 // fold (truncate (truncate x)) -> (truncate x) 7121 if (N0.getOpcode() == ISD::TRUNCATE) 7122 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7123 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7124 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7125 N0.getOpcode() == ISD::SIGN_EXTEND || 7126 N0.getOpcode() == ISD::ANY_EXTEND) { 7127 // if the source is smaller than the dest, we still need an extend. 7128 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7129 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7130 // if the source is larger than the dest, than we just need the truncate. 7131 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7132 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7133 // if the source and dest are the same type, we can drop both the extend 7134 // and the truncate. 7135 return N0.getOperand(0); 7136 } 7137 7138 // Fold extract-and-trunc into a narrow extract. For example: 7139 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7140 // i32 y = TRUNCATE(i64 x) 7141 // -- becomes -- 7142 // v16i8 b = BITCAST (v2i64 val) 7143 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7144 // 7145 // Note: We only run this optimization after type legalization (which often 7146 // creates this pattern) and before operation legalization after which 7147 // we need to be more careful about the vector instructions that we generate. 7148 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7149 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7150 7151 EVT VecTy = N0.getOperand(0).getValueType(); 7152 EVT ExTy = N0.getValueType(); 7153 EVT TrTy = N->getValueType(0); 7154 7155 unsigned NumElem = VecTy.getVectorNumElements(); 7156 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7157 7158 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7159 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7160 7161 SDValue EltNo = N0->getOperand(1); 7162 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7163 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7164 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7165 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7166 7167 SDLoc DL(N); 7168 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7169 DAG.getBitcast(NVT, N0.getOperand(0)), 7170 DAG.getConstant(Index, DL, IndexTy)); 7171 } 7172 } 7173 7174 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7175 if (N0.getOpcode() == ISD::SELECT) { 7176 EVT SrcVT = N0.getValueType(); 7177 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7178 TLI.isTruncateFree(SrcVT, VT)) { 7179 SDLoc SL(N0); 7180 SDValue Cond = N0.getOperand(0); 7181 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7182 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7183 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7184 } 7185 } 7186 7187 // trunc (shl x, K) -> shl (trunc x), K => K < vt.size / 2 7188 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7189 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 7190 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 7191 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 7192 uint64_t Amt = CAmt->getZExtValue(); 7193 unsigned Size = VT.getSizeInBits(); 7194 7195 if (Amt < Size / 2) { 7196 SDLoc SL(N); 7197 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 7198 7199 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 7200 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 7201 DAG.getConstant(Amt, SL, AmtVT)); 7202 } 7203 } 7204 } 7205 7206 // Fold a series of buildvector, bitcast, and truncate if possible. 7207 // For example fold 7208 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7209 // (2xi32 (buildvector x, y)). 7210 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7211 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7212 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7213 N0.getOperand(0).hasOneUse()) { 7214 7215 SDValue BuildVect = N0.getOperand(0); 7216 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7217 EVT TruncVecEltTy = VT.getVectorElementType(); 7218 7219 // Check that the element types match. 7220 if (BuildVectEltTy == TruncVecEltTy) { 7221 // Now we only need to compute the offset of the truncated elements. 7222 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7223 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7224 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7225 7226 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7227 "Invalid number of elements"); 7228 7229 SmallVector<SDValue, 8> Opnds; 7230 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7231 Opnds.push_back(BuildVect.getOperand(i)); 7232 7233 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 7234 } 7235 } 7236 7237 // See if we can simplify the input to this truncate through knowledge that 7238 // only the low bits are being used. 7239 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7240 // Currently we only perform this optimization on scalars because vectors 7241 // may have different active low bits. 7242 if (!VT.isVector()) { 7243 if (SDValue Shorter = 7244 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7245 VT.getSizeInBits()))) 7246 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7247 } 7248 // fold (truncate (load x)) -> (smaller load x) 7249 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7250 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7251 if (SDValue Reduced = ReduceLoadWidth(N)) 7252 return Reduced; 7253 7254 // Handle the case where the load remains an extending load even 7255 // after truncation. 7256 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7257 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7258 if (!LN0->isVolatile() && 7259 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7260 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7261 VT, LN0->getChain(), LN0->getBasePtr(), 7262 LN0->getMemoryVT(), 7263 LN0->getMemOperand()); 7264 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7265 return NewLoad; 7266 } 7267 } 7268 } 7269 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7270 // where ... are all 'undef'. 7271 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7272 SmallVector<EVT, 8> VTs; 7273 SDValue V; 7274 unsigned Idx = 0; 7275 unsigned NumDefs = 0; 7276 7277 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7278 SDValue X = N0.getOperand(i); 7279 if (!X.isUndef()) { 7280 V = X; 7281 Idx = i; 7282 NumDefs++; 7283 } 7284 // Stop if more than one members are non-undef. 7285 if (NumDefs > 1) 7286 break; 7287 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7288 VT.getVectorElementType(), 7289 X.getValueType().getVectorNumElements())); 7290 } 7291 7292 if (NumDefs == 0) 7293 return DAG.getUNDEF(VT); 7294 7295 if (NumDefs == 1) { 7296 assert(V.getNode() && "The single defined operand is empty!"); 7297 SmallVector<SDValue, 8> Opnds; 7298 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7299 if (i != Idx) { 7300 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7301 continue; 7302 } 7303 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7304 AddToWorklist(NV.getNode()); 7305 Opnds.push_back(NV); 7306 } 7307 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7308 } 7309 } 7310 7311 // Fold truncate of a bitcast of a vector to an extract of the low vector 7312 // element. 7313 // 7314 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 7315 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 7316 SDValue VecSrc = N0.getOperand(0); 7317 EVT SrcVT = VecSrc.getValueType(); 7318 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 7319 (!LegalOperations || 7320 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 7321 SDLoc SL(N); 7322 7323 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 7324 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 7325 VecSrc, DAG.getConstant(0, SL, IdxVT)); 7326 } 7327 } 7328 7329 // Simplify the operands using demanded-bits information. 7330 if (!VT.isVector() && 7331 SimplifyDemandedBits(SDValue(N, 0))) 7332 return SDValue(N, 0); 7333 7334 return SDValue(); 7335 } 7336 7337 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7338 SDValue Elt = N->getOperand(i); 7339 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7340 return Elt.getNode(); 7341 return Elt.getOperand(Elt.getResNo()).getNode(); 7342 } 7343 7344 /// build_pair (load, load) -> load 7345 /// if load locations are consecutive. 7346 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7347 assert(N->getOpcode() == ISD::BUILD_PAIR); 7348 7349 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7350 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7351 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7352 LD1->getAddressSpace() != LD2->getAddressSpace()) 7353 return SDValue(); 7354 EVT LD1VT = LD1->getValueType(0); 7355 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 7356 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 7357 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 7358 unsigned Align = LD1->getAlignment(); 7359 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7360 VT.getTypeForEVT(*DAG.getContext())); 7361 7362 if (NewAlign <= Align && 7363 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7364 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 7365 LD1->getPointerInfo(), Align); 7366 } 7367 7368 return SDValue(); 7369 } 7370 7371 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7372 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7373 // and Lo parts; on big-endian machines it doesn't. 7374 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7375 } 7376 7377 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 7378 const TargetLowering &TLI) { 7379 // If this is not a bitcast to an FP type or if the target doesn't have 7380 // IEEE754-compliant FP logic, we're done. 7381 EVT VT = N->getValueType(0); 7382 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 7383 return SDValue(); 7384 7385 // TODO: Use splat values for the constant-checking below and remove this 7386 // restriction. 7387 SDValue N0 = N->getOperand(0); 7388 EVT SourceVT = N0.getValueType(); 7389 if (SourceVT.isVector()) 7390 return SDValue(); 7391 7392 unsigned FPOpcode; 7393 APInt SignMask; 7394 switch (N0.getOpcode()) { 7395 case ISD::AND: 7396 FPOpcode = ISD::FABS; 7397 SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits()); 7398 break; 7399 case ISD::XOR: 7400 FPOpcode = ISD::FNEG; 7401 SignMask = APInt::getSignBit(SourceVT.getSizeInBits()); 7402 break; 7403 // TODO: ISD::OR --> ISD::FNABS? 7404 default: 7405 return SDValue(); 7406 } 7407 7408 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 7409 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 7410 SDValue LogicOp0 = N0.getOperand(0); 7411 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7412 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 7413 LogicOp0.getOpcode() == ISD::BITCAST && 7414 LogicOp0->getOperand(0).getValueType() == VT) 7415 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 7416 7417 return SDValue(); 7418 } 7419 7420 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7421 SDValue N0 = N->getOperand(0); 7422 EVT VT = N->getValueType(0); 7423 7424 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7425 // Only do this before legalize, since afterward the target may be depending 7426 // on the bitconvert. 7427 // First check to see if this is all constant. 7428 if (!LegalTypes && 7429 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7430 VT.isVector()) { 7431 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7432 7433 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7434 assert(!DestEltVT.isVector() && 7435 "Element type of vector ValueType must not be vector!"); 7436 if (isSimple) 7437 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7438 } 7439 7440 // If the input is a constant, let getNode fold it. 7441 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7442 // If we can't allow illegal operations, we need to check that this is just 7443 // a fp -> int or int -> conversion and that the resulting operation will 7444 // be legal. 7445 if (!LegalOperations || 7446 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7447 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7448 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7449 TLI.isOperationLegal(ISD::Constant, VT))) 7450 return DAG.getBitcast(VT, N0); 7451 } 7452 7453 // (conv (conv x, t1), t2) -> (conv x, t2) 7454 if (N0.getOpcode() == ISD::BITCAST) 7455 return DAG.getBitcast(VT, N0.getOperand(0)); 7456 7457 // fold (conv (load x)) -> (load (conv*)x) 7458 // If the resultant load doesn't need a higher alignment than the original! 7459 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7460 // Do not change the width of a volatile load. 7461 !cast<LoadSDNode>(N0)->isVolatile() && 7462 // Do not remove the cast if the types differ in endian layout. 7463 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7464 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7465 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7466 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7467 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7468 unsigned OrigAlign = LN0->getAlignment(); 7469 7470 bool Fast = false; 7471 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7472 LN0->getAddressSpace(), OrigAlign, &Fast) && 7473 Fast) { 7474 SDValue Load = 7475 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 7476 LN0->getPointerInfo(), OrigAlign, 7477 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7478 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7479 return Load; 7480 } 7481 } 7482 7483 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 7484 return V; 7485 7486 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7487 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7488 // 7489 // For ppc_fp128: 7490 // fold (bitcast (fneg x)) -> 7491 // flipbit = signbit 7492 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7493 // 7494 // fold (bitcast (fabs x)) -> 7495 // flipbit = (and (extract_element (bitcast x), 0), signbit) 7496 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7497 // This often reduces constant pool loads. 7498 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7499 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7500 N0.getNode()->hasOneUse() && VT.isInteger() && 7501 !VT.isVector() && !N0.getValueType().isVector()) { 7502 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 7503 AddToWorklist(NewConv.getNode()); 7504 7505 SDLoc DL(N); 7506 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7507 assert(VT.getSizeInBits() == 128); 7508 SDValue SignBit = DAG.getConstant( 7509 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 7510 SDValue FlipBit; 7511 if (N0.getOpcode() == ISD::FNEG) { 7512 FlipBit = SignBit; 7513 AddToWorklist(FlipBit.getNode()); 7514 } else { 7515 assert(N0.getOpcode() == ISD::FABS); 7516 SDValue Hi = 7517 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 7518 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7519 SDLoc(NewConv))); 7520 AddToWorklist(Hi.getNode()); 7521 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 7522 AddToWorklist(FlipBit.getNode()); 7523 } 7524 SDValue FlipBits = 7525 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7526 AddToWorklist(FlipBits.getNode()); 7527 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 7528 } 7529 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7530 if (N0.getOpcode() == ISD::FNEG) 7531 return DAG.getNode(ISD::XOR, DL, VT, 7532 NewConv, DAG.getConstant(SignBit, DL, VT)); 7533 assert(N0.getOpcode() == ISD::FABS); 7534 return DAG.getNode(ISD::AND, DL, VT, 7535 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7536 } 7537 7538 // fold (bitconvert (fcopysign cst, x)) -> 7539 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7540 // Note that we don't handle (copysign x, cst) because this can always be 7541 // folded to an fneg or fabs. 7542 // 7543 // For ppc_fp128: 7544 // fold (bitcast (fcopysign cst, x)) -> 7545 // flipbit = (and (extract_element 7546 // (xor (bitcast cst), (bitcast x)), 0), 7547 // signbit) 7548 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 7549 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7550 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7551 VT.isInteger() && !VT.isVector()) { 7552 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7553 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7554 if (isTypeLegal(IntXVT)) { 7555 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 7556 AddToWorklist(X.getNode()); 7557 7558 // If X has a different width than the result/lhs, sext it or truncate it. 7559 unsigned VTWidth = VT.getSizeInBits(); 7560 if (OrigXWidth < VTWidth) { 7561 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7562 AddToWorklist(X.getNode()); 7563 } else if (OrigXWidth > VTWidth) { 7564 // To get the sign bit in the right place, we have to shift it right 7565 // before truncating. 7566 SDLoc DL(X); 7567 X = DAG.getNode(ISD::SRL, DL, 7568 X.getValueType(), X, 7569 DAG.getConstant(OrigXWidth-VTWidth, DL, 7570 X.getValueType())); 7571 AddToWorklist(X.getNode()); 7572 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7573 AddToWorklist(X.getNode()); 7574 } 7575 7576 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7577 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 7578 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7579 AddToWorklist(Cst.getNode()); 7580 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 7581 AddToWorklist(X.getNode()); 7582 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 7583 AddToWorklist(XorResult.getNode()); 7584 SDValue XorResult64 = DAG.getNode( 7585 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 7586 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7587 SDLoc(XorResult))); 7588 AddToWorklist(XorResult64.getNode()); 7589 SDValue FlipBit = 7590 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 7591 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 7592 AddToWorklist(FlipBit.getNode()); 7593 SDValue FlipBits = 7594 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7595 AddToWorklist(FlipBits.getNode()); 7596 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 7597 } 7598 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7599 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7600 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7601 AddToWorklist(X.getNode()); 7602 7603 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7604 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7605 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7606 AddToWorklist(Cst.getNode()); 7607 7608 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7609 } 7610 } 7611 7612 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7613 if (N0.getOpcode() == ISD::BUILD_PAIR) 7614 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7615 return CombineLD; 7616 7617 // Remove double bitcasts from shuffles - this is often a legacy of 7618 // XformToShuffleWithZero being used to combine bitmaskings (of 7619 // float vectors bitcast to integer vectors) into shuffles. 7620 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7621 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7622 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7623 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7624 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7625 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7626 7627 // If operands are a bitcast, peek through if it casts the original VT. 7628 // If operands are a constant, just bitcast back to original VT. 7629 auto PeekThroughBitcast = [&](SDValue Op) { 7630 if (Op.getOpcode() == ISD::BITCAST && 7631 Op.getOperand(0).getValueType() == VT) 7632 return SDValue(Op.getOperand(0)); 7633 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7634 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7635 return DAG.getBitcast(VT, Op); 7636 return SDValue(); 7637 }; 7638 7639 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7640 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7641 if (!(SV0 && SV1)) 7642 return SDValue(); 7643 7644 int MaskScale = 7645 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7646 SmallVector<int, 8> NewMask; 7647 for (int M : SVN->getMask()) 7648 for (int i = 0; i != MaskScale; ++i) 7649 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7650 7651 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7652 if (!LegalMask) { 7653 std::swap(SV0, SV1); 7654 ShuffleVectorSDNode::commuteMask(NewMask); 7655 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7656 } 7657 7658 if (LegalMask) 7659 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7660 } 7661 7662 return SDValue(); 7663 } 7664 7665 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7666 EVT VT = N->getValueType(0); 7667 return CombineConsecutiveLoads(N, VT); 7668 } 7669 7670 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7671 /// operands. DstEltVT indicates the destination element value type. 7672 SDValue DAGCombiner:: 7673 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7674 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7675 7676 // If this is already the right type, we're done. 7677 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7678 7679 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7680 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7681 7682 // If this is a conversion of N elements of one type to N elements of another 7683 // type, convert each element. This handles FP<->INT cases. 7684 if (SrcBitSize == DstBitSize) { 7685 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7686 BV->getValueType(0).getVectorNumElements()); 7687 7688 // Due to the FP element handling below calling this routine recursively, 7689 // we can end up with a scalar-to-vector node here. 7690 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7691 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7692 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 7693 7694 SmallVector<SDValue, 8> Ops; 7695 for (SDValue Op : BV->op_values()) { 7696 // If the vector element type is not legal, the BUILD_VECTOR operands 7697 // are promoted and implicitly truncated. Make that explicit here. 7698 if (Op.getValueType() != SrcEltVT) 7699 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7700 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 7701 AddToWorklist(Ops.back().getNode()); 7702 } 7703 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 7704 } 7705 7706 // Otherwise, we're growing or shrinking the elements. To avoid having to 7707 // handle annoying details of growing/shrinking FP values, we convert them to 7708 // int first. 7709 if (SrcEltVT.isFloatingPoint()) { 7710 // Convert the input float vector to a int vector where the elements are the 7711 // same sizes. 7712 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7713 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7714 SrcEltVT = IntVT; 7715 } 7716 7717 // Now we know the input is an integer vector. If the output is a FP type, 7718 // convert to integer first, then to FP of the right size. 7719 if (DstEltVT.isFloatingPoint()) { 7720 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7721 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7722 7723 // Next, convert to FP elements of the same size. 7724 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7725 } 7726 7727 SDLoc DL(BV); 7728 7729 // Okay, we know the src/dst types are both integers of differing types. 7730 // Handling growing first. 7731 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7732 if (SrcBitSize < DstBitSize) { 7733 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7734 7735 SmallVector<SDValue, 8> Ops; 7736 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7737 i += NumInputsPerOutput) { 7738 bool isLE = DAG.getDataLayout().isLittleEndian(); 7739 APInt NewBits = APInt(DstBitSize, 0); 7740 bool EltIsUndef = true; 7741 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7742 // Shift the previously computed bits over. 7743 NewBits <<= SrcBitSize; 7744 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7745 if (Op.isUndef()) continue; 7746 EltIsUndef = false; 7747 7748 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7749 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7750 } 7751 7752 if (EltIsUndef) 7753 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7754 else 7755 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7756 } 7757 7758 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7759 return DAG.getBuildVector(VT, DL, Ops); 7760 } 7761 7762 // Finally, this must be the case where we are shrinking elements: each input 7763 // turns into multiple outputs. 7764 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7765 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7766 NumOutputsPerInput*BV->getNumOperands()); 7767 SmallVector<SDValue, 8> Ops; 7768 7769 for (const SDValue &Op : BV->op_values()) { 7770 if (Op.isUndef()) { 7771 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7772 continue; 7773 } 7774 7775 APInt OpVal = cast<ConstantSDNode>(Op)-> 7776 getAPIntValue().zextOrTrunc(SrcBitSize); 7777 7778 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7779 APInt ThisVal = OpVal.trunc(DstBitSize); 7780 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7781 OpVal = OpVal.lshr(DstBitSize); 7782 } 7783 7784 // For big endian targets, swap the order of the pieces of each element. 7785 if (DAG.getDataLayout().isBigEndian()) 7786 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7787 } 7788 7789 return DAG.getBuildVector(VT, DL, Ops); 7790 } 7791 7792 /// Try to perform FMA combining on a given FADD node. 7793 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7794 SDValue N0 = N->getOperand(0); 7795 SDValue N1 = N->getOperand(1); 7796 EVT VT = N->getValueType(0); 7797 SDLoc SL(N); 7798 7799 const TargetOptions &Options = DAG.getTarget().Options; 7800 bool AllowFusion = 7801 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7802 7803 // Floating-point multiply-add with intermediate rounding. 7804 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7805 7806 // Floating-point multiply-add without intermediate rounding. 7807 bool HasFMA = 7808 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7809 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7810 7811 // No valid opcode, do not combine. 7812 if (!HasFMAD && !HasFMA) 7813 return SDValue(); 7814 7815 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7816 ; 7817 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7818 return SDValue(); 7819 7820 // Always prefer FMAD to FMA for precision. 7821 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7822 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7823 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7824 7825 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7826 // prefer to fold the multiply with fewer uses. 7827 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7828 N1.getOpcode() == ISD::FMUL) { 7829 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7830 std::swap(N0, N1); 7831 } 7832 7833 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7834 if (N0.getOpcode() == ISD::FMUL && 7835 (Aggressive || N0->hasOneUse())) { 7836 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7837 N0.getOperand(0), N0.getOperand(1), N1); 7838 } 7839 7840 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7841 // Note: Commutes FADD operands. 7842 if (N1.getOpcode() == ISD::FMUL && 7843 (Aggressive || N1->hasOneUse())) { 7844 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7845 N1.getOperand(0), N1.getOperand(1), N0); 7846 } 7847 7848 // Look through FP_EXTEND nodes to do more combining. 7849 if (AllowFusion && LookThroughFPExt) { 7850 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7851 if (N0.getOpcode() == ISD::FP_EXTEND) { 7852 SDValue N00 = N0.getOperand(0); 7853 if (N00.getOpcode() == ISD::FMUL) 7854 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7855 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7856 N00.getOperand(0)), 7857 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7858 N00.getOperand(1)), N1); 7859 } 7860 7861 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7862 // Note: Commutes FADD operands. 7863 if (N1.getOpcode() == ISD::FP_EXTEND) { 7864 SDValue N10 = N1.getOperand(0); 7865 if (N10.getOpcode() == ISD::FMUL) 7866 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7867 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7868 N10.getOperand(0)), 7869 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7870 N10.getOperand(1)), N0); 7871 } 7872 } 7873 7874 // More folding opportunities when target permits. 7875 if ((AllowFusion || HasFMAD) && Aggressive) { 7876 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7877 if (N0.getOpcode() == PreferredFusedOpcode && 7878 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7879 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7880 N0.getOperand(0), N0.getOperand(1), 7881 DAG.getNode(PreferredFusedOpcode, SL, VT, 7882 N0.getOperand(2).getOperand(0), 7883 N0.getOperand(2).getOperand(1), 7884 N1)); 7885 } 7886 7887 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7888 if (N1->getOpcode() == PreferredFusedOpcode && 7889 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7890 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7891 N1.getOperand(0), N1.getOperand(1), 7892 DAG.getNode(PreferredFusedOpcode, SL, VT, 7893 N1.getOperand(2).getOperand(0), 7894 N1.getOperand(2).getOperand(1), 7895 N0)); 7896 } 7897 7898 if (AllowFusion && LookThroughFPExt) { 7899 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7900 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7901 auto FoldFAddFMAFPExtFMul = [&] ( 7902 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7903 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7904 DAG.getNode(PreferredFusedOpcode, SL, VT, 7905 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7906 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7907 Z)); 7908 }; 7909 if (N0.getOpcode() == PreferredFusedOpcode) { 7910 SDValue N02 = N0.getOperand(2); 7911 if (N02.getOpcode() == ISD::FP_EXTEND) { 7912 SDValue N020 = N02.getOperand(0); 7913 if (N020.getOpcode() == ISD::FMUL) 7914 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7915 N020.getOperand(0), N020.getOperand(1), 7916 N1); 7917 } 7918 } 7919 7920 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7921 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7922 // FIXME: This turns two single-precision and one double-precision 7923 // operation into two double-precision operations, which might not be 7924 // interesting for all targets, especially GPUs. 7925 auto FoldFAddFPExtFMAFMul = [&] ( 7926 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7927 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7928 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7929 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7930 DAG.getNode(PreferredFusedOpcode, SL, VT, 7931 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7932 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7933 Z)); 7934 }; 7935 if (N0.getOpcode() == ISD::FP_EXTEND) { 7936 SDValue N00 = N0.getOperand(0); 7937 if (N00.getOpcode() == PreferredFusedOpcode) { 7938 SDValue N002 = N00.getOperand(2); 7939 if (N002.getOpcode() == ISD::FMUL) 7940 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7941 N002.getOperand(0), N002.getOperand(1), 7942 N1); 7943 } 7944 } 7945 7946 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7947 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7948 if (N1.getOpcode() == PreferredFusedOpcode) { 7949 SDValue N12 = N1.getOperand(2); 7950 if (N12.getOpcode() == ISD::FP_EXTEND) { 7951 SDValue N120 = N12.getOperand(0); 7952 if (N120.getOpcode() == ISD::FMUL) 7953 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7954 N120.getOperand(0), N120.getOperand(1), 7955 N0); 7956 } 7957 } 7958 7959 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7960 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7961 // FIXME: This turns two single-precision and one double-precision 7962 // operation into two double-precision operations, which might not be 7963 // interesting for all targets, especially GPUs. 7964 if (N1.getOpcode() == ISD::FP_EXTEND) { 7965 SDValue N10 = N1.getOperand(0); 7966 if (N10.getOpcode() == PreferredFusedOpcode) { 7967 SDValue N102 = N10.getOperand(2); 7968 if (N102.getOpcode() == ISD::FMUL) 7969 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7970 N102.getOperand(0), N102.getOperand(1), 7971 N0); 7972 } 7973 } 7974 } 7975 } 7976 7977 return SDValue(); 7978 } 7979 7980 /// Try to perform FMA combining on a given FSUB node. 7981 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7982 SDValue N0 = N->getOperand(0); 7983 SDValue N1 = N->getOperand(1); 7984 EVT VT = N->getValueType(0); 7985 SDLoc SL(N); 7986 7987 const TargetOptions &Options = DAG.getTarget().Options; 7988 bool AllowFusion = 7989 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7990 7991 // Floating-point multiply-add with intermediate rounding. 7992 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7993 7994 // Floating-point multiply-add without intermediate rounding. 7995 bool HasFMA = 7996 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7997 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7998 7999 // No valid opcode, do not combine. 8000 if (!HasFMAD && !HasFMA) 8001 return SDValue(); 8002 8003 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 8004 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 8005 return SDValue(); 8006 8007 // Always prefer FMAD to FMA for precision. 8008 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8009 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8010 bool LookThroughFPExt = TLI.isFPExtFree(VT); 8011 8012 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 8013 if (N0.getOpcode() == ISD::FMUL && 8014 (Aggressive || N0->hasOneUse())) { 8015 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8016 N0.getOperand(0), N0.getOperand(1), 8017 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8018 } 8019 8020 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 8021 // Note: Commutes FSUB operands. 8022 if (N1.getOpcode() == ISD::FMUL && 8023 (Aggressive || N1->hasOneUse())) 8024 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8025 DAG.getNode(ISD::FNEG, SL, VT, 8026 N1.getOperand(0)), 8027 N1.getOperand(1), N0); 8028 8029 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 8030 if (N0.getOpcode() == ISD::FNEG && 8031 N0.getOperand(0).getOpcode() == ISD::FMUL && 8032 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 8033 SDValue N00 = N0.getOperand(0).getOperand(0); 8034 SDValue N01 = N0.getOperand(0).getOperand(1); 8035 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8036 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 8037 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8038 } 8039 8040 // Look through FP_EXTEND nodes to do more combining. 8041 if (AllowFusion && LookThroughFPExt) { 8042 // fold (fsub (fpext (fmul x, y)), z) 8043 // -> (fma (fpext x), (fpext y), (fneg z)) 8044 if (N0.getOpcode() == ISD::FP_EXTEND) { 8045 SDValue N00 = N0.getOperand(0); 8046 if (N00.getOpcode() == ISD::FMUL) 8047 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8048 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8049 N00.getOperand(0)), 8050 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8051 N00.getOperand(1)), 8052 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8053 } 8054 8055 // fold (fsub x, (fpext (fmul y, z))) 8056 // -> (fma (fneg (fpext y)), (fpext z), x) 8057 // Note: Commutes FSUB operands. 8058 if (N1.getOpcode() == ISD::FP_EXTEND) { 8059 SDValue N10 = N1.getOperand(0); 8060 if (N10.getOpcode() == ISD::FMUL) 8061 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8062 DAG.getNode(ISD::FNEG, SL, VT, 8063 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8064 N10.getOperand(0))), 8065 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8066 N10.getOperand(1)), 8067 N0); 8068 } 8069 8070 // fold (fsub (fpext (fneg (fmul, x, y))), z) 8071 // -> (fneg (fma (fpext x), (fpext y), z)) 8072 // Note: This could be removed with appropriate canonicalization of the 8073 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8074 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8075 // from implementing the canonicalization in visitFSUB. 8076 if (N0.getOpcode() == ISD::FP_EXTEND) { 8077 SDValue N00 = N0.getOperand(0); 8078 if (N00.getOpcode() == ISD::FNEG) { 8079 SDValue N000 = N00.getOperand(0); 8080 if (N000.getOpcode() == ISD::FMUL) { 8081 return DAG.getNode(ISD::FNEG, SL, VT, 8082 DAG.getNode(PreferredFusedOpcode, SL, VT, 8083 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8084 N000.getOperand(0)), 8085 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8086 N000.getOperand(1)), 8087 N1)); 8088 } 8089 } 8090 } 8091 8092 // fold (fsub (fneg (fpext (fmul, x, y))), z) 8093 // -> (fneg (fma (fpext x)), (fpext y), z) 8094 // Note: This could be removed with appropriate canonicalization of the 8095 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8096 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8097 // from implementing the canonicalization in visitFSUB. 8098 if (N0.getOpcode() == ISD::FNEG) { 8099 SDValue N00 = N0.getOperand(0); 8100 if (N00.getOpcode() == ISD::FP_EXTEND) { 8101 SDValue N000 = N00.getOperand(0); 8102 if (N000.getOpcode() == ISD::FMUL) { 8103 return DAG.getNode(ISD::FNEG, SL, VT, 8104 DAG.getNode(PreferredFusedOpcode, SL, VT, 8105 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8106 N000.getOperand(0)), 8107 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8108 N000.getOperand(1)), 8109 N1)); 8110 } 8111 } 8112 } 8113 8114 } 8115 8116 // More folding opportunities when target permits. 8117 if ((AllowFusion || HasFMAD) && Aggressive) { 8118 // fold (fsub (fma x, y, (fmul u, v)), z) 8119 // -> (fma x, y (fma u, v, (fneg z))) 8120 if (N0.getOpcode() == PreferredFusedOpcode && 8121 N0.getOperand(2).getOpcode() == ISD::FMUL) { 8122 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8123 N0.getOperand(0), N0.getOperand(1), 8124 DAG.getNode(PreferredFusedOpcode, SL, VT, 8125 N0.getOperand(2).getOperand(0), 8126 N0.getOperand(2).getOperand(1), 8127 DAG.getNode(ISD::FNEG, SL, VT, 8128 N1))); 8129 } 8130 8131 // fold (fsub x, (fma y, z, (fmul u, v))) 8132 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 8133 if (N1.getOpcode() == PreferredFusedOpcode && 8134 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8135 SDValue N20 = N1.getOperand(2).getOperand(0); 8136 SDValue N21 = N1.getOperand(2).getOperand(1); 8137 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8138 DAG.getNode(ISD::FNEG, SL, VT, 8139 N1.getOperand(0)), 8140 N1.getOperand(1), 8141 DAG.getNode(PreferredFusedOpcode, SL, VT, 8142 DAG.getNode(ISD::FNEG, SL, VT, N20), 8143 8144 N21, N0)); 8145 } 8146 8147 if (AllowFusion && LookThroughFPExt) { 8148 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 8149 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8150 if (N0.getOpcode() == PreferredFusedOpcode) { 8151 SDValue N02 = N0.getOperand(2); 8152 if (N02.getOpcode() == ISD::FP_EXTEND) { 8153 SDValue N020 = N02.getOperand(0); 8154 if (N020.getOpcode() == ISD::FMUL) 8155 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8156 N0.getOperand(0), N0.getOperand(1), 8157 DAG.getNode(PreferredFusedOpcode, SL, VT, 8158 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8159 N020.getOperand(0)), 8160 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8161 N020.getOperand(1)), 8162 DAG.getNode(ISD::FNEG, SL, VT, 8163 N1))); 8164 } 8165 } 8166 8167 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8168 // -> (fma (fpext x), (fpext y), 8169 // (fma (fpext u), (fpext v), (fneg z))) 8170 // FIXME: This turns two single-precision and one double-precision 8171 // operation into two double-precision operations, which might not be 8172 // interesting for all targets, especially GPUs. 8173 if (N0.getOpcode() == ISD::FP_EXTEND) { 8174 SDValue N00 = N0.getOperand(0); 8175 if (N00.getOpcode() == PreferredFusedOpcode) { 8176 SDValue N002 = N00.getOperand(2); 8177 if (N002.getOpcode() == ISD::FMUL) 8178 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8179 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8180 N00.getOperand(0)), 8181 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8182 N00.getOperand(1)), 8183 DAG.getNode(PreferredFusedOpcode, SL, VT, 8184 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8185 N002.getOperand(0)), 8186 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8187 N002.getOperand(1)), 8188 DAG.getNode(ISD::FNEG, SL, VT, 8189 N1))); 8190 } 8191 } 8192 8193 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8194 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8195 if (N1.getOpcode() == PreferredFusedOpcode && 8196 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8197 SDValue N120 = N1.getOperand(2).getOperand(0); 8198 if (N120.getOpcode() == ISD::FMUL) { 8199 SDValue N1200 = N120.getOperand(0); 8200 SDValue N1201 = N120.getOperand(1); 8201 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8202 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8203 N1.getOperand(1), 8204 DAG.getNode(PreferredFusedOpcode, SL, VT, 8205 DAG.getNode(ISD::FNEG, SL, VT, 8206 DAG.getNode(ISD::FP_EXTEND, SL, 8207 VT, N1200)), 8208 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8209 N1201), 8210 N0)); 8211 } 8212 } 8213 8214 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8215 // -> (fma (fneg (fpext y)), (fpext z), 8216 // (fma (fneg (fpext u)), (fpext v), x)) 8217 // FIXME: This turns two single-precision and one double-precision 8218 // operation into two double-precision operations, which might not be 8219 // interesting for all targets, especially GPUs. 8220 if (N1.getOpcode() == ISD::FP_EXTEND && 8221 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8222 SDValue N100 = N1.getOperand(0).getOperand(0); 8223 SDValue N101 = N1.getOperand(0).getOperand(1); 8224 SDValue N102 = N1.getOperand(0).getOperand(2); 8225 if (N102.getOpcode() == ISD::FMUL) { 8226 SDValue N1020 = N102.getOperand(0); 8227 SDValue N1021 = N102.getOperand(1); 8228 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8229 DAG.getNode(ISD::FNEG, SL, VT, 8230 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8231 N100)), 8232 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8233 DAG.getNode(PreferredFusedOpcode, SL, VT, 8234 DAG.getNode(ISD::FNEG, SL, VT, 8235 DAG.getNode(ISD::FP_EXTEND, SL, 8236 VT, N1020)), 8237 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8238 N1021), 8239 N0)); 8240 } 8241 } 8242 } 8243 } 8244 8245 return SDValue(); 8246 } 8247 8248 /// Try to perform FMA combining on a given FMUL node. 8249 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 8250 SDValue N0 = N->getOperand(0); 8251 SDValue N1 = N->getOperand(1); 8252 EVT VT = N->getValueType(0); 8253 SDLoc SL(N); 8254 8255 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8256 8257 const TargetOptions &Options = DAG.getTarget().Options; 8258 bool AllowFusion = 8259 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8260 8261 // Floating-point multiply-add with intermediate rounding. 8262 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8263 8264 // Floating-point multiply-add without intermediate rounding. 8265 bool HasFMA = 8266 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8267 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8268 8269 // No valid opcode, do not combine. 8270 if (!HasFMAD && !HasFMA) 8271 return SDValue(); 8272 8273 // Always prefer FMAD to FMA for precision. 8274 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8275 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8276 8277 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8278 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8279 auto FuseFADD = [&](SDValue X, SDValue Y) { 8280 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8281 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8282 if (XC1 && XC1->isExactlyValue(+1.0)) 8283 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8284 if (XC1 && XC1->isExactlyValue(-1.0)) 8285 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8286 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8287 } 8288 return SDValue(); 8289 }; 8290 8291 if (SDValue FMA = FuseFADD(N0, N1)) 8292 return FMA; 8293 if (SDValue FMA = FuseFADD(N1, N0)) 8294 return FMA; 8295 8296 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8297 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8298 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8299 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8300 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8301 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8302 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8303 if (XC0 && XC0->isExactlyValue(+1.0)) 8304 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8305 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8306 Y); 8307 if (XC0 && XC0->isExactlyValue(-1.0)) 8308 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8309 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8310 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8311 8312 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8313 if (XC1 && XC1->isExactlyValue(+1.0)) 8314 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8315 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8316 if (XC1 && XC1->isExactlyValue(-1.0)) 8317 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8318 } 8319 return SDValue(); 8320 }; 8321 8322 if (SDValue FMA = FuseFSUB(N0, N1)) 8323 return FMA; 8324 if (SDValue FMA = FuseFSUB(N1, N0)) 8325 return FMA; 8326 8327 return SDValue(); 8328 } 8329 8330 SDValue DAGCombiner::visitFADD(SDNode *N) { 8331 SDValue N0 = N->getOperand(0); 8332 SDValue N1 = N->getOperand(1); 8333 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8334 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8335 EVT VT = N->getValueType(0); 8336 SDLoc DL(N); 8337 const TargetOptions &Options = DAG.getTarget().Options; 8338 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8339 8340 // fold vector ops 8341 if (VT.isVector()) 8342 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8343 return FoldedVOp; 8344 8345 // fold (fadd c1, c2) -> c1 + c2 8346 if (N0CFP && N1CFP) 8347 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8348 8349 // canonicalize constant to RHS 8350 if (N0CFP && !N1CFP) 8351 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8352 8353 // fold (fadd A, (fneg B)) -> (fsub A, B) 8354 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8355 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8356 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8357 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8358 8359 // fold (fadd (fneg A), B) -> (fsub B, A) 8360 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8361 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8362 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8363 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8364 8365 // If 'unsafe math' is enabled, fold lots of things. 8366 if (Options.UnsafeFPMath) { 8367 // No FP constant should be created after legalization as Instruction 8368 // Selection pass has a hard time dealing with FP constants. 8369 bool AllowNewConst = (Level < AfterLegalizeDAG); 8370 8371 // fold (fadd A, 0) -> A 8372 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8373 if (N1C->isZero()) 8374 return N0; 8375 8376 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8377 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8378 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8379 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8380 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8381 Flags), 8382 Flags); 8383 8384 // If allowed, fold (fadd (fneg x), x) -> 0.0 8385 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8386 return DAG.getConstantFP(0.0, DL, VT); 8387 8388 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8389 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8390 return DAG.getConstantFP(0.0, DL, VT); 8391 8392 // We can fold chains of FADD's of the same value into multiplications. 8393 // This transform is not safe in general because we are reducing the number 8394 // of rounding steps. 8395 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8396 if (N0.getOpcode() == ISD::FMUL) { 8397 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8398 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8399 8400 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8401 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8402 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8403 DAG.getConstantFP(1.0, DL, VT), Flags); 8404 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8405 } 8406 8407 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8408 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8409 N1.getOperand(0) == N1.getOperand(1) && 8410 N0.getOperand(0) == N1.getOperand(0)) { 8411 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8412 DAG.getConstantFP(2.0, DL, VT), Flags); 8413 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8414 } 8415 } 8416 8417 if (N1.getOpcode() == ISD::FMUL) { 8418 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8419 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8420 8421 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8422 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8423 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8424 DAG.getConstantFP(1.0, DL, VT), Flags); 8425 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8426 } 8427 8428 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8429 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8430 N0.getOperand(0) == N0.getOperand(1) && 8431 N1.getOperand(0) == N0.getOperand(0)) { 8432 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8433 DAG.getConstantFP(2.0, DL, VT), Flags); 8434 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8435 } 8436 } 8437 8438 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8439 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8440 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8441 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8442 (N0.getOperand(0) == N1)) { 8443 return DAG.getNode(ISD::FMUL, DL, VT, 8444 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8445 } 8446 } 8447 8448 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8449 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8450 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8451 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8452 N1.getOperand(0) == N0) { 8453 return DAG.getNode(ISD::FMUL, DL, VT, 8454 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8455 } 8456 } 8457 8458 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8459 if (AllowNewConst && 8460 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8461 N0.getOperand(0) == N0.getOperand(1) && 8462 N1.getOperand(0) == N1.getOperand(1) && 8463 N0.getOperand(0) == N1.getOperand(0)) { 8464 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8465 DAG.getConstantFP(4.0, DL, VT), Flags); 8466 } 8467 } 8468 } // enable-unsafe-fp-math 8469 8470 // FADD -> FMA combines: 8471 if (SDValue Fused = visitFADDForFMACombine(N)) { 8472 AddToWorklist(Fused.getNode()); 8473 return Fused; 8474 } 8475 return SDValue(); 8476 } 8477 8478 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8479 SDValue N0 = N->getOperand(0); 8480 SDValue N1 = N->getOperand(1); 8481 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8482 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8483 EVT VT = N->getValueType(0); 8484 SDLoc dl(N); 8485 const TargetOptions &Options = DAG.getTarget().Options; 8486 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8487 8488 // fold vector ops 8489 if (VT.isVector()) 8490 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8491 return FoldedVOp; 8492 8493 // fold (fsub c1, c2) -> c1-c2 8494 if (N0CFP && N1CFP) 8495 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8496 8497 // fold (fsub A, (fneg B)) -> (fadd A, B) 8498 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8499 return DAG.getNode(ISD::FADD, dl, VT, N0, 8500 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8501 8502 // If 'unsafe math' is enabled, fold lots of things. 8503 if (Options.UnsafeFPMath) { 8504 // (fsub A, 0) -> A 8505 if (N1CFP && N1CFP->isZero()) 8506 return N0; 8507 8508 // (fsub 0, B) -> -B 8509 if (N0CFP && N0CFP->isZero()) { 8510 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8511 return GetNegatedExpression(N1, DAG, LegalOperations); 8512 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8513 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8514 } 8515 8516 // (fsub x, x) -> 0.0 8517 if (N0 == N1) 8518 return DAG.getConstantFP(0.0f, dl, VT); 8519 8520 // (fsub x, (fadd x, y)) -> (fneg y) 8521 // (fsub x, (fadd y, x)) -> (fneg y) 8522 if (N1.getOpcode() == ISD::FADD) { 8523 SDValue N10 = N1->getOperand(0); 8524 SDValue N11 = N1->getOperand(1); 8525 8526 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8527 return GetNegatedExpression(N11, DAG, LegalOperations); 8528 8529 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8530 return GetNegatedExpression(N10, DAG, LegalOperations); 8531 } 8532 } 8533 8534 // FSUB -> FMA combines: 8535 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8536 AddToWorklist(Fused.getNode()); 8537 return Fused; 8538 } 8539 8540 return SDValue(); 8541 } 8542 8543 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8544 SDValue N0 = N->getOperand(0); 8545 SDValue N1 = N->getOperand(1); 8546 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8547 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8548 EVT VT = N->getValueType(0); 8549 SDLoc DL(N); 8550 const TargetOptions &Options = DAG.getTarget().Options; 8551 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8552 8553 // fold vector ops 8554 if (VT.isVector()) { 8555 // This just handles C1 * C2 for vectors. Other vector folds are below. 8556 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8557 return FoldedVOp; 8558 } 8559 8560 // fold (fmul c1, c2) -> c1*c2 8561 if (N0CFP && N1CFP) 8562 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8563 8564 // canonicalize constant to RHS 8565 if (isConstantFPBuildVectorOrConstantFP(N0) && 8566 !isConstantFPBuildVectorOrConstantFP(N1)) 8567 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8568 8569 // fold (fmul A, 1.0) -> A 8570 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8571 return N0; 8572 8573 if (Options.UnsafeFPMath) { 8574 // fold (fmul A, 0) -> 0 8575 if (N1CFP && N1CFP->isZero()) 8576 return N1; 8577 8578 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8579 if (N0.getOpcode() == ISD::FMUL) { 8580 // Fold scalars or any vector constants (not just splats). 8581 // This fold is done in general by InstCombine, but extra fmul insts 8582 // may have been generated during lowering. 8583 SDValue N00 = N0.getOperand(0); 8584 SDValue N01 = N0.getOperand(1); 8585 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8586 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8587 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8588 8589 // Check 1: Make sure that the first operand of the inner multiply is NOT 8590 // a constant. Otherwise, we may induce infinite looping. 8591 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8592 // Check 2: Make sure that the second operand of the inner multiply and 8593 // the second operand of the outer multiply are constants. 8594 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8595 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8596 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8597 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8598 } 8599 } 8600 } 8601 8602 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8603 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8604 // during an early run of DAGCombiner can prevent folding with fmuls 8605 // inserted during lowering. 8606 if (N0.getOpcode() == ISD::FADD && 8607 (N0.getOperand(0) == N0.getOperand(1)) && 8608 N0.hasOneUse()) { 8609 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8610 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8611 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8612 } 8613 } 8614 8615 // fold (fmul X, 2.0) -> (fadd X, X) 8616 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8617 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8618 8619 // fold (fmul X, -1.0) -> (fneg X) 8620 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8621 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8622 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8623 8624 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8625 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8626 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8627 // Both can be negated for free, check to see if at least one is cheaper 8628 // negated. 8629 if (LHSNeg == 2 || RHSNeg == 2) 8630 return DAG.getNode(ISD::FMUL, DL, VT, 8631 GetNegatedExpression(N0, DAG, LegalOperations), 8632 GetNegatedExpression(N1, DAG, LegalOperations), 8633 Flags); 8634 } 8635 } 8636 8637 // FMUL -> FMA combines: 8638 if (SDValue Fused = visitFMULForFMACombine(N)) { 8639 AddToWorklist(Fused.getNode()); 8640 return Fused; 8641 } 8642 8643 return SDValue(); 8644 } 8645 8646 SDValue DAGCombiner::visitFMA(SDNode *N) { 8647 SDValue N0 = N->getOperand(0); 8648 SDValue N1 = N->getOperand(1); 8649 SDValue N2 = N->getOperand(2); 8650 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8651 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8652 EVT VT = N->getValueType(0); 8653 SDLoc dl(N); 8654 const TargetOptions &Options = DAG.getTarget().Options; 8655 8656 // Constant fold FMA. 8657 if (isa<ConstantFPSDNode>(N0) && 8658 isa<ConstantFPSDNode>(N1) && 8659 isa<ConstantFPSDNode>(N2)) { 8660 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8661 } 8662 8663 if (Options.UnsafeFPMath) { 8664 if (N0CFP && N0CFP->isZero()) 8665 return N2; 8666 if (N1CFP && N1CFP->isZero()) 8667 return N2; 8668 } 8669 // TODO: The FMA node should have flags that propagate to these nodes. 8670 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8671 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8672 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8673 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8674 8675 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8676 if (isConstantFPBuildVectorOrConstantFP(N0) && 8677 !isConstantFPBuildVectorOrConstantFP(N1)) 8678 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8679 8680 // TODO: FMA nodes should have flags that propagate to the created nodes. 8681 // For now, create a Flags object for use with all unsafe math transforms. 8682 SDNodeFlags Flags; 8683 Flags.setUnsafeAlgebra(true); 8684 8685 if (Options.UnsafeFPMath) { 8686 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8687 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8688 isConstantFPBuildVectorOrConstantFP(N1) && 8689 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8690 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8691 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8692 &Flags), &Flags); 8693 } 8694 8695 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8696 if (N0.getOpcode() == ISD::FMUL && 8697 isConstantFPBuildVectorOrConstantFP(N1) && 8698 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8699 return DAG.getNode(ISD::FMA, dl, VT, 8700 N0.getOperand(0), 8701 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8702 &Flags), 8703 N2); 8704 } 8705 } 8706 8707 // (fma x, 1, y) -> (fadd x, y) 8708 // (fma x, -1, y) -> (fadd (fneg x), y) 8709 if (N1CFP) { 8710 if (N1CFP->isExactlyValue(1.0)) 8711 // TODO: The FMA node should have flags that propagate to this node. 8712 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8713 8714 if (N1CFP->isExactlyValue(-1.0) && 8715 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8716 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8717 AddToWorklist(RHSNeg.getNode()); 8718 // TODO: The FMA node should have flags that propagate to this node. 8719 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8720 } 8721 } 8722 8723 if (Options.UnsafeFPMath) { 8724 // (fma x, c, x) -> (fmul x, (c+1)) 8725 if (N1CFP && N0 == N2) { 8726 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8727 DAG.getNode(ISD::FADD, dl, VT, 8728 N1, DAG.getConstantFP(1.0, dl, VT), 8729 &Flags), &Flags); 8730 } 8731 8732 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8733 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8734 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8735 DAG.getNode(ISD::FADD, dl, VT, 8736 N1, DAG.getConstantFP(-1.0, dl, VT), 8737 &Flags), &Flags); 8738 } 8739 } 8740 8741 return SDValue(); 8742 } 8743 8744 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8745 // reciprocal. 8746 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8747 // Notice that this is not always beneficial. One reason is different target 8748 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8749 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8750 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8751 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8752 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8753 const SDNodeFlags *Flags = N->getFlags(); 8754 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8755 return SDValue(); 8756 8757 // Skip if current node is a reciprocal. 8758 SDValue N0 = N->getOperand(0); 8759 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8760 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8761 return SDValue(); 8762 8763 // Exit early if the target does not want this transform or if there can't 8764 // possibly be enough uses of the divisor to make the transform worthwhile. 8765 SDValue N1 = N->getOperand(1); 8766 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8767 if (!MinUses || N1->use_size() < MinUses) 8768 return SDValue(); 8769 8770 // Find all FDIV users of the same divisor. 8771 // Use a set because duplicates may be present in the user list. 8772 SetVector<SDNode *> Users; 8773 for (auto *U : N1->uses()) { 8774 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8775 // This division is eligible for optimization only if global unsafe math 8776 // is enabled or if this division allows reciprocal formation. 8777 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8778 Users.insert(U); 8779 } 8780 } 8781 8782 // Now that we have the actual number of divisor uses, make sure it meets 8783 // the minimum threshold specified by the target. 8784 if (Users.size() < MinUses) 8785 return SDValue(); 8786 8787 EVT VT = N->getValueType(0); 8788 SDLoc DL(N); 8789 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8790 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8791 8792 // Dividend / Divisor -> Dividend * Reciprocal 8793 for (auto *U : Users) { 8794 SDValue Dividend = U->getOperand(0); 8795 if (Dividend != FPOne) { 8796 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8797 Reciprocal, Flags); 8798 CombineTo(U, NewNode); 8799 } else if (U != Reciprocal.getNode()) { 8800 // In the absence of fast-math-flags, this user node is always the 8801 // same node as Reciprocal, but with FMF they may be different nodes. 8802 CombineTo(U, Reciprocal); 8803 } 8804 } 8805 return SDValue(N, 0); // N was replaced. 8806 } 8807 8808 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8809 SDValue N0 = N->getOperand(0); 8810 SDValue N1 = N->getOperand(1); 8811 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8812 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8813 EVT VT = N->getValueType(0); 8814 SDLoc DL(N); 8815 const TargetOptions &Options = DAG.getTarget().Options; 8816 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8817 8818 // fold vector ops 8819 if (VT.isVector()) 8820 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8821 return FoldedVOp; 8822 8823 // fold (fdiv c1, c2) -> c1/c2 8824 if (N0CFP && N1CFP) 8825 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8826 8827 if (Options.UnsafeFPMath) { 8828 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8829 if (N1CFP) { 8830 // Compute the reciprocal 1.0 / c2. 8831 const APFloat &N1APF = N1CFP->getValueAPF(); 8832 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8833 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8834 // Only do the transform if the reciprocal is a legal fp immediate that 8835 // isn't too nasty (eg NaN, denormal, ...). 8836 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8837 (!LegalOperations || 8838 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8839 // backend)... we should handle this gracefully after Legalize. 8840 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8841 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8842 TLI.isFPImmLegal(Recip, VT))) 8843 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8844 DAG.getConstantFP(Recip, DL, VT), Flags); 8845 } 8846 8847 // If this FDIV is part of a reciprocal square root, it may be folded 8848 // into a target-specific square root estimate instruction. 8849 if (N1.getOpcode() == ISD::FSQRT) { 8850 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 8851 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8852 } 8853 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8854 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8855 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8856 Flags)) { 8857 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8858 AddToWorklist(RV.getNode()); 8859 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8860 } 8861 } else if (N1.getOpcode() == ISD::FP_ROUND && 8862 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8863 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8864 Flags)) { 8865 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8866 AddToWorklist(RV.getNode()); 8867 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8868 } 8869 } else if (N1.getOpcode() == ISD::FMUL) { 8870 // Look through an FMUL. Even though this won't remove the FDIV directly, 8871 // it's still worthwhile to get rid of the FSQRT if possible. 8872 SDValue SqrtOp; 8873 SDValue OtherOp; 8874 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8875 SqrtOp = N1.getOperand(0); 8876 OtherOp = N1.getOperand(1); 8877 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8878 SqrtOp = N1.getOperand(1); 8879 OtherOp = N1.getOperand(0); 8880 } 8881 if (SqrtOp.getNode()) { 8882 // We found a FSQRT, so try to make this fold: 8883 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8884 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8885 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8886 AddToWorklist(RV.getNode()); 8887 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8888 } 8889 } 8890 } 8891 8892 // Fold into a reciprocal estimate and multiply instead of a real divide. 8893 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8894 AddToWorklist(RV.getNode()); 8895 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8896 } 8897 } 8898 8899 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8900 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8901 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8902 // Both can be negated for free, check to see if at least one is cheaper 8903 // negated. 8904 if (LHSNeg == 2 || RHSNeg == 2) 8905 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8906 GetNegatedExpression(N0, DAG, LegalOperations), 8907 GetNegatedExpression(N1, DAG, LegalOperations), 8908 Flags); 8909 } 8910 } 8911 8912 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8913 return CombineRepeatedDivisors; 8914 8915 return SDValue(); 8916 } 8917 8918 SDValue DAGCombiner::visitFREM(SDNode *N) { 8919 SDValue N0 = N->getOperand(0); 8920 SDValue N1 = N->getOperand(1); 8921 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8922 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8923 EVT VT = N->getValueType(0); 8924 8925 // fold (frem c1, c2) -> fmod(c1,c2) 8926 if (N0CFP && N1CFP) 8927 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8928 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8929 8930 return SDValue(); 8931 } 8932 8933 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8934 if (!DAG.getTarget().Options.UnsafeFPMath) 8935 return SDValue(); 8936 8937 SDValue N0 = N->getOperand(0); 8938 if (TLI.isFsqrtCheap(N0, DAG)) 8939 return SDValue(); 8940 8941 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8942 // For now, create a Flags object for use with all unsafe math transforms. 8943 SDNodeFlags Flags; 8944 Flags.setUnsafeAlgebra(true); 8945 return buildSqrtEstimate(N0, &Flags); 8946 } 8947 8948 /// copysign(x, fp_extend(y)) -> copysign(x, y) 8949 /// copysign(x, fp_round(y)) -> copysign(x, y) 8950 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 8951 SDValue N1 = N->getOperand(1); 8952 if ((N1.getOpcode() == ISD::FP_EXTEND || 8953 N1.getOpcode() == ISD::FP_ROUND)) { 8954 // Do not optimize out type conversion of f128 type yet. 8955 // For some targets like x86_64, configuration is changed to keep one f128 8956 // value in one SSE register, but instruction selection cannot handle 8957 // FCOPYSIGN on SSE registers yet. 8958 EVT N1VT = N1->getValueType(0); 8959 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 8960 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 8961 } 8962 return false; 8963 } 8964 8965 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8966 SDValue N0 = N->getOperand(0); 8967 SDValue N1 = N->getOperand(1); 8968 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8969 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8970 EVT VT = N->getValueType(0); 8971 8972 if (N0CFP && N1CFP) // Constant fold 8973 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8974 8975 if (N1CFP) { 8976 const APFloat& V = N1CFP->getValueAPF(); 8977 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8978 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8979 if (!V.isNegative()) { 8980 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8981 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8982 } else { 8983 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8984 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8985 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8986 } 8987 } 8988 8989 // copysign(fabs(x), y) -> copysign(x, y) 8990 // copysign(fneg(x), y) -> copysign(x, y) 8991 // copysign(copysign(x,z), y) -> copysign(x, y) 8992 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8993 N0.getOpcode() == ISD::FCOPYSIGN) 8994 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8995 N0.getOperand(0), N1); 8996 8997 // copysign(x, abs(y)) -> abs(x) 8998 if (N1.getOpcode() == ISD::FABS) 8999 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9000 9001 // copysign(x, copysign(y,z)) -> copysign(x, z) 9002 if (N1.getOpcode() == ISD::FCOPYSIGN) 9003 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9004 N0, N1.getOperand(1)); 9005 9006 // copysign(x, fp_extend(y)) -> copysign(x, y) 9007 // copysign(x, fp_round(y)) -> copysign(x, y) 9008 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 9009 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9010 N0, N1.getOperand(0)); 9011 9012 return SDValue(); 9013 } 9014 9015 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 9016 SDValue N0 = N->getOperand(0); 9017 EVT VT = N->getValueType(0); 9018 EVT OpVT = N0.getValueType(); 9019 9020 // fold (sint_to_fp c1) -> c1fp 9021 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9022 // ...but only if the target supports immediate floating-point values 9023 (!LegalOperations || 9024 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9025 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9026 9027 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 9028 // but UINT_TO_FP is legal on this target, try to convert. 9029 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 9030 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 9031 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 9032 if (DAG.SignBitIsZero(N0)) 9033 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9034 } 9035 9036 // The next optimizations are desirable only if SELECT_CC can be lowered. 9037 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9038 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9039 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 9040 !VT.isVector() && 9041 (!LegalOperations || 9042 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9043 SDLoc DL(N); 9044 SDValue Ops[] = 9045 { N0.getOperand(0), N0.getOperand(1), 9046 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9047 N0.getOperand(2) }; 9048 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9049 } 9050 9051 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 9052 // (select_cc x, y, 1.0, 0.0,, cc) 9053 if (N0.getOpcode() == ISD::ZERO_EXTEND && 9054 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 9055 (!LegalOperations || 9056 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9057 SDLoc DL(N); 9058 SDValue Ops[] = 9059 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 9060 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9061 N0.getOperand(0).getOperand(2) }; 9062 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9063 } 9064 } 9065 9066 return SDValue(); 9067 } 9068 9069 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 9070 SDValue N0 = N->getOperand(0); 9071 EVT VT = N->getValueType(0); 9072 EVT OpVT = N0.getValueType(); 9073 9074 // fold (uint_to_fp c1) -> c1fp 9075 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9076 // ...but only if the target supports immediate floating-point values 9077 (!LegalOperations || 9078 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9079 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9080 9081 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 9082 // but SINT_TO_FP is legal on this target, try to convert. 9083 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 9084 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 9085 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 9086 if (DAG.SignBitIsZero(N0)) 9087 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9088 } 9089 9090 // The next optimizations are desirable only if SELECT_CC can be lowered. 9091 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9092 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9093 9094 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 9095 (!LegalOperations || 9096 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9097 SDLoc DL(N); 9098 SDValue Ops[] = 9099 { N0.getOperand(0), N0.getOperand(1), 9100 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9101 N0.getOperand(2) }; 9102 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9103 } 9104 } 9105 9106 return SDValue(); 9107 } 9108 9109 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 9110 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 9111 SDValue N0 = N->getOperand(0); 9112 EVT VT = N->getValueType(0); 9113 9114 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 9115 return SDValue(); 9116 9117 SDValue Src = N0.getOperand(0); 9118 EVT SrcVT = Src.getValueType(); 9119 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 9120 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 9121 9122 // We can safely assume the conversion won't overflow the output range, 9123 // because (for example) (uint8_t)18293.f is undefined behavior. 9124 9125 // Since we can assume the conversion won't overflow, our decision as to 9126 // whether the input will fit in the float should depend on the minimum 9127 // of the input range and output range. 9128 9129 // This means this is also safe for a signed input and unsigned output, since 9130 // a negative input would lead to undefined behavior. 9131 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 9132 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9133 unsigned ActualSize = std::min(InputSize, OutputSize); 9134 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9135 9136 // We can only fold away the float conversion if the input range can be 9137 // represented exactly in the float range. 9138 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9139 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9140 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9141 : ISD::ZERO_EXTEND; 9142 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9143 } 9144 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9145 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9146 return DAG.getBitcast(VT, Src); 9147 } 9148 return SDValue(); 9149 } 9150 9151 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9152 SDValue N0 = N->getOperand(0); 9153 EVT VT = N->getValueType(0); 9154 9155 // fold (fp_to_sint c1fp) -> c1 9156 if (isConstantFPBuildVectorOrConstantFP(N0)) 9157 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9158 9159 return FoldIntToFPToInt(N, DAG); 9160 } 9161 9162 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9163 SDValue N0 = N->getOperand(0); 9164 EVT VT = N->getValueType(0); 9165 9166 // fold (fp_to_uint c1fp) -> c1 9167 if (isConstantFPBuildVectorOrConstantFP(N0)) 9168 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9169 9170 return FoldIntToFPToInt(N, DAG); 9171 } 9172 9173 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9174 SDValue N0 = N->getOperand(0); 9175 SDValue N1 = N->getOperand(1); 9176 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9177 EVT VT = N->getValueType(0); 9178 9179 // fold (fp_round c1fp) -> c1fp 9180 if (N0CFP) 9181 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9182 9183 // fold (fp_round (fp_extend x)) -> x 9184 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9185 return N0.getOperand(0); 9186 9187 // fold (fp_round (fp_round x)) -> (fp_round x) 9188 if (N0.getOpcode() == ISD::FP_ROUND) { 9189 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9190 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 9191 9192 // Skip this folding if it results in an fp_round from f80 to f16. 9193 // 9194 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9195 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9196 // instructions from f32 or f64. Moreover, the first (value-preserving) 9197 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9198 // x86. 9199 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9200 return SDValue(); 9201 9202 // If the first fp_round isn't a value preserving truncation, it might 9203 // introduce a tie in the second fp_round, that wouldn't occur in the 9204 // single-step fp_round we want to fold to. 9205 // In other words, double rounding isn't the same as rounding. 9206 // Also, this is a value preserving truncation iff both fp_round's are. 9207 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9208 SDLoc DL(N); 9209 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9210 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9211 } 9212 } 9213 9214 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9215 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9216 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9217 N0.getOperand(0), N1); 9218 AddToWorklist(Tmp.getNode()); 9219 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9220 Tmp, N0.getOperand(1)); 9221 } 9222 9223 return SDValue(); 9224 } 9225 9226 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9227 SDValue N0 = N->getOperand(0); 9228 EVT VT = N->getValueType(0); 9229 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9230 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9231 9232 // fold (fp_round_inreg c1fp) -> c1fp 9233 if (N0CFP && isTypeLegal(EVT)) { 9234 SDLoc DL(N); 9235 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9236 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9237 } 9238 9239 return SDValue(); 9240 } 9241 9242 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9243 SDValue N0 = N->getOperand(0); 9244 EVT VT = N->getValueType(0); 9245 9246 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9247 if (N->hasOneUse() && 9248 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9249 return SDValue(); 9250 9251 // fold (fp_extend c1fp) -> c1fp 9252 if (isConstantFPBuildVectorOrConstantFP(N0)) 9253 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9254 9255 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9256 if (N0.getOpcode() == ISD::FP16_TO_FP && 9257 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9258 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9259 9260 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9261 // value of X. 9262 if (N0.getOpcode() == ISD::FP_ROUND 9263 && N0.getNode()->getConstantOperandVal(1) == 1) { 9264 SDValue In = N0.getOperand(0); 9265 if (In.getValueType() == VT) return In; 9266 if (VT.bitsLT(In.getValueType())) 9267 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9268 In, N0.getOperand(1)); 9269 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9270 } 9271 9272 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9273 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9274 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9275 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9276 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9277 LN0->getChain(), 9278 LN0->getBasePtr(), N0.getValueType(), 9279 LN0->getMemOperand()); 9280 CombineTo(N, ExtLoad); 9281 CombineTo(N0.getNode(), 9282 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9283 N0.getValueType(), ExtLoad, 9284 DAG.getIntPtrConstant(1, SDLoc(N0))), 9285 ExtLoad.getValue(1)); 9286 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9287 } 9288 9289 return SDValue(); 9290 } 9291 9292 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9293 SDValue N0 = N->getOperand(0); 9294 EVT VT = N->getValueType(0); 9295 9296 // fold (fceil c1) -> fceil(c1) 9297 if (isConstantFPBuildVectorOrConstantFP(N0)) 9298 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9299 9300 return SDValue(); 9301 } 9302 9303 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9304 SDValue N0 = N->getOperand(0); 9305 EVT VT = N->getValueType(0); 9306 9307 // fold (ftrunc c1) -> ftrunc(c1) 9308 if (isConstantFPBuildVectorOrConstantFP(N0)) 9309 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9310 9311 return SDValue(); 9312 } 9313 9314 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9315 SDValue N0 = N->getOperand(0); 9316 EVT VT = N->getValueType(0); 9317 9318 // fold (ffloor c1) -> ffloor(c1) 9319 if (isConstantFPBuildVectorOrConstantFP(N0)) 9320 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9321 9322 return SDValue(); 9323 } 9324 9325 // FIXME: FNEG and FABS have a lot in common; refactor. 9326 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9327 SDValue N0 = N->getOperand(0); 9328 EVT VT = N->getValueType(0); 9329 9330 // Constant fold FNEG. 9331 if (isConstantFPBuildVectorOrConstantFP(N0)) 9332 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9333 9334 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9335 &DAG.getTarget().Options)) 9336 return GetNegatedExpression(N0, DAG, LegalOperations); 9337 9338 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9339 // constant pool values. 9340 if (!TLI.isFNegFree(VT) && 9341 N0.getOpcode() == ISD::BITCAST && 9342 N0.getNode()->hasOneUse()) { 9343 SDValue Int = N0.getOperand(0); 9344 EVT IntVT = Int.getValueType(); 9345 if (IntVT.isInteger() && !IntVT.isVector()) { 9346 APInt SignMask; 9347 if (N0.getValueType().isVector()) { 9348 // For a vector, get a mask such as 0x80... per scalar element 9349 // and splat it. 9350 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9351 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9352 } else { 9353 // For a scalar, just generate 0x80... 9354 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9355 } 9356 SDLoc DL0(N0); 9357 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9358 DAG.getConstant(SignMask, DL0, IntVT)); 9359 AddToWorklist(Int.getNode()); 9360 return DAG.getBitcast(VT, Int); 9361 } 9362 } 9363 9364 // (fneg (fmul c, x)) -> (fmul -c, x) 9365 if (N0.getOpcode() == ISD::FMUL && 9366 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9367 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9368 if (CFP1) { 9369 APFloat CVal = CFP1->getValueAPF(); 9370 CVal.changeSign(); 9371 if (Level >= AfterLegalizeDAG && 9372 (TLI.isFPImmLegal(CVal, VT) || 9373 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9374 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9375 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9376 N0.getOperand(1)), 9377 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9378 } 9379 } 9380 9381 return SDValue(); 9382 } 9383 9384 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9385 SDValue N0 = N->getOperand(0); 9386 SDValue N1 = N->getOperand(1); 9387 EVT VT = N->getValueType(0); 9388 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9389 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9390 9391 if (N0CFP && N1CFP) { 9392 const APFloat &C0 = N0CFP->getValueAPF(); 9393 const APFloat &C1 = N1CFP->getValueAPF(); 9394 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9395 } 9396 9397 // Canonicalize to constant on RHS. 9398 if (isConstantFPBuildVectorOrConstantFP(N0) && 9399 !isConstantFPBuildVectorOrConstantFP(N1)) 9400 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9401 9402 return SDValue(); 9403 } 9404 9405 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9406 SDValue N0 = N->getOperand(0); 9407 SDValue N1 = N->getOperand(1); 9408 EVT VT = N->getValueType(0); 9409 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9410 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9411 9412 if (N0CFP && N1CFP) { 9413 const APFloat &C0 = N0CFP->getValueAPF(); 9414 const APFloat &C1 = N1CFP->getValueAPF(); 9415 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9416 } 9417 9418 // Canonicalize to constant on RHS. 9419 if (isConstantFPBuildVectorOrConstantFP(N0) && 9420 !isConstantFPBuildVectorOrConstantFP(N1)) 9421 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9422 9423 return SDValue(); 9424 } 9425 9426 SDValue DAGCombiner::visitFABS(SDNode *N) { 9427 SDValue N0 = N->getOperand(0); 9428 EVT VT = N->getValueType(0); 9429 9430 // fold (fabs c1) -> fabs(c1) 9431 if (isConstantFPBuildVectorOrConstantFP(N0)) 9432 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9433 9434 // fold (fabs (fabs x)) -> (fabs x) 9435 if (N0.getOpcode() == ISD::FABS) 9436 return N->getOperand(0); 9437 9438 // fold (fabs (fneg x)) -> (fabs x) 9439 // fold (fabs (fcopysign x, y)) -> (fabs x) 9440 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9441 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9442 9443 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9444 // constant pool values. 9445 if (!TLI.isFAbsFree(VT) && 9446 N0.getOpcode() == ISD::BITCAST && 9447 N0.getNode()->hasOneUse()) { 9448 SDValue Int = N0.getOperand(0); 9449 EVT IntVT = Int.getValueType(); 9450 if (IntVT.isInteger() && !IntVT.isVector()) { 9451 APInt SignMask; 9452 if (N0.getValueType().isVector()) { 9453 // For a vector, get a mask such as 0x7f... per scalar element 9454 // and splat it. 9455 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9456 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9457 } else { 9458 // For a scalar, just generate 0x7f... 9459 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9460 } 9461 SDLoc DL(N0); 9462 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9463 DAG.getConstant(SignMask, DL, IntVT)); 9464 AddToWorklist(Int.getNode()); 9465 return DAG.getBitcast(N->getValueType(0), Int); 9466 } 9467 } 9468 9469 return SDValue(); 9470 } 9471 9472 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9473 SDValue Chain = N->getOperand(0); 9474 SDValue N1 = N->getOperand(1); 9475 SDValue N2 = N->getOperand(2); 9476 9477 // If N is a constant we could fold this into a fallthrough or unconditional 9478 // branch. However that doesn't happen very often in normal code, because 9479 // Instcombine/SimplifyCFG should have handled the available opportunities. 9480 // If we did this folding here, it would be necessary to update the 9481 // MachineBasicBlock CFG, which is awkward. 9482 9483 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9484 // on the target. 9485 if (N1.getOpcode() == ISD::SETCC && 9486 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9487 N1.getOperand(0).getValueType())) { 9488 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9489 Chain, N1.getOperand(2), 9490 N1.getOperand(0), N1.getOperand(1), N2); 9491 } 9492 9493 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9494 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9495 (N1.getOperand(0).hasOneUse() && 9496 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9497 SDNode *Trunc = nullptr; 9498 if (N1.getOpcode() == ISD::TRUNCATE) { 9499 // Look pass the truncate. 9500 Trunc = N1.getNode(); 9501 N1 = N1.getOperand(0); 9502 } 9503 9504 // Match this pattern so that we can generate simpler code: 9505 // 9506 // %a = ... 9507 // %b = and i32 %a, 2 9508 // %c = srl i32 %b, 1 9509 // brcond i32 %c ... 9510 // 9511 // into 9512 // 9513 // %a = ... 9514 // %b = and i32 %a, 2 9515 // %c = setcc eq %b, 0 9516 // brcond %c ... 9517 // 9518 // This applies only when the AND constant value has one bit set and the 9519 // SRL constant is equal to the log2 of the AND constant. The back-end is 9520 // smart enough to convert the result into a TEST/JMP sequence. 9521 SDValue Op0 = N1.getOperand(0); 9522 SDValue Op1 = N1.getOperand(1); 9523 9524 if (Op0.getOpcode() == ISD::AND && 9525 Op1.getOpcode() == ISD::Constant) { 9526 SDValue AndOp1 = Op0.getOperand(1); 9527 9528 if (AndOp1.getOpcode() == ISD::Constant) { 9529 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9530 9531 if (AndConst.isPowerOf2() && 9532 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9533 SDLoc DL(N); 9534 SDValue SetCC = 9535 DAG.getSetCC(DL, 9536 getSetCCResultType(Op0.getValueType()), 9537 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9538 ISD::SETNE); 9539 9540 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9541 MVT::Other, Chain, SetCC, N2); 9542 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9543 // will convert it back to (X & C1) >> C2. 9544 CombineTo(N, NewBRCond, false); 9545 // Truncate is dead. 9546 if (Trunc) 9547 deleteAndRecombine(Trunc); 9548 // Replace the uses of SRL with SETCC 9549 WorklistRemover DeadNodes(*this); 9550 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9551 deleteAndRecombine(N1.getNode()); 9552 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9553 } 9554 } 9555 } 9556 9557 if (Trunc) 9558 // Restore N1 if the above transformation doesn't match. 9559 N1 = N->getOperand(1); 9560 } 9561 9562 // Transform br(xor(x, y)) -> br(x != y) 9563 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9564 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9565 SDNode *TheXor = N1.getNode(); 9566 SDValue Op0 = TheXor->getOperand(0); 9567 SDValue Op1 = TheXor->getOperand(1); 9568 if (Op0.getOpcode() == Op1.getOpcode()) { 9569 // Avoid missing important xor optimizations. 9570 if (SDValue Tmp = visitXOR(TheXor)) { 9571 if (Tmp.getNode() != TheXor) { 9572 DEBUG(dbgs() << "\nReplacing.8 "; 9573 TheXor->dump(&DAG); 9574 dbgs() << "\nWith: "; 9575 Tmp.getNode()->dump(&DAG); 9576 dbgs() << '\n'); 9577 WorklistRemover DeadNodes(*this); 9578 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9579 deleteAndRecombine(TheXor); 9580 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9581 MVT::Other, Chain, Tmp, N2); 9582 } 9583 9584 // visitXOR has changed XOR's operands or replaced the XOR completely, 9585 // bail out. 9586 return SDValue(N, 0); 9587 } 9588 } 9589 9590 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9591 bool Equal = false; 9592 if (isOneConstant(Op0) && Op0.hasOneUse() && 9593 Op0.getOpcode() == ISD::XOR) { 9594 TheXor = Op0.getNode(); 9595 Equal = true; 9596 } 9597 9598 EVT SetCCVT = N1.getValueType(); 9599 if (LegalTypes) 9600 SetCCVT = getSetCCResultType(SetCCVT); 9601 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9602 SetCCVT, 9603 Op0, Op1, 9604 Equal ? ISD::SETEQ : ISD::SETNE); 9605 // Replace the uses of XOR with SETCC 9606 WorklistRemover DeadNodes(*this); 9607 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9608 deleteAndRecombine(N1.getNode()); 9609 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9610 MVT::Other, Chain, SetCC, N2); 9611 } 9612 } 9613 9614 return SDValue(); 9615 } 9616 9617 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9618 // 9619 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9620 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9621 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9622 9623 // If N is a constant we could fold this into a fallthrough or unconditional 9624 // branch. However that doesn't happen very often in normal code, because 9625 // Instcombine/SimplifyCFG should have handled the available opportunities. 9626 // If we did this folding here, it would be necessary to update the 9627 // MachineBasicBlock CFG, which is awkward. 9628 9629 // Use SimplifySetCC to simplify SETCC's. 9630 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9631 CondLHS, CondRHS, CC->get(), SDLoc(N), 9632 false); 9633 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9634 9635 // fold to a simpler setcc 9636 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9637 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9638 N->getOperand(0), Simp.getOperand(2), 9639 Simp.getOperand(0), Simp.getOperand(1), 9640 N->getOperand(4)); 9641 9642 return SDValue(); 9643 } 9644 9645 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9646 /// and that N may be folded in the load / store addressing mode. 9647 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9648 SelectionDAG &DAG, 9649 const TargetLowering &TLI) { 9650 EVT VT; 9651 unsigned AS; 9652 9653 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9654 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9655 return false; 9656 VT = LD->getMemoryVT(); 9657 AS = LD->getAddressSpace(); 9658 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9659 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9660 return false; 9661 VT = ST->getMemoryVT(); 9662 AS = ST->getAddressSpace(); 9663 } else 9664 return false; 9665 9666 TargetLowering::AddrMode AM; 9667 if (N->getOpcode() == ISD::ADD) { 9668 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9669 if (Offset) 9670 // [reg +/- imm] 9671 AM.BaseOffs = Offset->getSExtValue(); 9672 else 9673 // [reg +/- reg] 9674 AM.Scale = 1; 9675 } else if (N->getOpcode() == ISD::SUB) { 9676 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9677 if (Offset) 9678 // [reg +/- imm] 9679 AM.BaseOffs = -Offset->getSExtValue(); 9680 else 9681 // [reg +/- reg] 9682 AM.Scale = 1; 9683 } else 9684 return false; 9685 9686 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9687 VT.getTypeForEVT(*DAG.getContext()), AS); 9688 } 9689 9690 /// Try turning a load/store into a pre-indexed load/store when the base 9691 /// pointer is an add or subtract and it has other uses besides the load/store. 9692 /// After the transformation, the new indexed load/store has effectively folded 9693 /// the add/subtract in and all of its other uses are redirected to the 9694 /// new load/store. 9695 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9696 if (Level < AfterLegalizeDAG) 9697 return false; 9698 9699 bool isLoad = true; 9700 SDValue Ptr; 9701 EVT VT; 9702 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9703 if (LD->isIndexed()) 9704 return false; 9705 VT = LD->getMemoryVT(); 9706 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9707 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9708 return false; 9709 Ptr = LD->getBasePtr(); 9710 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9711 if (ST->isIndexed()) 9712 return false; 9713 VT = ST->getMemoryVT(); 9714 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9715 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9716 return false; 9717 Ptr = ST->getBasePtr(); 9718 isLoad = false; 9719 } else { 9720 return false; 9721 } 9722 9723 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9724 // out. There is no reason to make this a preinc/predec. 9725 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9726 Ptr.getNode()->hasOneUse()) 9727 return false; 9728 9729 // Ask the target to do addressing mode selection. 9730 SDValue BasePtr; 9731 SDValue Offset; 9732 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9733 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9734 return false; 9735 9736 // Backends without true r+i pre-indexed forms may need to pass a 9737 // constant base with a variable offset so that constant coercion 9738 // will work with the patterns in canonical form. 9739 bool Swapped = false; 9740 if (isa<ConstantSDNode>(BasePtr)) { 9741 std::swap(BasePtr, Offset); 9742 Swapped = true; 9743 } 9744 9745 // Don't create a indexed load / store with zero offset. 9746 if (isNullConstant(Offset)) 9747 return false; 9748 9749 // Try turning it into a pre-indexed load / store except when: 9750 // 1) The new base ptr is a frame index. 9751 // 2) If N is a store and the new base ptr is either the same as or is a 9752 // predecessor of the value being stored. 9753 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9754 // that would create a cycle. 9755 // 4) All uses are load / store ops that use it as old base ptr. 9756 9757 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9758 // (plus the implicit offset) to a register to preinc anyway. 9759 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9760 return false; 9761 9762 // Check #2. 9763 if (!isLoad) { 9764 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9765 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9766 return false; 9767 } 9768 9769 // Caches for hasPredecessorHelper. 9770 SmallPtrSet<const SDNode *, 32> Visited; 9771 SmallVector<const SDNode *, 16> Worklist; 9772 Worklist.push_back(N); 9773 9774 // If the offset is a constant, there may be other adds of constants that 9775 // can be folded with this one. We should do this to avoid having to keep 9776 // a copy of the original base pointer. 9777 SmallVector<SDNode *, 16> OtherUses; 9778 if (isa<ConstantSDNode>(Offset)) 9779 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9780 UE = BasePtr.getNode()->use_end(); 9781 UI != UE; ++UI) { 9782 SDUse &Use = UI.getUse(); 9783 // Skip the use that is Ptr and uses of other results from BasePtr's 9784 // node (important for nodes that return multiple results). 9785 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9786 continue; 9787 9788 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 9789 continue; 9790 9791 if (Use.getUser()->getOpcode() != ISD::ADD && 9792 Use.getUser()->getOpcode() != ISD::SUB) { 9793 OtherUses.clear(); 9794 break; 9795 } 9796 9797 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9798 if (!isa<ConstantSDNode>(Op1)) { 9799 OtherUses.clear(); 9800 break; 9801 } 9802 9803 // FIXME: In some cases, we can be smarter about this. 9804 if (Op1.getValueType() != Offset.getValueType()) { 9805 OtherUses.clear(); 9806 break; 9807 } 9808 9809 OtherUses.push_back(Use.getUser()); 9810 } 9811 9812 if (Swapped) 9813 std::swap(BasePtr, Offset); 9814 9815 // Now check for #3 and #4. 9816 bool RealUse = false; 9817 9818 for (SDNode *Use : Ptr.getNode()->uses()) { 9819 if (Use == N) 9820 continue; 9821 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 9822 return false; 9823 9824 // If Ptr may be folded in addressing mode of other use, then it's 9825 // not profitable to do this transformation. 9826 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9827 RealUse = true; 9828 } 9829 9830 if (!RealUse) 9831 return false; 9832 9833 SDValue Result; 9834 if (isLoad) 9835 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9836 BasePtr, Offset, AM); 9837 else 9838 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9839 BasePtr, Offset, AM); 9840 ++PreIndexedNodes; 9841 ++NodesCombined; 9842 DEBUG(dbgs() << "\nReplacing.4 "; 9843 N->dump(&DAG); 9844 dbgs() << "\nWith: "; 9845 Result.getNode()->dump(&DAG); 9846 dbgs() << '\n'); 9847 WorklistRemover DeadNodes(*this); 9848 if (isLoad) { 9849 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9850 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9851 } else { 9852 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9853 } 9854 9855 // Finally, since the node is now dead, remove it from the graph. 9856 deleteAndRecombine(N); 9857 9858 if (Swapped) 9859 std::swap(BasePtr, Offset); 9860 9861 // Replace other uses of BasePtr that can be updated to use Ptr 9862 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9863 unsigned OffsetIdx = 1; 9864 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9865 OffsetIdx = 0; 9866 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9867 BasePtr.getNode() && "Expected BasePtr operand"); 9868 9869 // We need to replace ptr0 in the following expression: 9870 // x0 * offset0 + y0 * ptr0 = t0 9871 // knowing that 9872 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9873 // 9874 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9875 // indexed load/store and the expresion that needs to be re-written. 9876 // 9877 // Therefore, we have: 9878 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9879 9880 ConstantSDNode *CN = 9881 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9882 int X0, X1, Y0, Y1; 9883 const APInt &Offset0 = CN->getAPIntValue(); 9884 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9885 9886 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9887 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9888 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9889 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9890 9891 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9892 9893 APInt CNV = Offset0; 9894 if (X0 < 0) CNV = -CNV; 9895 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9896 else CNV = CNV - Offset1; 9897 9898 SDLoc DL(OtherUses[i]); 9899 9900 // We can now generate the new expression. 9901 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9902 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9903 9904 SDValue NewUse = DAG.getNode(Opcode, 9905 DL, 9906 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9907 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9908 deleteAndRecombine(OtherUses[i]); 9909 } 9910 9911 // Replace the uses of Ptr with uses of the updated base value. 9912 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9913 deleteAndRecombine(Ptr.getNode()); 9914 9915 return true; 9916 } 9917 9918 /// Try to combine a load/store with a add/sub of the base pointer node into a 9919 /// post-indexed load/store. The transformation folded the add/subtract into the 9920 /// new indexed load/store effectively and all of its uses are redirected to the 9921 /// new load/store. 9922 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9923 if (Level < AfterLegalizeDAG) 9924 return false; 9925 9926 bool isLoad = true; 9927 SDValue Ptr; 9928 EVT VT; 9929 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9930 if (LD->isIndexed()) 9931 return false; 9932 VT = LD->getMemoryVT(); 9933 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9934 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9935 return false; 9936 Ptr = LD->getBasePtr(); 9937 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9938 if (ST->isIndexed()) 9939 return false; 9940 VT = ST->getMemoryVT(); 9941 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9942 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9943 return false; 9944 Ptr = ST->getBasePtr(); 9945 isLoad = false; 9946 } else { 9947 return false; 9948 } 9949 9950 if (Ptr.getNode()->hasOneUse()) 9951 return false; 9952 9953 for (SDNode *Op : Ptr.getNode()->uses()) { 9954 if (Op == N || 9955 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9956 continue; 9957 9958 SDValue BasePtr; 9959 SDValue Offset; 9960 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9961 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9962 // Don't create a indexed load / store with zero offset. 9963 if (isNullConstant(Offset)) 9964 continue; 9965 9966 // Try turning it into a post-indexed load / store except when 9967 // 1) All uses are load / store ops that use it as base ptr (and 9968 // it may be folded as addressing mmode). 9969 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9970 // nor a successor of N. Otherwise, if Op is folded that would 9971 // create a cycle. 9972 9973 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9974 continue; 9975 9976 // Check for #1. 9977 bool TryNext = false; 9978 for (SDNode *Use : BasePtr.getNode()->uses()) { 9979 if (Use == Ptr.getNode()) 9980 continue; 9981 9982 // If all the uses are load / store addresses, then don't do the 9983 // transformation. 9984 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9985 bool RealUse = false; 9986 for (SDNode *UseUse : Use->uses()) { 9987 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9988 RealUse = true; 9989 } 9990 9991 if (!RealUse) { 9992 TryNext = true; 9993 break; 9994 } 9995 } 9996 } 9997 9998 if (TryNext) 9999 continue; 10000 10001 // Check for #2 10002 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 10003 SDValue Result = isLoad 10004 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 10005 BasePtr, Offset, AM) 10006 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 10007 BasePtr, Offset, AM); 10008 ++PostIndexedNodes; 10009 ++NodesCombined; 10010 DEBUG(dbgs() << "\nReplacing.5 "; 10011 N->dump(&DAG); 10012 dbgs() << "\nWith: "; 10013 Result.getNode()->dump(&DAG); 10014 dbgs() << '\n'); 10015 WorklistRemover DeadNodes(*this); 10016 if (isLoad) { 10017 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 10018 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 10019 } else { 10020 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 10021 } 10022 10023 // Finally, since the node is now dead, remove it from the graph. 10024 deleteAndRecombine(N); 10025 10026 // Replace the uses of Use with uses of the updated base value. 10027 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 10028 Result.getValue(isLoad ? 1 : 0)); 10029 deleteAndRecombine(Op); 10030 return true; 10031 } 10032 } 10033 } 10034 10035 return false; 10036 } 10037 10038 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 10039 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 10040 ISD::MemIndexedMode AM = LD->getAddressingMode(); 10041 assert(AM != ISD::UNINDEXED); 10042 SDValue BP = LD->getOperand(1); 10043 SDValue Inc = LD->getOperand(2); 10044 10045 // Some backends use TargetConstants for load offsets, but don't expect 10046 // TargetConstants in general ADD nodes. We can convert these constants into 10047 // regular Constants (if the constant is not opaque). 10048 assert((Inc.getOpcode() != ISD::TargetConstant || 10049 !cast<ConstantSDNode>(Inc)->isOpaque()) && 10050 "Cannot split out indexing using opaque target constants"); 10051 if (Inc.getOpcode() == ISD::TargetConstant) { 10052 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 10053 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 10054 ConstInc->getValueType(0)); 10055 } 10056 10057 unsigned Opc = 10058 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 10059 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 10060 } 10061 10062 SDValue DAGCombiner::visitLOAD(SDNode *N) { 10063 LoadSDNode *LD = cast<LoadSDNode>(N); 10064 SDValue Chain = LD->getChain(); 10065 SDValue Ptr = LD->getBasePtr(); 10066 10067 // If load is not volatile and there are no uses of the loaded value (and 10068 // the updated indexed value in case of indexed loads), change uses of the 10069 // chain value into uses of the chain input (i.e. delete the dead load). 10070 if (!LD->isVolatile()) { 10071 if (N->getValueType(1) == MVT::Other) { 10072 // Unindexed loads. 10073 if (!N->hasAnyUseOfValue(0)) { 10074 // It's not safe to use the two value CombineTo variant here. e.g. 10075 // v1, chain2 = load chain1, loc 10076 // v2, chain3 = load chain2, loc 10077 // v3 = add v2, c 10078 // Now we replace use of chain2 with chain1. This makes the second load 10079 // isomorphic to the one we are deleting, and thus makes this load live. 10080 DEBUG(dbgs() << "\nReplacing.6 "; 10081 N->dump(&DAG); 10082 dbgs() << "\nWith chain: "; 10083 Chain.getNode()->dump(&DAG); 10084 dbgs() << "\n"); 10085 WorklistRemover DeadNodes(*this); 10086 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10087 10088 if (N->use_empty()) 10089 deleteAndRecombine(N); 10090 10091 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10092 } 10093 } else { 10094 // Indexed loads. 10095 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 10096 10097 // If this load has an opaque TargetConstant offset, then we cannot split 10098 // the indexing into an add/sub directly (that TargetConstant may not be 10099 // valid for a different type of node, and we cannot convert an opaque 10100 // target constant into a regular constant). 10101 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 10102 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 10103 10104 if (!N->hasAnyUseOfValue(0) && 10105 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 10106 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 10107 SDValue Index; 10108 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 10109 Index = SplitIndexingFromLoad(LD); 10110 // Try to fold the base pointer arithmetic into subsequent loads and 10111 // stores. 10112 AddUsersToWorklist(N); 10113 } else 10114 Index = DAG.getUNDEF(N->getValueType(1)); 10115 DEBUG(dbgs() << "\nReplacing.7 "; 10116 N->dump(&DAG); 10117 dbgs() << "\nWith: "; 10118 Undef.getNode()->dump(&DAG); 10119 dbgs() << " and 2 other values\n"); 10120 WorklistRemover DeadNodes(*this); 10121 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 10122 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 10123 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 10124 deleteAndRecombine(N); 10125 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10126 } 10127 } 10128 } 10129 10130 // If this load is directly stored, replace the load value with the stored 10131 // value. 10132 // TODO: Handle store large -> read small portion. 10133 // TODO: Handle TRUNCSTORE/LOADEXT 10134 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 10135 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10136 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10137 if (PrevST->getBasePtr() == Ptr && 10138 PrevST->getValue().getValueType() == N->getValueType(0)) 10139 return CombineTo(N, Chain.getOperand(1), Chain); 10140 } 10141 } 10142 10143 // Try to infer better alignment information than the load already has. 10144 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10145 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10146 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10147 SDValue NewLoad = DAG.getExtLoad( 10148 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 10149 LD->getPointerInfo(), LD->getMemoryVT(), Align, 10150 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10151 if (NewLoad.getNode() != N) 10152 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10153 } 10154 } 10155 } 10156 10157 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10158 : DAG.getSubtarget().useAA(); 10159 #ifndef NDEBUG 10160 if (CombinerAAOnlyFunc.getNumOccurrences() && 10161 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10162 UseAA = false; 10163 #endif 10164 if (UseAA && LD->isUnindexed()) { 10165 // Walk up chain skipping non-aliasing memory nodes. 10166 SDValue BetterChain = FindBetterChain(N, Chain); 10167 10168 // If there is a better chain. 10169 if (Chain != BetterChain) { 10170 SDValue ReplLoad; 10171 10172 // Replace the chain to void dependency. 10173 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10174 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10175 BetterChain, Ptr, LD->getMemOperand()); 10176 } else { 10177 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10178 LD->getValueType(0), 10179 BetterChain, Ptr, LD->getMemoryVT(), 10180 LD->getMemOperand()); 10181 } 10182 10183 // Create token factor to keep old chain connected. 10184 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10185 MVT::Other, Chain, ReplLoad.getValue(1)); 10186 10187 // Make sure the new and old chains are cleaned up. 10188 AddToWorklist(Token.getNode()); 10189 10190 // Replace uses with load result and token factor. Don't add users 10191 // to work list. 10192 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10193 } 10194 } 10195 10196 // Try transforming N to an indexed load. 10197 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10198 return SDValue(N, 0); 10199 10200 // Try to slice up N to more direct loads if the slices are mapped to 10201 // different register banks or pairing can take place. 10202 if (SliceUpLoad(N)) 10203 return SDValue(N, 0); 10204 10205 return SDValue(); 10206 } 10207 10208 namespace { 10209 /// \brief Helper structure used to slice a load in smaller loads. 10210 /// Basically a slice is obtained from the following sequence: 10211 /// Origin = load Ty1, Base 10212 /// Shift = srl Ty1 Origin, CstTy Amount 10213 /// Inst = trunc Shift to Ty2 10214 /// 10215 /// Then, it will be rewriten into: 10216 /// Slice = load SliceTy, Base + SliceOffset 10217 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10218 /// 10219 /// SliceTy is deduced from the number of bits that are actually used to 10220 /// build Inst. 10221 struct LoadedSlice { 10222 /// \brief Helper structure used to compute the cost of a slice. 10223 struct Cost { 10224 /// Are we optimizing for code size. 10225 bool ForCodeSize; 10226 /// Various cost. 10227 unsigned Loads; 10228 unsigned Truncates; 10229 unsigned CrossRegisterBanksCopies; 10230 unsigned ZExts; 10231 unsigned Shift; 10232 10233 Cost(bool ForCodeSize = false) 10234 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10235 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10236 10237 /// \brief Get the cost of one isolated slice. 10238 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10239 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10240 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10241 EVT TruncType = LS.Inst->getValueType(0); 10242 EVT LoadedType = LS.getLoadedType(); 10243 if (TruncType != LoadedType && 10244 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10245 ZExts = 1; 10246 } 10247 10248 /// \brief Account for slicing gain in the current cost. 10249 /// Slicing provide a few gains like removing a shift or a 10250 /// truncate. This method allows to grow the cost of the original 10251 /// load with the gain from this slice. 10252 void addSliceGain(const LoadedSlice &LS) { 10253 // Each slice saves a truncate. 10254 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10255 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10256 LS.Inst->getValueType(0))) 10257 ++Truncates; 10258 // If there is a shift amount, this slice gets rid of it. 10259 if (LS.Shift) 10260 ++Shift; 10261 // If this slice can merge a cross register bank copy, account for it. 10262 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10263 ++CrossRegisterBanksCopies; 10264 } 10265 10266 Cost &operator+=(const Cost &RHS) { 10267 Loads += RHS.Loads; 10268 Truncates += RHS.Truncates; 10269 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10270 ZExts += RHS.ZExts; 10271 Shift += RHS.Shift; 10272 return *this; 10273 } 10274 10275 bool operator==(const Cost &RHS) const { 10276 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10277 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10278 ZExts == RHS.ZExts && Shift == RHS.Shift; 10279 } 10280 10281 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10282 10283 bool operator<(const Cost &RHS) const { 10284 // Assume cross register banks copies are as expensive as loads. 10285 // FIXME: Do we want some more target hooks? 10286 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10287 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10288 // Unless we are optimizing for code size, consider the 10289 // expensive operation first. 10290 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10291 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10292 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10293 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10294 } 10295 10296 bool operator>(const Cost &RHS) const { return RHS < *this; } 10297 10298 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10299 10300 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10301 }; 10302 // The last instruction that represent the slice. This should be a 10303 // truncate instruction. 10304 SDNode *Inst; 10305 // The original load instruction. 10306 LoadSDNode *Origin; 10307 // The right shift amount in bits from the original load. 10308 unsigned Shift; 10309 // The DAG from which Origin came from. 10310 // This is used to get some contextual information about legal types, etc. 10311 SelectionDAG *DAG; 10312 10313 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10314 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10315 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10316 10317 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10318 /// \return Result is \p BitWidth and has used bits set to 1 and 10319 /// not used bits set to 0. 10320 APInt getUsedBits() const { 10321 // Reproduce the trunc(lshr) sequence: 10322 // - Start from the truncated value. 10323 // - Zero extend to the desired bit width. 10324 // - Shift left. 10325 assert(Origin && "No original load to compare against."); 10326 unsigned BitWidth = Origin->getValueSizeInBits(0); 10327 assert(Inst && "This slice is not bound to an instruction"); 10328 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10329 "Extracted slice is bigger than the whole type!"); 10330 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10331 UsedBits.setAllBits(); 10332 UsedBits = UsedBits.zext(BitWidth); 10333 UsedBits <<= Shift; 10334 return UsedBits; 10335 } 10336 10337 /// \brief Get the size of the slice to be loaded in bytes. 10338 unsigned getLoadedSize() const { 10339 unsigned SliceSize = getUsedBits().countPopulation(); 10340 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10341 return SliceSize / 8; 10342 } 10343 10344 /// \brief Get the type that will be loaded for this slice. 10345 /// Note: This may not be the final type for the slice. 10346 EVT getLoadedType() const { 10347 assert(DAG && "Missing context"); 10348 LLVMContext &Ctxt = *DAG->getContext(); 10349 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10350 } 10351 10352 /// \brief Get the alignment of the load used for this slice. 10353 unsigned getAlignment() const { 10354 unsigned Alignment = Origin->getAlignment(); 10355 unsigned Offset = getOffsetFromBase(); 10356 if (Offset != 0) 10357 Alignment = MinAlign(Alignment, Alignment + Offset); 10358 return Alignment; 10359 } 10360 10361 /// \brief Check if this slice can be rewritten with legal operations. 10362 bool isLegal() const { 10363 // An invalid slice is not legal. 10364 if (!Origin || !Inst || !DAG) 10365 return false; 10366 10367 // Offsets are for indexed load only, we do not handle that. 10368 if (!Origin->getOffset().isUndef()) 10369 return false; 10370 10371 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10372 10373 // Check that the type is legal. 10374 EVT SliceType = getLoadedType(); 10375 if (!TLI.isTypeLegal(SliceType)) 10376 return false; 10377 10378 // Check that the load is legal for this type. 10379 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10380 return false; 10381 10382 // Check that the offset can be computed. 10383 // 1. Check its type. 10384 EVT PtrType = Origin->getBasePtr().getValueType(); 10385 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10386 return false; 10387 10388 // 2. Check that it fits in the immediate. 10389 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10390 return false; 10391 10392 // 3. Check that the computation is legal. 10393 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10394 return false; 10395 10396 // Check that the zext is legal if it needs one. 10397 EVT TruncateType = Inst->getValueType(0); 10398 if (TruncateType != SliceType && 10399 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10400 return false; 10401 10402 return true; 10403 } 10404 10405 /// \brief Get the offset in bytes of this slice in the original chunk of 10406 /// bits. 10407 /// \pre DAG != nullptr. 10408 uint64_t getOffsetFromBase() const { 10409 assert(DAG && "Missing context."); 10410 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10411 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10412 uint64_t Offset = Shift / 8; 10413 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10414 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10415 "The size of the original loaded type is not a multiple of a" 10416 " byte."); 10417 // If Offset is bigger than TySizeInBytes, it means we are loading all 10418 // zeros. This should have been optimized before in the process. 10419 assert(TySizeInBytes > Offset && 10420 "Invalid shift amount for given loaded size"); 10421 if (IsBigEndian) 10422 Offset = TySizeInBytes - Offset - getLoadedSize(); 10423 return Offset; 10424 } 10425 10426 /// \brief Generate the sequence of instructions to load the slice 10427 /// represented by this object and redirect the uses of this slice to 10428 /// this new sequence of instructions. 10429 /// \pre this->Inst && this->Origin are valid Instructions and this 10430 /// object passed the legal check: LoadedSlice::isLegal returned true. 10431 /// \return The last instruction of the sequence used to load the slice. 10432 SDValue loadSlice() const { 10433 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10434 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10435 SDValue BaseAddr = OldBaseAddr; 10436 // Get the offset in that chunk of bytes w.r.t. the endianess. 10437 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10438 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10439 if (Offset) { 10440 // BaseAddr = BaseAddr + Offset. 10441 EVT ArithType = BaseAddr.getValueType(); 10442 SDLoc DL(Origin); 10443 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10444 DAG->getConstant(Offset, DL, ArithType)); 10445 } 10446 10447 // Create the type of the loaded slice according to its size. 10448 EVT SliceType = getLoadedType(); 10449 10450 // Create the load for the slice. 10451 SDValue LastInst = 10452 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10453 Origin->getPointerInfo().getWithOffset(Offset), 10454 getAlignment(), Origin->getMemOperand()->getFlags()); 10455 // If the final type is not the same as the loaded type, this means that 10456 // we have to pad with zero. Create a zero extend for that. 10457 EVT FinalType = Inst->getValueType(0); 10458 if (SliceType != FinalType) 10459 LastInst = 10460 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10461 return LastInst; 10462 } 10463 10464 /// \brief Check if this slice can be merged with an expensive cross register 10465 /// bank copy. E.g., 10466 /// i = load i32 10467 /// f = bitcast i32 i to float 10468 bool canMergeExpensiveCrossRegisterBankCopy() const { 10469 if (!Inst || !Inst->hasOneUse()) 10470 return false; 10471 SDNode *Use = *Inst->use_begin(); 10472 if (Use->getOpcode() != ISD::BITCAST) 10473 return false; 10474 assert(DAG && "Missing context"); 10475 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10476 EVT ResVT = Use->getValueType(0); 10477 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10478 const TargetRegisterClass *ArgRC = 10479 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10480 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10481 return false; 10482 10483 // At this point, we know that we perform a cross-register-bank copy. 10484 // Check if it is expensive. 10485 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10486 // Assume bitcasts are cheap, unless both register classes do not 10487 // explicitly share a common sub class. 10488 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10489 return false; 10490 10491 // Check if it will be merged with the load. 10492 // 1. Check the alignment constraint. 10493 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10494 ResVT.getTypeForEVT(*DAG->getContext())); 10495 10496 if (RequiredAlignment > getAlignment()) 10497 return false; 10498 10499 // 2. Check that the load is a legal operation for that type. 10500 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10501 return false; 10502 10503 // 3. Check that we do not have a zext in the way. 10504 if (Inst->getValueType(0) != getLoadedType()) 10505 return false; 10506 10507 return true; 10508 } 10509 }; 10510 } 10511 10512 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10513 /// \p UsedBits looks like 0..0 1..1 0..0. 10514 static bool areUsedBitsDense(const APInt &UsedBits) { 10515 // If all the bits are one, this is dense! 10516 if (UsedBits.isAllOnesValue()) 10517 return true; 10518 10519 // Get rid of the unused bits on the right. 10520 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10521 // Get rid of the unused bits on the left. 10522 if (NarrowedUsedBits.countLeadingZeros()) 10523 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10524 // Check that the chunk of bits is completely used. 10525 return NarrowedUsedBits.isAllOnesValue(); 10526 } 10527 10528 /// \brief Check whether or not \p First and \p Second are next to each other 10529 /// in memory. This means that there is no hole between the bits loaded 10530 /// by \p First and the bits loaded by \p Second. 10531 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10532 const LoadedSlice &Second) { 10533 assert(First.Origin == Second.Origin && First.Origin && 10534 "Unable to match different memory origins."); 10535 APInt UsedBits = First.getUsedBits(); 10536 assert((UsedBits & Second.getUsedBits()) == 0 && 10537 "Slices are not supposed to overlap."); 10538 UsedBits |= Second.getUsedBits(); 10539 return areUsedBitsDense(UsedBits); 10540 } 10541 10542 /// \brief Adjust the \p GlobalLSCost according to the target 10543 /// paring capabilities and the layout of the slices. 10544 /// \pre \p GlobalLSCost should account for at least as many loads as 10545 /// there is in the slices in \p LoadedSlices. 10546 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10547 LoadedSlice::Cost &GlobalLSCost) { 10548 unsigned NumberOfSlices = LoadedSlices.size(); 10549 // If there is less than 2 elements, no pairing is possible. 10550 if (NumberOfSlices < 2) 10551 return; 10552 10553 // Sort the slices so that elements that are likely to be next to each 10554 // other in memory are next to each other in the list. 10555 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10556 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10557 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10558 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10559 }); 10560 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10561 // First (resp. Second) is the first (resp. Second) potentially candidate 10562 // to be placed in a paired load. 10563 const LoadedSlice *First = nullptr; 10564 const LoadedSlice *Second = nullptr; 10565 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10566 // Set the beginning of the pair. 10567 First = Second) { 10568 10569 Second = &LoadedSlices[CurrSlice]; 10570 10571 // If First is NULL, it means we start a new pair. 10572 // Get to the next slice. 10573 if (!First) 10574 continue; 10575 10576 EVT LoadedType = First->getLoadedType(); 10577 10578 // If the types of the slices are different, we cannot pair them. 10579 if (LoadedType != Second->getLoadedType()) 10580 continue; 10581 10582 // Check if the target supplies paired loads for this type. 10583 unsigned RequiredAlignment = 0; 10584 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10585 // move to the next pair, this type is hopeless. 10586 Second = nullptr; 10587 continue; 10588 } 10589 // Check if we meet the alignment requirement. 10590 if (RequiredAlignment > First->getAlignment()) 10591 continue; 10592 10593 // Check that both loads are next to each other in memory. 10594 if (!areSlicesNextToEachOther(*First, *Second)) 10595 continue; 10596 10597 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10598 --GlobalLSCost.Loads; 10599 // Move to the next pair. 10600 Second = nullptr; 10601 } 10602 } 10603 10604 /// \brief Check the profitability of all involved LoadedSlice. 10605 /// Currently, it is considered profitable if there is exactly two 10606 /// involved slices (1) which are (2) next to each other in memory, and 10607 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10608 /// 10609 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10610 /// the elements themselves. 10611 /// 10612 /// FIXME: When the cost model will be mature enough, we can relax 10613 /// constraints (1) and (2). 10614 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10615 const APInt &UsedBits, bool ForCodeSize) { 10616 unsigned NumberOfSlices = LoadedSlices.size(); 10617 if (StressLoadSlicing) 10618 return NumberOfSlices > 1; 10619 10620 // Check (1). 10621 if (NumberOfSlices != 2) 10622 return false; 10623 10624 // Check (2). 10625 if (!areUsedBitsDense(UsedBits)) 10626 return false; 10627 10628 // Check (3). 10629 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10630 // The original code has one big load. 10631 OrigCost.Loads = 1; 10632 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10633 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10634 // Accumulate the cost of all the slices. 10635 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10636 GlobalSlicingCost += SliceCost; 10637 10638 // Account as cost in the original configuration the gain obtained 10639 // with the current slices. 10640 OrigCost.addSliceGain(LS); 10641 } 10642 10643 // If the target supports paired load, adjust the cost accordingly. 10644 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10645 return OrigCost > GlobalSlicingCost; 10646 } 10647 10648 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10649 /// operations, split it in the various pieces being extracted. 10650 /// 10651 /// This sort of thing is introduced by SROA. 10652 /// This slicing takes care not to insert overlapping loads. 10653 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10654 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10655 if (Level < AfterLegalizeDAG) 10656 return false; 10657 10658 LoadSDNode *LD = cast<LoadSDNode>(N); 10659 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10660 !LD->getValueType(0).isInteger()) 10661 return false; 10662 10663 // Keep track of already used bits to detect overlapping values. 10664 // In that case, we will just abort the transformation. 10665 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10666 10667 SmallVector<LoadedSlice, 4> LoadedSlices; 10668 10669 // Check if this load is used as several smaller chunks of bits. 10670 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10671 // of computation for each trunc. 10672 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10673 UI != UIEnd; ++UI) { 10674 // Skip the uses of the chain. 10675 if (UI.getUse().getResNo() != 0) 10676 continue; 10677 10678 SDNode *User = *UI; 10679 unsigned Shift = 0; 10680 10681 // Check if this is a trunc(lshr). 10682 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10683 isa<ConstantSDNode>(User->getOperand(1))) { 10684 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10685 User = *User->use_begin(); 10686 } 10687 10688 // At this point, User is a Truncate, iff we encountered, trunc or 10689 // trunc(lshr). 10690 if (User->getOpcode() != ISD::TRUNCATE) 10691 return false; 10692 10693 // The width of the type must be a power of 2 and greater than 8-bits. 10694 // Otherwise the load cannot be represented in LLVM IR. 10695 // Moreover, if we shifted with a non-8-bits multiple, the slice 10696 // will be across several bytes. We do not support that. 10697 unsigned Width = User->getValueSizeInBits(0); 10698 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10699 return 0; 10700 10701 // Build the slice for this chain of computations. 10702 LoadedSlice LS(User, LD, Shift, &DAG); 10703 APInt CurrentUsedBits = LS.getUsedBits(); 10704 10705 // Check if this slice overlaps with another. 10706 if ((CurrentUsedBits & UsedBits) != 0) 10707 return false; 10708 // Update the bits used globally. 10709 UsedBits |= CurrentUsedBits; 10710 10711 // Check if the new slice would be legal. 10712 if (!LS.isLegal()) 10713 return false; 10714 10715 // Record the slice. 10716 LoadedSlices.push_back(LS); 10717 } 10718 10719 // Abort slicing if it does not seem to be profitable. 10720 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10721 return false; 10722 10723 ++SlicedLoads; 10724 10725 // Rewrite each chain to use an independent load. 10726 // By construction, each chain can be represented by a unique load. 10727 10728 // Prepare the argument for the new token factor for all the slices. 10729 SmallVector<SDValue, 8> ArgChains; 10730 for (SmallVectorImpl<LoadedSlice>::const_iterator 10731 LSIt = LoadedSlices.begin(), 10732 LSItEnd = LoadedSlices.end(); 10733 LSIt != LSItEnd; ++LSIt) { 10734 SDValue SliceInst = LSIt->loadSlice(); 10735 CombineTo(LSIt->Inst, SliceInst, true); 10736 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10737 SliceInst = SliceInst.getOperand(0); 10738 assert(SliceInst->getOpcode() == ISD::LOAD && 10739 "It takes more than a zext to get to the loaded slice!!"); 10740 ArgChains.push_back(SliceInst.getValue(1)); 10741 } 10742 10743 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10744 ArgChains); 10745 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10746 return true; 10747 } 10748 10749 /// Check to see if V is (and load (ptr), imm), where the load is having 10750 /// specific bytes cleared out. If so, return the byte size being masked out 10751 /// and the shift amount. 10752 static std::pair<unsigned, unsigned> 10753 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10754 std::pair<unsigned, unsigned> Result(0, 0); 10755 10756 // Check for the structure we're looking for. 10757 if (V->getOpcode() != ISD::AND || 10758 !isa<ConstantSDNode>(V->getOperand(1)) || 10759 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10760 return Result; 10761 10762 // Check the chain and pointer. 10763 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10764 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10765 10766 // The store should be chained directly to the load or be an operand of a 10767 // tokenfactor. 10768 if (LD == Chain.getNode()) 10769 ; // ok. 10770 else if (Chain->getOpcode() != ISD::TokenFactor) 10771 return Result; // Fail. 10772 else { 10773 bool isOk = false; 10774 for (const SDValue &ChainOp : Chain->op_values()) 10775 if (ChainOp.getNode() == LD) { 10776 isOk = true; 10777 break; 10778 } 10779 if (!isOk) return Result; 10780 } 10781 10782 // This only handles simple types. 10783 if (V.getValueType() != MVT::i16 && 10784 V.getValueType() != MVT::i32 && 10785 V.getValueType() != MVT::i64) 10786 return Result; 10787 10788 // Check the constant mask. Invert it so that the bits being masked out are 10789 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10790 // follow the sign bit for uniformity. 10791 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10792 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10793 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10794 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10795 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10796 if (NotMaskLZ == 64) return Result; // All zero mask. 10797 10798 // See if we have a continuous run of bits. If so, we have 0*1+0* 10799 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10800 return Result; 10801 10802 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10803 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10804 NotMaskLZ -= 64-V.getValueSizeInBits(); 10805 10806 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10807 switch (MaskedBytes) { 10808 case 1: 10809 case 2: 10810 case 4: break; 10811 default: return Result; // All one mask, or 5-byte mask. 10812 } 10813 10814 // Verify that the first bit starts at a multiple of mask so that the access 10815 // is aligned the same as the access width. 10816 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10817 10818 Result.first = MaskedBytes; 10819 Result.second = NotMaskTZ/8; 10820 return Result; 10821 } 10822 10823 10824 /// Check to see if IVal is something that provides a value as specified by 10825 /// MaskInfo. If so, replace the specified store with a narrower store of 10826 /// truncated IVal. 10827 static SDNode * 10828 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10829 SDValue IVal, StoreSDNode *St, 10830 DAGCombiner *DC) { 10831 unsigned NumBytes = MaskInfo.first; 10832 unsigned ByteShift = MaskInfo.second; 10833 SelectionDAG &DAG = DC->getDAG(); 10834 10835 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10836 // that uses this. If not, this is not a replacement. 10837 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10838 ByteShift*8, (ByteShift+NumBytes)*8); 10839 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10840 10841 // Check that it is legal on the target to do this. It is legal if the new 10842 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10843 // legalization. 10844 MVT VT = MVT::getIntegerVT(NumBytes*8); 10845 if (!DC->isTypeLegal(VT)) 10846 return nullptr; 10847 10848 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10849 // shifted by ByteShift and truncated down to NumBytes. 10850 if (ByteShift) { 10851 SDLoc DL(IVal); 10852 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10853 DAG.getConstant(ByteShift*8, DL, 10854 DC->getShiftAmountTy(IVal.getValueType()))); 10855 } 10856 10857 // Figure out the offset for the store and the alignment of the access. 10858 unsigned StOffset; 10859 unsigned NewAlign = St->getAlignment(); 10860 10861 if (DAG.getDataLayout().isLittleEndian()) 10862 StOffset = ByteShift; 10863 else 10864 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10865 10866 SDValue Ptr = St->getBasePtr(); 10867 if (StOffset) { 10868 SDLoc DL(IVal); 10869 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10870 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10871 NewAlign = MinAlign(NewAlign, StOffset); 10872 } 10873 10874 // Truncate down to the new size. 10875 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10876 10877 ++OpsNarrowed; 10878 return DAG 10879 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10880 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 10881 .getNode(); 10882 } 10883 10884 10885 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10886 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10887 /// narrowing the load and store if it would end up being a win for performance 10888 /// or code size. 10889 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10890 StoreSDNode *ST = cast<StoreSDNode>(N); 10891 if (ST->isVolatile()) 10892 return SDValue(); 10893 10894 SDValue Chain = ST->getChain(); 10895 SDValue Value = ST->getValue(); 10896 SDValue Ptr = ST->getBasePtr(); 10897 EVT VT = Value.getValueType(); 10898 10899 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10900 return SDValue(); 10901 10902 unsigned Opc = Value.getOpcode(); 10903 10904 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10905 // is a byte mask indicating a consecutive number of bytes, check to see if 10906 // Y is known to provide just those bytes. If so, we try to replace the 10907 // load + replace + store sequence with a single (narrower) store, which makes 10908 // the load dead. 10909 if (Opc == ISD::OR) { 10910 std::pair<unsigned, unsigned> MaskedLoad; 10911 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10912 if (MaskedLoad.first) 10913 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10914 Value.getOperand(1), ST,this)) 10915 return SDValue(NewST, 0); 10916 10917 // Or is commutative, so try swapping X and Y. 10918 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10919 if (MaskedLoad.first) 10920 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10921 Value.getOperand(0), ST,this)) 10922 return SDValue(NewST, 0); 10923 } 10924 10925 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10926 Value.getOperand(1).getOpcode() != ISD::Constant) 10927 return SDValue(); 10928 10929 SDValue N0 = Value.getOperand(0); 10930 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10931 Chain == SDValue(N0.getNode(), 1)) { 10932 LoadSDNode *LD = cast<LoadSDNode>(N0); 10933 if (LD->getBasePtr() != Ptr || 10934 LD->getPointerInfo().getAddrSpace() != 10935 ST->getPointerInfo().getAddrSpace()) 10936 return SDValue(); 10937 10938 // Find the type to narrow it the load / op / store to. 10939 SDValue N1 = Value.getOperand(1); 10940 unsigned BitWidth = N1.getValueSizeInBits(); 10941 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10942 if (Opc == ISD::AND) 10943 Imm ^= APInt::getAllOnesValue(BitWidth); 10944 if (Imm == 0 || Imm.isAllOnesValue()) 10945 return SDValue(); 10946 unsigned ShAmt = Imm.countTrailingZeros(); 10947 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10948 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10949 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10950 // The narrowing should be profitable, the load/store operation should be 10951 // legal (or custom) and the store size should be equal to the NewVT width. 10952 while (NewBW < BitWidth && 10953 (NewVT.getStoreSizeInBits() != NewBW || 10954 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10955 !TLI.isNarrowingProfitable(VT, NewVT))) { 10956 NewBW = NextPowerOf2(NewBW); 10957 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10958 } 10959 if (NewBW >= BitWidth) 10960 return SDValue(); 10961 10962 // If the lsb changed does not start at the type bitwidth boundary, 10963 // start at the previous one. 10964 if (ShAmt % NewBW) 10965 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10966 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10967 std::min(BitWidth, ShAmt + NewBW)); 10968 if ((Imm & Mask) == Imm) { 10969 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10970 if (Opc == ISD::AND) 10971 NewImm ^= APInt::getAllOnesValue(NewBW); 10972 uint64_t PtrOff = ShAmt / 8; 10973 // For big endian targets, we need to adjust the offset to the pointer to 10974 // load the correct bytes. 10975 if (DAG.getDataLayout().isBigEndian()) 10976 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10977 10978 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10979 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10980 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10981 return SDValue(); 10982 10983 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10984 Ptr.getValueType(), Ptr, 10985 DAG.getConstant(PtrOff, SDLoc(LD), 10986 Ptr.getValueType())); 10987 SDValue NewLD = 10988 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 10989 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 10990 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10991 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10992 DAG.getConstant(NewImm, SDLoc(Value), 10993 NewVT)); 10994 SDValue NewST = 10995 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 10996 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 10997 10998 AddToWorklist(NewPtr.getNode()); 10999 AddToWorklist(NewLD.getNode()); 11000 AddToWorklist(NewVal.getNode()); 11001 WorklistRemover DeadNodes(*this); 11002 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 11003 ++OpsNarrowed; 11004 return NewST; 11005 } 11006 } 11007 11008 return SDValue(); 11009 } 11010 11011 /// For a given floating point load / store pair, if the load value isn't used 11012 /// by any other operations, then consider transforming the pair to integer 11013 /// load / store operations if the target deems the transformation profitable. 11014 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 11015 StoreSDNode *ST = cast<StoreSDNode>(N); 11016 SDValue Chain = ST->getChain(); 11017 SDValue Value = ST->getValue(); 11018 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 11019 Value.hasOneUse() && 11020 Chain == SDValue(Value.getNode(), 1)) { 11021 LoadSDNode *LD = cast<LoadSDNode>(Value); 11022 EVT VT = LD->getMemoryVT(); 11023 if (!VT.isFloatingPoint() || 11024 VT != ST->getMemoryVT() || 11025 LD->isNonTemporal() || 11026 ST->isNonTemporal() || 11027 LD->getPointerInfo().getAddrSpace() != 0 || 11028 ST->getPointerInfo().getAddrSpace() != 0) 11029 return SDValue(); 11030 11031 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 11032 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 11033 !TLI.isOperationLegal(ISD::STORE, IntVT) || 11034 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 11035 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 11036 return SDValue(); 11037 11038 unsigned LDAlign = LD->getAlignment(); 11039 unsigned STAlign = ST->getAlignment(); 11040 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 11041 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 11042 if (LDAlign < ABIAlign || STAlign < ABIAlign) 11043 return SDValue(); 11044 11045 SDValue NewLD = 11046 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 11047 LD->getPointerInfo(), LDAlign); 11048 11049 SDValue NewST = 11050 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 11051 ST->getPointerInfo(), STAlign); 11052 11053 AddToWorklist(NewLD.getNode()); 11054 AddToWorklist(NewST.getNode()); 11055 WorklistRemover DeadNodes(*this); 11056 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 11057 ++LdStFP2Int; 11058 return NewST; 11059 } 11060 11061 return SDValue(); 11062 } 11063 11064 namespace { 11065 /// Helper struct to parse and store a memory address as base + index + offset. 11066 /// We ignore sign extensions when it is safe to do so. 11067 /// The following two expressions are not equivalent. To differentiate we need 11068 /// to store whether there was a sign extension involved in the index 11069 /// computation. 11070 /// (load (i64 add (i64 copyfromreg %c) 11071 /// (i64 signextend (add (i8 load %index) 11072 /// (i8 1)))) 11073 /// vs 11074 /// 11075 /// (load (i64 add (i64 copyfromreg %c) 11076 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 11077 /// (i32 1))))) 11078 struct BaseIndexOffset { 11079 SDValue Base; 11080 SDValue Index; 11081 int64_t Offset; 11082 bool IsIndexSignExt; 11083 11084 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 11085 11086 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 11087 bool IsIndexSignExt) : 11088 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 11089 11090 bool equalBaseIndex(const BaseIndexOffset &Other) { 11091 return Other.Base == Base && Other.Index == Index && 11092 Other.IsIndexSignExt == IsIndexSignExt; 11093 } 11094 11095 /// Parses tree in Ptr for base, index, offset addresses. 11096 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 11097 bool IsIndexSignExt = false; 11098 11099 // Split up a folded GlobalAddress+Offset into its component parts. 11100 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 11101 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 11102 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 11103 SDLoc(GA), 11104 GA->getValueType(0), 11105 /*Offset=*/0, 11106 /*isTargetGA=*/false, 11107 GA->getTargetFlags()), 11108 SDValue(), 11109 GA->getOffset(), 11110 IsIndexSignExt); 11111 } 11112 11113 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 11114 // instruction, then it could be just the BASE or everything else we don't 11115 // know how to handle. Just use Ptr as BASE and give up. 11116 if (Ptr->getOpcode() != ISD::ADD) 11117 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11118 11119 // We know that we have at least an ADD instruction. Try to pattern match 11120 // the simple case of BASE + OFFSET. 11121 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 11122 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 11123 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 11124 IsIndexSignExt); 11125 } 11126 11127 // Inside a loop the current BASE pointer is calculated using an ADD and a 11128 // MUL instruction. In this case Ptr is the actual BASE pointer. 11129 // (i64 add (i64 %array_ptr) 11130 // (i64 mul (i64 %induction_var) 11131 // (i64 %element_size))) 11132 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 11133 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11134 11135 // Look at Base + Index + Offset cases. 11136 SDValue Base = Ptr->getOperand(0); 11137 SDValue IndexOffset = Ptr->getOperand(1); 11138 11139 // Skip signextends. 11140 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 11141 IndexOffset = IndexOffset->getOperand(0); 11142 IsIndexSignExt = true; 11143 } 11144 11145 // Either the case of Base + Index (no offset) or something else. 11146 if (IndexOffset->getOpcode() != ISD::ADD) 11147 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 11148 11149 // Now we have the case of Base + Index + offset. 11150 SDValue Index = IndexOffset->getOperand(0); 11151 SDValue Offset = IndexOffset->getOperand(1); 11152 11153 if (!isa<ConstantSDNode>(Offset)) 11154 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11155 11156 // Ignore signextends. 11157 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 11158 Index = Index->getOperand(0); 11159 IsIndexSignExt = true; 11160 } else IsIndexSignExt = false; 11161 11162 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 11163 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 11164 } 11165 }; 11166 } // namespace 11167 11168 // This is a helper function for visitMUL to check the profitability 11169 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11170 // MulNode is the original multiply, AddNode is (add x, c1), 11171 // and ConstNode is c2. 11172 // 11173 // If the (add x, c1) has multiple uses, we could increase 11174 // the number of adds if we make this transformation. 11175 // It would only be worth doing this if we can remove a 11176 // multiply in the process. Check for that here. 11177 // To illustrate: 11178 // (A + c1) * c3 11179 // (A + c2) * c3 11180 // We're checking for cases where we have common "c3 * A" expressions. 11181 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11182 SDValue &AddNode, 11183 SDValue &ConstNode) { 11184 APInt Val; 11185 11186 // If the add only has one use, this would be OK to do. 11187 if (AddNode.getNode()->hasOneUse()) 11188 return true; 11189 11190 // Walk all the users of the constant with which we're multiplying. 11191 for (SDNode *Use : ConstNode->uses()) { 11192 11193 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11194 continue; 11195 11196 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11197 SDNode *OtherOp; 11198 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11199 11200 // OtherOp is what we're multiplying against the constant. 11201 if (Use->getOperand(0) == ConstNode) 11202 OtherOp = Use->getOperand(1).getNode(); 11203 else 11204 OtherOp = Use->getOperand(0).getNode(); 11205 11206 // Check to see if multiply is with the same operand of our "add". 11207 // 11208 // ConstNode = CONST 11209 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11210 // ... 11211 // AddNode = (A + c1) <-- MulVar is A. 11212 // = AddNode * ConstNode <-- current visiting instruction. 11213 // 11214 // If we make this transformation, we will have a common 11215 // multiply (ConstNode * A) that we can save. 11216 if (OtherOp == MulVar) 11217 return true; 11218 11219 // Now check to see if a future expansion will give us a common 11220 // multiply. 11221 // 11222 // ConstNode = CONST 11223 // AddNode = (A + c1) 11224 // ... = AddNode * ConstNode <-- current visiting instruction. 11225 // ... 11226 // OtherOp = (A + c2) 11227 // Use = OtherOp * ConstNode <-- visiting Use. 11228 // 11229 // If we make this transformation, we will have a common 11230 // multiply (CONST * A) after we also do the same transformation 11231 // to the "t2" instruction. 11232 if (OtherOp->getOpcode() == ISD::ADD && 11233 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11234 OtherOp->getOperand(0).getNode() == MulVar) 11235 return true; 11236 } 11237 } 11238 11239 // Didn't find a case where this would be profitable. 11240 return false; 11241 } 11242 11243 SDValue DAGCombiner::getMergedConstantVectorStore( 11244 SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores, 11245 SmallVectorImpl<SDValue> &Chains, EVT Ty) const { 11246 SmallVector<SDValue, 8> BuildVector; 11247 11248 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11249 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11250 Chains.push_back(St->getChain()); 11251 BuildVector.push_back(St->getValue()); 11252 } 11253 11254 return DAG.getBuildVector(Ty, SL, BuildVector); 11255 } 11256 11257 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11258 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11259 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11260 // Make sure we have something to merge. 11261 if (NumStores < 2) 11262 return false; 11263 11264 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11265 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11266 unsigned LatestNodeUsed = 0; 11267 11268 for (unsigned i=0; i < NumStores; ++i) { 11269 // Find a chain for the new wide-store operand. Notice that some 11270 // of the store nodes that we found may not be selected for inclusion 11271 // in the wide store. The chain we use needs to be the chain of the 11272 // latest store node which is *used* and replaced by the wide store. 11273 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11274 LatestNodeUsed = i; 11275 } 11276 11277 SmallVector<SDValue, 8> Chains; 11278 11279 // The latest Node in the DAG. 11280 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11281 SDLoc DL(StoreNodes[0].MemNode); 11282 11283 SDValue StoredVal; 11284 if (UseVector) { 11285 bool IsVec = MemVT.isVector(); 11286 unsigned Elts = NumStores; 11287 if (IsVec) { 11288 // When merging vector stores, get the total number of elements. 11289 Elts *= MemVT.getVectorNumElements(); 11290 } 11291 // Get the type for the merged vector store. 11292 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11293 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11294 11295 if (IsConstantSrc) { 11296 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11297 } else { 11298 SmallVector<SDValue, 8> Ops; 11299 for (unsigned i = 0; i < NumStores; ++i) { 11300 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11301 SDValue Val = St->getValue(); 11302 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11303 if (Val.getValueType() != MemVT) 11304 return false; 11305 Ops.push_back(Val); 11306 Chains.push_back(St->getChain()); 11307 } 11308 11309 // Build the extracted vector elements back into a vector. 11310 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11311 DL, Ty, Ops); } 11312 } else { 11313 // We should always use a vector store when merging extracted vector 11314 // elements, so this path implies a store of constants. 11315 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11316 11317 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11318 APInt StoreInt(SizeInBits, 0); 11319 11320 // Construct a single integer constant which is made of the smaller 11321 // constant inputs. 11322 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11323 for (unsigned i = 0; i < NumStores; ++i) { 11324 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11325 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11326 Chains.push_back(St->getChain()); 11327 11328 SDValue Val = St->getValue(); 11329 StoreInt <<= ElementSizeBytes * 8; 11330 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11331 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11332 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11333 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11334 } else { 11335 llvm_unreachable("Invalid constant element type"); 11336 } 11337 } 11338 11339 // Create the new Load and Store operations. 11340 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11341 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11342 } 11343 11344 assert(!Chains.empty()); 11345 11346 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11347 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11348 FirstInChain->getBasePtr(), 11349 FirstInChain->getPointerInfo(), 11350 FirstInChain->getAlignment()); 11351 11352 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11353 : DAG.getSubtarget().useAA(); 11354 if (UseAA) { 11355 // Replace all merged stores with the new store. 11356 for (unsigned i = 0; i < NumStores; ++i) 11357 CombineTo(StoreNodes[i].MemNode, NewStore); 11358 } else { 11359 // Replace the last store with the new store. 11360 CombineTo(LatestOp, NewStore); 11361 // Erase all other stores. 11362 for (unsigned i = 0; i < NumStores; ++i) { 11363 if (StoreNodes[i].MemNode == LatestOp) 11364 continue; 11365 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11366 // ReplaceAllUsesWith will replace all uses that existed when it was 11367 // called, but graph optimizations may cause new ones to appear. For 11368 // example, the case in pr14333 looks like 11369 // 11370 // St's chain -> St -> another store -> X 11371 // 11372 // And the only difference from St to the other store is the chain. 11373 // When we change it's chain to be St's chain they become identical, 11374 // get CSEed and the net result is that X is now a use of St. 11375 // Since we know that St is redundant, just iterate. 11376 while (!St->use_empty()) 11377 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11378 deleteAndRecombine(St); 11379 } 11380 } 11381 11382 return true; 11383 } 11384 11385 void DAGCombiner::getStoreMergeAndAliasCandidates( 11386 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11387 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11388 // This holds the base pointer, index, and the offset in bytes from the base 11389 // pointer. 11390 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11391 11392 // We must have a base and an offset. 11393 if (!BasePtr.Base.getNode()) 11394 return; 11395 11396 // Do not handle stores to undef base pointers. 11397 if (BasePtr.Base.isUndef()) 11398 return; 11399 11400 // Walk up the chain and look for nodes with offsets from the same 11401 // base pointer. Stop when reaching an instruction with a different kind 11402 // or instruction which has a different base pointer. 11403 EVT MemVT = St->getMemoryVT(); 11404 unsigned Seq = 0; 11405 StoreSDNode *Index = St; 11406 11407 11408 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11409 : DAG.getSubtarget().useAA(); 11410 11411 if (UseAA) { 11412 // Look at other users of the same chain. Stores on the same chain do not 11413 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11414 // to be on the same chain, so don't bother looking at adjacent chains. 11415 11416 SDValue Chain = St->getChain(); 11417 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11418 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11419 if (I.getOperandNo() != 0) 11420 continue; 11421 11422 if (OtherST->isVolatile() || OtherST->isIndexed()) 11423 continue; 11424 11425 if (OtherST->getMemoryVT() != MemVT) 11426 continue; 11427 11428 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11429 11430 if (Ptr.equalBaseIndex(BasePtr)) 11431 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11432 } 11433 } 11434 11435 return; 11436 } 11437 11438 while (Index) { 11439 // If the chain has more than one use, then we can't reorder the mem ops. 11440 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11441 break; 11442 11443 // Find the base pointer and offset for this memory node. 11444 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11445 11446 // Check that the base pointer is the same as the original one. 11447 if (!Ptr.equalBaseIndex(BasePtr)) 11448 break; 11449 11450 // The memory operands must not be volatile. 11451 if (Index->isVolatile() || Index->isIndexed()) 11452 break; 11453 11454 // No truncation. 11455 if (Index->isTruncatingStore()) 11456 break; 11457 11458 // The stored memory type must be the same. 11459 if (Index->getMemoryVT() != MemVT) 11460 break; 11461 11462 // We do not allow under-aligned stores in order to prevent 11463 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11464 // be irrelevant here; what MATTERS is that we not move memory 11465 // operations that potentially overlap past each-other. 11466 if (Index->getAlignment() < MemVT.getStoreSize()) 11467 break; 11468 11469 // We found a potential memory operand to merge. 11470 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11471 11472 // Find the next memory operand in the chain. If the next operand in the 11473 // chain is a store then move up and continue the scan with the next 11474 // memory operand. If the next operand is a load save it and use alias 11475 // information to check if it interferes with anything. 11476 SDNode *NextInChain = Index->getChain().getNode(); 11477 while (1) { 11478 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11479 // We found a store node. Use it for the next iteration. 11480 Index = STn; 11481 break; 11482 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11483 if (Ldn->isVolatile()) { 11484 Index = nullptr; 11485 break; 11486 } 11487 11488 // Save the load node for later. Continue the scan. 11489 AliasLoadNodes.push_back(Ldn); 11490 NextInChain = Ldn->getChain().getNode(); 11491 continue; 11492 } else { 11493 Index = nullptr; 11494 break; 11495 } 11496 } 11497 } 11498 } 11499 11500 // We need to check that merging these stores does not cause a loop 11501 // in the DAG. Any store candidate may depend on another candidate 11502 // indirectly through its operand (we already consider dependencies 11503 // through the chain). Check in parallel by searching up from 11504 // non-chain operands of candidates. 11505 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 11506 SmallVectorImpl<MemOpLink> &StoreNodes) { 11507 SmallPtrSet<const SDNode *, 16> Visited; 11508 SmallVector<const SDNode *, 8> Worklist; 11509 // search ops of store candidates 11510 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11511 SDNode *n = StoreNodes[i].MemNode; 11512 // Potential loops may happen only through non-chain operands 11513 for (unsigned j = 1; j < n->getNumOperands(); ++j) 11514 Worklist.push_back(n->getOperand(j).getNode()); 11515 } 11516 // search through DAG. We can stop early if we find a storenode 11517 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11518 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 11519 return false; 11520 } 11521 return true; 11522 } 11523 11524 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11525 if (OptLevel == CodeGenOpt::None) 11526 return false; 11527 11528 EVT MemVT = St->getMemoryVT(); 11529 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11530 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11531 Attribute::NoImplicitFloat); 11532 11533 // This function cannot currently deal with non-byte-sized memory sizes. 11534 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11535 return false; 11536 11537 if (!MemVT.isSimple()) 11538 return false; 11539 11540 // Perform an early exit check. Do not bother looking at stored values that 11541 // are not constants, loads, or extracted vector elements. 11542 SDValue StoredVal = St->getValue(); 11543 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11544 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11545 isa<ConstantFPSDNode>(StoredVal); 11546 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11547 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11548 11549 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11550 return false; 11551 11552 // Don't merge vectors into wider vectors if the source data comes from loads. 11553 // TODO: This restriction can be lifted by using logic similar to the 11554 // ExtractVecSrc case. 11555 if (MemVT.isVector() && IsLoadSrc) 11556 return false; 11557 11558 // Only look at ends of store sequences. 11559 SDValue Chain = SDValue(St, 0); 11560 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11561 return false; 11562 11563 // Save the LoadSDNodes that we find in the chain. 11564 // We need to make sure that these nodes do not interfere with 11565 // any of the store nodes. 11566 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11567 11568 // Save the StoreSDNodes that we find in the chain. 11569 SmallVector<MemOpLink, 8> StoreNodes; 11570 11571 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11572 11573 // Check if there is anything to merge. 11574 if (StoreNodes.size() < 2) 11575 return false; 11576 11577 // only do dependence check in AA case 11578 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11579 : DAG.getSubtarget().useAA(); 11580 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes)) 11581 return false; 11582 11583 // Sort the memory operands according to their distance from the 11584 // base pointer. As a secondary criteria: make sure stores coming 11585 // later in the code come first in the list. This is important for 11586 // the non-UseAA case, because we're merging stores into the FINAL 11587 // store along a chain which potentially contains aliasing stores. 11588 // Thus, if there are multiple stores to the same address, the last 11589 // one can be considered for merging but not the others. 11590 std::sort(StoreNodes.begin(), StoreNodes.end(), 11591 [](MemOpLink LHS, MemOpLink RHS) { 11592 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11593 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11594 LHS.SequenceNum < RHS.SequenceNum); 11595 }); 11596 11597 // Scan the memory operations on the chain and find the first non-consecutive 11598 // store memory address. 11599 unsigned LastConsecutiveStore = 0; 11600 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11601 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11602 11603 // Check that the addresses are consecutive starting from the second 11604 // element in the list of stores. 11605 if (i > 0) { 11606 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11607 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11608 break; 11609 } 11610 11611 // Check if this store interferes with any of the loads that we found. 11612 // If we find a load that alias with this store. Stop the sequence. 11613 if (any_of(AliasLoadNodes, [&](LSBaseSDNode *Ldn) { 11614 return isAlias(Ldn, StoreNodes[i].MemNode); 11615 })) 11616 break; 11617 11618 // Mark this node as useful. 11619 LastConsecutiveStore = i; 11620 } 11621 11622 // The node with the lowest store address. 11623 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11624 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11625 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11626 LLVMContext &Context = *DAG.getContext(); 11627 const DataLayout &DL = DAG.getDataLayout(); 11628 11629 // Store the constants into memory as one consecutive store. 11630 if (IsConstantSrc) { 11631 unsigned LastLegalType = 0; 11632 unsigned LastLegalVectorType = 0; 11633 bool NonZero = false; 11634 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11635 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11636 SDValue StoredVal = St->getValue(); 11637 11638 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11639 NonZero |= !C->isNullValue(); 11640 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11641 NonZero |= !C->getConstantFPValue()->isNullValue(); 11642 } else { 11643 // Non-constant. 11644 break; 11645 } 11646 11647 // Find a legal type for the constant store. 11648 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11649 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11650 bool IsFast; 11651 if (TLI.isTypeLegal(StoreTy) && 11652 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11653 FirstStoreAlign, &IsFast) && IsFast) { 11654 LastLegalType = i+1; 11655 // Or check whether a truncstore is legal. 11656 } else if (TLI.getTypeAction(Context, StoreTy) == 11657 TargetLowering::TypePromoteInteger) { 11658 EVT LegalizedStoredValueTy = 11659 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11660 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11661 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11662 FirstStoreAS, FirstStoreAlign, &IsFast) && 11663 IsFast) { 11664 LastLegalType = i + 1; 11665 } 11666 } 11667 11668 // We only use vectors if the constant is known to be zero or the target 11669 // allows it and the function is not marked with the noimplicitfloat 11670 // attribute. 11671 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11672 FirstStoreAS)) && 11673 !NoVectors) { 11674 // Find a legal type for the vector store. 11675 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11676 if (TLI.isTypeLegal(Ty) && 11677 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11678 FirstStoreAlign, &IsFast) && IsFast) 11679 LastLegalVectorType = i + 1; 11680 } 11681 } 11682 11683 // Check if we found a legal integer type to store. 11684 if (LastLegalType == 0 && LastLegalVectorType == 0) 11685 return false; 11686 11687 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11688 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11689 11690 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11691 true, UseVector); 11692 } 11693 11694 // When extracting multiple vector elements, try to store them 11695 // in one vector store rather than a sequence of scalar stores. 11696 if (IsExtractVecSrc) { 11697 unsigned NumStoresToMerge = 0; 11698 bool IsVec = MemVT.isVector(); 11699 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11700 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11701 unsigned StoreValOpcode = St->getValue().getOpcode(); 11702 // This restriction could be loosened. 11703 // Bail out if any stored values are not elements extracted from a vector. 11704 // It should be possible to handle mixed sources, but load sources need 11705 // more careful handling (see the block of code below that handles 11706 // consecutive loads). 11707 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11708 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11709 return false; 11710 11711 // Find a legal type for the vector store. 11712 unsigned Elts = i + 1; 11713 if (IsVec) { 11714 // When merging vector stores, get the total number of elements. 11715 Elts *= MemVT.getVectorNumElements(); 11716 } 11717 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11718 bool IsFast; 11719 if (TLI.isTypeLegal(Ty) && 11720 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11721 FirstStoreAlign, &IsFast) && IsFast) 11722 NumStoresToMerge = i + 1; 11723 } 11724 11725 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11726 false, true); 11727 } 11728 11729 // Below we handle the case of multiple consecutive stores that 11730 // come from multiple consecutive loads. We merge them into a single 11731 // wide load and a single wide store. 11732 11733 // Look for load nodes which are used by the stored values. 11734 SmallVector<MemOpLink, 8> LoadNodes; 11735 11736 // Find acceptable loads. Loads need to have the same chain (token factor), 11737 // must not be zext, volatile, indexed, and they must be consecutive. 11738 BaseIndexOffset LdBasePtr; 11739 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11740 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11741 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11742 if (!Ld) break; 11743 11744 // Loads must only have one use. 11745 if (!Ld->hasNUsesOfValue(1, 0)) 11746 break; 11747 11748 // The memory operands must not be volatile. 11749 if (Ld->isVolatile() || Ld->isIndexed()) 11750 break; 11751 11752 // We do not accept ext loads. 11753 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11754 break; 11755 11756 // The stored memory type must be the same. 11757 if (Ld->getMemoryVT() != MemVT) 11758 break; 11759 11760 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 11761 // If this is not the first ptr that we check. 11762 if (LdBasePtr.Base.getNode()) { 11763 // The base ptr must be the same. 11764 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11765 break; 11766 } else { 11767 // Check that all other base pointers are the same as this one. 11768 LdBasePtr = LdPtr; 11769 } 11770 11771 // We found a potential memory operand to merge. 11772 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11773 } 11774 11775 if (LoadNodes.size() < 2) 11776 return false; 11777 11778 // If we have load/store pair instructions and we only have two values, 11779 // don't bother. 11780 unsigned RequiredAlignment; 11781 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11782 St->getAlignment() >= RequiredAlignment) 11783 return false; 11784 11785 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11786 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11787 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11788 11789 // Scan the memory operations on the chain and find the first non-consecutive 11790 // load memory address. These variables hold the index in the store node 11791 // array. 11792 unsigned LastConsecutiveLoad = 0; 11793 // This variable refers to the size and not index in the array. 11794 unsigned LastLegalVectorType = 0; 11795 unsigned LastLegalIntegerType = 0; 11796 StartAddress = LoadNodes[0].OffsetFromBase; 11797 SDValue FirstChain = FirstLoad->getChain(); 11798 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11799 // All loads must share the same chain. 11800 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11801 break; 11802 11803 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11804 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11805 break; 11806 LastConsecutiveLoad = i; 11807 // Find a legal type for the vector store. 11808 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11809 bool IsFastSt, IsFastLd; 11810 if (TLI.isTypeLegal(StoreTy) && 11811 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11812 FirstStoreAlign, &IsFastSt) && IsFastSt && 11813 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11814 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11815 LastLegalVectorType = i + 1; 11816 } 11817 11818 // Find a legal type for the integer store. 11819 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11820 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11821 if (TLI.isTypeLegal(StoreTy) && 11822 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11823 FirstStoreAlign, &IsFastSt) && IsFastSt && 11824 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11825 FirstLoadAlign, &IsFastLd) && IsFastLd) 11826 LastLegalIntegerType = i + 1; 11827 // Or check whether a truncstore and extload is legal. 11828 else if (TLI.getTypeAction(Context, StoreTy) == 11829 TargetLowering::TypePromoteInteger) { 11830 EVT LegalizedStoredValueTy = 11831 TLI.getTypeToTransformTo(Context, StoreTy); 11832 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11833 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11834 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11835 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11836 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11837 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11838 IsFastSt && 11839 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11840 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11841 IsFastLd) 11842 LastLegalIntegerType = i+1; 11843 } 11844 } 11845 11846 // Only use vector types if the vector type is larger than the integer type. 11847 // If they are the same, use integers. 11848 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11849 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11850 11851 // We add +1 here because the LastXXX variables refer to location while 11852 // the NumElem refers to array/index size. 11853 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11854 NumElem = std::min(LastLegalType, NumElem); 11855 11856 if (NumElem < 2) 11857 return false; 11858 11859 // Collect the chains from all merged stores. 11860 SmallVector<SDValue, 8> MergeStoreChains; 11861 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11862 11863 // The latest Node in the DAG. 11864 unsigned LatestNodeUsed = 0; 11865 for (unsigned i=1; i<NumElem; ++i) { 11866 // Find a chain for the new wide-store operand. Notice that some 11867 // of the store nodes that we found may not be selected for inclusion 11868 // in the wide store. The chain we use needs to be the chain of the 11869 // latest store node which is *used* and replaced by the wide store. 11870 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11871 LatestNodeUsed = i; 11872 11873 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11874 } 11875 11876 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11877 11878 // Find if it is better to use vectors or integers to load and store 11879 // to memory. 11880 EVT JointMemOpVT; 11881 if (UseVectorTy) { 11882 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11883 } else { 11884 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11885 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11886 } 11887 11888 SDLoc LoadDL(LoadNodes[0].MemNode); 11889 SDLoc StoreDL(StoreNodes[0].MemNode); 11890 11891 // The merged loads are required to have the same incoming chain, so 11892 // using the first's chain is acceptable. 11893 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 11894 FirstLoad->getBasePtr(), 11895 FirstLoad->getPointerInfo(), FirstLoadAlign); 11896 11897 SDValue NewStoreChain = 11898 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11899 11900 SDValue NewStore = 11901 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11902 FirstInChain->getPointerInfo(), FirstStoreAlign); 11903 11904 // Transfer chain users from old loads to the new load. 11905 for (unsigned i = 0; i < NumElem; ++i) { 11906 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11907 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11908 SDValue(NewLoad.getNode(), 1)); 11909 } 11910 11911 if (UseAA) { 11912 // Replace the all stores with the new store. 11913 for (unsigned i = 0; i < NumElem; ++i) 11914 CombineTo(StoreNodes[i].MemNode, NewStore); 11915 } else { 11916 // Replace the last store with the new store. 11917 CombineTo(LatestOp, NewStore); 11918 // Erase all other stores. 11919 for (unsigned i = 0; i < NumElem; ++i) { 11920 // Remove all Store nodes. 11921 if (StoreNodes[i].MemNode == LatestOp) 11922 continue; 11923 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11924 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11925 deleteAndRecombine(St); 11926 } 11927 } 11928 11929 return true; 11930 } 11931 11932 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11933 SDLoc SL(ST); 11934 SDValue ReplStore; 11935 11936 // Replace the chain to avoid dependency. 11937 if (ST->isTruncatingStore()) { 11938 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11939 ST->getBasePtr(), ST->getMemoryVT(), 11940 ST->getMemOperand()); 11941 } else { 11942 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11943 ST->getMemOperand()); 11944 } 11945 11946 // Create token to keep both nodes around. 11947 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11948 MVT::Other, ST->getChain(), ReplStore); 11949 11950 // Make sure the new and old chains are cleaned up. 11951 AddToWorklist(Token.getNode()); 11952 11953 // Don't add users to work list. 11954 return CombineTo(ST, Token, false); 11955 } 11956 11957 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11958 SDValue Value = ST->getValue(); 11959 if (Value.getOpcode() == ISD::TargetConstantFP) 11960 return SDValue(); 11961 11962 SDLoc DL(ST); 11963 11964 SDValue Chain = ST->getChain(); 11965 SDValue Ptr = ST->getBasePtr(); 11966 11967 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11968 11969 // NOTE: If the original store is volatile, this transform must not increase 11970 // the number of stores. For example, on x86-32 an f64 can be stored in one 11971 // processor operation but an i64 (which is not legal) requires two. So the 11972 // transform should not be done in this case. 11973 11974 SDValue Tmp; 11975 switch (CFP->getSimpleValueType(0).SimpleTy) { 11976 default: 11977 llvm_unreachable("Unknown FP type"); 11978 case MVT::f16: // We don't do this for these yet. 11979 case MVT::f80: 11980 case MVT::f128: 11981 case MVT::ppcf128: 11982 return SDValue(); 11983 case MVT::f32: 11984 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11985 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11986 ; 11987 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11988 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11989 MVT::i32); 11990 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11991 } 11992 11993 return SDValue(); 11994 case MVT::f64: 11995 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11996 !ST->isVolatile()) || 11997 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11998 ; 11999 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 12000 getZExtValue(), SDLoc(CFP), MVT::i64); 12001 return DAG.getStore(Chain, DL, Tmp, 12002 Ptr, ST->getMemOperand()); 12003 } 12004 12005 if (!ST->isVolatile() && 12006 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 12007 // Many FP stores are not made apparent until after legalize, e.g. for 12008 // argument passing. Since this is so common, custom legalize the 12009 // 64-bit integer store into two 32-bit stores. 12010 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 12011 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 12012 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 12013 if (DAG.getDataLayout().isBigEndian()) 12014 std::swap(Lo, Hi); 12015 12016 unsigned Alignment = ST->getAlignment(); 12017 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 12018 AAMDNodes AAInfo = ST->getAAInfo(); 12019 12020 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 12021 ST->getAlignment(), MMOFlags, AAInfo); 12022 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12023 DAG.getConstant(4, DL, Ptr.getValueType())); 12024 Alignment = MinAlign(Alignment, 4U); 12025 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 12026 ST->getPointerInfo().getWithOffset(4), 12027 Alignment, MMOFlags, AAInfo); 12028 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 12029 St0, St1); 12030 } 12031 12032 return SDValue(); 12033 } 12034 } 12035 12036 SDValue DAGCombiner::visitSTORE(SDNode *N) { 12037 StoreSDNode *ST = cast<StoreSDNode>(N); 12038 SDValue Chain = ST->getChain(); 12039 SDValue Value = ST->getValue(); 12040 SDValue Ptr = ST->getBasePtr(); 12041 12042 // If this is a store of a bit convert, store the input value if the 12043 // resultant store does not need a higher alignment than the original. 12044 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 12045 ST->isUnindexed()) { 12046 EVT SVT = Value.getOperand(0).getValueType(); 12047 if (((!LegalOperations && !ST->isVolatile()) || 12048 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 12049 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 12050 unsigned OrigAlign = ST->getAlignment(); 12051 bool Fast = false; 12052 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 12053 ST->getAddressSpace(), OrigAlign, &Fast) && 12054 Fast) { 12055 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 12056 ST->getPointerInfo(), OrigAlign, 12057 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12058 } 12059 } 12060 } 12061 12062 // Turn 'store undef, Ptr' -> nothing. 12063 if (Value.isUndef() && ST->isUnindexed()) 12064 return Chain; 12065 12066 // Try to infer better alignment information than the store already has. 12067 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 12068 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12069 if (Align > ST->getAlignment()) { 12070 SDValue NewStore = 12071 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 12072 ST->getMemoryVT(), Align, 12073 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12074 if (NewStore.getNode() != N) 12075 return CombineTo(ST, NewStore, true); 12076 } 12077 } 12078 } 12079 12080 // Try transforming a pair floating point load / store ops to integer 12081 // load / store ops. 12082 if (SDValue NewST = TransformFPLoadStorePair(N)) 12083 return NewST; 12084 12085 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12086 : DAG.getSubtarget().useAA(); 12087 #ifndef NDEBUG 12088 if (CombinerAAOnlyFunc.getNumOccurrences() && 12089 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12090 UseAA = false; 12091 #endif 12092 if (UseAA && ST->isUnindexed()) { 12093 // FIXME: We should do this even without AA enabled. AA will just allow 12094 // FindBetterChain to work in more situations. The problem with this is that 12095 // any combine that expects memory operations to be on consecutive chains 12096 // first needs to be updated to look for users of the same chain. 12097 12098 // Walk up chain skipping non-aliasing memory nodes, on this store and any 12099 // adjacent stores. 12100 if (findBetterNeighborChains(ST)) { 12101 // replaceStoreChain uses CombineTo, which handled all of the worklist 12102 // manipulation. Return the original node to not do anything else. 12103 return SDValue(ST, 0); 12104 } 12105 Chain = ST->getChain(); 12106 } 12107 12108 // Try transforming N to an indexed store. 12109 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12110 return SDValue(N, 0); 12111 12112 // FIXME: is there such a thing as a truncating indexed store? 12113 if (ST->isTruncatingStore() && ST->isUnindexed() && 12114 Value.getValueType().isInteger()) { 12115 // See if we can simplify the input to this truncstore with knowledge that 12116 // only the low bits are being used. For example: 12117 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 12118 SDValue Shorter = 12119 GetDemandedBits(Value, 12120 APInt::getLowBitsSet( 12121 Value.getValueType().getScalarType().getSizeInBits(), 12122 ST->getMemoryVT().getScalarType().getSizeInBits())); 12123 AddToWorklist(Value.getNode()); 12124 if (Shorter.getNode()) 12125 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12126 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12127 12128 // Otherwise, see if we can simplify the operation with 12129 // SimplifyDemandedBits, which only works if the value has a single use. 12130 if (SimplifyDemandedBits(Value, 12131 APInt::getLowBitsSet( 12132 Value.getValueType().getScalarType().getSizeInBits(), 12133 ST->getMemoryVT().getScalarType().getSizeInBits()))) 12134 return SDValue(N, 0); 12135 } 12136 12137 // If this is a load followed by a store to the same location, then the store 12138 // is dead/noop. 12139 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12140 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12141 ST->isUnindexed() && !ST->isVolatile() && 12142 // There can't be any side effects between the load and store, such as 12143 // a call or store. 12144 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12145 // The store is dead, remove it. 12146 return Chain; 12147 } 12148 } 12149 12150 // If this is a store followed by a store with the same value to the same 12151 // location, then the store is dead/noop. 12152 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12153 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12154 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12155 ST1->isUnindexed() && !ST1->isVolatile()) { 12156 // The store is dead, remove it. 12157 return Chain; 12158 } 12159 } 12160 12161 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12162 // truncating store. We can do this even if this is already a truncstore. 12163 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12164 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12165 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12166 ST->getMemoryVT())) { 12167 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12168 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12169 } 12170 12171 // Only perform this optimization before the types are legal, because we 12172 // don't want to perform this optimization on every DAGCombine invocation. 12173 if (!LegalTypes) { 12174 bool EverChanged = false; 12175 12176 do { 12177 // There can be multiple store sequences on the same chain. 12178 // Keep trying to merge store sequences until we are unable to do so 12179 // or until we merge the last store on the chain. 12180 bool Changed = MergeConsecutiveStores(ST); 12181 EverChanged |= Changed; 12182 if (!Changed) break; 12183 } while (ST->getOpcode() != ISD::DELETED_NODE); 12184 12185 if (EverChanged) 12186 return SDValue(N, 0); 12187 } 12188 12189 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12190 // 12191 // Make sure to do this only after attempting to merge stores in order to 12192 // avoid changing the types of some subset of stores due to visit order, 12193 // preventing their merging. 12194 if (isa<ConstantFPSDNode>(Value)) { 12195 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12196 return NewSt; 12197 } 12198 12199 return ReduceLoadOpStoreWidth(N); 12200 } 12201 12202 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12203 SDValue InVec = N->getOperand(0); 12204 SDValue InVal = N->getOperand(1); 12205 SDValue EltNo = N->getOperand(2); 12206 SDLoc dl(N); 12207 12208 // If the inserted element is an UNDEF, just use the input vector. 12209 if (InVal.isUndef()) 12210 return InVec; 12211 12212 EVT VT = InVec.getValueType(); 12213 12214 // If we can't generate a legal BUILD_VECTOR, exit 12215 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12216 return SDValue(); 12217 12218 // Check that we know which element is being inserted 12219 if (!isa<ConstantSDNode>(EltNo)) 12220 return SDValue(); 12221 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12222 12223 // Canonicalize insert_vector_elt dag nodes. 12224 // Example: 12225 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12226 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12227 // 12228 // Do this only if the child insert_vector node has one use; also 12229 // do this only if indices are both constants and Idx1 < Idx0. 12230 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12231 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12232 unsigned OtherElt = 12233 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12234 if (Elt < OtherElt) { 12235 // Swap nodes. 12236 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 12237 InVec.getOperand(0), InVal, EltNo); 12238 AddToWorklist(NewOp.getNode()); 12239 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12240 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12241 } 12242 } 12243 12244 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12245 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12246 // vector elements. 12247 SmallVector<SDValue, 8> Ops; 12248 // Do not combine these two vectors if the output vector will not replace 12249 // the input vector. 12250 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12251 Ops.append(InVec.getNode()->op_begin(), 12252 InVec.getNode()->op_end()); 12253 } else if (InVec.isUndef()) { 12254 unsigned NElts = VT.getVectorNumElements(); 12255 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12256 } else { 12257 return SDValue(); 12258 } 12259 12260 // Insert the element 12261 if (Elt < Ops.size()) { 12262 // All the operands of BUILD_VECTOR must have the same type; 12263 // we enforce that here. 12264 EVT OpVT = Ops[0].getValueType(); 12265 if (InVal.getValueType() != OpVT) 12266 InVal = OpVT.bitsGT(InVal.getValueType()) ? 12267 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 12268 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 12269 Ops[Elt] = InVal; 12270 } 12271 12272 // Return the new vector 12273 return DAG.getBuildVector(VT, dl, Ops); 12274 } 12275 12276 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12277 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12278 assert(!OriginalLoad->isVolatile()); 12279 12280 EVT ResultVT = EVE->getValueType(0); 12281 EVT VecEltVT = InVecVT.getVectorElementType(); 12282 unsigned Align = OriginalLoad->getAlignment(); 12283 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12284 VecEltVT.getTypeForEVT(*DAG.getContext())); 12285 12286 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12287 return SDValue(); 12288 12289 Align = NewAlign; 12290 12291 SDValue NewPtr = OriginalLoad->getBasePtr(); 12292 SDValue Offset; 12293 EVT PtrType = NewPtr.getValueType(); 12294 MachinePointerInfo MPI; 12295 SDLoc DL(EVE); 12296 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12297 int Elt = ConstEltNo->getZExtValue(); 12298 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12299 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12300 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12301 } else { 12302 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12303 Offset = DAG.getNode( 12304 ISD::MUL, DL, PtrType, Offset, 12305 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12306 MPI = OriginalLoad->getPointerInfo(); 12307 } 12308 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12309 12310 // The replacement we need to do here is a little tricky: we need to 12311 // replace an extractelement of a load with a load. 12312 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12313 // Note that this replacement assumes that the extractvalue is the only 12314 // use of the load; that's okay because we don't want to perform this 12315 // transformation in other cases anyway. 12316 SDValue Load; 12317 SDValue Chain; 12318 if (ResultVT.bitsGT(VecEltVT)) { 12319 // If the result type of vextract is wider than the load, then issue an 12320 // extending load instead. 12321 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12322 VecEltVT) 12323 ? ISD::ZEXTLOAD 12324 : ISD::EXTLOAD; 12325 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 12326 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 12327 Align, OriginalLoad->getMemOperand()->getFlags(), 12328 OriginalLoad->getAAInfo()); 12329 Chain = Load.getValue(1); 12330 } else { 12331 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 12332 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 12333 OriginalLoad->getAAInfo()); 12334 Chain = Load.getValue(1); 12335 if (ResultVT.bitsLT(VecEltVT)) 12336 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12337 else 12338 Load = DAG.getBitcast(ResultVT, Load); 12339 } 12340 WorklistRemover DeadNodes(*this); 12341 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12342 SDValue To[] = { Load, Chain }; 12343 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12344 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12345 // worklist explicitly as well. 12346 AddToWorklist(Load.getNode()); 12347 AddUsersToWorklist(Load.getNode()); // Add users too 12348 // Make sure to revisit this node to clean it up; it will usually be dead. 12349 AddToWorklist(EVE); 12350 ++OpsNarrowed; 12351 return SDValue(EVE, 0); 12352 } 12353 12354 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12355 // (vextract (scalar_to_vector val, 0) -> val 12356 SDValue InVec = N->getOperand(0); 12357 EVT VT = InVec.getValueType(); 12358 EVT NVT = N->getValueType(0); 12359 12360 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12361 // Check if the result type doesn't match the inserted element type. A 12362 // SCALAR_TO_VECTOR may truncate the inserted element and the 12363 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12364 SDValue InOp = InVec.getOperand(0); 12365 if (InOp.getValueType() != NVT) { 12366 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12367 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12368 } 12369 return InOp; 12370 } 12371 12372 SDValue EltNo = N->getOperand(1); 12373 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12374 12375 // extract_vector_elt (build_vector x, y), 1 -> y 12376 if (ConstEltNo && 12377 InVec.getOpcode() == ISD::BUILD_VECTOR && 12378 TLI.isTypeLegal(VT) && 12379 (InVec.hasOneUse() || 12380 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12381 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12382 EVT InEltVT = Elt.getValueType(); 12383 12384 // Sometimes build_vector's scalar input types do not match result type. 12385 if (NVT == InEltVT) 12386 return Elt; 12387 12388 // TODO: It may be useful to truncate if free if the build_vector implicitly 12389 // converts. 12390 } 12391 12392 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 12393 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 12394 ConstEltNo->isNullValue() && VT.isInteger()) { 12395 SDValue BCSrc = InVec.getOperand(0); 12396 if (BCSrc.getValueType().isScalarInteger()) 12397 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 12398 } 12399 12400 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 12401 // 12402 // This only really matters if the index is non-constant since other combines 12403 // on the constant elements already work. 12404 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 12405 EltNo == InVec.getOperand(2)) { 12406 SDValue Elt = InVec.getOperand(1); 12407 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 12408 } 12409 12410 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12411 // We only perform this optimization before the op legalization phase because 12412 // we may introduce new vector instructions which are not backed by TD 12413 // patterns. For example on AVX, extracting elements from a wide vector 12414 // without using extract_subvector. However, if we can find an underlying 12415 // scalar value, then we can always use that. 12416 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12417 int NumElem = VT.getVectorNumElements(); 12418 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12419 // Find the new index to extract from. 12420 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12421 12422 // Extracting an undef index is undef. 12423 if (OrigElt == -1) 12424 return DAG.getUNDEF(NVT); 12425 12426 // Select the right vector half to extract from. 12427 SDValue SVInVec; 12428 if (OrigElt < NumElem) { 12429 SVInVec = InVec->getOperand(0); 12430 } else { 12431 SVInVec = InVec->getOperand(1); 12432 OrigElt -= NumElem; 12433 } 12434 12435 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12436 SDValue InOp = SVInVec.getOperand(OrigElt); 12437 if (InOp.getValueType() != NVT) { 12438 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12439 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12440 } 12441 12442 return InOp; 12443 } 12444 12445 // FIXME: We should handle recursing on other vector shuffles and 12446 // scalar_to_vector here as well. 12447 12448 if (!LegalOperations) { 12449 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12450 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12451 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12452 } 12453 } 12454 12455 bool BCNumEltsChanged = false; 12456 EVT ExtVT = VT.getVectorElementType(); 12457 EVT LVT = ExtVT; 12458 12459 // If the result of load has to be truncated, then it's not necessarily 12460 // profitable. 12461 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12462 return SDValue(); 12463 12464 if (InVec.getOpcode() == ISD::BITCAST) { 12465 // Don't duplicate a load with other uses. 12466 if (!InVec.hasOneUse()) 12467 return SDValue(); 12468 12469 EVT BCVT = InVec.getOperand(0).getValueType(); 12470 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12471 return SDValue(); 12472 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12473 BCNumEltsChanged = true; 12474 InVec = InVec.getOperand(0); 12475 ExtVT = BCVT.getVectorElementType(); 12476 } 12477 12478 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12479 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12480 ISD::isNormalLoad(InVec.getNode()) && 12481 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12482 SDValue Index = N->getOperand(1); 12483 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 12484 if (!OrigLoad->isVolatile()) { 12485 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12486 OrigLoad); 12487 } 12488 } 12489 } 12490 12491 // Perform only after legalization to ensure build_vector / vector_shuffle 12492 // optimizations have already been done. 12493 if (!LegalOperations) return SDValue(); 12494 12495 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12496 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12497 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12498 12499 if (ConstEltNo) { 12500 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12501 12502 LoadSDNode *LN0 = nullptr; 12503 const ShuffleVectorSDNode *SVN = nullptr; 12504 if (ISD::isNormalLoad(InVec.getNode())) { 12505 LN0 = cast<LoadSDNode>(InVec); 12506 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12507 InVec.getOperand(0).getValueType() == ExtVT && 12508 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12509 // Don't duplicate a load with other uses. 12510 if (!InVec.hasOneUse()) 12511 return SDValue(); 12512 12513 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12514 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12515 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12516 // => 12517 // (load $addr+1*size) 12518 12519 // Don't duplicate a load with other uses. 12520 if (!InVec.hasOneUse()) 12521 return SDValue(); 12522 12523 // If the bit convert changed the number of elements, it is unsafe 12524 // to examine the mask. 12525 if (BCNumEltsChanged) 12526 return SDValue(); 12527 12528 // Select the input vector, guarding against out of range extract vector. 12529 unsigned NumElems = VT.getVectorNumElements(); 12530 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12531 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12532 12533 if (InVec.getOpcode() == ISD::BITCAST) { 12534 // Don't duplicate a load with other uses. 12535 if (!InVec.hasOneUse()) 12536 return SDValue(); 12537 12538 InVec = InVec.getOperand(0); 12539 } 12540 if (ISD::isNormalLoad(InVec.getNode())) { 12541 LN0 = cast<LoadSDNode>(InVec); 12542 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12543 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12544 } 12545 } 12546 12547 // Make sure we found a non-volatile load and the extractelement is 12548 // the only use. 12549 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12550 return SDValue(); 12551 12552 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12553 if (Elt == -1) 12554 return DAG.getUNDEF(LVT); 12555 12556 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12557 } 12558 12559 return SDValue(); 12560 } 12561 12562 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12563 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12564 // We perform this optimization post type-legalization because 12565 // the type-legalizer often scalarizes integer-promoted vectors. 12566 // Performing this optimization before may create bit-casts which 12567 // will be type-legalized to complex code sequences. 12568 // We perform this optimization only before the operation legalizer because we 12569 // may introduce illegal operations. 12570 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12571 return SDValue(); 12572 12573 unsigned NumInScalars = N->getNumOperands(); 12574 SDLoc dl(N); 12575 EVT VT = N->getValueType(0); 12576 12577 // Check to see if this is a BUILD_VECTOR of a bunch of values 12578 // which come from any_extend or zero_extend nodes. If so, we can create 12579 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12580 // optimizations. We do not handle sign-extend because we can't fill the sign 12581 // using shuffles. 12582 EVT SourceType = MVT::Other; 12583 bool AllAnyExt = true; 12584 12585 for (unsigned i = 0; i != NumInScalars; ++i) { 12586 SDValue In = N->getOperand(i); 12587 // Ignore undef inputs. 12588 if (In.isUndef()) continue; 12589 12590 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12591 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12592 12593 // Abort if the element is not an extension. 12594 if (!ZeroExt && !AnyExt) { 12595 SourceType = MVT::Other; 12596 break; 12597 } 12598 12599 // The input is a ZeroExt or AnyExt. Check the original type. 12600 EVT InTy = In.getOperand(0).getValueType(); 12601 12602 // Check that all of the widened source types are the same. 12603 if (SourceType == MVT::Other) 12604 // First time. 12605 SourceType = InTy; 12606 else if (InTy != SourceType) { 12607 // Multiple income types. Abort. 12608 SourceType = MVT::Other; 12609 break; 12610 } 12611 12612 // Check if all of the extends are ANY_EXTENDs. 12613 AllAnyExt &= AnyExt; 12614 } 12615 12616 // In order to have valid types, all of the inputs must be extended from the 12617 // same source type and all of the inputs must be any or zero extend. 12618 // Scalar sizes must be a power of two. 12619 EVT OutScalarTy = VT.getScalarType(); 12620 bool ValidTypes = SourceType != MVT::Other && 12621 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12622 isPowerOf2_32(SourceType.getSizeInBits()); 12623 12624 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12625 // turn into a single shuffle instruction. 12626 if (!ValidTypes) 12627 return SDValue(); 12628 12629 bool isLE = DAG.getDataLayout().isLittleEndian(); 12630 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12631 assert(ElemRatio > 1 && "Invalid element size ratio"); 12632 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12633 DAG.getConstant(0, SDLoc(N), SourceType); 12634 12635 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12636 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12637 12638 // Populate the new build_vector 12639 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12640 SDValue Cast = N->getOperand(i); 12641 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12642 Cast.getOpcode() == ISD::ZERO_EXTEND || 12643 Cast.isUndef()) && "Invalid cast opcode"); 12644 SDValue In; 12645 if (Cast.isUndef()) 12646 In = DAG.getUNDEF(SourceType); 12647 else 12648 In = Cast->getOperand(0); 12649 unsigned Index = isLE ? (i * ElemRatio) : 12650 (i * ElemRatio + (ElemRatio - 1)); 12651 12652 assert(Index < Ops.size() && "Invalid index"); 12653 Ops[Index] = In; 12654 } 12655 12656 // The type of the new BUILD_VECTOR node. 12657 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12658 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12659 "Invalid vector size"); 12660 // Check if the new vector type is legal. 12661 if (!isTypeLegal(VecVT)) return SDValue(); 12662 12663 // Make the new BUILD_VECTOR. 12664 SDValue BV = DAG.getBuildVector(VecVT, dl, Ops); 12665 12666 // The new BUILD_VECTOR node has the potential to be further optimized. 12667 AddToWorklist(BV.getNode()); 12668 // Bitcast to the desired type. 12669 return DAG.getBitcast(VT, BV); 12670 } 12671 12672 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12673 EVT VT = N->getValueType(0); 12674 12675 unsigned NumInScalars = N->getNumOperands(); 12676 SDLoc dl(N); 12677 12678 EVT SrcVT = MVT::Other; 12679 unsigned Opcode = ISD::DELETED_NODE; 12680 unsigned NumDefs = 0; 12681 12682 for (unsigned i = 0; i != NumInScalars; ++i) { 12683 SDValue In = N->getOperand(i); 12684 unsigned Opc = In.getOpcode(); 12685 12686 if (Opc == ISD::UNDEF) 12687 continue; 12688 12689 // If all scalar values are floats and converted from integers. 12690 if (Opcode == ISD::DELETED_NODE && 12691 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12692 Opcode = Opc; 12693 } 12694 12695 if (Opc != Opcode) 12696 return SDValue(); 12697 12698 EVT InVT = In.getOperand(0).getValueType(); 12699 12700 // If all scalar values are typed differently, bail out. It's chosen to 12701 // simplify BUILD_VECTOR of integer types. 12702 if (SrcVT == MVT::Other) 12703 SrcVT = InVT; 12704 if (SrcVT != InVT) 12705 return SDValue(); 12706 NumDefs++; 12707 } 12708 12709 // If the vector has just one element defined, it's not worth to fold it into 12710 // a vectorized one. 12711 if (NumDefs < 2) 12712 return SDValue(); 12713 12714 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12715 && "Should only handle conversion from integer to float."); 12716 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12717 12718 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12719 12720 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12721 return SDValue(); 12722 12723 // Just because the floating-point vector type is legal does not necessarily 12724 // mean that the corresponding integer vector type is. 12725 if (!isTypeLegal(NVT)) 12726 return SDValue(); 12727 12728 SmallVector<SDValue, 8> Opnds; 12729 for (unsigned i = 0; i != NumInScalars; ++i) { 12730 SDValue In = N->getOperand(i); 12731 12732 if (In.isUndef()) 12733 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12734 else 12735 Opnds.push_back(In.getOperand(0)); 12736 } 12737 SDValue BV = DAG.getBuildVector(NVT, dl, Opnds); 12738 AddToWorklist(BV.getNode()); 12739 12740 return DAG.getNode(Opcode, dl, VT, BV); 12741 } 12742 12743 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12744 unsigned NumInScalars = N->getNumOperands(); 12745 SDLoc dl(N); 12746 EVT VT = N->getValueType(0); 12747 12748 // A vector built entirely of undefs is undef. 12749 if (ISD::allOperandsUndef(N)) 12750 return DAG.getUNDEF(VT); 12751 12752 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12753 return V; 12754 12755 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12756 return V; 12757 12758 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12759 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12760 // at most two distinct vectors, turn this into a shuffle node. 12761 12762 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12763 if (!isTypeLegal(VT)) 12764 return SDValue(); 12765 12766 // May only combine to shuffle after legalize if shuffle is legal. 12767 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12768 return SDValue(); 12769 12770 SDValue VecIn1, VecIn2; 12771 bool UsesZeroVector = false; 12772 for (unsigned i = 0; i != NumInScalars; ++i) { 12773 SDValue Op = N->getOperand(i); 12774 // Ignore undef inputs. 12775 if (Op.isUndef()) continue; 12776 12777 // See if we can combine this build_vector into a blend with a zero vector. 12778 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12779 UsesZeroVector = true; 12780 continue; 12781 } 12782 12783 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12784 // constant index, bail out. 12785 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12786 !isa<ConstantSDNode>(Op.getOperand(1))) { 12787 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12788 break; 12789 } 12790 12791 // We allow up to two distinct input vectors. 12792 SDValue ExtractedFromVec = Op.getOperand(0); 12793 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12794 continue; 12795 12796 if (!VecIn1.getNode()) { 12797 VecIn1 = ExtractedFromVec; 12798 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12799 VecIn2 = ExtractedFromVec; 12800 } else { 12801 // Too many inputs. 12802 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12803 break; 12804 } 12805 } 12806 12807 // If everything is good, we can make a shuffle operation. 12808 if (VecIn1.getNode()) { 12809 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12810 SmallVector<int, 8> Mask; 12811 for (unsigned i = 0; i != NumInScalars; ++i) { 12812 unsigned Opcode = N->getOperand(i).getOpcode(); 12813 if (Opcode == ISD::UNDEF) { 12814 Mask.push_back(-1); 12815 continue; 12816 } 12817 12818 // Operands can also be zero. 12819 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12820 assert(UsesZeroVector && 12821 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12822 "Unexpected node found!"); 12823 Mask.push_back(NumInScalars+i); 12824 continue; 12825 } 12826 12827 // If extracting from the first vector, just use the index directly. 12828 SDValue Extract = N->getOperand(i); 12829 SDValue ExtVal = Extract.getOperand(1); 12830 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12831 if (Extract.getOperand(0) == VecIn1) { 12832 Mask.push_back(ExtIndex); 12833 continue; 12834 } 12835 12836 // Otherwise, use InIdx + InputVecSize 12837 Mask.push_back(InNumElements + ExtIndex); 12838 } 12839 12840 // Avoid introducing illegal shuffles with zero. 12841 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12842 return SDValue(); 12843 12844 // We can't generate a shuffle node with mismatched input and output types. 12845 // Attempt to transform a single input vector to the correct type. 12846 if ((VT != VecIn1.getValueType())) { 12847 // If the input vector type has a different base type to the output 12848 // vector type, bail out. 12849 EVT VTElemType = VT.getVectorElementType(); 12850 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12851 (VecIn2.getNode() && 12852 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12853 return SDValue(); 12854 12855 // If the input vector is too small, widen it. 12856 // We only support widening of vectors which are half the size of the 12857 // output registers. For example XMM->YMM widening on X86 with AVX. 12858 EVT VecInT = VecIn1.getValueType(); 12859 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12860 // If we only have one small input, widen it by adding undef values. 12861 if (!VecIn2.getNode()) 12862 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12863 DAG.getUNDEF(VecIn1.getValueType())); 12864 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12865 // If we have two small inputs of the same type, try to concat them. 12866 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12867 VecIn2 = SDValue(nullptr, 0); 12868 } else 12869 return SDValue(); 12870 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12871 // If the input vector is too large, try to split it. 12872 // We don't support having two input vectors that are too large. 12873 // If the zero vector was used, we can not split the vector, 12874 // since we'd need 3 inputs. 12875 if (UsesZeroVector || VecIn2.getNode()) 12876 return SDValue(); 12877 12878 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12879 return SDValue(); 12880 12881 // Try to replace VecIn1 with two extract_subvectors 12882 // No need to update the masks, they should still be correct. 12883 VecIn2 = DAG.getNode( 12884 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12885 DAG.getConstant(VT.getVectorNumElements(), dl, 12886 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12887 VecIn1 = DAG.getNode( 12888 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12889 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12890 } else 12891 return SDValue(); 12892 } 12893 12894 if (UsesZeroVector) 12895 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12896 DAG.getConstantFP(0.0, dl, VT); 12897 else 12898 // If VecIn2 is unused then change it to undef. 12899 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12900 12901 // Check that we were able to transform all incoming values to the same 12902 // type. 12903 if (VecIn2.getValueType() != VecIn1.getValueType() || 12904 VecIn1.getValueType() != VT) 12905 return SDValue(); 12906 12907 // Return the new VECTOR_SHUFFLE node. 12908 SDValue Ops[2]; 12909 Ops[0] = VecIn1; 12910 Ops[1] = VecIn2; 12911 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], Mask); 12912 } 12913 12914 return SDValue(); 12915 } 12916 12917 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12918 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12919 EVT OpVT = N->getOperand(0).getValueType(); 12920 12921 // If the operands are legal vectors, leave them alone. 12922 if (TLI.isTypeLegal(OpVT)) 12923 return SDValue(); 12924 12925 SDLoc DL(N); 12926 EVT VT = N->getValueType(0); 12927 SmallVector<SDValue, 8> Ops; 12928 12929 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12930 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12931 12932 // Keep track of what we encounter. 12933 bool AnyInteger = false; 12934 bool AnyFP = false; 12935 for (const SDValue &Op : N->ops()) { 12936 if (ISD::BITCAST == Op.getOpcode() && 12937 !Op.getOperand(0).getValueType().isVector()) 12938 Ops.push_back(Op.getOperand(0)); 12939 else if (ISD::UNDEF == Op.getOpcode()) 12940 Ops.push_back(ScalarUndef); 12941 else 12942 return SDValue(); 12943 12944 // Note whether we encounter an integer or floating point scalar. 12945 // If it's neither, bail out, it could be something weird like x86mmx. 12946 EVT LastOpVT = Ops.back().getValueType(); 12947 if (LastOpVT.isFloatingPoint()) 12948 AnyFP = true; 12949 else if (LastOpVT.isInteger()) 12950 AnyInteger = true; 12951 else 12952 return SDValue(); 12953 } 12954 12955 // If any of the operands is a floating point scalar bitcast to a vector, 12956 // use floating point types throughout, and bitcast everything. 12957 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12958 if (AnyFP) { 12959 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12960 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12961 if (AnyInteger) { 12962 for (SDValue &Op : Ops) { 12963 if (Op.getValueType() == SVT) 12964 continue; 12965 if (Op.isUndef()) 12966 Op = ScalarUndef; 12967 else 12968 Op = DAG.getBitcast(SVT, Op); 12969 } 12970 } 12971 } 12972 12973 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12974 VT.getSizeInBits() / SVT.getSizeInBits()); 12975 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 12976 } 12977 12978 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12979 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12980 // most two distinct vectors the same size as the result, attempt to turn this 12981 // into a legal shuffle. 12982 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12983 EVT VT = N->getValueType(0); 12984 EVT OpVT = N->getOperand(0).getValueType(); 12985 int NumElts = VT.getVectorNumElements(); 12986 int NumOpElts = OpVT.getVectorNumElements(); 12987 12988 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12989 SmallVector<int, 8> Mask; 12990 12991 for (SDValue Op : N->ops()) { 12992 // Peek through any bitcast. 12993 while (Op.getOpcode() == ISD::BITCAST) 12994 Op = Op.getOperand(0); 12995 12996 // UNDEF nodes convert to UNDEF shuffle mask values. 12997 if (Op.isUndef()) { 12998 Mask.append((unsigned)NumOpElts, -1); 12999 continue; 13000 } 13001 13002 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13003 return SDValue(); 13004 13005 // What vector are we extracting the subvector from and at what index? 13006 SDValue ExtVec = Op.getOperand(0); 13007 13008 // We want the EVT of the original extraction to correctly scale the 13009 // extraction index. 13010 EVT ExtVT = ExtVec.getValueType(); 13011 13012 // Peek through any bitcast. 13013 while (ExtVec.getOpcode() == ISD::BITCAST) 13014 ExtVec = ExtVec.getOperand(0); 13015 13016 // UNDEF nodes convert to UNDEF shuffle mask values. 13017 if (ExtVec.isUndef()) { 13018 Mask.append((unsigned)NumOpElts, -1); 13019 continue; 13020 } 13021 13022 if (!isa<ConstantSDNode>(Op.getOperand(1))) 13023 return SDValue(); 13024 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 13025 13026 // Ensure that we are extracting a subvector from a vector the same 13027 // size as the result. 13028 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 13029 return SDValue(); 13030 13031 // Scale the subvector index to account for any bitcast. 13032 int NumExtElts = ExtVT.getVectorNumElements(); 13033 if (0 == (NumExtElts % NumElts)) 13034 ExtIdx /= (NumExtElts / NumElts); 13035 else if (0 == (NumElts % NumExtElts)) 13036 ExtIdx *= (NumElts / NumExtElts); 13037 else 13038 return SDValue(); 13039 13040 // At most we can reference 2 inputs in the final shuffle. 13041 if (SV0.isUndef() || SV0 == ExtVec) { 13042 SV0 = ExtVec; 13043 for (int i = 0; i != NumOpElts; ++i) 13044 Mask.push_back(i + ExtIdx); 13045 } else if (SV1.isUndef() || SV1 == ExtVec) { 13046 SV1 = ExtVec; 13047 for (int i = 0; i != NumOpElts; ++i) 13048 Mask.push_back(i + ExtIdx + NumElts); 13049 } else { 13050 return SDValue(); 13051 } 13052 } 13053 13054 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 13055 return SDValue(); 13056 13057 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 13058 DAG.getBitcast(VT, SV1), Mask); 13059 } 13060 13061 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 13062 // If we only have one input vector, we don't need to do any concatenation. 13063 if (N->getNumOperands() == 1) 13064 return N->getOperand(0); 13065 13066 // Check if all of the operands are undefs. 13067 EVT VT = N->getValueType(0); 13068 if (ISD::allOperandsUndef(N)) 13069 return DAG.getUNDEF(VT); 13070 13071 // Optimize concat_vectors where all but the first of the vectors are undef. 13072 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 13073 return Op.isUndef(); 13074 })) { 13075 SDValue In = N->getOperand(0); 13076 assert(In.getValueType().isVector() && "Must concat vectors"); 13077 13078 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 13079 if (In->getOpcode() == ISD::BITCAST && 13080 !In->getOperand(0)->getValueType(0).isVector()) { 13081 SDValue Scalar = In->getOperand(0); 13082 13083 // If the bitcast type isn't legal, it might be a trunc of a legal type; 13084 // look through the trunc so we can still do the transform: 13085 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 13086 if (Scalar->getOpcode() == ISD::TRUNCATE && 13087 !TLI.isTypeLegal(Scalar.getValueType()) && 13088 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 13089 Scalar = Scalar->getOperand(0); 13090 13091 EVT SclTy = Scalar->getValueType(0); 13092 13093 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 13094 return SDValue(); 13095 13096 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 13097 VT.getSizeInBits() / SclTy.getSizeInBits()); 13098 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 13099 return SDValue(); 13100 13101 SDLoc dl = SDLoc(N); 13102 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 13103 return DAG.getBitcast(VT, Res); 13104 } 13105 } 13106 13107 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 13108 // We have already tested above for an UNDEF only concatenation. 13109 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 13110 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 13111 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 13112 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 13113 }; 13114 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 13115 SmallVector<SDValue, 8> Opnds; 13116 EVT SVT = VT.getScalarType(); 13117 13118 EVT MinVT = SVT; 13119 if (!SVT.isFloatingPoint()) { 13120 // If BUILD_VECTOR are from built from integer, they may have different 13121 // operand types. Get the smallest type and truncate all operands to it. 13122 bool FoundMinVT = false; 13123 for (const SDValue &Op : N->ops()) 13124 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13125 EVT OpSVT = Op.getOperand(0)->getValueType(0); 13126 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 13127 FoundMinVT = true; 13128 } 13129 assert(FoundMinVT && "Concat vector type mismatch"); 13130 } 13131 13132 for (const SDValue &Op : N->ops()) { 13133 EVT OpVT = Op.getValueType(); 13134 unsigned NumElts = OpVT.getVectorNumElements(); 13135 13136 if (ISD::UNDEF == Op.getOpcode()) 13137 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 13138 13139 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13140 if (SVT.isFloatingPoint()) { 13141 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 13142 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 13143 } else { 13144 for (unsigned i = 0; i != NumElts; ++i) 13145 Opnds.push_back( 13146 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 13147 } 13148 } 13149 } 13150 13151 assert(VT.getVectorNumElements() == Opnds.size() && 13152 "Concat vector type mismatch"); 13153 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 13154 } 13155 13156 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 13157 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 13158 return V; 13159 13160 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 13161 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 13162 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 13163 return V; 13164 13165 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 13166 // nodes often generate nop CONCAT_VECTOR nodes. 13167 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 13168 // place the incoming vectors at the exact same location. 13169 SDValue SingleSource = SDValue(); 13170 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 13171 13172 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13173 SDValue Op = N->getOperand(i); 13174 13175 if (Op.isUndef()) 13176 continue; 13177 13178 // Check if this is the identity extract: 13179 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13180 return SDValue(); 13181 13182 // Find the single incoming vector for the extract_subvector. 13183 if (SingleSource.getNode()) { 13184 if (Op.getOperand(0) != SingleSource) 13185 return SDValue(); 13186 } else { 13187 SingleSource = Op.getOperand(0); 13188 13189 // Check the source type is the same as the type of the result. 13190 // If not, this concat may extend the vector, so we can not 13191 // optimize it away. 13192 if (SingleSource.getValueType() != N->getValueType(0)) 13193 return SDValue(); 13194 } 13195 13196 unsigned IdentityIndex = i * PartNumElem; 13197 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13198 // The extract index must be constant. 13199 if (!CS) 13200 return SDValue(); 13201 13202 // Check that we are reading from the identity index. 13203 if (CS->getZExtValue() != IdentityIndex) 13204 return SDValue(); 13205 } 13206 13207 if (SingleSource.getNode()) 13208 return SingleSource; 13209 13210 return SDValue(); 13211 } 13212 13213 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 13214 EVT NVT = N->getValueType(0); 13215 SDValue V = N->getOperand(0); 13216 13217 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 13218 // Combine: 13219 // (extract_subvec (concat V1, V2, ...), i) 13220 // Into: 13221 // Vi if possible 13222 // Only operand 0 is checked as 'concat' assumes all inputs of the same 13223 // type. 13224 if (V->getOperand(0).getValueType() != NVT) 13225 return SDValue(); 13226 unsigned Idx = N->getConstantOperandVal(1); 13227 unsigned NumElems = NVT.getVectorNumElements(); 13228 assert((Idx % NumElems) == 0 && 13229 "IDX in concat is not a multiple of the result vector length."); 13230 return V->getOperand(Idx / NumElems); 13231 } 13232 13233 // Skip bitcasting 13234 if (V->getOpcode() == ISD::BITCAST) 13235 V = V.getOperand(0); 13236 13237 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13238 SDLoc dl(N); 13239 // Handle only simple case where vector being inserted and vector 13240 // being extracted are of same type, and are half size of larger vectors. 13241 EVT BigVT = V->getOperand(0).getValueType(); 13242 EVT SmallVT = V->getOperand(1).getValueType(); 13243 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 13244 return SDValue(); 13245 13246 // Only handle cases where both indexes are constants with the same type. 13247 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13248 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13249 13250 if (InsIdx && ExtIdx && 13251 InsIdx->getValueType(0).getSizeInBits() <= 64 && 13252 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 13253 // Combine: 13254 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 13255 // Into: 13256 // indices are equal or bit offsets are equal => V1 13257 // otherwise => (extract_subvec V1, ExtIdx) 13258 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 13259 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 13260 return DAG.getBitcast(NVT, V->getOperand(1)); 13261 return DAG.getNode( 13262 ISD::EXTRACT_SUBVECTOR, dl, NVT, 13263 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 13264 N->getOperand(1)); 13265 } 13266 } 13267 13268 return SDValue(); 13269 } 13270 13271 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 13272 SDValue V, SelectionDAG &DAG) { 13273 SDLoc DL(V); 13274 EVT VT = V.getValueType(); 13275 13276 switch (V.getOpcode()) { 13277 default: 13278 return V; 13279 13280 case ISD::CONCAT_VECTORS: { 13281 EVT OpVT = V->getOperand(0).getValueType(); 13282 int OpSize = OpVT.getVectorNumElements(); 13283 SmallBitVector OpUsedElements(OpSize, false); 13284 bool FoundSimplification = false; 13285 SmallVector<SDValue, 4> NewOps; 13286 NewOps.reserve(V->getNumOperands()); 13287 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 13288 SDValue Op = V->getOperand(i); 13289 bool OpUsed = false; 13290 for (int j = 0; j < OpSize; ++j) 13291 if (UsedElements[i * OpSize + j]) { 13292 OpUsedElements[j] = true; 13293 OpUsed = true; 13294 } 13295 NewOps.push_back( 13296 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13297 : DAG.getUNDEF(OpVT)); 13298 FoundSimplification |= Op == NewOps.back(); 13299 OpUsedElements.reset(); 13300 } 13301 if (FoundSimplification) 13302 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13303 return V; 13304 } 13305 13306 case ISD::INSERT_SUBVECTOR: { 13307 SDValue BaseV = V->getOperand(0); 13308 SDValue SubV = V->getOperand(1); 13309 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13310 if (!IdxN) 13311 return V; 13312 13313 int SubSize = SubV.getValueType().getVectorNumElements(); 13314 int Idx = IdxN->getZExtValue(); 13315 bool SubVectorUsed = false; 13316 SmallBitVector SubUsedElements(SubSize, false); 13317 for (int i = 0; i < SubSize; ++i) 13318 if (UsedElements[i + Idx]) { 13319 SubVectorUsed = true; 13320 SubUsedElements[i] = true; 13321 UsedElements[i + Idx] = false; 13322 } 13323 13324 // Now recurse on both the base and sub vectors. 13325 SDValue SimplifiedSubV = 13326 SubVectorUsed 13327 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13328 : DAG.getUNDEF(SubV.getValueType()); 13329 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13330 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13331 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13332 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13333 return V; 13334 } 13335 } 13336 } 13337 13338 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13339 SDValue N1, SelectionDAG &DAG) { 13340 EVT VT = SVN->getValueType(0); 13341 int NumElts = VT.getVectorNumElements(); 13342 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13343 for (int M : SVN->getMask()) 13344 if (M >= 0 && M < NumElts) 13345 N0UsedElements[M] = true; 13346 else if (M >= NumElts) 13347 N1UsedElements[M - NumElts] = true; 13348 13349 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13350 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13351 if (S0 == N0 && S1 == N1) 13352 return SDValue(); 13353 13354 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13355 } 13356 13357 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13358 // or turn a shuffle of a single concat into simpler shuffle then concat. 13359 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13360 EVT VT = N->getValueType(0); 13361 unsigned NumElts = VT.getVectorNumElements(); 13362 13363 SDValue N0 = N->getOperand(0); 13364 SDValue N1 = N->getOperand(1); 13365 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13366 13367 SmallVector<SDValue, 4> Ops; 13368 EVT ConcatVT = N0.getOperand(0).getValueType(); 13369 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13370 unsigned NumConcats = NumElts / NumElemsPerConcat; 13371 13372 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13373 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13374 // half vector elements. 13375 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 13376 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13377 SVN->getMask().end(), [](int i) { return i == -1; })) { 13378 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13379 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13380 N1 = DAG.getUNDEF(ConcatVT); 13381 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13382 } 13383 13384 // Look at every vector that's inserted. We're looking for exact 13385 // subvector-sized copies from a concatenated vector 13386 for (unsigned I = 0; I != NumConcats; ++I) { 13387 // Make sure we're dealing with a copy. 13388 unsigned Begin = I * NumElemsPerConcat; 13389 bool AllUndef = true, NoUndef = true; 13390 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13391 if (SVN->getMaskElt(J) >= 0) 13392 AllUndef = false; 13393 else 13394 NoUndef = false; 13395 } 13396 13397 if (NoUndef) { 13398 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13399 return SDValue(); 13400 13401 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13402 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13403 return SDValue(); 13404 13405 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13406 if (FirstElt < N0.getNumOperands()) 13407 Ops.push_back(N0.getOperand(FirstElt)); 13408 else 13409 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13410 13411 } else if (AllUndef) { 13412 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13413 } else { // Mixed with general masks and undefs, can't do optimization. 13414 return SDValue(); 13415 } 13416 } 13417 13418 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13419 } 13420 13421 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13422 EVT VT = N->getValueType(0); 13423 unsigned NumElts = VT.getVectorNumElements(); 13424 13425 SDValue N0 = N->getOperand(0); 13426 SDValue N1 = N->getOperand(1); 13427 13428 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13429 13430 // Canonicalize shuffle undef, undef -> undef 13431 if (N0.isUndef() && N1.isUndef()) 13432 return DAG.getUNDEF(VT); 13433 13434 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13435 13436 // Canonicalize shuffle v, v -> v, undef 13437 if (N0 == N1) { 13438 SmallVector<int, 8> NewMask; 13439 for (unsigned i = 0; i != NumElts; ++i) { 13440 int Idx = SVN->getMaskElt(i); 13441 if (Idx >= (int)NumElts) Idx -= NumElts; 13442 NewMask.push_back(Idx); 13443 } 13444 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 13445 } 13446 13447 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13448 if (N0.isUndef()) 13449 return DAG.getCommutedVectorShuffle(*SVN); 13450 13451 // Remove references to rhs if it is undef 13452 if (N1.isUndef()) { 13453 bool Changed = false; 13454 SmallVector<int, 8> NewMask; 13455 for (unsigned i = 0; i != NumElts; ++i) { 13456 int Idx = SVN->getMaskElt(i); 13457 if (Idx >= (int)NumElts) { 13458 Idx = -1; 13459 Changed = true; 13460 } 13461 NewMask.push_back(Idx); 13462 } 13463 if (Changed) 13464 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 13465 } 13466 13467 // If it is a splat, check if the argument vector is another splat or a 13468 // build_vector. 13469 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13470 SDNode *V = N0.getNode(); 13471 13472 // If this is a bit convert that changes the element type of the vector but 13473 // not the number of vector elements, look through it. Be careful not to 13474 // look though conversions that change things like v4f32 to v2f64. 13475 if (V->getOpcode() == ISD::BITCAST) { 13476 SDValue ConvInput = V->getOperand(0); 13477 if (ConvInput.getValueType().isVector() && 13478 ConvInput.getValueType().getVectorNumElements() == NumElts) 13479 V = ConvInput.getNode(); 13480 } 13481 13482 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13483 assert(V->getNumOperands() == NumElts && 13484 "BUILD_VECTOR has wrong number of operands"); 13485 SDValue Base; 13486 bool AllSame = true; 13487 for (unsigned i = 0; i != NumElts; ++i) { 13488 if (!V->getOperand(i).isUndef()) { 13489 Base = V->getOperand(i); 13490 break; 13491 } 13492 } 13493 // Splat of <u, u, u, u>, return <u, u, u, u> 13494 if (!Base.getNode()) 13495 return N0; 13496 for (unsigned i = 0; i != NumElts; ++i) { 13497 if (V->getOperand(i) != Base) { 13498 AllSame = false; 13499 break; 13500 } 13501 } 13502 // Splat of <x, x, x, x>, return <x, x, x, x> 13503 if (AllSame) 13504 return N0; 13505 13506 // Canonicalize any other splat as a build_vector. 13507 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13508 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13509 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 13510 13511 // We may have jumped through bitcasts, so the type of the 13512 // BUILD_VECTOR may not match the type of the shuffle. 13513 if (V->getValueType(0) != VT) 13514 NewBV = DAG.getBitcast(VT, NewBV); 13515 return NewBV; 13516 } 13517 } 13518 13519 // There are various patterns used to build up a vector from smaller vectors, 13520 // subvectors, or elements. Scan chains of these and replace unused insertions 13521 // or components with undef. 13522 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13523 return S; 13524 13525 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13526 Level < AfterLegalizeVectorOps && 13527 (N1.isUndef() || 13528 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13529 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13530 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 13531 return V; 13532 } 13533 13534 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13535 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13536 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13537 SmallVector<SDValue, 8> Ops; 13538 for (int M : SVN->getMask()) { 13539 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13540 if (M >= 0) { 13541 int Idx = M % NumElts; 13542 SDValue &S = (M < (int)NumElts ? N0 : N1); 13543 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13544 Op = S.getOperand(Idx); 13545 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13546 if (Idx == 0) 13547 Op = S.getOperand(0); 13548 } else { 13549 // Operand can't be combined - bail out. 13550 break; 13551 } 13552 } 13553 Ops.push_back(Op); 13554 } 13555 if (Ops.size() == VT.getVectorNumElements()) { 13556 // BUILD_VECTOR requires all inputs to be of the same type, find the 13557 // maximum type and extend them all. 13558 EVT SVT = VT.getScalarType(); 13559 if (SVT.isInteger()) 13560 for (SDValue &Op : Ops) 13561 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13562 if (SVT != VT.getScalarType()) 13563 for (SDValue &Op : Ops) 13564 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13565 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13566 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13567 return DAG.getBuildVector(VT, SDLoc(N), Ops); 13568 } 13569 } 13570 13571 // If this shuffle only has a single input that is a bitcasted shuffle, 13572 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13573 // back to their original types. 13574 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13575 N1.isUndef() && Level < AfterLegalizeVectorOps && 13576 TLI.isTypeLegal(VT)) { 13577 13578 // Peek through the bitcast only if there is one user. 13579 SDValue BC0 = N0; 13580 while (BC0.getOpcode() == ISD::BITCAST) { 13581 if (!BC0.hasOneUse()) 13582 break; 13583 BC0 = BC0.getOperand(0); 13584 } 13585 13586 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13587 if (Scale == 1) 13588 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13589 13590 SmallVector<int, 8> NewMask; 13591 for (int M : Mask) 13592 for (int s = 0; s != Scale; ++s) 13593 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13594 return NewMask; 13595 }; 13596 13597 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13598 EVT SVT = VT.getScalarType(); 13599 EVT InnerVT = BC0->getValueType(0); 13600 EVT InnerSVT = InnerVT.getScalarType(); 13601 13602 // Determine which shuffle works with the smaller scalar type. 13603 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13604 EVT ScaleSVT = ScaleVT.getScalarType(); 13605 13606 if (TLI.isTypeLegal(ScaleVT) && 13607 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13608 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13609 13610 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13611 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13612 13613 // Scale the shuffle masks to the smaller scalar type. 13614 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13615 SmallVector<int, 8> InnerMask = 13616 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13617 SmallVector<int, 8> OuterMask = 13618 ScaleShuffleMask(SVN->getMask(), OuterScale); 13619 13620 // Merge the shuffle masks. 13621 SmallVector<int, 8> NewMask; 13622 for (int M : OuterMask) 13623 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13624 13625 // Test for shuffle mask legality over both commutations. 13626 SDValue SV0 = BC0->getOperand(0); 13627 SDValue SV1 = BC0->getOperand(1); 13628 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13629 if (!LegalMask) { 13630 std::swap(SV0, SV1); 13631 ShuffleVectorSDNode::commuteMask(NewMask); 13632 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13633 } 13634 13635 if (LegalMask) { 13636 SV0 = DAG.getBitcast(ScaleVT, SV0); 13637 SV1 = DAG.getBitcast(ScaleVT, SV1); 13638 return DAG.getBitcast( 13639 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13640 } 13641 } 13642 } 13643 } 13644 13645 // Canonicalize shuffles according to rules: 13646 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13647 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13648 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13649 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13650 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13651 TLI.isTypeLegal(VT)) { 13652 // The incoming shuffle must be of the same type as the result of the 13653 // current shuffle. 13654 assert(N1->getOperand(0).getValueType() == VT && 13655 "Shuffle types don't match"); 13656 13657 SDValue SV0 = N1->getOperand(0); 13658 SDValue SV1 = N1->getOperand(1); 13659 bool HasSameOp0 = N0 == SV0; 13660 bool IsSV1Undef = SV1.isUndef(); 13661 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13662 // Commute the operands of this shuffle so that next rule 13663 // will trigger. 13664 return DAG.getCommutedVectorShuffle(*SVN); 13665 } 13666 13667 // Try to fold according to rules: 13668 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13669 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13670 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13671 // Don't try to fold shuffles with illegal type. 13672 // Only fold if this shuffle is the only user of the other shuffle. 13673 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13674 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13675 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13676 13677 // The incoming shuffle must be of the same type as the result of the 13678 // current shuffle. 13679 assert(OtherSV->getOperand(0).getValueType() == VT && 13680 "Shuffle types don't match"); 13681 13682 SDValue SV0, SV1; 13683 SmallVector<int, 4> Mask; 13684 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13685 // operand, and SV1 as the second operand. 13686 for (unsigned i = 0; i != NumElts; ++i) { 13687 int Idx = SVN->getMaskElt(i); 13688 if (Idx < 0) { 13689 // Propagate Undef. 13690 Mask.push_back(Idx); 13691 continue; 13692 } 13693 13694 SDValue CurrentVec; 13695 if (Idx < (int)NumElts) { 13696 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13697 // shuffle mask to identify which vector is actually referenced. 13698 Idx = OtherSV->getMaskElt(Idx); 13699 if (Idx < 0) { 13700 // Propagate Undef. 13701 Mask.push_back(Idx); 13702 continue; 13703 } 13704 13705 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13706 : OtherSV->getOperand(1); 13707 } else { 13708 // This shuffle index references an element within N1. 13709 CurrentVec = N1; 13710 } 13711 13712 // Simple case where 'CurrentVec' is UNDEF. 13713 if (CurrentVec.isUndef()) { 13714 Mask.push_back(-1); 13715 continue; 13716 } 13717 13718 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13719 // will be the first or second operand of the combined shuffle. 13720 Idx = Idx % NumElts; 13721 if (!SV0.getNode() || SV0 == CurrentVec) { 13722 // Ok. CurrentVec is the left hand side. 13723 // Update the mask accordingly. 13724 SV0 = CurrentVec; 13725 Mask.push_back(Idx); 13726 continue; 13727 } 13728 13729 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13730 if (SV1.getNode() && SV1 != CurrentVec) 13731 return SDValue(); 13732 13733 // Ok. CurrentVec is the right hand side. 13734 // Update the mask accordingly. 13735 SV1 = CurrentVec; 13736 Mask.push_back(Idx + NumElts); 13737 } 13738 13739 // Check if all indices in Mask are Undef. In case, propagate Undef. 13740 bool isUndefMask = true; 13741 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13742 isUndefMask &= Mask[i] < 0; 13743 13744 if (isUndefMask) 13745 return DAG.getUNDEF(VT); 13746 13747 if (!SV0.getNode()) 13748 SV0 = DAG.getUNDEF(VT); 13749 if (!SV1.getNode()) 13750 SV1 = DAG.getUNDEF(VT); 13751 13752 // Avoid introducing shuffles with illegal mask. 13753 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13754 ShuffleVectorSDNode::commuteMask(Mask); 13755 13756 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13757 return SDValue(); 13758 13759 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13760 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13761 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13762 std::swap(SV0, SV1); 13763 } 13764 13765 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13766 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13767 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13768 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 13769 } 13770 13771 return SDValue(); 13772 } 13773 13774 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13775 SDValue InVal = N->getOperand(0); 13776 EVT VT = N->getValueType(0); 13777 13778 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13779 // with a VECTOR_SHUFFLE. 13780 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13781 SDValue InVec = InVal->getOperand(0); 13782 SDValue EltNo = InVal->getOperand(1); 13783 13784 // FIXME: We could support implicit truncation if the shuffle can be 13785 // scaled to a smaller vector scalar type. 13786 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13787 if (C0 && VT == InVec.getValueType() && 13788 VT.getScalarType() == InVal.getValueType()) { 13789 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13790 int Elt = C0->getZExtValue(); 13791 NewMask[0] = Elt; 13792 13793 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13794 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13795 NewMask); 13796 } 13797 } 13798 13799 return SDValue(); 13800 } 13801 13802 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13803 EVT VT = N->getValueType(0); 13804 SDValue N0 = N->getOperand(0); 13805 SDValue N1 = N->getOperand(1); 13806 SDValue N2 = N->getOperand(2); 13807 13808 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 13809 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 13810 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 13811 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 13812 N0.getOperand(1).getValueType() == N1.getValueType() && 13813 N0.getOperand(2) == N2) 13814 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 13815 N1, N2); 13816 13817 if (N0.getValueType() != N1.getValueType()) 13818 return SDValue(); 13819 13820 // If the input vector is a concatenation, and the insert replaces 13821 // one of the halves, we can optimize into a single concat_vectors. 13822 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 && 13823 N2.getOpcode() == ISD::Constant) { 13824 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13825 13826 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13827 // (concat_vectors Z, Y) 13828 if (InsIdx == 0) 13829 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1, 13830 N0.getOperand(1)); 13831 13832 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13833 // (concat_vectors X, Z) 13834 if (InsIdx == VT.getVectorNumElements() / 2) 13835 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0), 13836 N1); 13837 } 13838 13839 return SDValue(); 13840 } 13841 13842 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13843 SDValue N0 = N->getOperand(0); 13844 13845 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13846 if (N0->getOpcode() == ISD::FP16_TO_FP) 13847 return N0->getOperand(0); 13848 13849 return SDValue(); 13850 } 13851 13852 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13853 SDValue N0 = N->getOperand(0); 13854 13855 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13856 if (N0->getOpcode() == ISD::AND) { 13857 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13858 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13859 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13860 N0.getOperand(0)); 13861 } 13862 } 13863 13864 return SDValue(); 13865 } 13866 13867 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13868 /// with the destination vector and a zero vector. 13869 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13870 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13871 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13872 EVT VT = N->getValueType(0); 13873 SDValue LHS = N->getOperand(0); 13874 SDValue RHS = N->getOperand(1); 13875 SDLoc dl(N); 13876 13877 // Make sure we're not running after operation legalization where it 13878 // may have custom lowered the vector shuffles. 13879 if (LegalOperations) 13880 return SDValue(); 13881 13882 if (N->getOpcode() != ISD::AND) 13883 return SDValue(); 13884 13885 if (RHS.getOpcode() == ISD::BITCAST) 13886 RHS = RHS.getOperand(0); 13887 13888 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13889 return SDValue(); 13890 13891 EVT RVT = RHS.getValueType(); 13892 unsigned NumElts = RHS.getNumOperands(); 13893 13894 // Attempt to create a valid clear mask, splitting the mask into 13895 // sub elements and checking to see if each is 13896 // all zeros or all ones - suitable for shuffle masking. 13897 auto BuildClearMask = [&](int Split) { 13898 int NumSubElts = NumElts * Split; 13899 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13900 13901 SmallVector<int, 8> Indices; 13902 for (int i = 0; i != NumSubElts; ++i) { 13903 int EltIdx = i / Split; 13904 int SubIdx = i % Split; 13905 SDValue Elt = RHS.getOperand(EltIdx); 13906 if (Elt.isUndef()) { 13907 Indices.push_back(-1); 13908 continue; 13909 } 13910 13911 APInt Bits; 13912 if (isa<ConstantSDNode>(Elt)) 13913 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13914 else if (isa<ConstantFPSDNode>(Elt)) 13915 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13916 else 13917 return SDValue(); 13918 13919 // Extract the sub element from the constant bit mask. 13920 if (DAG.getDataLayout().isBigEndian()) { 13921 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13922 } else { 13923 Bits = Bits.lshr(SubIdx * NumSubBits); 13924 } 13925 13926 if (Split > 1) 13927 Bits = Bits.trunc(NumSubBits); 13928 13929 if (Bits.isAllOnesValue()) 13930 Indices.push_back(i); 13931 else if (Bits == 0) 13932 Indices.push_back(i + NumSubElts); 13933 else 13934 return SDValue(); 13935 } 13936 13937 // Let's see if the target supports this vector_shuffle. 13938 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13939 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13940 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13941 return SDValue(); 13942 13943 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13944 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13945 DAG.getBitcast(ClearVT, LHS), 13946 Zero, Indices)); 13947 }; 13948 13949 // Determine maximum split level (byte level masking). 13950 int MaxSplit = 1; 13951 if (RVT.getScalarSizeInBits() % 8 == 0) 13952 MaxSplit = RVT.getScalarSizeInBits() / 8; 13953 13954 for (int Split = 1; Split <= MaxSplit; ++Split) 13955 if (RVT.getScalarSizeInBits() % Split == 0) 13956 if (SDValue S = BuildClearMask(Split)) 13957 return S; 13958 13959 return SDValue(); 13960 } 13961 13962 /// Visit a binary vector operation, like ADD. 13963 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13964 assert(N->getValueType(0).isVector() && 13965 "SimplifyVBinOp only works on vectors!"); 13966 13967 SDValue LHS = N->getOperand(0); 13968 SDValue RHS = N->getOperand(1); 13969 SDValue Ops[] = {LHS, RHS}; 13970 13971 // See if we can constant fold the vector operation. 13972 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 13973 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 13974 return Fold; 13975 13976 // Try to convert a constant mask AND into a shuffle clear mask. 13977 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13978 return Shuffle; 13979 13980 // Type legalization might introduce new shuffles in the DAG. 13981 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13982 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13983 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13984 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13985 LHS.getOperand(1).isUndef() && 13986 RHS.getOperand(1).isUndef()) { 13987 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13988 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13989 13990 if (SVN0->getMask().equals(SVN1->getMask())) { 13991 EVT VT = N->getValueType(0); 13992 SDValue UndefVector = LHS.getOperand(1); 13993 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13994 LHS.getOperand(0), RHS.getOperand(0), 13995 N->getFlags()); 13996 AddUsersToWorklist(N); 13997 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13998 SVN0->getMask()); 13999 } 14000 } 14001 14002 return SDValue(); 14003 } 14004 14005 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 14006 SDValue N2) { 14007 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 14008 14009 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 14010 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 14011 14012 // If we got a simplified select_cc node back from SimplifySelectCC, then 14013 // break it down into a new SETCC node, and a new SELECT node, and then return 14014 // the SELECT node, since we were called with a SELECT node. 14015 if (SCC.getNode()) { 14016 // Check to see if we got a select_cc back (to turn into setcc/select). 14017 // Otherwise, just return whatever node we got back, like fabs. 14018 if (SCC.getOpcode() == ISD::SELECT_CC) { 14019 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 14020 N0.getValueType(), 14021 SCC.getOperand(0), SCC.getOperand(1), 14022 SCC.getOperand(4)); 14023 AddToWorklist(SETCC.getNode()); 14024 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 14025 SCC.getOperand(2), SCC.getOperand(3)); 14026 } 14027 14028 return SCC; 14029 } 14030 return SDValue(); 14031 } 14032 14033 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 14034 /// being selected between, see if we can simplify the select. Callers of this 14035 /// should assume that TheSelect is deleted if this returns true. As such, they 14036 /// should return the appropriate thing (e.g. the node) back to the top-level of 14037 /// the DAG combiner loop to avoid it being looked at. 14038 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 14039 SDValue RHS) { 14040 14041 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14042 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 14043 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 14044 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 14045 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 14046 SDValue Sqrt = RHS; 14047 ISD::CondCode CC; 14048 SDValue CmpLHS; 14049 const ConstantFPSDNode *Zero = nullptr; 14050 14051 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 14052 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 14053 CmpLHS = TheSelect->getOperand(0); 14054 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 14055 } else { 14056 // SELECT or VSELECT 14057 SDValue Cmp = TheSelect->getOperand(0); 14058 if (Cmp.getOpcode() == ISD::SETCC) { 14059 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 14060 CmpLHS = Cmp.getOperand(0); 14061 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 14062 } 14063 } 14064 if (Zero && Zero->isZero() && 14065 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 14066 CC == ISD::SETULT || CC == ISD::SETLT)) { 14067 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14068 CombineTo(TheSelect, Sqrt); 14069 return true; 14070 } 14071 } 14072 } 14073 // Cannot simplify select with vector condition 14074 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 14075 14076 // If this is a select from two identical things, try to pull the operation 14077 // through the select. 14078 if (LHS.getOpcode() != RHS.getOpcode() || 14079 !LHS.hasOneUse() || !RHS.hasOneUse()) 14080 return false; 14081 14082 // If this is a load and the token chain is identical, replace the select 14083 // of two loads with a load through a select of the address to load from. 14084 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 14085 // constants have been dropped into the constant pool. 14086 if (LHS.getOpcode() == ISD::LOAD) { 14087 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 14088 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 14089 14090 // Token chains must be identical. 14091 if (LHS.getOperand(0) != RHS.getOperand(0) || 14092 // Do not let this transformation reduce the number of volatile loads. 14093 LLD->isVolatile() || RLD->isVolatile() || 14094 // FIXME: If either is a pre/post inc/dec load, 14095 // we'd need to split out the address adjustment. 14096 LLD->isIndexed() || RLD->isIndexed() || 14097 // If this is an EXTLOAD, the VT's must match. 14098 LLD->getMemoryVT() != RLD->getMemoryVT() || 14099 // If this is an EXTLOAD, the kind of extension must match. 14100 (LLD->getExtensionType() != RLD->getExtensionType() && 14101 // The only exception is if one of the extensions is anyext. 14102 LLD->getExtensionType() != ISD::EXTLOAD && 14103 RLD->getExtensionType() != ISD::EXTLOAD) || 14104 // FIXME: this discards src value information. This is 14105 // over-conservative. It would be beneficial to be able to remember 14106 // both potential memory locations. Since we are discarding 14107 // src value info, don't do the transformation if the memory 14108 // locations are not in the default address space. 14109 LLD->getPointerInfo().getAddrSpace() != 0 || 14110 RLD->getPointerInfo().getAddrSpace() != 0 || 14111 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 14112 LLD->getBasePtr().getValueType())) 14113 return false; 14114 14115 // Check that the select condition doesn't reach either load. If so, 14116 // folding this will induce a cycle into the DAG. If not, this is safe to 14117 // xform, so create a select of the addresses. 14118 SDValue Addr; 14119 if (TheSelect->getOpcode() == ISD::SELECT) { 14120 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 14121 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 14122 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 14123 return false; 14124 // The loads must not depend on one another. 14125 if (LLD->isPredecessorOf(RLD) || 14126 RLD->isPredecessorOf(LLD)) 14127 return false; 14128 Addr = DAG.getSelect(SDLoc(TheSelect), 14129 LLD->getBasePtr().getValueType(), 14130 TheSelect->getOperand(0), LLD->getBasePtr(), 14131 RLD->getBasePtr()); 14132 } else { // Otherwise SELECT_CC 14133 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 14134 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 14135 14136 if ((LLD->hasAnyUseOfValue(1) && 14137 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 14138 (RLD->hasAnyUseOfValue(1) && 14139 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 14140 return false; 14141 14142 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 14143 LLD->getBasePtr().getValueType(), 14144 TheSelect->getOperand(0), 14145 TheSelect->getOperand(1), 14146 LLD->getBasePtr(), RLD->getBasePtr(), 14147 TheSelect->getOperand(4)); 14148 } 14149 14150 SDValue Load; 14151 // It is safe to replace the two loads if they have different alignments, 14152 // but the new load must be the minimum (most restrictive) alignment of the 14153 // inputs. 14154 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 14155 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 14156 if (!RLD->isInvariant()) 14157 MMOFlags &= ~MachineMemOperand::MOInvariant; 14158 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 14159 // FIXME: Discards pointer and AA info. 14160 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 14161 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 14162 MMOFlags); 14163 } else { 14164 // FIXME: Discards pointer and AA info. 14165 Load = DAG.getExtLoad( 14166 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 14167 : LLD->getExtensionType(), 14168 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 14169 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 14170 } 14171 14172 // Users of the select now use the result of the load. 14173 CombineTo(TheSelect, Load); 14174 14175 // Users of the old loads now use the new load's chain. We know the 14176 // old-load value is dead now. 14177 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 14178 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 14179 return true; 14180 } 14181 14182 return false; 14183 } 14184 14185 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 14186 /// where 'cond' is the comparison specified by CC. 14187 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 14188 SDValue N2, SDValue N3, ISD::CondCode CC, 14189 bool NotExtCompare) { 14190 // (x ? y : y) -> y. 14191 if (N2 == N3) return N2; 14192 14193 EVT VT = N2.getValueType(); 14194 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 14195 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 14196 14197 // Determine if the condition we're dealing with is constant 14198 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 14199 N0, N1, CC, DL, false); 14200 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 14201 14202 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 14203 // fold select_cc true, x, y -> x 14204 // fold select_cc false, x, y -> y 14205 return !SCCC->isNullValue() ? N2 : N3; 14206 } 14207 14208 // Check to see if we can simplify the select into an fabs node 14209 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 14210 // Allow either -0.0 or 0.0 14211 if (CFP->isZero()) { 14212 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 14213 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 14214 N0 == N2 && N3.getOpcode() == ISD::FNEG && 14215 N2 == N3.getOperand(0)) 14216 return DAG.getNode(ISD::FABS, DL, VT, N0); 14217 14218 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 14219 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 14220 N0 == N3 && N2.getOpcode() == ISD::FNEG && 14221 N2.getOperand(0) == N3) 14222 return DAG.getNode(ISD::FABS, DL, VT, N3); 14223 } 14224 } 14225 14226 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 14227 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 14228 // in it. This is a win when the constant is not otherwise available because 14229 // it replaces two constant pool loads with one. We only do this if the FP 14230 // type is known to be legal, because if it isn't, then we are before legalize 14231 // types an we want the other legalization to happen first (e.g. to avoid 14232 // messing with soft float) and if the ConstantFP is not legal, because if 14233 // it is legal, we may not need to store the FP constant in a constant pool. 14234 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 14235 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 14236 if (TLI.isTypeLegal(N2.getValueType()) && 14237 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 14238 TargetLowering::Legal && 14239 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 14240 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 14241 // If both constants have multiple uses, then we won't need to do an 14242 // extra load, they are likely around in registers for other users. 14243 (TV->hasOneUse() || FV->hasOneUse())) { 14244 Constant *Elts[] = { 14245 const_cast<ConstantFP*>(FV->getConstantFPValue()), 14246 const_cast<ConstantFP*>(TV->getConstantFPValue()) 14247 }; 14248 Type *FPTy = Elts[0]->getType(); 14249 const DataLayout &TD = DAG.getDataLayout(); 14250 14251 // Create a ConstantArray of the two constants. 14252 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 14253 SDValue CPIdx = 14254 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 14255 TD.getPrefTypeAlignment(FPTy)); 14256 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 14257 14258 // Get the offsets to the 0 and 1 element of the array so that we can 14259 // select between them. 14260 SDValue Zero = DAG.getIntPtrConstant(0, DL); 14261 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 14262 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 14263 14264 SDValue Cond = DAG.getSetCC(DL, 14265 getSetCCResultType(N0.getValueType()), 14266 N0, N1, CC); 14267 AddToWorklist(Cond.getNode()); 14268 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 14269 Cond, One, Zero); 14270 AddToWorklist(CstOffset.getNode()); 14271 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 14272 CstOffset); 14273 AddToWorklist(CPIdx.getNode()); 14274 return DAG.getLoad( 14275 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 14276 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 14277 Alignment); 14278 } 14279 } 14280 14281 // Check to see if we can perform the "gzip trick", transforming 14282 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 14283 if (isNullConstant(N3) && CC == ISD::SETLT && 14284 (isNullConstant(N1) || // (a < 0) ? b : 0 14285 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 14286 EVT XType = N0.getValueType(); 14287 EVT AType = N2.getValueType(); 14288 if (XType.bitsGE(AType)) { 14289 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 14290 // single-bit constant. 14291 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14292 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 14293 ShCtV = XType.getSizeInBits() - ShCtV - 1; 14294 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 14295 getShiftAmountTy(N0.getValueType())); 14296 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 14297 XType, N0, ShCt); 14298 AddToWorklist(Shift.getNode()); 14299 14300 if (XType.bitsGT(AType)) { 14301 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14302 AddToWorklist(Shift.getNode()); 14303 } 14304 14305 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14306 } 14307 14308 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 14309 XType, N0, 14310 DAG.getConstant(XType.getSizeInBits() - 1, 14311 SDLoc(N0), 14312 getShiftAmountTy(N0.getValueType()))); 14313 AddToWorklist(Shift.getNode()); 14314 14315 if (XType.bitsGT(AType)) { 14316 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14317 AddToWorklist(Shift.getNode()); 14318 } 14319 14320 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14321 } 14322 } 14323 14324 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14325 // where y is has a single bit set. 14326 // A plaintext description would be, we can turn the SELECT_CC into an AND 14327 // when the condition can be materialized as an all-ones register. Any 14328 // single bit-test can be materialized as an all-ones register with 14329 // shift-left and shift-right-arith. 14330 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14331 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14332 SDValue AndLHS = N0->getOperand(0); 14333 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14334 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14335 // Shift the tested bit over the sign bit. 14336 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 14337 SDValue ShlAmt = 14338 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14339 getShiftAmountTy(AndLHS.getValueType())); 14340 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14341 14342 // Now arithmetic right shift it all the way over, so the result is either 14343 // all-ones, or zero. 14344 SDValue ShrAmt = 14345 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14346 getShiftAmountTy(Shl.getValueType())); 14347 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14348 14349 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14350 } 14351 } 14352 14353 // fold select C, 16, 0 -> shl C, 4 14354 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14355 TLI.getBooleanContents(N0.getValueType()) == 14356 TargetLowering::ZeroOrOneBooleanContent) { 14357 14358 // If the caller doesn't want us to simplify this into a zext of a compare, 14359 // don't do it. 14360 if (NotExtCompare && N2C->isOne()) 14361 return SDValue(); 14362 14363 // Get a SetCC of the condition 14364 // NOTE: Don't create a SETCC if it's not legal on this target. 14365 if (!LegalOperations || 14366 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14367 SDValue Temp, SCC; 14368 // cast from setcc result type to select result type 14369 if (LegalTypes) { 14370 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14371 N0, N1, CC); 14372 if (N2.getValueType().bitsLT(SCC.getValueType())) 14373 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14374 N2.getValueType()); 14375 else 14376 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14377 N2.getValueType(), SCC); 14378 } else { 14379 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14380 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14381 N2.getValueType(), SCC); 14382 } 14383 14384 AddToWorklist(SCC.getNode()); 14385 AddToWorklist(Temp.getNode()); 14386 14387 if (N2C->isOne()) 14388 return Temp; 14389 14390 // shl setcc result by log2 n2c 14391 return DAG.getNode( 14392 ISD::SHL, DL, N2.getValueType(), Temp, 14393 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14394 getShiftAmountTy(Temp.getValueType()))); 14395 } 14396 } 14397 14398 // Check to see if this is an integer abs. 14399 // select_cc setg[te] X, 0, X, -X -> 14400 // select_cc setgt X, -1, X, -X -> 14401 // select_cc setl[te] X, 0, -X, X -> 14402 // select_cc setlt X, 1, -X, X -> 14403 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14404 if (N1C) { 14405 ConstantSDNode *SubC = nullptr; 14406 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14407 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14408 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14409 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14410 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14411 (N1C->isOne() && CC == ISD::SETLT)) && 14412 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14413 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14414 14415 EVT XType = N0.getValueType(); 14416 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14417 SDLoc DL(N0); 14418 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14419 N0, 14420 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14421 getShiftAmountTy(N0.getValueType()))); 14422 SDValue Add = DAG.getNode(ISD::ADD, DL, 14423 XType, N0, Shift); 14424 AddToWorklist(Shift.getNode()); 14425 AddToWorklist(Add.getNode()); 14426 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14427 } 14428 } 14429 14430 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 14431 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 14432 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 14433 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 14434 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 14435 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 14436 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 14437 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 14438 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 14439 SDValue ValueOnZero = N2; 14440 SDValue Count = N3; 14441 // If the condition is NE instead of E, swap the operands. 14442 if (CC == ISD::SETNE) 14443 std::swap(ValueOnZero, Count); 14444 // Check if the value on zero is a constant equal to the bits in the type. 14445 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 14446 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 14447 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 14448 // legal, combine to just cttz. 14449 if ((Count.getOpcode() == ISD::CTTZ || 14450 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 14451 N0 == Count.getOperand(0) && 14452 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 14453 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 14454 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 14455 // legal, combine to just ctlz. 14456 if ((Count.getOpcode() == ISD::CTLZ || 14457 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 14458 N0 == Count.getOperand(0) && 14459 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 14460 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 14461 } 14462 } 14463 } 14464 14465 return SDValue(); 14466 } 14467 14468 /// This is a stub for TargetLowering::SimplifySetCC. 14469 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 14470 ISD::CondCode Cond, const SDLoc &DL, 14471 bool foldBooleans) { 14472 TargetLowering::DAGCombinerInfo 14473 DagCombineInfo(DAG, Level, false, this); 14474 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14475 } 14476 14477 /// Given an ISD::SDIV node expressing a divide by constant, return 14478 /// a DAG expression to select that will generate the same value by multiplying 14479 /// by a magic number. 14480 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14481 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14482 // when optimising for minimum size, we don't want to expand a div to a mul 14483 // and a shift. 14484 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 14485 return SDValue(); 14486 14487 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14488 if (!C) 14489 return SDValue(); 14490 14491 // Avoid division by zero. 14492 if (C->isNullValue()) 14493 return SDValue(); 14494 14495 std::vector<SDNode*> Built; 14496 SDValue S = 14497 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14498 14499 for (SDNode *N : Built) 14500 AddToWorklist(N); 14501 return S; 14502 } 14503 14504 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14505 /// DAG expression that will generate the same value by right shifting. 14506 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14507 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14508 if (!C) 14509 return SDValue(); 14510 14511 // Avoid division by zero. 14512 if (C->isNullValue()) 14513 return SDValue(); 14514 14515 std::vector<SDNode *> Built; 14516 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14517 14518 for (SDNode *N : Built) 14519 AddToWorklist(N); 14520 return S; 14521 } 14522 14523 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14524 /// expression that will generate the same value by multiplying by a magic 14525 /// number. 14526 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14527 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14528 // when optimising for minimum size, we don't want to expand a div to a mul 14529 // and a shift. 14530 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 14531 return SDValue(); 14532 14533 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14534 if (!C) 14535 return SDValue(); 14536 14537 // Avoid division by zero. 14538 if (C->isNullValue()) 14539 return SDValue(); 14540 14541 std::vector<SDNode*> Built; 14542 SDValue S = 14543 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14544 14545 for (SDNode *N : Built) 14546 AddToWorklist(N); 14547 return S; 14548 } 14549 14550 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14551 if (Level >= AfterLegalizeDAG) 14552 return SDValue(); 14553 14554 // Expose the DAG combiner to the target combiner implementations. 14555 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14556 14557 unsigned Iterations = 0; 14558 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14559 if (Iterations) { 14560 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14561 // For the reciprocal, we need to find the zero of the function: 14562 // F(X) = A X - 1 [which has a zero at X = 1/A] 14563 // => 14564 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14565 // does not require additional intermediate precision] 14566 EVT VT = Op.getValueType(); 14567 SDLoc DL(Op); 14568 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14569 14570 AddToWorklist(Est.getNode()); 14571 14572 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14573 for (unsigned i = 0; i < Iterations; ++i) { 14574 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14575 AddToWorklist(NewEst.getNode()); 14576 14577 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14578 AddToWorklist(NewEst.getNode()); 14579 14580 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14581 AddToWorklist(NewEst.getNode()); 14582 14583 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14584 AddToWorklist(Est.getNode()); 14585 } 14586 } 14587 return Est; 14588 } 14589 14590 return SDValue(); 14591 } 14592 14593 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14594 /// For the reciprocal sqrt, we need to find the zero of the function: 14595 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14596 /// => 14597 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14598 /// As a result, we precompute A/2 prior to the iteration loop. 14599 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 14600 unsigned Iterations, 14601 SDNodeFlags *Flags, bool Reciprocal) { 14602 EVT VT = Arg.getValueType(); 14603 SDLoc DL(Arg); 14604 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14605 14606 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14607 // this entire sequence requires only one FP constant. 14608 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14609 AddToWorklist(HalfArg.getNode()); 14610 14611 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14612 AddToWorklist(HalfArg.getNode()); 14613 14614 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14615 for (unsigned i = 0; i < Iterations; ++i) { 14616 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14617 AddToWorklist(NewEst.getNode()); 14618 14619 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14620 AddToWorklist(NewEst.getNode()); 14621 14622 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14623 AddToWorklist(NewEst.getNode()); 14624 14625 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14626 AddToWorklist(Est.getNode()); 14627 } 14628 14629 // If non-reciprocal square root is requested, multiply the result by Arg. 14630 if (!Reciprocal) { 14631 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14632 AddToWorklist(Est.getNode()); 14633 } 14634 14635 return Est; 14636 } 14637 14638 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14639 /// For the reciprocal sqrt, we need to find the zero of the function: 14640 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14641 /// => 14642 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14643 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 14644 unsigned Iterations, 14645 SDNodeFlags *Flags, bool Reciprocal) { 14646 EVT VT = Arg.getValueType(); 14647 SDLoc DL(Arg); 14648 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14649 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14650 14651 // This routine must enter the loop below to work correctly 14652 // when (Reciprocal == false). 14653 assert(Iterations > 0); 14654 14655 // Newton iterations for reciprocal square root: 14656 // E = (E * -0.5) * ((A * E) * E + -3.0) 14657 for (unsigned i = 0; i < Iterations; ++i) { 14658 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 14659 AddToWorklist(AE.getNode()); 14660 14661 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 14662 AddToWorklist(AEE.getNode()); 14663 14664 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 14665 AddToWorklist(RHS.getNode()); 14666 14667 // When calculating a square root at the last iteration build: 14668 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 14669 // (notice a common subexpression) 14670 SDValue LHS; 14671 if (Reciprocal || (i + 1) < Iterations) { 14672 // RSQRT: LHS = (E * -0.5) 14673 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14674 } else { 14675 // SQRT: LHS = (A * E) * -0.5 14676 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 14677 } 14678 AddToWorklist(LHS.getNode()); 14679 14680 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 14681 AddToWorklist(Est.getNode()); 14682 } 14683 14684 return Est; 14685 } 14686 14687 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 14688 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 14689 /// Op can be zero. 14690 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, 14691 bool Reciprocal) { 14692 if (Level >= AfterLegalizeDAG) 14693 return SDValue(); 14694 14695 // Expose the DAG combiner to the target combiner implementations. 14696 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14697 unsigned Iterations = 0; 14698 bool UseOneConstNR = false; 14699 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14700 AddToWorklist(Est.getNode()); 14701 if (Iterations) { 14702 Est = UseOneConstNR 14703 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 14704 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 14705 } 14706 return Est; 14707 } 14708 14709 return SDValue(); 14710 } 14711 14712 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14713 return buildSqrtEstimateImpl(Op, Flags, true); 14714 } 14715 14716 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14717 SDValue Est = buildSqrtEstimateImpl(Op, Flags, false); 14718 if (!Est) 14719 return SDValue(); 14720 14721 // Unfortunately, Est is now NaN if the input was exactly 0. 14722 // Select out this case and force the answer to 0. 14723 EVT VT = Est.getValueType(); 14724 SDLoc DL(Op); 14725 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 14726 EVT CCVT = getSetCCResultType(VT); 14727 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ); 14728 AddToWorklist(ZeroCmp.getNode()); 14729 14730 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp, 14731 Zero, Est); 14732 AddToWorklist(Est.getNode()); 14733 return Est; 14734 } 14735 14736 /// Return true if base is a frame index, which is known not to alias with 14737 /// anything but itself. Provides base object and offset as results. 14738 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14739 const GlobalValue *&GV, const void *&CV) { 14740 // Assume it is a primitive operation. 14741 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14742 14743 // If it's an adding a simple constant then integrate the offset. 14744 if (Base.getOpcode() == ISD::ADD) { 14745 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14746 Base = Base.getOperand(0); 14747 Offset += C->getZExtValue(); 14748 } 14749 } 14750 14751 // Return the underlying GlobalValue, and update the Offset. Return false 14752 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14753 // by multiple nodes with different offsets. 14754 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14755 GV = G->getGlobal(); 14756 Offset += G->getOffset(); 14757 return false; 14758 } 14759 14760 // Return the underlying Constant value, and update the Offset. Return false 14761 // for ConstantSDNodes since the same constant pool entry may be represented 14762 // by multiple nodes with different offsets. 14763 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14764 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14765 : (const void *)C->getConstVal(); 14766 Offset += C->getOffset(); 14767 return false; 14768 } 14769 // If it's any of the following then it can't alias with anything but itself. 14770 return isa<FrameIndexSDNode>(Base); 14771 } 14772 14773 /// Return true if there is any possibility that the two addresses overlap. 14774 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14775 // If they are the same then they must be aliases. 14776 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14777 14778 // If they are both volatile then they cannot be reordered. 14779 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14780 14781 // If one operation reads from invariant memory, and the other may store, they 14782 // cannot alias. These should really be checking the equivalent of mayWrite, 14783 // but it only matters for memory nodes other than load /store. 14784 if (Op0->isInvariant() && Op1->writeMem()) 14785 return false; 14786 14787 if (Op1->isInvariant() && Op0->writeMem()) 14788 return false; 14789 14790 // Gather base node and offset information. 14791 SDValue Base1, Base2; 14792 int64_t Offset1, Offset2; 14793 const GlobalValue *GV1, *GV2; 14794 const void *CV1, *CV2; 14795 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14796 Base1, Offset1, GV1, CV1); 14797 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14798 Base2, Offset2, GV2, CV2); 14799 14800 // If they have a same base address then check to see if they overlap. 14801 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14802 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14803 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14804 14805 // It is possible for different frame indices to alias each other, mostly 14806 // when tail call optimization reuses return address slots for arguments. 14807 // To catch this case, look up the actual index of frame indices to compute 14808 // the real alias relationship. 14809 if (isFrameIndex1 && isFrameIndex2) { 14810 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 14811 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14812 Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14813 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14814 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14815 } 14816 14817 // Otherwise, if we know what the bases are, and they aren't identical, then 14818 // we know they cannot alias. 14819 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14820 return false; 14821 14822 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14823 // compared to the size and offset of the access, we may be able to prove they 14824 // do not alias. This check is conservative for now to catch cases created by 14825 // splitting vector types. 14826 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14827 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14828 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14829 Op1->getMemoryVT().getSizeInBits() >> 3) && 14830 (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) { 14831 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14832 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14833 14834 // There is no overlap between these relatively aligned accesses of similar 14835 // size, return no alias. 14836 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14837 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14838 return false; 14839 } 14840 14841 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14842 ? CombinerGlobalAA 14843 : DAG.getSubtarget().useAA(); 14844 #ifndef NDEBUG 14845 if (CombinerAAOnlyFunc.getNumOccurrences() && 14846 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14847 UseAA = false; 14848 #endif 14849 if (UseAA && 14850 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14851 // Use alias analysis information. 14852 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14853 Op1->getSrcValueOffset()); 14854 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14855 Op0->getSrcValueOffset() - MinOffset; 14856 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14857 Op1->getSrcValueOffset() - MinOffset; 14858 AliasResult AAResult = 14859 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14860 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14861 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14862 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14863 if (AAResult == NoAlias) 14864 return false; 14865 } 14866 14867 // Otherwise we have to assume they alias. 14868 return true; 14869 } 14870 14871 /// Walk up chain skipping non-aliasing memory nodes, 14872 /// looking for aliasing nodes and adding them to the Aliases vector. 14873 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14874 SmallVectorImpl<SDValue> &Aliases) { 14875 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14876 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14877 14878 // Get alias information for node. 14879 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14880 14881 // Starting off. 14882 Chains.push_back(OriginalChain); 14883 unsigned Depth = 0; 14884 14885 // Look at each chain and determine if it is an alias. If so, add it to the 14886 // aliases list. If not, then continue up the chain looking for the next 14887 // candidate. 14888 while (!Chains.empty()) { 14889 SDValue Chain = Chains.pop_back_val(); 14890 14891 // For TokenFactor nodes, look at each operand and only continue up the 14892 // chain until we reach the depth limit. 14893 // 14894 // FIXME: The depth check could be made to return the last non-aliasing 14895 // chain we found before we hit a tokenfactor rather than the original 14896 // chain. 14897 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 14898 Aliases.clear(); 14899 Aliases.push_back(OriginalChain); 14900 return; 14901 } 14902 14903 // Don't bother if we've been before. 14904 if (!Visited.insert(Chain.getNode()).second) 14905 continue; 14906 14907 switch (Chain.getOpcode()) { 14908 case ISD::EntryToken: 14909 // Entry token is ideal chain operand, but handled in FindBetterChain. 14910 break; 14911 14912 case ISD::LOAD: 14913 case ISD::STORE: { 14914 // Get alias information for Chain. 14915 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14916 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14917 14918 // If chain is alias then stop here. 14919 if (!(IsLoad && IsOpLoad) && 14920 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14921 Aliases.push_back(Chain); 14922 } else { 14923 // Look further up the chain. 14924 Chains.push_back(Chain.getOperand(0)); 14925 ++Depth; 14926 } 14927 break; 14928 } 14929 14930 case ISD::TokenFactor: 14931 // We have to check each of the operands of the token factor for "small" 14932 // token factors, so we queue them up. Adding the operands to the queue 14933 // (stack) in reverse order maintains the original order and increases the 14934 // likelihood that getNode will find a matching token factor (CSE.) 14935 if (Chain.getNumOperands() > 16) { 14936 Aliases.push_back(Chain); 14937 break; 14938 } 14939 for (unsigned n = Chain.getNumOperands(); n;) 14940 Chains.push_back(Chain.getOperand(--n)); 14941 ++Depth; 14942 break; 14943 14944 default: 14945 // For all other instructions we will just have to take what we can get. 14946 Aliases.push_back(Chain); 14947 break; 14948 } 14949 } 14950 } 14951 14952 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14953 /// (aliasing node.) 14954 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14955 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14956 14957 // Accumulate all the aliases to this node. 14958 GatherAllAliases(N, OldChain, Aliases); 14959 14960 // If no operands then chain to entry token. 14961 if (Aliases.size() == 0) 14962 return DAG.getEntryNode(); 14963 14964 // If a single operand then chain to it. We don't need to revisit it. 14965 if (Aliases.size() == 1) 14966 return Aliases[0]; 14967 14968 // Construct a custom tailored token factor. 14969 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14970 } 14971 14972 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 14973 // This holds the base pointer, index, and the offset in bytes from the base 14974 // pointer. 14975 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 14976 14977 // We must have a base and an offset. 14978 if (!BasePtr.Base.getNode()) 14979 return false; 14980 14981 // Do not handle stores to undef base pointers. 14982 if (BasePtr.Base.isUndef()) 14983 return false; 14984 14985 SmallVector<StoreSDNode *, 8> ChainedStores; 14986 ChainedStores.push_back(St); 14987 14988 // Walk up the chain and look for nodes with offsets from the same 14989 // base pointer. Stop when reaching an instruction with a different kind 14990 // or instruction which has a different base pointer. 14991 StoreSDNode *Index = St; 14992 while (Index) { 14993 // If the chain has more than one use, then we can't reorder the mem ops. 14994 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14995 break; 14996 14997 if (Index->isVolatile() || Index->isIndexed()) 14998 break; 14999 15000 // Find the base pointer and offset for this memory node. 15001 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 15002 15003 // Check that the base pointer is the same as the original one. 15004 if (!Ptr.equalBaseIndex(BasePtr)) 15005 break; 15006 15007 // Find the next memory operand in the chain. If the next operand in the 15008 // chain is a store then move up and continue the scan with the next 15009 // memory operand. If the next operand is a load save it and use alias 15010 // information to check if it interferes with anything. 15011 SDNode *NextInChain = Index->getChain().getNode(); 15012 while (true) { 15013 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 15014 // We found a store node. Use it for the next iteration. 15015 if (STn->isVolatile() || STn->isIndexed()) { 15016 Index = nullptr; 15017 break; 15018 } 15019 ChainedStores.push_back(STn); 15020 Index = STn; 15021 break; 15022 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 15023 NextInChain = Ldn->getChain().getNode(); 15024 continue; 15025 } else { 15026 Index = nullptr; 15027 break; 15028 } 15029 } 15030 } 15031 15032 bool MadeChangeToSt = false; 15033 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 15034 15035 for (StoreSDNode *ChainedStore : ChainedStores) { 15036 SDValue Chain = ChainedStore->getChain(); 15037 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 15038 15039 if (Chain != BetterChain) { 15040 if (ChainedStore == St) 15041 MadeChangeToSt = true; 15042 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 15043 } 15044 } 15045 15046 // Do all replacements after finding the replacements to make to avoid making 15047 // the chains more complicated by introducing new TokenFactors. 15048 for (auto Replacement : BetterChains) 15049 replaceStoreChain(Replacement.first, Replacement.second); 15050 15051 return MadeChangeToSt; 15052 } 15053 15054 /// This is the entry point for the file. 15055 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 15056 CodeGenOpt::Level OptLevel) { 15057 /// This is the main entry point to this class. 15058 DAGCombiner(*this, AA, OptLevel).Run(Level); 15059 } 15060