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 // Return true if this node is a setcc, or is a select_cc 730 // that selects between the target values used for true and false, making it 731 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 732 // the appropriate nodes based on the type of node we are checking. This 733 // simplifies life a bit for the callers. 734 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 735 SDValue &CC) const { 736 if (N.getOpcode() == ISD::SETCC) { 737 LHS = N.getOperand(0); 738 RHS = N.getOperand(1); 739 CC = N.getOperand(2); 740 return true; 741 } 742 743 if (N.getOpcode() != ISD::SELECT_CC || 744 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 745 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 746 return false; 747 748 if (TLI.getBooleanContents(N.getValueType()) == 749 TargetLowering::UndefinedBooleanContent) 750 return false; 751 752 LHS = N.getOperand(0); 753 RHS = N.getOperand(1); 754 CC = N.getOperand(4); 755 return true; 756 } 757 758 /// Return true if this is a SetCC-equivalent operation with only one use. 759 /// If this is true, it allows the users to invert the operation for free when 760 /// it is profitable to do so. 761 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 762 SDValue N0, N1, N2; 763 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 764 return true; 765 return false; 766 } 767 768 // \brief Returns the SDNode if it is a constant float BuildVector 769 // or constant float. 770 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 771 if (isa<ConstantFPSDNode>(N)) 772 return N.getNode(); 773 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 774 return N.getNode(); 775 return nullptr; 776 } 777 778 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 779 // int. 780 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 781 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 782 return CN; 783 784 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 785 BitVector UndefElements; 786 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 787 788 // BuildVectors can truncate their operands. Ignore that case here. 789 // FIXME: We blindly ignore splats which include undef which is overly 790 // pessimistic. 791 if (CN && UndefElements.none() && 792 CN->getValueType(0) == N.getValueType().getScalarType()) 793 return CN; 794 } 795 796 return nullptr; 797 } 798 799 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 800 // float. 801 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 802 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 803 return CN; 804 805 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 806 BitVector UndefElements; 807 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 808 809 if (CN && UndefElements.none()) 810 return CN; 811 } 812 813 return nullptr; 814 } 815 816 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 817 SDValue N1) { 818 EVT VT = N0.getValueType(); 819 if (N0.getOpcode() == Opc) { 820 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 821 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 822 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 823 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 824 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 825 return SDValue(); 826 } 827 if (N0.hasOneUse()) { 828 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 829 // use 830 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 831 if (!OpNode.getNode()) 832 return SDValue(); 833 AddToWorklist(OpNode.getNode()); 834 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 835 } 836 } 837 } 838 839 if (N1.getOpcode() == Opc) { 840 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 841 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 842 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 843 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 844 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 845 return SDValue(); 846 } 847 if (N1.hasOneUse()) { 848 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 849 // use 850 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 851 if (!OpNode.getNode()) 852 return SDValue(); 853 AddToWorklist(OpNode.getNode()); 854 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 855 } 856 } 857 } 858 859 return SDValue(); 860 } 861 862 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 863 bool AddTo) { 864 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 865 ++NodesCombined; 866 DEBUG(dbgs() << "\nReplacing.1 "; 867 N->dump(&DAG); 868 dbgs() << "\nWith: "; 869 To[0].getNode()->dump(&DAG); 870 dbgs() << " and " << NumTo-1 << " other values\n"); 871 for (unsigned i = 0, e = NumTo; i != e; ++i) 872 assert((!To[i].getNode() || 873 N->getValueType(i) == To[i].getValueType()) && 874 "Cannot combine value to value of different type!"); 875 876 WorklistRemover DeadNodes(*this); 877 DAG.ReplaceAllUsesWith(N, To); 878 if (AddTo) { 879 // Push the new nodes and any users onto the worklist 880 for (unsigned i = 0, e = NumTo; i != e; ++i) { 881 if (To[i].getNode()) { 882 AddToWorklist(To[i].getNode()); 883 AddUsersToWorklist(To[i].getNode()); 884 } 885 } 886 } 887 888 // Finally, if the node is now dead, remove it from the graph. The node 889 // may not be dead if the replacement process recursively simplified to 890 // something else needing this node. 891 if (N->use_empty()) 892 deleteAndRecombine(N); 893 return SDValue(N, 0); 894 } 895 896 void DAGCombiner:: 897 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 898 // Replace all uses. If any nodes become isomorphic to other nodes and 899 // are deleted, make sure to remove them from our worklist. 900 WorklistRemover DeadNodes(*this); 901 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 902 903 // Push the new node and any (possibly new) users onto the worklist. 904 AddToWorklist(TLO.New.getNode()); 905 AddUsersToWorklist(TLO.New.getNode()); 906 907 // Finally, if the node is now dead, remove it from the graph. The node 908 // may not be dead if the replacement process recursively simplified to 909 // something else needing this node. 910 if (TLO.Old.getNode()->use_empty()) 911 deleteAndRecombine(TLO.Old.getNode()); 912 } 913 914 /// Check the specified integer node value to see if it can be simplified or if 915 /// things it uses can be simplified by bit propagation. If so, return true. 916 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 917 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 918 APInt KnownZero, KnownOne; 919 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 920 return false; 921 922 // Revisit the node. 923 AddToWorklist(Op.getNode()); 924 925 // Replace the old value with the new one. 926 ++NodesCombined; 927 DEBUG(dbgs() << "\nReplacing.2 "; 928 TLO.Old.getNode()->dump(&DAG); 929 dbgs() << "\nWith: "; 930 TLO.New.getNode()->dump(&DAG); 931 dbgs() << '\n'); 932 933 CommitTargetLoweringOpt(TLO); 934 return true; 935 } 936 937 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 938 SDLoc dl(Load); 939 EVT VT = Load->getValueType(0); 940 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 941 942 DEBUG(dbgs() << "\nReplacing.9 "; 943 Load->dump(&DAG); 944 dbgs() << "\nWith: "; 945 Trunc.getNode()->dump(&DAG); 946 dbgs() << '\n'); 947 WorklistRemover DeadNodes(*this); 948 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 949 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 950 deleteAndRecombine(Load); 951 AddToWorklist(Trunc.getNode()); 952 } 953 954 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 955 Replace = false; 956 SDLoc dl(Op); 957 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 958 LoadSDNode *LD = cast<LoadSDNode>(Op); 959 EVT MemVT = LD->getMemoryVT(); 960 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 961 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 962 : ISD::EXTLOAD) 963 : LD->getExtensionType(); 964 Replace = true; 965 return DAG.getExtLoad(ExtType, dl, PVT, 966 LD->getChain(), LD->getBasePtr(), 967 MemVT, LD->getMemOperand()); 968 } 969 970 unsigned Opc = Op.getOpcode(); 971 switch (Opc) { 972 default: break; 973 case ISD::AssertSext: 974 return DAG.getNode(ISD::AssertSext, dl, PVT, 975 SExtPromoteOperand(Op.getOperand(0), PVT), 976 Op.getOperand(1)); 977 case ISD::AssertZext: 978 return DAG.getNode(ISD::AssertZext, dl, PVT, 979 ZExtPromoteOperand(Op.getOperand(0), PVT), 980 Op.getOperand(1)); 981 case ISD::Constant: { 982 unsigned ExtOpc = 983 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 984 return DAG.getNode(ExtOpc, dl, PVT, Op); 985 } 986 } 987 988 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 989 return SDValue(); 990 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 991 } 992 993 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 994 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 995 return SDValue(); 996 EVT OldVT = Op.getValueType(); 997 SDLoc dl(Op); 998 bool Replace = false; 999 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1000 if (!NewOp.getNode()) 1001 return SDValue(); 1002 AddToWorklist(NewOp.getNode()); 1003 1004 if (Replace) 1005 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1006 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 1007 DAG.getValueType(OldVT)); 1008 } 1009 1010 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1011 EVT OldVT = Op.getValueType(); 1012 SDLoc dl(Op); 1013 bool Replace = false; 1014 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1015 if (!NewOp.getNode()) 1016 return SDValue(); 1017 AddToWorklist(NewOp.getNode()); 1018 1019 if (Replace) 1020 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1021 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1022 } 1023 1024 /// Promote the specified integer binary operation if the target indicates it is 1025 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1026 /// i32 since i16 instructions are longer. 1027 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1028 if (!LegalOperations) 1029 return SDValue(); 1030 1031 EVT VT = Op.getValueType(); 1032 if (VT.isVector() || !VT.isInteger()) 1033 return SDValue(); 1034 1035 // If operation type is 'undesirable', e.g. i16 on x86, consider 1036 // promoting it. 1037 unsigned Opc = Op.getOpcode(); 1038 if (TLI.isTypeDesirableForOp(Opc, VT)) 1039 return SDValue(); 1040 1041 EVT PVT = VT; 1042 // Consult target whether it is a good idea to promote this operation and 1043 // what's the right type to promote it to. 1044 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1045 assert(PVT != VT && "Don't know what type to promote to!"); 1046 1047 bool Replace0 = false; 1048 SDValue N0 = Op.getOperand(0); 1049 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1050 if (!NN0.getNode()) 1051 return SDValue(); 1052 1053 bool Replace1 = false; 1054 SDValue N1 = Op.getOperand(1); 1055 SDValue NN1; 1056 if (N0 == N1) 1057 NN1 = NN0; 1058 else { 1059 NN1 = PromoteOperand(N1, PVT, Replace1); 1060 if (!NN1.getNode()) 1061 return SDValue(); 1062 } 1063 1064 AddToWorklist(NN0.getNode()); 1065 if (NN1.getNode()) 1066 AddToWorklist(NN1.getNode()); 1067 1068 if (Replace0) 1069 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1070 if (Replace1) 1071 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1072 1073 DEBUG(dbgs() << "\nPromoting "; 1074 Op.getNode()->dump(&DAG)); 1075 SDLoc dl(Op); 1076 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1077 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1078 } 1079 return SDValue(); 1080 } 1081 1082 /// Promote the specified integer shift operation if the target indicates it is 1083 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1084 /// i32 since i16 instructions are longer. 1085 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1086 if (!LegalOperations) 1087 return SDValue(); 1088 1089 EVT VT = Op.getValueType(); 1090 if (VT.isVector() || !VT.isInteger()) 1091 return SDValue(); 1092 1093 // If operation type is 'undesirable', e.g. i16 on x86, consider 1094 // promoting it. 1095 unsigned Opc = Op.getOpcode(); 1096 if (TLI.isTypeDesirableForOp(Opc, VT)) 1097 return SDValue(); 1098 1099 EVT PVT = VT; 1100 // Consult target whether it is a good idea to promote this operation and 1101 // what's the right type to promote it to. 1102 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1103 assert(PVT != VT && "Don't know what type to promote to!"); 1104 1105 bool Replace = false; 1106 SDValue N0 = Op.getOperand(0); 1107 if (Opc == ISD::SRA) 1108 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1109 else if (Opc == ISD::SRL) 1110 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1111 else 1112 N0 = PromoteOperand(N0, PVT, Replace); 1113 if (!N0.getNode()) 1114 return SDValue(); 1115 1116 AddToWorklist(N0.getNode()); 1117 if (Replace) 1118 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1119 1120 DEBUG(dbgs() << "\nPromoting "; 1121 Op.getNode()->dump(&DAG)); 1122 SDLoc dl(Op); 1123 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1124 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1125 } 1126 return SDValue(); 1127 } 1128 1129 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1130 if (!LegalOperations) 1131 return SDValue(); 1132 1133 EVT VT = Op.getValueType(); 1134 if (VT.isVector() || !VT.isInteger()) 1135 return SDValue(); 1136 1137 // If operation type is 'undesirable', e.g. i16 on x86, consider 1138 // promoting it. 1139 unsigned Opc = Op.getOpcode(); 1140 if (TLI.isTypeDesirableForOp(Opc, VT)) 1141 return SDValue(); 1142 1143 EVT PVT = VT; 1144 // Consult target whether it is a good idea to promote this operation and 1145 // what's the right type to promote it to. 1146 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1147 assert(PVT != VT && "Don't know what type to promote to!"); 1148 // fold (aext (aext x)) -> (aext x) 1149 // fold (aext (zext x)) -> (zext x) 1150 // fold (aext (sext x)) -> (sext x) 1151 DEBUG(dbgs() << "\nPromoting "; 1152 Op.getNode()->dump(&DAG)); 1153 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1154 } 1155 return SDValue(); 1156 } 1157 1158 bool DAGCombiner::PromoteLoad(SDValue Op) { 1159 if (!LegalOperations) 1160 return false; 1161 1162 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1163 return false; 1164 1165 EVT VT = Op.getValueType(); 1166 if (VT.isVector() || !VT.isInteger()) 1167 return false; 1168 1169 // If operation type is 'undesirable', e.g. i16 on x86, consider 1170 // promoting it. 1171 unsigned Opc = Op.getOpcode(); 1172 if (TLI.isTypeDesirableForOp(Opc, VT)) 1173 return false; 1174 1175 EVT PVT = VT; 1176 // Consult target whether it is a good idea to promote this operation and 1177 // what's the right type to promote it to. 1178 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1179 assert(PVT != VT && "Don't know what type to promote to!"); 1180 1181 SDLoc dl(Op); 1182 SDNode *N = Op.getNode(); 1183 LoadSDNode *LD = cast<LoadSDNode>(N); 1184 EVT MemVT = LD->getMemoryVT(); 1185 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1186 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1187 : ISD::EXTLOAD) 1188 : LD->getExtensionType(); 1189 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1190 LD->getChain(), LD->getBasePtr(), 1191 MemVT, LD->getMemOperand()); 1192 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1193 1194 DEBUG(dbgs() << "\nPromoting "; 1195 N->dump(&DAG); 1196 dbgs() << "\nTo: "; 1197 Result.getNode()->dump(&DAG); 1198 dbgs() << '\n'); 1199 WorklistRemover DeadNodes(*this); 1200 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1201 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1202 deleteAndRecombine(N); 1203 AddToWorklist(Result.getNode()); 1204 return true; 1205 } 1206 return false; 1207 } 1208 1209 /// \brief Recursively delete a node which has no uses and any operands for 1210 /// which it is the only use. 1211 /// 1212 /// Note that this both deletes the nodes and removes them from the worklist. 1213 /// It also adds any nodes who have had a user deleted to the worklist as they 1214 /// may now have only one use and subject to other combines. 1215 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1216 if (!N->use_empty()) 1217 return false; 1218 1219 SmallSetVector<SDNode *, 16> Nodes; 1220 Nodes.insert(N); 1221 do { 1222 N = Nodes.pop_back_val(); 1223 if (!N) 1224 continue; 1225 1226 if (N->use_empty()) { 1227 for (const SDValue &ChildN : N->op_values()) 1228 Nodes.insert(ChildN.getNode()); 1229 1230 removeFromWorklist(N); 1231 DAG.DeleteNode(N); 1232 } else { 1233 AddToWorklist(N); 1234 } 1235 } while (!Nodes.empty()); 1236 return true; 1237 } 1238 1239 //===----------------------------------------------------------------------===// 1240 // Main DAG Combiner implementation 1241 //===----------------------------------------------------------------------===// 1242 1243 void DAGCombiner::Run(CombineLevel AtLevel) { 1244 // set the instance variables, so that the various visit routines may use it. 1245 Level = AtLevel; 1246 LegalOperations = Level >= AfterLegalizeVectorOps; 1247 LegalTypes = Level >= AfterLegalizeTypes; 1248 1249 // Add all the dag nodes to the worklist. 1250 for (SDNode &Node : DAG.allnodes()) 1251 AddToWorklist(&Node); 1252 1253 // Create a dummy node (which is not added to allnodes), that adds a reference 1254 // to the root node, preventing it from being deleted, and tracking any 1255 // changes of the root. 1256 HandleSDNode Dummy(DAG.getRoot()); 1257 1258 // While the worklist isn't empty, find a node and try to combine it. 1259 while (!WorklistMap.empty()) { 1260 SDNode *N; 1261 // The Worklist holds the SDNodes in order, but it may contain null entries. 1262 do { 1263 N = Worklist.pop_back_val(); 1264 } while (!N); 1265 1266 bool GoodWorklistEntry = WorklistMap.erase(N); 1267 (void)GoodWorklistEntry; 1268 assert(GoodWorklistEntry && 1269 "Found a worklist entry without a corresponding map entry!"); 1270 1271 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1272 // N is deleted from the DAG, since they too may now be dead or may have a 1273 // reduced number of uses, allowing other xforms. 1274 if (recursivelyDeleteUnusedNodes(N)) 1275 continue; 1276 1277 WorklistRemover DeadNodes(*this); 1278 1279 // If this combine is running after legalizing the DAG, re-legalize any 1280 // nodes pulled off the worklist. 1281 if (Level == AfterLegalizeDAG) { 1282 SmallSetVector<SDNode *, 16> UpdatedNodes; 1283 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1284 1285 for (SDNode *LN : UpdatedNodes) { 1286 AddToWorklist(LN); 1287 AddUsersToWorklist(LN); 1288 } 1289 if (!NIsValid) 1290 continue; 1291 } 1292 1293 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1294 1295 // Add any operands of the new node which have not yet been combined to the 1296 // worklist as well. Because the worklist uniques things already, this 1297 // won't repeatedly process the same operand. 1298 CombinedNodes.insert(N); 1299 for (const SDValue &ChildN : N->op_values()) 1300 if (!CombinedNodes.count(ChildN.getNode())) 1301 AddToWorklist(ChildN.getNode()); 1302 1303 SDValue RV = combine(N); 1304 1305 if (!RV.getNode()) 1306 continue; 1307 1308 ++NodesCombined; 1309 1310 // If we get back the same node we passed in, rather than a new node or 1311 // zero, we know that the node must have defined multiple values and 1312 // CombineTo was used. Since CombineTo takes care of the worklist 1313 // mechanics for us, we have no work to do in this case. 1314 if (RV.getNode() == N) 1315 continue; 1316 1317 assert(N->getOpcode() != ISD::DELETED_NODE && 1318 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1319 "Node was deleted but visit returned new node!"); 1320 1321 DEBUG(dbgs() << " ... into: "; 1322 RV.getNode()->dump(&DAG)); 1323 1324 if (N->getNumValues() == RV.getNode()->getNumValues()) 1325 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1326 else { 1327 assert(N->getValueType(0) == RV.getValueType() && 1328 N->getNumValues() == 1 && "Type mismatch"); 1329 SDValue OpV = RV; 1330 DAG.ReplaceAllUsesWith(N, &OpV); 1331 } 1332 1333 // Push the new node and any users onto the worklist 1334 AddToWorklist(RV.getNode()); 1335 AddUsersToWorklist(RV.getNode()); 1336 1337 // Finally, if the node is now dead, remove it from the graph. The node 1338 // may not be dead if the replacement process recursively simplified to 1339 // something else needing this node. This will also take care of adding any 1340 // operands which have lost a user to the worklist. 1341 recursivelyDeleteUnusedNodes(N); 1342 } 1343 1344 // If the root changed (e.g. it was a dead load, update the root). 1345 DAG.setRoot(Dummy.getValue()); 1346 DAG.RemoveDeadNodes(); 1347 } 1348 1349 SDValue DAGCombiner::visit(SDNode *N) { 1350 switch (N->getOpcode()) { 1351 default: break; 1352 case ISD::TokenFactor: return visitTokenFactor(N); 1353 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1354 case ISD::ADD: return visitADD(N); 1355 case ISD::SUB: return visitSUB(N); 1356 case ISD::ADDC: return visitADDC(N); 1357 case ISD::SUBC: return visitSUBC(N); 1358 case ISD::ADDE: return visitADDE(N); 1359 case ISD::SUBE: return visitSUBE(N); 1360 case ISD::MUL: return visitMUL(N); 1361 case ISD::SDIV: return visitSDIV(N); 1362 case ISD::UDIV: return visitUDIV(N); 1363 case ISD::SREM: 1364 case ISD::UREM: return visitREM(N); 1365 case ISD::MULHU: return visitMULHU(N); 1366 case ISD::MULHS: return visitMULHS(N); 1367 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1368 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1369 case ISD::SMULO: return visitSMULO(N); 1370 case ISD::UMULO: return visitUMULO(N); 1371 case ISD::SMIN: 1372 case ISD::SMAX: 1373 case ISD::UMIN: 1374 case ISD::UMAX: return visitIMINMAX(N); 1375 case ISD::AND: return visitAND(N); 1376 case ISD::OR: return visitOR(N); 1377 case ISD::XOR: return visitXOR(N); 1378 case ISD::SHL: return visitSHL(N); 1379 case ISD::SRA: return visitSRA(N); 1380 case ISD::SRL: return visitSRL(N); 1381 case ISD::ROTR: 1382 case ISD::ROTL: return visitRotate(N); 1383 case ISD::BSWAP: return visitBSWAP(N); 1384 case ISD::BITREVERSE: return visitBITREVERSE(N); 1385 case ISD::CTLZ: return visitCTLZ(N); 1386 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1387 case ISD::CTTZ: return visitCTTZ(N); 1388 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1389 case ISD::CTPOP: return visitCTPOP(N); 1390 case ISD::SELECT: return visitSELECT(N); 1391 case ISD::VSELECT: return visitVSELECT(N); 1392 case ISD::SELECT_CC: return visitSELECT_CC(N); 1393 case ISD::SETCC: return visitSETCC(N); 1394 case ISD::SETCCE: return visitSETCCE(N); 1395 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1396 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1397 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1398 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1399 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1400 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1401 case ISD::TRUNCATE: return visitTRUNCATE(N); 1402 case ISD::BITCAST: return visitBITCAST(N); 1403 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1404 case ISD::FADD: return visitFADD(N); 1405 case ISD::FSUB: return visitFSUB(N); 1406 case ISD::FMUL: return visitFMUL(N); 1407 case ISD::FMA: return visitFMA(N); 1408 case ISD::FDIV: return visitFDIV(N); 1409 case ISD::FREM: return visitFREM(N); 1410 case ISD::FSQRT: return visitFSQRT(N); 1411 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1412 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1413 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1414 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1415 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1416 case ISD::FP_ROUND: return visitFP_ROUND(N); 1417 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1418 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1419 case ISD::FNEG: return visitFNEG(N); 1420 case ISD::FABS: return visitFABS(N); 1421 case ISD::FFLOOR: return visitFFLOOR(N); 1422 case ISD::FMINNUM: return visitFMINNUM(N); 1423 case ISD::FMAXNUM: return visitFMAXNUM(N); 1424 case ISD::FCEIL: return visitFCEIL(N); 1425 case ISD::FTRUNC: return visitFTRUNC(N); 1426 case ISD::BRCOND: return visitBRCOND(N); 1427 case ISD::BR_CC: return visitBR_CC(N); 1428 case ISD::LOAD: return visitLOAD(N); 1429 case ISD::STORE: return visitSTORE(N); 1430 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1431 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1432 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1433 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1434 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1435 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1436 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1437 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1438 case ISD::MGATHER: return visitMGATHER(N); 1439 case ISD::MLOAD: return visitMLOAD(N); 1440 case ISD::MSCATTER: return visitMSCATTER(N); 1441 case ISD::MSTORE: return visitMSTORE(N); 1442 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1443 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1444 } 1445 return SDValue(); 1446 } 1447 1448 SDValue DAGCombiner::combine(SDNode *N) { 1449 SDValue RV = visit(N); 1450 1451 // If nothing happened, try a target-specific DAG combine. 1452 if (!RV.getNode()) { 1453 assert(N->getOpcode() != ISD::DELETED_NODE && 1454 "Node was deleted but visit returned NULL!"); 1455 1456 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1457 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1458 1459 // Expose the DAG combiner to the target combiner impls. 1460 TargetLowering::DAGCombinerInfo 1461 DagCombineInfo(DAG, Level, false, this); 1462 1463 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1464 } 1465 } 1466 1467 // If nothing happened still, try promoting the operation. 1468 if (!RV.getNode()) { 1469 switch (N->getOpcode()) { 1470 default: break; 1471 case ISD::ADD: 1472 case ISD::SUB: 1473 case ISD::MUL: 1474 case ISD::AND: 1475 case ISD::OR: 1476 case ISD::XOR: 1477 RV = PromoteIntBinOp(SDValue(N, 0)); 1478 break; 1479 case ISD::SHL: 1480 case ISD::SRA: 1481 case ISD::SRL: 1482 RV = PromoteIntShiftOp(SDValue(N, 0)); 1483 break; 1484 case ISD::SIGN_EXTEND: 1485 case ISD::ZERO_EXTEND: 1486 case ISD::ANY_EXTEND: 1487 RV = PromoteExtend(SDValue(N, 0)); 1488 break; 1489 case ISD::LOAD: 1490 if (PromoteLoad(SDValue(N, 0))) 1491 RV = SDValue(N, 0); 1492 break; 1493 } 1494 } 1495 1496 // If N is a commutative binary node, try commuting it to enable more 1497 // sdisel CSE. 1498 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1499 N->getNumValues() == 1) { 1500 SDValue N0 = N->getOperand(0); 1501 SDValue N1 = N->getOperand(1); 1502 1503 // Constant operands are canonicalized to RHS. 1504 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1505 SDValue Ops[] = {N1, N0}; 1506 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1507 N->getFlags()); 1508 if (CSENode) 1509 return SDValue(CSENode, 0); 1510 } 1511 } 1512 1513 return RV; 1514 } 1515 1516 /// Given a node, return its input chain if it has one, otherwise return a null 1517 /// sd operand. 1518 static SDValue getInputChainForNode(SDNode *N) { 1519 if (unsigned NumOps = N->getNumOperands()) { 1520 if (N->getOperand(0).getValueType() == MVT::Other) 1521 return N->getOperand(0); 1522 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1523 return N->getOperand(NumOps-1); 1524 for (unsigned i = 1; i < NumOps-1; ++i) 1525 if (N->getOperand(i).getValueType() == MVT::Other) 1526 return N->getOperand(i); 1527 } 1528 return SDValue(); 1529 } 1530 1531 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1532 // If N has two operands, where one has an input chain equal to the other, 1533 // the 'other' chain is redundant. 1534 if (N->getNumOperands() == 2) { 1535 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1536 return N->getOperand(0); 1537 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1538 return N->getOperand(1); 1539 } 1540 1541 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1542 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1543 SmallPtrSet<SDNode*, 16> SeenOps; 1544 bool Changed = false; // If we should replace this token factor. 1545 1546 // Start out with this token factor. 1547 TFs.push_back(N); 1548 1549 // Iterate through token factors. The TFs grows when new token factors are 1550 // encountered. 1551 for (unsigned i = 0; i < TFs.size(); ++i) { 1552 SDNode *TF = TFs[i]; 1553 1554 // Check each of the operands. 1555 for (const SDValue &Op : TF->op_values()) { 1556 1557 switch (Op.getOpcode()) { 1558 case ISD::EntryToken: 1559 // Entry tokens don't need to be added to the list. They are 1560 // redundant. 1561 Changed = true; 1562 break; 1563 1564 case ISD::TokenFactor: 1565 if (Op.hasOneUse() && 1566 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1567 // Queue up for processing. 1568 TFs.push_back(Op.getNode()); 1569 // Clean up in case the token factor is removed. 1570 AddToWorklist(Op.getNode()); 1571 Changed = true; 1572 break; 1573 } 1574 // Fall thru 1575 1576 default: 1577 // Only add if it isn't already in the list. 1578 if (SeenOps.insert(Op.getNode()).second) 1579 Ops.push_back(Op); 1580 else 1581 Changed = true; 1582 break; 1583 } 1584 } 1585 } 1586 1587 SDValue Result; 1588 1589 // If we've changed things around then replace token factor. 1590 if (Changed) { 1591 if (Ops.empty()) { 1592 // The entry token is the only possible outcome. 1593 Result = DAG.getEntryNode(); 1594 } else { 1595 // New and improved token factor. 1596 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1597 } 1598 1599 // Add users to worklist if AA is enabled, since it may introduce 1600 // a lot of new chained token factors while removing memory deps. 1601 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1602 : DAG.getSubtarget().useAA(); 1603 return CombineTo(N, Result, UseAA /*add to worklist*/); 1604 } 1605 1606 return Result; 1607 } 1608 1609 /// MERGE_VALUES can always be eliminated. 1610 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1611 WorklistRemover DeadNodes(*this); 1612 // Replacing results may cause a different MERGE_VALUES to suddenly 1613 // be CSE'd with N, and carry its uses with it. Iterate until no 1614 // uses remain, to ensure that the node can be safely deleted. 1615 // First add the users of this node to the work list so that they 1616 // can be tried again once they have new operands. 1617 AddUsersToWorklist(N); 1618 do { 1619 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1620 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1621 } while (!N->use_empty()); 1622 deleteAndRecombine(N); 1623 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1624 } 1625 1626 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1627 /// ConstantSDNode pointer else nullptr. 1628 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1629 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1630 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1631 } 1632 1633 SDValue DAGCombiner::visitADD(SDNode *N) { 1634 SDValue N0 = N->getOperand(0); 1635 SDValue N1 = N->getOperand(1); 1636 EVT VT = N0.getValueType(); 1637 1638 // fold vector ops 1639 if (VT.isVector()) { 1640 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1641 return FoldedVOp; 1642 1643 // fold (add x, 0) -> x, vector edition 1644 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1645 return N0; 1646 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1647 return N1; 1648 } 1649 1650 // fold (add x, undef) -> undef 1651 if (N0.isUndef()) 1652 return N0; 1653 if (N1.isUndef()) 1654 return N1; 1655 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1656 // canonicalize constant to RHS 1657 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1658 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1659 // fold (add c1, c2) -> c1+c2 1660 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, 1661 N0.getNode(), N1.getNode()); 1662 } 1663 // fold (add x, 0) -> x 1664 if (isNullConstant(N1)) 1665 return N0; 1666 // fold ((c1-A)+c2) -> (c1+c2)-A 1667 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) { 1668 if (N0.getOpcode() == ISD::SUB) 1669 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1670 SDLoc DL(N); 1671 return DAG.getNode(ISD::SUB, DL, VT, 1672 DAG.getConstant(N1C->getAPIntValue()+ 1673 N0C->getAPIntValue(), DL, VT), 1674 N0.getOperand(1)); 1675 } 1676 } 1677 // reassociate add 1678 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1679 return RADD; 1680 // fold ((0-A) + B) -> B-A 1681 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1682 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1683 // fold (A + (0-B)) -> A-B 1684 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1685 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1686 // fold (A+(B-A)) -> B 1687 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1688 return N1.getOperand(0); 1689 // fold ((B-A)+A) -> B 1690 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1691 return N0.getOperand(0); 1692 // fold (A+(B-(A+C))) to (B-C) 1693 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1694 N0 == N1.getOperand(1).getOperand(0)) 1695 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1696 N1.getOperand(1).getOperand(1)); 1697 // fold (A+(B-(C+A))) to (B-C) 1698 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1699 N0 == N1.getOperand(1).getOperand(1)) 1700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1701 N1.getOperand(1).getOperand(0)); 1702 // fold (A+((B-A)+or-C)) to (B+or-C) 1703 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1704 N1.getOperand(0).getOpcode() == ISD::SUB && 1705 N0 == N1.getOperand(0).getOperand(1)) 1706 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1707 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1708 1709 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1710 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1711 SDValue N00 = N0.getOperand(0); 1712 SDValue N01 = N0.getOperand(1); 1713 SDValue N10 = N1.getOperand(0); 1714 SDValue N11 = N1.getOperand(1); 1715 1716 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1717 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1718 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1719 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1720 } 1721 1722 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1723 return SDValue(N, 0); 1724 1725 // fold (a+b) -> (a|b) iff a and b share no bits. 1726 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 1727 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1)) 1728 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1729 1730 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1731 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1732 isNullConstant(N1.getOperand(0).getOperand(0))) 1733 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1734 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1735 N1.getOperand(0).getOperand(1), 1736 N1.getOperand(1))); 1737 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1738 isNullConstant(N0.getOperand(0).getOperand(0))) 1739 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1740 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1741 N0.getOperand(0).getOperand(1), 1742 N0.getOperand(1))); 1743 1744 if (N1.getOpcode() == ISD::AND) { 1745 SDValue AndOp0 = N1.getOperand(0); 1746 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1747 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1748 1749 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1750 // and similar xforms where the inner op is either ~0 or 0. 1751 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1752 SDLoc DL(N); 1753 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1754 } 1755 } 1756 1757 // add (sext i1), X -> sub X, (zext i1) 1758 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1759 N0.getOperand(0).getValueType() == MVT::i1 && 1760 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1761 SDLoc DL(N); 1762 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1763 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1764 } 1765 1766 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1767 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1768 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1769 if (TN->getVT() == MVT::i1) { 1770 SDLoc DL(N); 1771 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1772 DAG.getConstant(1, DL, VT)); 1773 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1774 } 1775 } 1776 1777 return SDValue(); 1778 } 1779 1780 SDValue DAGCombiner::visitADDC(SDNode *N) { 1781 SDValue N0 = N->getOperand(0); 1782 SDValue N1 = N->getOperand(1); 1783 EVT VT = N0.getValueType(); 1784 1785 // If the flag result is dead, turn this into an ADD. 1786 if (!N->hasAnyUseOfValue(1)) 1787 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1788 DAG.getNode(ISD::CARRY_FALSE, 1789 SDLoc(N), MVT::Glue)); 1790 1791 // canonicalize constant to RHS. 1792 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1793 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1794 if (N0C && !N1C) 1795 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1796 1797 // fold (addc x, 0) -> x + no carry out 1798 if (isNullConstant(N1)) 1799 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1800 SDLoc(N), MVT::Glue)); 1801 1802 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1803 APInt LHSZero, LHSOne; 1804 APInt RHSZero, RHSOne; 1805 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1806 1807 if (LHSZero.getBoolValue()) { 1808 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1809 1810 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1811 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1812 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1813 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1814 DAG.getNode(ISD::CARRY_FALSE, 1815 SDLoc(N), MVT::Glue)); 1816 } 1817 1818 return SDValue(); 1819 } 1820 1821 SDValue DAGCombiner::visitADDE(SDNode *N) { 1822 SDValue N0 = N->getOperand(0); 1823 SDValue N1 = N->getOperand(1); 1824 SDValue CarryIn = N->getOperand(2); 1825 1826 // canonicalize constant to RHS 1827 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1828 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1829 if (N0C && !N1C) 1830 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1831 N1, N0, CarryIn); 1832 1833 // fold (adde x, y, false) -> (addc x, y) 1834 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1835 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1836 1837 return SDValue(); 1838 } 1839 1840 // Since it may not be valid to emit a fold to zero for vector initializers 1841 // check if we can before folding. 1842 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 1843 SelectionDAG &DAG, bool LegalOperations, 1844 bool LegalTypes) { 1845 if (!VT.isVector()) 1846 return DAG.getConstant(0, DL, VT); 1847 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1848 return DAG.getConstant(0, DL, VT); 1849 return SDValue(); 1850 } 1851 1852 SDValue DAGCombiner::visitSUB(SDNode *N) { 1853 SDValue N0 = N->getOperand(0); 1854 SDValue N1 = N->getOperand(1); 1855 EVT VT = N0.getValueType(); 1856 1857 // fold vector ops 1858 if (VT.isVector()) { 1859 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1860 return FoldedVOp; 1861 1862 // fold (sub x, 0) -> x, vector edition 1863 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1864 return N0; 1865 } 1866 1867 // fold (sub x, x) -> 0 1868 // FIXME: Refactor this and xor and other similar operations together. 1869 if (N0 == N1) 1870 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1871 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1872 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1873 // fold (sub c1, c2) -> c1-c2 1874 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, 1875 N0.getNode(), N1.getNode()); 1876 } 1877 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1878 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1879 // fold (sub x, c) -> (add x, -c) 1880 if (N1C) { 1881 SDLoc DL(N); 1882 return DAG.getNode(ISD::ADD, DL, VT, N0, 1883 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1884 } 1885 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1886 if (isAllOnesConstant(N0)) 1887 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1888 // fold A-(A-B) -> B 1889 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1890 return N1.getOperand(1); 1891 // fold (A+B)-A -> B 1892 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1893 return N0.getOperand(1); 1894 // fold (A+B)-B -> A 1895 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1896 return N0.getOperand(0); 1897 // fold C2-(A+C1) -> (C2-C1)-A 1898 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1899 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1900 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1901 SDLoc DL(N); 1902 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1903 DL, VT); 1904 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1905 N1.getOperand(0)); 1906 } 1907 // fold ((A+(B+or-C))-B) -> A+or-C 1908 if (N0.getOpcode() == ISD::ADD && 1909 (N0.getOperand(1).getOpcode() == ISD::SUB || 1910 N0.getOperand(1).getOpcode() == ISD::ADD) && 1911 N0.getOperand(1).getOperand(0) == N1) 1912 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1913 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1914 // fold ((A+(C+B))-B) -> A+C 1915 if (N0.getOpcode() == ISD::ADD && 1916 N0.getOperand(1).getOpcode() == ISD::ADD && 1917 N0.getOperand(1).getOperand(1) == N1) 1918 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1919 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1920 // fold ((A-(B-C))-C) -> A-B 1921 if (N0.getOpcode() == ISD::SUB && 1922 N0.getOperand(1).getOpcode() == ISD::SUB && 1923 N0.getOperand(1).getOperand(1) == N1) 1924 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1925 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1926 1927 // If either operand of a sub is undef, the result is undef 1928 if (N0.isUndef()) 1929 return N0; 1930 if (N1.isUndef()) 1931 return N1; 1932 1933 // If the relocation model supports it, consider symbol offsets. 1934 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1935 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1936 // fold (sub Sym, c) -> Sym-c 1937 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1938 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1939 GA->getOffset() - 1940 (uint64_t)N1C->getSExtValue()); 1941 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1942 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1943 if (GA->getGlobal() == GB->getGlobal()) 1944 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1945 SDLoc(N), VT); 1946 } 1947 1948 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1949 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1950 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1951 if (TN->getVT() == MVT::i1) { 1952 SDLoc DL(N); 1953 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1954 DAG.getConstant(1, DL, VT)); 1955 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1956 } 1957 } 1958 1959 return SDValue(); 1960 } 1961 1962 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1963 SDValue N0 = N->getOperand(0); 1964 SDValue N1 = N->getOperand(1); 1965 EVT VT = N0.getValueType(); 1966 SDLoc DL(N); 1967 1968 // If the flag result is dead, turn this into an SUB. 1969 if (!N->hasAnyUseOfValue(1)) 1970 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 1971 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1972 1973 // fold (subc x, x) -> 0 + no borrow 1974 if (N0 == N1) 1975 return CombineTo(N, DAG.getConstant(0, DL, VT), 1976 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1977 1978 // fold (subc x, 0) -> x + no borrow 1979 if (isNullConstant(N1)) 1980 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1981 1982 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1983 if (isAllOnesConstant(N0)) 1984 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 1985 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1986 1987 return SDValue(); 1988 } 1989 1990 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1991 SDValue N0 = N->getOperand(0); 1992 SDValue N1 = N->getOperand(1); 1993 SDValue CarryIn = N->getOperand(2); 1994 1995 // fold (sube x, y, false) -> (subc x, y) 1996 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1997 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1998 1999 return SDValue(); 2000 } 2001 2002 SDValue DAGCombiner::visitMUL(SDNode *N) { 2003 SDValue N0 = N->getOperand(0); 2004 SDValue N1 = N->getOperand(1); 2005 EVT VT = N0.getValueType(); 2006 2007 // fold (mul x, undef) -> 0 2008 if (N0.isUndef() || N1.isUndef()) 2009 return DAG.getConstant(0, SDLoc(N), VT); 2010 2011 bool N0IsConst = false; 2012 bool N1IsConst = false; 2013 bool N1IsOpaqueConst = false; 2014 bool N0IsOpaqueConst = false; 2015 APInt ConstValue0, ConstValue1; 2016 // fold vector ops 2017 if (VT.isVector()) { 2018 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2019 return FoldedVOp; 2020 2021 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 2022 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 2023 } else { 2024 N0IsConst = isa<ConstantSDNode>(N0); 2025 if (N0IsConst) { 2026 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2027 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2028 } 2029 N1IsConst = isa<ConstantSDNode>(N1); 2030 if (N1IsConst) { 2031 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2032 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2033 } 2034 } 2035 2036 // fold (mul c1, c2) -> c1*c2 2037 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2038 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2039 N0.getNode(), N1.getNode()); 2040 2041 // canonicalize constant to RHS (vector doesn't have to splat) 2042 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2043 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2044 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2045 // fold (mul x, 0) -> 0 2046 if (N1IsConst && ConstValue1 == 0) 2047 return N1; 2048 // We require a splat of the entire scalar bit width for non-contiguous 2049 // bit patterns. 2050 bool IsFullSplat = 2051 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2052 // fold (mul x, 1) -> x 2053 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2054 return N0; 2055 // fold (mul x, -1) -> 0-x 2056 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2057 SDLoc DL(N); 2058 return DAG.getNode(ISD::SUB, DL, VT, 2059 DAG.getConstant(0, DL, VT), N0); 2060 } 2061 // fold (mul x, (1 << c)) -> x << c 2062 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2063 IsFullSplat) { 2064 SDLoc DL(N); 2065 return DAG.getNode(ISD::SHL, DL, VT, N0, 2066 DAG.getConstant(ConstValue1.logBase2(), DL, 2067 getShiftAmountTy(N0.getValueType()))); 2068 } 2069 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2070 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2071 IsFullSplat) { 2072 unsigned Log2Val = (-ConstValue1).logBase2(); 2073 SDLoc DL(N); 2074 // FIXME: If the input is something that is easily negated (e.g. a 2075 // single-use add), we should put the negate there. 2076 return DAG.getNode(ISD::SUB, DL, VT, 2077 DAG.getConstant(0, DL, VT), 2078 DAG.getNode(ISD::SHL, DL, VT, N0, 2079 DAG.getConstant(Log2Val, DL, 2080 getShiftAmountTy(N0.getValueType())))); 2081 } 2082 2083 APInt Val; 2084 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2085 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2086 (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2087 isa<ConstantSDNode>(N0.getOperand(1)))) { 2088 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 2089 AddToWorklist(C3.getNode()); 2090 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 2091 } 2092 2093 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2094 // use. 2095 { 2096 SDValue Sh(nullptr, 0), Y(nullptr, 0); 2097 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2098 if (N0.getOpcode() == ISD::SHL && 2099 (ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2100 isa<ConstantSDNode>(N0.getOperand(1))) && 2101 N0.getNode()->hasOneUse()) { 2102 Sh = N0; Y = N1; 2103 } else if (N1.getOpcode() == ISD::SHL && 2104 isa<ConstantSDNode>(N1.getOperand(1)) && 2105 N1.getNode()->hasOneUse()) { 2106 Sh = N1; Y = N0; 2107 } 2108 2109 if (Sh.getNode()) { 2110 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 2111 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 2112 } 2113 } 2114 2115 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2116 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2117 N0.getOpcode() == ISD::ADD && 2118 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2119 isMulAddWithConstProfitable(N, N0, N1)) 2120 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2121 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2122 N0.getOperand(0), N1), 2123 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2124 N0.getOperand(1), N1)); 2125 2126 // reassociate mul 2127 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2128 return RMUL; 2129 2130 return SDValue(); 2131 } 2132 2133 /// Return true if divmod libcall is available. 2134 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2135 const TargetLowering &TLI) { 2136 RTLIB::Libcall LC; 2137 EVT NodeType = Node->getValueType(0); 2138 if (!NodeType.isSimple()) 2139 return false; 2140 switch (NodeType.getSimpleVT().SimpleTy) { 2141 default: return false; // No libcall for vector types. 2142 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2143 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2144 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2145 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2146 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2147 } 2148 2149 return TLI.getLibcallName(LC) != nullptr; 2150 } 2151 2152 /// Issue divrem if both quotient and remainder are needed. 2153 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2154 if (Node->use_empty()) 2155 return SDValue(); // This is a dead node, leave it alone. 2156 2157 unsigned Opcode = Node->getOpcode(); 2158 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2159 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2160 2161 // DivMod lib calls can still work on non-legal types if using lib-calls. 2162 EVT VT = Node->getValueType(0); 2163 if (VT.isVector() || !VT.isInteger()) 2164 return SDValue(); 2165 2166 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2167 return SDValue(); 2168 2169 // If DIVREM is going to get expanded into a libcall, 2170 // but there is no libcall available, then don't combine. 2171 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2172 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2173 return SDValue(); 2174 2175 // If div is legal, it's better to do the normal expansion 2176 unsigned OtherOpcode = 0; 2177 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2178 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2179 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2180 return SDValue(); 2181 } else { 2182 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2183 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2184 return SDValue(); 2185 } 2186 2187 SDValue Op0 = Node->getOperand(0); 2188 SDValue Op1 = Node->getOperand(1); 2189 SDValue combined; 2190 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2191 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2192 SDNode *User = *UI; 2193 if (User == Node || User->use_empty()) 2194 continue; 2195 // Convert the other matching node(s), too; 2196 // otherwise, the DIVREM may get target-legalized into something 2197 // target-specific that we won't be able to recognize. 2198 unsigned UserOpc = User->getOpcode(); 2199 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2200 User->getOperand(0) == Op0 && 2201 User->getOperand(1) == Op1) { 2202 if (!combined) { 2203 if (UserOpc == OtherOpcode) { 2204 SDVTList VTs = DAG.getVTList(VT, VT); 2205 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2206 } else if (UserOpc == DivRemOpc) { 2207 combined = SDValue(User, 0); 2208 } else { 2209 assert(UserOpc == Opcode); 2210 continue; 2211 } 2212 } 2213 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2214 CombineTo(User, combined); 2215 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2216 CombineTo(User, combined.getValue(1)); 2217 } 2218 } 2219 return combined; 2220 } 2221 2222 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2223 SDValue N0 = N->getOperand(0); 2224 SDValue N1 = N->getOperand(1); 2225 EVT VT = N->getValueType(0); 2226 2227 // fold vector ops 2228 if (VT.isVector()) 2229 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2230 return FoldedVOp; 2231 2232 SDLoc DL(N); 2233 2234 // fold (sdiv c1, c2) -> c1/c2 2235 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2236 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2237 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2238 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2239 // fold (sdiv X, 1) -> X 2240 if (N1C && N1C->isOne()) 2241 return N0; 2242 // fold (sdiv X, -1) -> 0-X 2243 if (N1C && N1C->isAllOnesValue()) 2244 return DAG.getNode(ISD::SUB, DL, VT, 2245 DAG.getConstant(0, DL, VT), N0); 2246 2247 // If we know the sign bits of both operands are zero, strength reduce to a 2248 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2249 if (!VT.isVector()) { 2250 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2251 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2252 } 2253 2254 // fold (sdiv X, pow2) -> simple ops after legalize 2255 // FIXME: We check for the exact bit here because the generic lowering gives 2256 // better results in that case. The target-specific lowering should learn how 2257 // to handle exact sdivs efficiently. 2258 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2259 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2260 (N1C->getAPIntValue().isPowerOf2() || 2261 (-N1C->getAPIntValue()).isPowerOf2())) { 2262 // Target-specific implementation of sdiv x, pow2. 2263 if (SDValue Res = BuildSDIVPow2(N)) 2264 return Res; 2265 2266 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2267 2268 // Splat the sign bit into the register 2269 SDValue SGN = 2270 DAG.getNode(ISD::SRA, DL, VT, N0, 2271 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2272 getShiftAmountTy(N0.getValueType()))); 2273 AddToWorklist(SGN.getNode()); 2274 2275 // Add (N0 < 0) ? abs2 - 1 : 0; 2276 SDValue SRL = 2277 DAG.getNode(ISD::SRL, DL, VT, SGN, 2278 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2279 getShiftAmountTy(SGN.getValueType()))); 2280 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2281 AddToWorklist(SRL.getNode()); 2282 AddToWorklist(ADD.getNode()); // Divide by pow2 2283 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2284 DAG.getConstant(lg2, DL, 2285 getShiftAmountTy(ADD.getValueType()))); 2286 2287 // If we're dividing by a positive value, we're done. Otherwise, we must 2288 // negate the result. 2289 if (N1C->getAPIntValue().isNonNegative()) 2290 return SRA; 2291 2292 AddToWorklist(SRA.getNode()); 2293 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2294 } 2295 2296 // If integer divide is expensive and we satisfy the requirements, emit an 2297 // alternate sequence. Targets may check function attributes for size/speed 2298 // trade-offs. 2299 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2300 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2301 if (SDValue Op = BuildSDIV(N)) 2302 return Op; 2303 2304 // sdiv, srem -> sdivrem 2305 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2306 // Otherwise, we break the simplification logic in visitREM(). 2307 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2308 if (SDValue DivRem = useDivRem(N)) 2309 return DivRem; 2310 2311 // undef / X -> 0 2312 if (N0.isUndef()) 2313 return DAG.getConstant(0, DL, VT); 2314 // X / undef -> undef 2315 if (N1.isUndef()) 2316 return N1; 2317 2318 return SDValue(); 2319 } 2320 2321 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2322 SDValue N0 = N->getOperand(0); 2323 SDValue N1 = N->getOperand(1); 2324 EVT VT = N->getValueType(0); 2325 2326 // fold vector ops 2327 if (VT.isVector()) 2328 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2329 return FoldedVOp; 2330 2331 SDLoc DL(N); 2332 2333 // fold (udiv c1, c2) -> c1/c2 2334 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2335 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2336 if (N0C && N1C) 2337 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2338 N0C, N1C)) 2339 return Folded; 2340 // fold (udiv x, (1 << c)) -> x >>u c 2341 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2342 return DAG.getNode(ISD::SRL, DL, VT, N0, 2343 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2344 getShiftAmountTy(N0.getValueType()))); 2345 2346 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2347 if (N1.getOpcode() == ISD::SHL) { 2348 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2349 if (SHC->getAPIntValue().isPowerOf2()) { 2350 EVT ADDVT = N1.getOperand(1).getValueType(); 2351 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2352 N1.getOperand(1), 2353 DAG.getConstant(SHC->getAPIntValue() 2354 .logBase2(), 2355 DL, ADDVT)); 2356 AddToWorklist(Add.getNode()); 2357 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2358 } 2359 } 2360 } 2361 2362 // fold (udiv x, c) -> alternate 2363 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2364 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2365 if (SDValue Op = BuildUDIV(N)) 2366 return Op; 2367 2368 // sdiv, srem -> sdivrem 2369 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2370 // Otherwise, we break the simplification logic in visitREM(). 2371 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2372 if (SDValue DivRem = useDivRem(N)) 2373 return DivRem; 2374 2375 // undef / X -> 0 2376 if (N0.isUndef()) 2377 return DAG.getConstant(0, DL, VT); 2378 // X / undef -> undef 2379 if (N1.isUndef()) 2380 return N1; 2381 2382 return SDValue(); 2383 } 2384 2385 // handles ISD::SREM and ISD::UREM 2386 SDValue DAGCombiner::visitREM(SDNode *N) { 2387 unsigned Opcode = N->getOpcode(); 2388 SDValue N0 = N->getOperand(0); 2389 SDValue N1 = N->getOperand(1); 2390 EVT VT = N->getValueType(0); 2391 bool isSigned = (Opcode == ISD::SREM); 2392 SDLoc DL(N); 2393 2394 // fold (rem c1, c2) -> c1%c2 2395 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2396 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2397 if (N0C && N1C) 2398 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2399 return Folded; 2400 2401 if (isSigned) { 2402 // If we know the sign bits of both operands are zero, strength reduce to a 2403 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2404 if (!VT.isVector()) { 2405 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2406 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2407 } 2408 } else { 2409 // fold (urem x, pow2) -> (and x, pow2-1) 2410 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2411 N1C->getAPIntValue().isPowerOf2()) { 2412 return DAG.getNode(ISD::AND, DL, VT, N0, 2413 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2414 } 2415 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2416 if (N1.getOpcode() == ISD::SHL) { 2417 ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0)); 2418 if (SHC && SHC->getAPIntValue().isPowerOf2()) { 2419 APInt NegOne = APInt::getAllOnesValue(VT.getSizeInBits()); 2420 SDValue Add = 2421 DAG.getNode(ISD::ADD, DL, VT, N1, DAG.getConstant(NegOne, DL, VT)); 2422 AddToWorklist(Add.getNode()); 2423 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2424 } 2425 } 2426 } 2427 2428 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2429 2430 // If X/C can be simplified by the division-by-constant logic, lower 2431 // X%C to the equivalent of X-X/C*C. 2432 // To avoid mangling nodes, this simplification requires that the combine() 2433 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2434 // against this by skipping the simplification if isIntDivCheap(). When 2435 // div is not cheap, combine will not return a DIVREM. Regardless, 2436 // checking cheapness here makes sense since the simplification results in 2437 // fatter code. 2438 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2439 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2440 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2441 AddToWorklist(Div.getNode()); 2442 SDValue OptimizedDiv = combine(Div.getNode()); 2443 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2444 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2445 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2446 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2447 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2448 AddToWorklist(Mul.getNode()); 2449 return Sub; 2450 } 2451 } 2452 2453 // sdiv, srem -> sdivrem 2454 if (SDValue DivRem = useDivRem(N)) 2455 return DivRem.getValue(1); 2456 2457 // undef % X -> 0 2458 if (N0.isUndef()) 2459 return DAG.getConstant(0, DL, VT); 2460 // X % undef -> undef 2461 if (N1.isUndef()) 2462 return N1; 2463 2464 return SDValue(); 2465 } 2466 2467 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2468 SDValue N0 = N->getOperand(0); 2469 SDValue N1 = N->getOperand(1); 2470 EVT VT = N->getValueType(0); 2471 SDLoc DL(N); 2472 2473 // fold (mulhs x, 0) -> 0 2474 if (isNullConstant(N1)) 2475 return N1; 2476 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2477 if (isOneConstant(N1)) { 2478 SDLoc DL(N); 2479 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2480 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2481 DL, 2482 getShiftAmountTy(N0.getValueType()))); 2483 } 2484 // fold (mulhs x, undef) -> 0 2485 if (N0.isUndef() || N1.isUndef()) 2486 return DAG.getConstant(0, SDLoc(N), VT); 2487 2488 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2489 // plus a shift. 2490 if (VT.isSimple() && !VT.isVector()) { 2491 MVT Simple = VT.getSimpleVT(); 2492 unsigned SimpleSize = Simple.getSizeInBits(); 2493 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2494 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2495 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2496 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2497 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2498 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2499 DAG.getConstant(SimpleSize, DL, 2500 getShiftAmountTy(N1.getValueType()))); 2501 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2502 } 2503 } 2504 2505 return SDValue(); 2506 } 2507 2508 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2509 SDValue N0 = N->getOperand(0); 2510 SDValue N1 = N->getOperand(1); 2511 EVT VT = N->getValueType(0); 2512 SDLoc DL(N); 2513 2514 // fold (mulhu x, 0) -> 0 2515 if (isNullConstant(N1)) 2516 return N1; 2517 // fold (mulhu x, 1) -> 0 2518 if (isOneConstant(N1)) 2519 return DAG.getConstant(0, DL, N0.getValueType()); 2520 // fold (mulhu x, undef) -> 0 2521 if (N0.isUndef() || N1.isUndef()) 2522 return DAG.getConstant(0, DL, VT); 2523 2524 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2525 // plus a shift. 2526 if (VT.isSimple() && !VT.isVector()) { 2527 MVT Simple = VT.getSimpleVT(); 2528 unsigned SimpleSize = Simple.getSizeInBits(); 2529 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2530 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2531 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2532 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2533 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2534 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2535 DAG.getConstant(SimpleSize, DL, 2536 getShiftAmountTy(N1.getValueType()))); 2537 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2538 } 2539 } 2540 2541 return SDValue(); 2542 } 2543 2544 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2545 /// give the opcodes for the two computations that are being performed. Return 2546 /// true if a simplification was made. 2547 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2548 unsigned HiOp) { 2549 // If the high half is not needed, just compute the low half. 2550 bool HiExists = N->hasAnyUseOfValue(1); 2551 if (!HiExists && 2552 (!LegalOperations || 2553 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2554 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2555 return CombineTo(N, Res, Res); 2556 } 2557 2558 // If the low half is not needed, just compute the high half. 2559 bool LoExists = N->hasAnyUseOfValue(0); 2560 if (!LoExists && 2561 (!LegalOperations || 2562 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2563 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2564 return CombineTo(N, Res, Res); 2565 } 2566 2567 // If both halves are used, return as it is. 2568 if (LoExists && HiExists) 2569 return SDValue(); 2570 2571 // If the two computed results can be simplified separately, separate them. 2572 if (LoExists) { 2573 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2574 AddToWorklist(Lo.getNode()); 2575 SDValue LoOpt = combine(Lo.getNode()); 2576 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2577 (!LegalOperations || 2578 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2579 return CombineTo(N, LoOpt, LoOpt); 2580 } 2581 2582 if (HiExists) { 2583 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2584 AddToWorklist(Hi.getNode()); 2585 SDValue HiOpt = combine(Hi.getNode()); 2586 if (HiOpt.getNode() && HiOpt != Hi && 2587 (!LegalOperations || 2588 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2589 return CombineTo(N, HiOpt, HiOpt); 2590 } 2591 2592 return SDValue(); 2593 } 2594 2595 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2596 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2597 return Res; 2598 2599 EVT VT = N->getValueType(0); 2600 SDLoc DL(N); 2601 2602 // If the type is twice as wide is legal, transform the mulhu to a wider 2603 // multiply plus a shift. 2604 if (VT.isSimple() && !VT.isVector()) { 2605 MVT Simple = VT.getSimpleVT(); 2606 unsigned SimpleSize = Simple.getSizeInBits(); 2607 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2608 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2609 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2610 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2611 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2612 // Compute the high part as N1. 2613 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2614 DAG.getConstant(SimpleSize, DL, 2615 getShiftAmountTy(Lo.getValueType()))); 2616 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2617 // Compute the low part as N0. 2618 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2619 return CombineTo(N, Lo, Hi); 2620 } 2621 } 2622 2623 return SDValue(); 2624 } 2625 2626 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2627 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2628 return Res; 2629 2630 EVT VT = N->getValueType(0); 2631 SDLoc DL(N); 2632 2633 // If the type is twice as wide is legal, transform the mulhu to a wider 2634 // multiply plus a shift. 2635 if (VT.isSimple() && !VT.isVector()) { 2636 MVT Simple = VT.getSimpleVT(); 2637 unsigned SimpleSize = Simple.getSizeInBits(); 2638 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2639 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2640 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2641 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2642 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2643 // Compute the high part as N1. 2644 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2645 DAG.getConstant(SimpleSize, DL, 2646 getShiftAmountTy(Lo.getValueType()))); 2647 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2648 // Compute the low part as N0. 2649 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2650 return CombineTo(N, Lo, Hi); 2651 } 2652 } 2653 2654 return SDValue(); 2655 } 2656 2657 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2658 // (smulo x, 2) -> (saddo x, x) 2659 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2660 if (C2->getAPIntValue() == 2) 2661 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2662 N->getOperand(0), N->getOperand(0)); 2663 2664 return SDValue(); 2665 } 2666 2667 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2668 // (umulo x, 2) -> (uaddo x, x) 2669 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2670 if (C2->getAPIntValue() == 2) 2671 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2672 N->getOperand(0), N->getOperand(0)); 2673 2674 return SDValue(); 2675 } 2676 2677 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2678 SDValue N0 = N->getOperand(0); 2679 SDValue N1 = N->getOperand(1); 2680 EVT VT = N0.getValueType(); 2681 2682 // fold vector ops 2683 if (VT.isVector()) 2684 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2685 return FoldedVOp; 2686 2687 // fold (add c1, c2) -> c1+c2 2688 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2689 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2690 if (N0C && N1C) 2691 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2692 2693 // canonicalize constant to RHS 2694 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2695 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2696 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2697 2698 return SDValue(); 2699 } 2700 2701 /// If this is a binary operator with two operands of the same opcode, try to 2702 /// simplify it. 2703 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2704 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2705 EVT VT = N0.getValueType(); 2706 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2707 2708 // Bail early if none of these transforms apply. 2709 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2710 2711 // For each of OP in AND/OR/XOR: 2712 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2713 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2714 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2715 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2716 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2717 // 2718 // do not sink logical op inside of a vector extend, since it may combine 2719 // into a vsetcc. 2720 EVT Op0VT = N0.getOperand(0).getValueType(); 2721 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2722 N0.getOpcode() == ISD::SIGN_EXTEND || 2723 N0.getOpcode() == ISD::BSWAP || 2724 // Avoid infinite looping with PromoteIntBinOp. 2725 (N0.getOpcode() == ISD::ANY_EXTEND && 2726 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2727 (N0.getOpcode() == ISD::TRUNCATE && 2728 (!TLI.isZExtFree(VT, Op0VT) || 2729 !TLI.isTruncateFree(Op0VT, VT)) && 2730 TLI.isTypeLegal(Op0VT))) && 2731 !VT.isVector() && 2732 Op0VT == N1.getOperand(0).getValueType() && 2733 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2734 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2735 N0.getOperand(0).getValueType(), 2736 N0.getOperand(0), N1.getOperand(0)); 2737 AddToWorklist(ORNode.getNode()); 2738 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2739 } 2740 2741 // For each of OP in SHL/SRL/SRA/AND... 2742 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2743 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2744 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2745 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2746 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2747 N0.getOperand(1) == N1.getOperand(1)) { 2748 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2749 N0.getOperand(0).getValueType(), 2750 N0.getOperand(0), N1.getOperand(0)); 2751 AddToWorklist(ORNode.getNode()); 2752 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2753 ORNode, N0.getOperand(1)); 2754 } 2755 2756 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2757 // Only perform this optimization up until type legalization, before 2758 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2759 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2760 // we don't want to undo this promotion. 2761 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2762 // on scalars. 2763 if ((N0.getOpcode() == ISD::BITCAST || 2764 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2765 Level <= AfterLegalizeTypes) { 2766 SDValue In0 = N0.getOperand(0); 2767 SDValue In1 = N1.getOperand(0); 2768 EVT In0Ty = In0.getValueType(); 2769 EVT In1Ty = In1.getValueType(); 2770 SDLoc DL(N); 2771 // If both incoming values are integers, and the original types are the 2772 // same. 2773 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2774 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2775 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2776 AddToWorklist(Op.getNode()); 2777 return BC; 2778 } 2779 } 2780 2781 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2782 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2783 // If both shuffles use the same mask, and both shuffle within a single 2784 // vector, then it is worthwhile to move the swizzle after the operation. 2785 // The type-legalizer generates this pattern when loading illegal 2786 // vector types from memory. In many cases this allows additional shuffle 2787 // optimizations. 2788 // There are other cases where moving the shuffle after the xor/and/or 2789 // is profitable even if shuffles don't perform a swizzle. 2790 // If both shuffles use the same mask, and both shuffles have the same first 2791 // or second operand, then it might still be profitable to move the shuffle 2792 // after the xor/and/or operation. 2793 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2794 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2795 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2796 2797 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2798 "Inputs to shuffles are not the same type"); 2799 2800 // Check that both shuffles use the same mask. The masks are known to be of 2801 // the same length because the result vector type is the same. 2802 // Check also that shuffles have only one use to avoid introducing extra 2803 // instructions. 2804 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2805 SVN0->getMask().equals(SVN1->getMask())) { 2806 SDValue ShOp = N0->getOperand(1); 2807 2808 // Don't try to fold this node if it requires introducing a 2809 // build vector of all zeros that might be illegal at this stage. 2810 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2811 if (!LegalTypes) 2812 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2813 else 2814 ShOp = SDValue(); 2815 } 2816 2817 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2818 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2819 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2820 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2821 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2822 N0->getOperand(0), N1->getOperand(0)); 2823 AddToWorklist(NewNode.getNode()); 2824 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2825 SVN0->getMask()); 2826 } 2827 2828 // Don't try to fold this node if it requires introducing a 2829 // build vector of all zeros that might be illegal at this stage. 2830 ShOp = N0->getOperand(0); 2831 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2832 if (!LegalTypes) 2833 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2834 else 2835 ShOp = SDValue(); 2836 } 2837 2838 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2839 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2840 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2841 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2842 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2843 N0->getOperand(1), N1->getOperand(1)); 2844 AddToWorklist(NewNode.getNode()); 2845 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2846 SVN0->getMask()); 2847 } 2848 } 2849 } 2850 2851 return SDValue(); 2852 } 2853 2854 /// This contains all DAGCombine rules which reduce two values combined by 2855 /// an And operation to a single value. This makes them reusable in the context 2856 /// of visitSELECT(). Rules involving constants are not included as 2857 /// visitSELECT() already handles those cases. 2858 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2859 SDNode *LocReference) { 2860 EVT VT = N1.getValueType(); 2861 2862 // fold (and x, undef) -> 0 2863 if (N0.isUndef() || N1.isUndef()) 2864 return DAG.getConstant(0, SDLoc(LocReference), VT); 2865 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2866 SDValue LL, LR, RL, RR, CC0, CC1; 2867 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2868 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2869 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2870 2871 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2872 LL.getValueType().isInteger()) { 2873 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2874 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2875 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2876 LR.getValueType(), LL, RL); 2877 AddToWorklist(ORNode.getNode()); 2878 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2879 } 2880 if (isAllOnesConstant(LR)) { 2881 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2882 if (Op1 == ISD::SETEQ) { 2883 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2884 LR.getValueType(), LL, RL); 2885 AddToWorklist(ANDNode.getNode()); 2886 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2887 } 2888 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2889 if (Op1 == ISD::SETGT) { 2890 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2891 LR.getValueType(), LL, RL); 2892 AddToWorklist(ORNode.getNode()); 2893 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2894 } 2895 } 2896 } 2897 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2898 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2899 Op0 == Op1 && LL.getValueType().isInteger() && 2900 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2901 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2902 SDLoc DL(N0); 2903 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2904 LL, DAG.getConstant(1, DL, 2905 LL.getValueType())); 2906 AddToWorklist(ADDNode.getNode()); 2907 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2908 DAG.getConstant(2, DL, LL.getValueType()), 2909 ISD::SETUGE); 2910 } 2911 // canonicalize equivalent to ll == rl 2912 if (LL == RR && LR == RL) { 2913 Op1 = ISD::getSetCCSwappedOperands(Op1); 2914 std::swap(RL, RR); 2915 } 2916 if (LL == RL && LR == RR) { 2917 bool isInteger = LL.getValueType().isInteger(); 2918 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2919 if (Result != ISD::SETCC_INVALID && 2920 (!LegalOperations || 2921 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2922 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2923 EVT CCVT = getSetCCResultType(LL.getValueType()); 2924 if (N0.getValueType() == CCVT || 2925 (!LegalOperations && N0.getValueType() == MVT::i1)) 2926 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2927 LL, LR, Result); 2928 } 2929 } 2930 } 2931 2932 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2933 VT.getSizeInBits() <= 64) { 2934 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2935 APInt ADDC = ADDI->getAPIntValue(); 2936 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2937 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2938 // immediate for an add, but it is legal if its top c2 bits are set, 2939 // transform the ADD so the immediate doesn't need to be materialized 2940 // in a register. 2941 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2942 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2943 SRLI->getZExtValue()); 2944 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2945 ADDC |= Mask; 2946 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2947 SDLoc DL(N0); 2948 SDValue NewAdd = 2949 DAG.getNode(ISD::ADD, DL, VT, 2950 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2951 CombineTo(N0.getNode(), NewAdd); 2952 // Return N so it doesn't get rechecked! 2953 return SDValue(LocReference, 0); 2954 } 2955 } 2956 } 2957 } 2958 } 2959 } 2960 2961 // Reduce bit extract of low half of an integer to the narrower type. 2962 // (and (srl i64:x, K), KMask) -> 2963 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 2964 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 2965 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 2966 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2967 unsigned Size = VT.getSizeInBits(); 2968 const APInt &AndMask = CAnd->getAPIntValue(); 2969 unsigned ShiftBits = CShift->getZExtValue(); 2970 unsigned MaskBits = AndMask.countTrailingOnes(); 2971 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 2972 2973 if (APIntOps::isMask(AndMask) && 2974 // Required bits must not span the two halves of the integer and 2975 // must fit in the half size type. 2976 (ShiftBits + MaskBits <= Size / 2) && 2977 TLI.isNarrowingProfitable(VT, HalfVT) && 2978 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 2979 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 2980 TLI.isTruncateFree(VT, HalfVT) && 2981 TLI.isZExtFree(HalfVT, VT)) { 2982 // The isNarrowingProfitable is to avoid regressions on PPC and 2983 // AArch64 which match a few 64-bit bit insert / bit extract patterns 2984 // on downstream users of this. Those patterns could probably be 2985 // extended to handle extensions mixed in. 2986 2987 SDValue SL(N0); 2988 assert(ShiftBits != 0 && MaskBits <= Size); 2989 2990 // Extracting the highest bit of the low half. 2991 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 2992 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 2993 N0.getOperand(0)); 2994 2995 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 2996 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 2997 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 2998 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 2999 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3000 } 3001 } 3002 } 3003 } 3004 3005 return SDValue(); 3006 } 3007 3008 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3009 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3010 bool &NarrowLoad) { 3011 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3012 3013 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 3014 return false; 3015 3016 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3017 LoadedVT = LoadN->getMemoryVT(); 3018 3019 if (ExtVT == LoadedVT && 3020 (!LegalOperations || 3021 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3022 // ZEXTLOAD will match without needing to change the size of the value being 3023 // loaded. 3024 NarrowLoad = false; 3025 return true; 3026 } 3027 3028 // Do not change the width of a volatile load. 3029 if (LoadN->isVolatile()) 3030 return false; 3031 3032 // Do not generate loads of non-round integer types since these can 3033 // be expensive (and would be wrong if the type is not byte sized). 3034 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3035 return false; 3036 3037 if (LegalOperations && 3038 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3039 return false; 3040 3041 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3042 return false; 3043 3044 NarrowLoad = true; 3045 return true; 3046 } 3047 3048 SDValue DAGCombiner::visitAND(SDNode *N) { 3049 SDValue N0 = N->getOperand(0); 3050 SDValue N1 = N->getOperand(1); 3051 EVT VT = N1.getValueType(); 3052 3053 // fold vector ops 3054 if (VT.isVector()) { 3055 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3056 return FoldedVOp; 3057 3058 // fold (and x, 0) -> 0, vector edition 3059 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3060 // do not return N0, because undef node may exist in N0 3061 return DAG.getConstant( 3062 APInt::getNullValue( 3063 N0.getValueType().getScalarType().getSizeInBits()), 3064 SDLoc(N), N0.getValueType()); 3065 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3066 // do not return N1, because undef node may exist in N1 3067 return DAG.getConstant( 3068 APInt::getNullValue( 3069 N1.getValueType().getScalarType().getSizeInBits()), 3070 SDLoc(N), N1.getValueType()); 3071 3072 // fold (and x, -1) -> x, vector edition 3073 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3074 return N1; 3075 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3076 return N0; 3077 } 3078 3079 // fold (and c1, c2) -> c1&c2 3080 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3081 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3082 if (N0C && N1C && !N1C->isOpaque()) 3083 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3084 // canonicalize constant to RHS 3085 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3086 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3087 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3088 // fold (and x, -1) -> x 3089 if (isAllOnesConstant(N1)) 3090 return N0; 3091 // if (and x, c) is known to be zero, return 0 3092 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3093 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3094 APInt::getAllOnesValue(BitWidth))) 3095 return DAG.getConstant(0, SDLoc(N), VT); 3096 // reassociate and 3097 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3098 return RAND; 3099 // fold (and (or x, C), D) -> D if (C & D) == D 3100 if (N1C && N0.getOpcode() == ISD::OR) 3101 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3102 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3103 return N1; 3104 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3105 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3106 SDValue N0Op0 = N0.getOperand(0); 3107 APInt Mask = ~N1C->getAPIntValue(); 3108 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 3109 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3110 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3111 N0.getValueType(), N0Op0); 3112 3113 // Replace uses of the AND with uses of the Zero extend node. 3114 CombineTo(N, Zext); 3115 3116 // We actually want to replace all uses of the any_extend with the 3117 // zero_extend, to avoid duplicating things. This will later cause this 3118 // AND to be folded. 3119 CombineTo(N0.getNode(), Zext); 3120 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3121 } 3122 } 3123 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3124 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3125 // already be zero by virtue of the width of the base type of the load. 3126 // 3127 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3128 // more cases. 3129 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3130 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3131 N0.getOperand(0).getOpcode() == ISD::LOAD && 3132 N0.getOperand(0).getResNo() == 0) || 3133 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3134 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3135 N0 : N0.getOperand(0) ); 3136 3137 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3138 // This can be a pure constant or a vector splat, in which case we treat the 3139 // vector as a scalar and use the splat value. 3140 APInt Constant = APInt::getNullValue(1); 3141 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3142 Constant = C->getAPIntValue(); 3143 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3144 APInt SplatValue, SplatUndef; 3145 unsigned SplatBitSize; 3146 bool HasAnyUndefs; 3147 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3148 SplatBitSize, HasAnyUndefs); 3149 if (IsSplat) { 3150 // Undef bits can contribute to a possible optimisation if set, so 3151 // set them. 3152 SplatValue |= SplatUndef; 3153 3154 // The splat value may be something like "0x00FFFFFF", which means 0 for 3155 // the first vector value and FF for the rest, repeating. We need a mask 3156 // that will apply equally to all members of the vector, so AND all the 3157 // lanes of the constant together. 3158 EVT VT = Vector->getValueType(0); 3159 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3160 3161 // If the splat value has been compressed to a bitlength lower 3162 // than the size of the vector lane, we need to re-expand it to 3163 // the lane size. 3164 if (BitWidth > SplatBitSize) 3165 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3166 SplatBitSize < BitWidth; 3167 SplatBitSize = SplatBitSize * 2) 3168 SplatValue |= SplatValue.shl(SplatBitSize); 3169 3170 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3171 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3172 if (SplatBitSize % BitWidth == 0) { 3173 Constant = APInt::getAllOnesValue(BitWidth); 3174 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3175 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3176 } 3177 } 3178 } 3179 3180 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3181 // actually legal and isn't going to get expanded, else this is a false 3182 // optimisation. 3183 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3184 Load->getValueType(0), 3185 Load->getMemoryVT()); 3186 3187 // Resize the constant to the same size as the original memory access before 3188 // extension. If it is still the AllOnesValue then this AND is completely 3189 // unneeded. 3190 Constant = 3191 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3192 3193 bool B; 3194 switch (Load->getExtensionType()) { 3195 default: B = false; break; 3196 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3197 case ISD::ZEXTLOAD: 3198 case ISD::NON_EXTLOAD: B = true; break; 3199 } 3200 3201 if (B && Constant.isAllOnesValue()) { 3202 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3203 // preserve semantics once we get rid of the AND. 3204 SDValue NewLoad(Load, 0); 3205 if (Load->getExtensionType() == ISD::EXTLOAD) { 3206 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3207 Load->getValueType(0), SDLoc(Load), 3208 Load->getChain(), Load->getBasePtr(), 3209 Load->getOffset(), Load->getMemoryVT(), 3210 Load->getMemOperand()); 3211 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3212 if (Load->getNumValues() == 3) { 3213 // PRE/POST_INC loads have 3 values. 3214 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3215 NewLoad.getValue(2) }; 3216 CombineTo(Load, To, 3, true); 3217 } else { 3218 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3219 } 3220 } 3221 3222 // Fold the AND away, taking care not to fold to the old load node if we 3223 // replaced it. 3224 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3225 3226 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3227 } 3228 } 3229 3230 // fold (and (load x), 255) -> (zextload x, i8) 3231 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3232 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3233 if (N1C && (N0.getOpcode() == ISD::LOAD || 3234 (N0.getOpcode() == ISD::ANY_EXTEND && 3235 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3236 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3237 LoadSDNode *LN0 = HasAnyExt 3238 ? cast<LoadSDNode>(N0.getOperand(0)) 3239 : cast<LoadSDNode>(N0); 3240 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3241 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3242 auto NarrowLoad = false; 3243 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3244 EVT ExtVT, LoadedVT; 3245 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3246 NarrowLoad)) { 3247 if (!NarrowLoad) { 3248 SDValue NewLoad = 3249 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3250 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3251 LN0->getMemOperand()); 3252 AddToWorklist(N); 3253 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3254 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3255 } else { 3256 EVT PtrType = LN0->getOperand(1).getValueType(); 3257 3258 unsigned Alignment = LN0->getAlignment(); 3259 SDValue NewPtr = LN0->getBasePtr(); 3260 3261 // For big endian targets, we need to add an offset to the pointer 3262 // to load the correct bytes. For little endian systems, we merely 3263 // need to read fewer bytes from the same pointer. 3264 if (DAG.getDataLayout().isBigEndian()) { 3265 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3266 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3267 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3268 SDLoc DL(LN0); 3269 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3270 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3271 Alignment = MinAlign(Alignment, PtrOff); 3272 } 3273 3274 AddToWorklist(NewPtr.getNode()); 3275 3276 SDValue Load = DAG.getExtLoad( 3277 ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr, 3278 LN0->getPointerInfo(), ExtVT, Alignment, 3279 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 3280 AddToWorklist(N); 3281 CombineTo(LN0, Load, Load.getValue(1)); 3282 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3283 } 3284 } 3285 } 3286 } 3287 3288 if (SDValue Combined = visitANDLike(N0, N1, N)) 3289 return Combined; 3290 3291 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3292 if (N0.getOpcode() == N1.getOpcode()) 3293 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3294 return Tmp; 3295 3296 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3297 // fold (and (sra)) -> (and (srl)) when possible. 3298 if (!VT.isVector() && 3299 SimplifyDemandedBits(SDValue(N, 0))) 3300 return SDValue(N, 0); 3301 3302 // fold (zext_inreg (extload x)) -> (zextload x) 3303 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3304 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3305 EVT MemVT = LN0->getMemoryVT(); 3306 // If we zero all the possible extended bits, then we can turn this into 3307 // a zextload if we are running before legalize or the operation is legal. 3308 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3309 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3310 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3311 ((!LegalOperations && !LN0->isVolatile()) || 3312 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3313 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3314 LN0->getChain(), LN0->getBasePtr(), 3315 MemVT, LN0->getMemOperand()); 3316 AddToWorklist(N); 3317 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3318 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3319 } 3320 } 3321 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3322 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3323 N0.hasOneUse()) { 3324 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3325 EVT MemVT = LN0->getMemoryVT(); 3326 // If we zero all the possible extended bits, then we can turn this into 3327 // a zextload if we are running before legalize or the operation is legal. 3328 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3329 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3330 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3331 ((!LegalOperations && !LN0->isVolatile()) || 3332 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3333 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3334 LN0->getChain(), LN0->getBasePtr(), 3335 MemVT, LN0->getMemOperand()); 3336 AddToWorklist(N); 3337 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3338 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3339 } 3340 } 3341 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3342 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3343 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3344 N0.getOperand(1), false)) 3345 return BSwap; 3346 } 3347 3348 return SDValue(); 3349 } 3350 3351 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3352 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3353 bool DemandHighBits) { 3354 if (!LegalOperations) 3355 return SDValue(); 3356 3357 EVT VT = N->getValueType(0); 3358 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3359 return SDValue(); 3360 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3361 return SDValue(); 3362 3363 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3364 bool LookPassAnd0 = false; 3365 bool LookPassAnd1 = false; 3366 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3367 std::swap(N0, N1); 3368 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3369 std::swap(N0, N1); 3370 if (N0.getOpcode() == ISD::AND) { 3371 if (!N0.getNode()->hasOneUse()) 3372 return SDValue(); 3373 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3374 if (!N01C || N01C->getZExtValue() != 0xFF00) 3375 return SDValue(); 3376 N0 = N0.getOperand(0); 3377 LookPassAnd0 = true; 3378 } 3379 3380 if (N1.getOpcode() == ISD::AND) { 3381 if (!N1.getNode()->hasOneUse()) 3382 return SDValue(); 3383 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3384 if (!N11C || N11C->getZExtValue() != 0xFF) 3385 return SDValue(); 3386 N1 = N1.getOperand(0); 3387 LookPassAnd1 = true; 3388 } 3389 3390 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3391 std::swap(N0, N1); 3392 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3393 return SDValue(); 3394 if (!N0.getNode()->hasOneUse() || 3395 !N1.getNode()->hasOneUse()) 3396 return SDValue(); 3397 3398 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3399 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3400 if (!N01C || !N11C) 3401 return SDValue(); 3402 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3403 return SDValue(); 3404 3405 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3406 SDValue N00 = N0->getOperand(0); 3407 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3408 if (!N00.getNode()->hasOneUse()) 3409 return SDValue(); 3410 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3411 if (!N001C || N001C->getZExtValue() != 0xFF) 3412 return SDValue(); 3413 N00 = N00.getOperand(0); 3414 LookPassAnd0 = true; 3415 } 3416 3417 SDValue N10 = N1->getOperand(0); 3418 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3419 if (!N10.getNode()->hasOneUse()) 3420 return SDValue(); 3421 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3422 if (!N101C || N101C->getZExtValue() != 0xFF00) 3423 return SDValue(); 3424 N10 = N10.getOperand(0); 3425 LookPassAnd1 = true; 3426 } 3427 3428 if (N00 != N10) 3429 return SDValue(); 3430 3431 // Make sure everything beyond the low halfword gets set to zero since the SRL 3432 // 16 will clear the top bits. 3433 unsigned OpSizeInBits = VT.getSizeInBits(); 3434 if (DemandHighBits && OpSizeInBits > 16) { 3435 // If the left-shift isn't masked out then the only way this is a bswap is 3436 // if all bits beyond the low 8 are 0. In that case the entire pattern 3437 // reduces to a left shift anyway: leave it for other parts of the combiner. 3438 if (!LookPassAnd0) 3439 return SDValue(); 3440 3441 // However, if the right shift isn't masked out then it might be because 3442 // it's not needed. See if we can spot that too. 3443 if (!LookPassAnd1 && 3444 !DAG.MaskedValueIsZero( 3445 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3446 return SDValue(); 3447 } 3448 3449 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3450 if (OpSizeInBits > 16) { 3451 SDLoc DL(N); 3452 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3453 DAG.getConstant(OpSizeInBits - 16, DL, 3454 getShiftAmountTy(VT))); 3455 } 3456 return Res; 3457 } 3458 3459 /// Return true if the specified node is an element that makes up a 32-bit 3460 /// packed halfword byteswap. 3461 /// ((x & 0x000000ff) << 8) | 3462 /// ((x & 0x0000ff00) >> 8) | 3463 /// ((x & 0x00ff0000) << 8) | 3464 /// ((x & 0xff000000) >> 8) 3465 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3466 if (!N.getNode()->hasOneUse()) 3467 return false; 3468 3469 unsigned Opc = N.getOpcode(); 3470 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3471 return false; 3472 3473 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3474 if (!N1C) 3475 return false; 3476 3477 unsigned Num; 3478 switch (N1C->getZExtValue()) { 3479 default: 3480 return false; 3481 case 0xFF: Num = 0; break; 3482 case 0xFF00: Num = 1; break; 3483 case 0xFF0000: Num = 2; break; 3484 case 0xFF000000: Num = 3; break; 3485 } 3486 3487 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3488 SDValue N0 = N.getOperand(0); 3489 if (Opc == ISD::AND) { 3490 if (Num == 0 || Num == 2) { 3491 // (x >> 8) & 0xff 3492 // (x >> 8) & 0xff0000 3493 if (N0.getOpcode() != ISD::SRL) 3494 return false; 3495 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3496 if (!C || C->getZExtValue() != 8) 3497 return false; 3498 } else { 3499 // (x << 8) & 0xff00 3500 // (x << 8) & 0xff000000 3501 if (N0.getOpcode() != ISD::SHL) 3502 return false; 3503 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3504 if (!C || C->getZExtValue() != 8) 3505 return false; 3506 } 3507 } else if (Opc == ISD::SHL) { 3508 // (x & 0xff) << 8 3509 // (x & 0xff0000) << 8 3510 if (Num != 0 && Num != 2) 3511 return false; 3512 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3513 if (!C || C->getZExtValue() != 8) 3514 return false; 3515 } else { // Opc == ISD::SRL 3516 // (x & 0xff00) >> 8 3517 // (x & 0xff000000) >> 8 3518 if (Num != 1 && Num != 3) 3519 return false; 3520 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3521 if (!C || C->getZExtValue() != 8) 3522 return false; 3523 } 3524 3525 if (Parts[Num]) 3526 return false; 3527 3528 Parts[Num] = N0.getOperand(0).getNode(); 3529 return true; 3530 } 3531 3532 /// Match a 32-bit packed halfword bswap. That is 3533 /// ((x & 0x000000ff) << 8) | 3534 /// ((x & 0x0000ff00) >> 8) | 3535 /// ((x & 0x00ff0000) << 8) | 3536 /// ((x & 0xff000000) >> 8) 3537 /// => (rotl (bswap x), 16) 3538 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3539 if (!LegalOperations) 3540 return SDValue(); 3541 3542 EVT VT = N->getValueType(0); 3543 if (VT != MVT::i32) 3544 return SDValue(); 3545 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3546 return SDValue(); 3547 3548 // Look for either 3549 // (or (or (and), (and)), (or (and), (and))) 3550 // (or (or (or (and), (and)), (and)), (and)) 3551 if (N0.getOpcode() != ISD::OR) 3552 return SDValue(); 3553 SDValue N00 = N0.getOperand(0); 3554 SDValue N01 = N0.getOperand(1); 3555 SDNode *Parts[4] = {}; 3556 3557 if (N1.getOpcode() == ISD::OR && 3558 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3559 // (or (or (and), (and)), (or (and), (and))) 3560 SDValue N000 = N00.getOperand(0); 3561 if (!isBSwapHWordElement(N000, Parts)) 3562 return SDValue(); 3563 3564 SDValue N001 = N00.getOperand(1); 3565 if (!isBSwapHWordElement(N001, Parts)) 3566 return SDValue(); 3567 SDValue N010 = N01.getOperand(0); 3568 if (!isBSwapHWordElement(N010, Parts)) 3569 return SDValue(); 3570 SDValue N011 = N01.getOperand(1); 3571 if (!isBSwapHWordElement(N011, Parts)) 3572 return SDValue(); 3573 } else { 3574 // (or (or (or (and), (and)), (and)), (and)) 3575 if (!isBSwapHWordElement(N1, Parts)) 3576 return SDValue(); 3577 if (!isBSwapHWordElement(N01, Parts)) 3578 return SDValue(); 3579 if (N00.getOpcode() != ISD::OR) 3580 return SDValue(); 3581 SDValue N000 = N00.getOperand(0); 3582 if (!isBSwapHWordElement(N000, Parts)) 3583 return SDValue(); 3584 SDValue N001 = N00.getOperand(1); 3585 if (!isBSwapHWordElement(N001, Parts)) 3586 return SDValue(); 3587 } 3588 3589 // Make sure the parts are all coming from the same node. 3590 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3591 return SDValue(); 3592 3593 SDLoc DL(N); 3594 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3595 SDValue(Parts[0], 0)); 3596 3597 // Result of the bswap should be rotated by 16. If it's not legal, then 3598 // do (x << 16) | (x >> 16). 3599 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3600 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3601 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3602 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3603 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3604 return DAG.getNode(ISD::OR, DL, VT, 3605 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3606 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3607 } 3608 3609 /// This contains all DAGCombine rules which reduce two values combined by 3610 /// an Or operation to a single value \see visitANDLike(). 3611 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3612 EVT VT = N1.getValueType(); 3613 // fold (or x, undef) -> -1 3614 if (!LegalOperations && 3615 (N0.isUndef() || N1.isUndef())) { 3616 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3617 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3618 SDLoc(LocReference), VT); 3619 } 3620 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3621 SDValue LL, LR, RL, RR, CC0, CC1; 3622 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3623 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3624 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3625 3626 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3627 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3628 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3629 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3630 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3631 LR.getValueType(), LL, RL); 3632 AddToWorklist(ORNode.getNode()); 3633 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3634 } 3635 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3636 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3637 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3638 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3639 LR.getValueType(), LL, RL); 3640 AddToWorklist(ANDNode.getNode()); 3641 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3642 } 3643 } 3644 // canonicalize equivalent to ll == rl 3645 if (LL == RR && LR == RL) { 3646 Op1 = ISD::getSetCCSwappedOperands(Op1); 3647 std::swap(RL, RR); 3648 } 3649 if (LL == RL && LR == RR) { 3650 bool isInteger = LL.getValueType().isInteger(); 3651 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3652 if (Result != ISD::SETCC_INVALID && 3653 (!LegalOperations || 3654 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3655 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3656 EVT CCVT = getSetCCResultType(LL.getValueType()); 3657 if (N0.getValueType() == CCVT || 3658 (!LegalOperations && N0.getValueType() == MVT::i1)) 3659 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3660 LL, LR, Result); 3661 } 3662 } 3663 } 3664 3665 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3666 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3667 // Don't increase # computations. 3668 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3669 // We can only do this xform if we know that bits from X that are set in C2 3670 // but not in C1 are already zero. Likewise for Y. 3671 if (const ConstantSDNode *N0O1C = 3672 getAsNonOpaqueConstant(N0.getOperand(1))) { 3673 if (const ConstantSDNode *N1O1C = 3674 getAsNonOpaqueConstant(N1.getOperand(1))) { 3675 // We can only do this xform if we know that bits from X that are set in 3676 // C2 but not in C1 are already zero. Likewise for Y. 3677 const APInt &LHSMask = N0O1C->getAPIntValue(); 3678 const APInt &RHSMask = N1O1C->getAPIntValue(); 3679 3680 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3681 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3682 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3683 N0.getOperand(0), N1.getOperand(0)); 3684 SDLoc DL(LocReference); 3685 return DAG.getNode(ISD::AND, DL, VT, X, 3686 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3687 } 3688 } 3689 } 3690 } 3691 3692 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3693 if (N0.getOpcode() == ISD::AND && 3694 N1.getOpcode() == ISD::AND && 3695 N0.getOperand(0) == N1.getOperand(0) && 3696 // Don't increase # computations. 3697 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3698 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3699 N0.getOperand(1), N1.getOperand(1)); 3700 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3701 } 3702 3703 return SDValue(); 3704 } 3705 3706 SDValue DAGCombiner::visitOR(SDNode *N) { 3707 SDValue N0 = N->getOperand(0); 3708 SDValue N1 = N->getOperand(1); 3709 EVT VT = N1.getValueType(); 3710 3711 // fold vector ops 3712 if (VT.isVector()) { 3713 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3714 return FoldedVOp; 3715 3716 // fold (or x, 0) -> x, vector edition 3717 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3718 return N1; 3719 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3720 return N0; 3721 3722 // fold (or x, -1) -> -1, vector edition 3723 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3724 // do not return N0, because undef node may exist in N0 3725 return DAG.getConstant( 3726 APInt::getAllOnesValue( 3727 N0.getValueType().getScalarType().getSizeInBits()), 3728 SDLoc(N), N0.getValueType()); 3729 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3730 // do not return N1, because undef node may exist in N1 3731 return DAG.getConstant( 3732 APInt::getAllOnesValue( 3733 N1.getValueType().getScalarType().getSizeInBits()), 3734 SDLoc(N), N1.getValueType()); 3735 3736 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 3737 // Do this only if the resulting shuffle is legal. 3738 if (isa<ShuffleVectorSDNode>(N0) && 3739 isa<ShuffleVectorSDNode>(N1) && 3740 // Avoid folding a node with illegal type. 3741 TLI.isTypeLegal(VT)) { 3742 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 3743 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 3744 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 3745 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 3746 // Ensure both shuffles have a zero input. 3747 if ((ZeroN00 || ZeroN01) && (ZeroN10 || ZeroN11)) { 3748 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 3749 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 3750 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3751 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3752 bool CanFold = true; 3753 int NumElts = VT.getVectorNumElements(); 3754 SmallVector<int, 4> Mask(NumElts); 3755 3756 for (int i = 0; i != NumElts; ++i) { 3757 int M0 = SV0->getMaskElt(i); 3758 int M1 = SV1->getMaskElt(i); 3759 3760 // Determine if either index is pointing to a zero vector. 3761 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 3762 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 3763 3764 // If one element is zero and the otherside is undef, keep undef. 3765 // This also handles the case that both are undef. 3766 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 3767 Mask[i] = -1; 3768 continue; 3769 } 3770 3771 // Make sure only one of the elements is zero. 3772 if (M0Zero == M1Zero) { 3773 CanFold = false; 3774 break; 3775 } 3776 3777 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 3778 3779 // We have a zero and non-zero element. If the non-zero came from 3780 // SV0 make the index a LHS index. If it came from SV1, make it 3781 // a RHS index. We need to mod by NumElts because we don't care 3782 // which operand it came from in the original shuffles. 3783 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 3784 } 3785 3786 if (CanFold) { 3787 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 3788 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 3789 3790 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3791 if (!LegalMask) { 3792 std::swap(NewLHS, NewRHS); 3793 ShuffleVectorSDNode::commuteMask(Mask); 3794 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 3795 } 3796 3797 if (LegalMask) 3798 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 3799 } 3800 } 3801 } 3802 } 3803 3804 // fold (or c1, c2) -> c1|c2 3805 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3806 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3807 if (N0C && N1C && !N1C->isOpaque()) 3808 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3809 // canonicalize constant to RHS 3810 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3811 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3812 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3813 // fold (or x, 0) -> x 3814 if (isNullConstant(N1)) 3815 return N0; 3816 // fold (or x, -1) -> -1 3817 if (isAllOnesConstant(N1)) 3818 return N1; 3819 // fold (or x, c) -> c iff (x & ~c) == 0 3820 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3821 return N1; 3822 3823 if (SDValue Combined = visitORLike(N0, N1, N)) 3824 return Combined; 3825 3826 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3827 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3828 return BSwap; 3829 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3830 return BSwap; 3831 3832 // reassociate or 3833 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3834 return ROR; 3835 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3836 // iff (c1 & c2) == 0. 3837 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3838 isa<ConstantSDNode>(N0.getOperand(1))) { 3839 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3840 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3841 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3842 N1C, C1)) 3843 return DAG.getNode( 3844 ISD::AND, SDLoc(N), VT, 3845 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3846 return SDValue(); 3847 } 3848 } 3849 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3850 if (N0.getOpcode() == N1.getOpcode()) 3851 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3852 return Tmp; 3853 3854 // See if this is some rotate idiom. 3855 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3856 return SDValue(Rot, 0); 3857 3858 // Simplify the operands using demanded-bits information. 3859 if (!VT.isVector() && 3860 SimplifyDemandedBits(SDValue(N, 0))) 3861 return SDValue(N, 0); 3862 3863 return SDValue(); 3864 } 3865 3866 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3867 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3868 if (Op.getOpcode() == ISD::AND) { 3869 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3870 Mask = Op.getOperand(1); 3871 Op = Op.getOperand(0); 3872 } else { 3873 return false; 3874 } 3875 } 3876 3877 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3878 Shift = Op; 3879 return true; 3880 } 3881 3882 return false; 3883 } 3884 3885 // Return true if we can prove that, whenever Neg and Pos are both in the 3886 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 3887 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3888 // 3889 // (or (shift1 X, Neg), (shift2 X, Pos)) 3890 // 3891 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3892 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 3893 // to consider shift amounts with defined behavior. 3894 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 3895 // If EltSize is a power of 2 then: 3896 // 3897 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 3898 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 3899 // 3900 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 3901 // for the stronger condition: 3902 // 3903 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 3904 // 3905 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 3906 // we can just replace Neg with Neg' for the rest of the function. 3907 // 3908 // In other cases we check for the even stronger condition: 3909 // 3910 // Neg == EltSize - Pos [B] 3911 // 3912 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3913 // behavior if Pos == 0 (and consequently Neg == EltSize). 3914 // 3915 // We could actually use [A] whenever EltSize is a power of 2, but the 3916 // only extra cases that it would match are those uninteresting ones 3917 // where Neg and Pos are never in range at the same time. E.g. for 3918 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3919 // as well as (sub 32, Pos), but: 3920 // 3921 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3922 // 3923 // always invokes undefined behavior for 32-bit X. 3924 // 3925 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 3926 unsigned MaskLoBits = 0; 3927 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 3928 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 3929 if (NegC->getAPIntValue() == EltSize - 1) { 3930 Neg = Neg.getOperand(0); 3931 MaskLoBits = Log2_64(EltSize); 3932 } 3933 } 3934 } 3935 3936 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3937 if (Neg.getOpcode() != ISD::SUB) 3938 return false; 3939 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 3940 if (!NegC) 3941 return false; 3942 SDValue NegOp1 = Neg.getOperand(1); 3943 3944 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 3945 // Pos'. The truncation is redundant for the purpose of the equality. 3946 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 3947 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3948 if (PosC->getAPIntValue() == EltSize - 1) 3949 Pos = Pos.getOperand(0); 3950 3951 // The condition we need is now: 3952 // 3953 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 3954 // 3955 // If NegOp1 == Pos then we need: 3956 // 3957 // EltSize & Mask == NegC & Mask 3958 // 3959 // (because "x & Mask" is a truncation and distributes through subtraction). 3960 APInt Width; 3961 if (Pos == NegOp1) 3962 Width = NegC->getAPIntValue(); 3963 3964 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3965 // Then the condition we want to prove becomes: 3966 // 3967 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 3968 // 3969 // which, again because "x & Mask" is a truncation, becomes: 3970 // 3971 // NegC & Mask == (EltSize - PosC) & Mask 3972 // EltSize & Mask == (NegC + PosC) & Mask 3973 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 3974 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3975 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 3976 else 3977 return false; 3978 } else 3979 return false; 3980 3981 // Now we just need to check that EltSize & Mask == Width & Mask. 3982 if (MaskLoBits) 3983 // EltSize & Mask is 0 since Mask is EltSize - 1. 3984 return Width.getLoBits(MaskLoBits) == 0; 3985 return Width == EltSize; 3986 } 3987 3988 // A subroutine of MatchRotate used once we have found an OR of two opposite 3989 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3990 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3991 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3992 // Neg with outer conversions stripped away. 3993 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3994 SDValue Neg, SDValue InnerPos, 3995 SDValue InnerNeg, unsigned PosOpcode, 3996 unsigned NegOpcode, const SDLoc &DL) { 3997 // fold (or (shl x, (*ext y)), 3998 // (srl x, (*ext (sub 32, y)))) -> 3999 // (rotl x, y) or (rotr x, (sub 32, y)) 4000 // 4001 // fold (or (shl x, (*ext (sub 32, y))), 4002 // (srl x, (*ext y))) -> 4003 // (rotr x, y) or (rotl x, (sub 32, y)) 4004 EVT VT = Shifted.getValueType(); 4005 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4006 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4007 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4008 HasPos ? Pos : Neg).getNode(); 4009 } 4010 4011 return nullptr; 4012 } 4013 4014 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4015 // idioms for rotate, and if the target supports rotation instructions, generate 4016 // a rot[lr]. 4017 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 4018 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4019 EVT VT = LHS.getValueType(); 4020 if (!TLI.isTypeLegal(VT)) return nullptr; 4021 4022 // The target must have at least one rotate flavor. 4023 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4024 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4025 if (!HasROTL && !HasROTR) return nullptr; 4026 4027 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4028 SDValue LHSShift; // The shift. 4029 SDValue LHSMask; // AND value if any. 4030 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4031 return nullptr; // Not part of a rotate. 4032 4033 SDValue RHSShift; // The shift. 4034 SDValue RHSMask; // AND value if any. 4035 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4036 return nullptr; // Not part of a rotate. 4037 4038 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4039 return nullptr; // Not shifting the same value. 4040 4041 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4042 return nullptr; // Shifts must disagree. 4043 4044 // Canonicalize shl to left side in a shl/srl pair. 4045 if (RHSShift.getOpcode() == ISD::SHL) { 4046 std::swap(LHS, RHS); 4047 std::swap(LHSShift, RHSShift); 4048 std::swap(LHSMask, RHSMask); 4049 } 4050 4051 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4052 SDValue LHSShiftArg = LHSShift.getOperand(0); 4053 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4054 SDValue RHSShiftArg = RHSShift.getOperand(0); 4055 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4056 4057 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4058 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4059 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4060 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4061 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4062 if ((LShVal + RShVal) != EltSizeInBits) 4063 return nullptr; 4064 4065 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4066 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4067 4068 // If there is an AND of either shifted operand, apply it to the result. 4069 if (LHSMask.getNode() || RHSMask.getNode()) { 4070 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4071 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4072 4073 if (LHSMask.getNode()) { 4074 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4075 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4076 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4077 DAG.getConstant(RHSBits, DL, VT))); 4078 } 4079 if (RHSMask.getNode()) { 4080 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4081 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4082 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4083 DAG.getConstant(LHSBits, DL, VT))); 4084 } 4085 4086 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4087 } 4088 4089 return Rot.getNode(); 4090 } 4091 4092 // If there is a mask here, and we have a variable shift, we can't be sure 4093 // that we're masking out the right stuff. 4094 if (LHSMask.getNode() || RHSMask.getNode()) 4095 return nullptr; 4096 4097 // If the shift amount is sign/zext/any-extended just peel it off. 4098 SDValue LExtOp0 = LHSShiftAmt; 4099 SDValue RExtOp0 = RHSShiftAmt; 4100 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4101 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4102 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4103 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4104 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4105 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4106 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4107 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4108 LExtOp0 = LHSShiftAmt.getOperand(0); 4109 RExtOp0 = RHSShiftAmt.getOperand(0); 4110 } 4111 4112 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4113 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4114 if (TryL) 4115 return TryL; 4116 4117 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4118 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4119 if (TryR) 4120 return TryR; 4121 4122 return nullptr; 4123 } 4124 4125 SDValue DAGCombiner::visitXOR(SDNode *N) { 4126 SDValue N0 = N->getOperand(0); 4127 SDValue N1 = N->getOperand(1); 4128 EVT VT = N0.getValueType(); 4129 4130 // fold vector ops 4131 if (VT.isVector()) { 4132 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4133 return FoldedVOp; 4134 4135 // fold (xor x, 0) -> x, vector edition 4136 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4137 return N1; 4138 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4139 return N0; 4140 } 4141 4142 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4143 if (N0.isUndef() && N1.isUndef()) 4144 return DAG.getConstant(0, SDLoc(N), VT); 4145 // fold (xor x, undef) -> undef 4146 if (N0.isUndef()) 4147 return N0; 4148 if (N1.isUndef()) 4149 return N1; 4150 // fold (xor c1, c2) -> c1^c2 4151 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4152 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4153 if (N0C && N1C) 4154 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4155 // canonicalize constant to RHS 4156 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4157 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4158 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4159 // fold (xor x, 0) -> x 4160 if (isNullConstant(N1)) 4161 return N0; 4162 // reassociate xor 4163 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4164 return RXOR; 4165 4166 // fold !(x cc y) -> (x !cc y) 4167 SDValue LHS, RHS, CC; 4168 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4169 bool isInt = LHS.getValueType().isInteger(); 4170 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4171 isInt); 4172 4173 if (!LegalOperations || 4174 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4175 switch (N0.getOpcode()) { 4176 default: 4177 llvm_unreachable("Unhandled SetCC Equivalent!"); 4178 case ISD::SETCC: 4179 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4180 case ISD::SELECT_CC: 4181 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4182 N0.getOperand(3), NotCC); 4183 } 4184 } 4185 } 4186 4187 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4188 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4189 N0.getNode()->hasOneUse() && 4190 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4191 SDValue V = N0.getOperand(0); 4192 SDLoc DL(N0); 4193 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4194 DAG.getConstant(1, DL, V.getValueType())); 4195 AddToWorklist(V.getNode()); 4196 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4197 } 4198 4199 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4200 if (isOneConstant(N1) && VT == MVT::i1 && 4201 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4202 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4203 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4204 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4205 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4206 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4207 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4208 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4209 } 4210 } 4211 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4212 if (isAllOnesConstant(N1) && 4213 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4214 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4215 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4216 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4217 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4218 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4219 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4220 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4221 } 4222 } 4223 // fold (xor (and x, y), y) -> (and (not x), y) 4224 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4225 N0->getOperand(1) == N1) { 4226 SDValue X = N0->getOperand(0); 4227 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4228 AddToWorklist(NotX.getNode()); 4229 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4230 } 4231 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4232 if (N1C && N0.getOpcode() == ISD::XOR) { 4233 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4234 SDLoc DL(N); 4235 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4236 DAG.getConstant(N1C->getAPIntValue() ^ 4237 N00C->getAPIntValue(), DL, VT)); 4238 } 4239 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4240 SDLoc DL(N); 4241 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4242 DAG.getConstant(N1C->getAPIntValue() ^ 4243 N01C->getAPIntValue(), DL, VT)); 4244 } 4245 } 4246 // fold (xor x, x) -> 0 4247 if (N0 == N1) 4248 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4249 4250 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4251 // Here is a concrete example of this equivalence: 4252 // i16 x == 14 4253 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4254 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4255 // 4256 // => 4257 // 4258 // i16 ~1 == 0b1111111111111110 4259 // i16 rol(~1, 14) == 0b1011111111111111 4260 // 4261 // Some additional tips to help conceptualize this transform: 4262 // - Try to see the operation as placing a single zero in a value of all ones. 4263 // - There exists no value for x which would allow the result to contain zero. 4264 // - Values of x larger than the bitwidth are undefined and do not require a 4265 // consistent result. 4266 // - Pushing the zero left requires shifting one bits in from the right. 4267 // A rotate left of ~1 is a nice way of achieving the desired result. 4268 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4269 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4270 SDLoc DL(N); 4271 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4272 N0.getOperand(1)); 4273 } 4274 4275 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4276 if (N0.getOpcode() == N1.getOpcode()) 4277 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4278 return Tmp; 4279 4280 // Simplify the expression using non-local knowledge. 4281 if (!VT.isVector() && 4282 SimplifyDemandedBits(SDValue(N, 0))) 4283 return SDValue(N, 0); 4284 4285 return SDValue(); 4286 } 4287 4288 /// Handle transforms common to the three shifts, when the shift amount is a 4289 /// constant. 4290 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4291 SDNode *LHS = N->getOperand(0).getNode(); 4292 if (!LHS->hasOneUse()) return SDValue(); 4293 4294 // We want to pull some binops through shifts, so that we have (and (shift)) 4295 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4296 // thing happens with address calculations, so it's important to canonicalize 4297 // it. 4298 bool HighBitSet = false; // Can we transform this if the high bit is set? 4299 4300 switch (LHS->getOpcode()) { 4301 default: return SDValue(); 4302 case ISD::OR: 4303 case ISD::XOR: 4304 HighBitSet = false; // We can only transform sra if the high bit is clear. 4305 break; 4306 case ISD::AND: 4307 HighBitSet = true; // We can only transform sra if the high bit is set. 4308 break; 4309 case ISD::ADD: 4310 if (N->getOpcode() != ISD::SHL) 4311 return SDValue(); // only shl(add) not sr[al](add). 4312 HighBitSet = false; // We can only transform sra if the high bit is clear. 4313 break; 4314 } 4315 4316 // We require the RHS of the binop to be a constant and not opaque as well. 4317 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4318 if (!BinOpCst) return SDValue(); 4319 4320 // FIXME: disable this unless the input to the binop is a shift by a constant. 4321 // If it is not a shift, it pessimizes some common cases like: 4322 // 4323 // void foo(int *X, int i) { X[i & 1235] = 1; } 4324 // int bar(int *X, int i) { return X[i & 255]; } 4325 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4326 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4327 BinOpLHSVal->getOpcode() != ISD::SRA && 4328 BinOpLHSVal->getOpcode() != ISD::SRL) || 4329 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4330 return SDValue(); 4331 4332 EVT VT = N->getValueType(0); 4333 4334 // If this is a signed shift right, and the high bit is modified by the 4335 // logical operation, do not perform the transformation. The highBitSet 4336 // boolean indicates the value of the high bit of the constant which would 4337 // cause it to be modified for this operation. 4338 if (N->getOpcode() == ISD::SRA) { 4339 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4340 if (BinOpRHSSignSet != HighBitSet) 4341 return SDValue(); 4342 } 4343 4344 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4345 return SDValue(); 4346 4347 // Fold the constants, shifting the binop RHS by the shift amount. 4348 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4349 N->getValueType(0), 4350 LHS->getOperand(1), N->getOperand(1)); 4351 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4352 4353 // Create the new shift. 4354 SDValue NewShift = DAG.getNode(N->getOpcode(), 4355 SDLoc(LHS->getOperand(0)), 4356 VT, LHS->getOperand(0), N->getOperand(1)); 4357 4358 // Create the new binop. 4359 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4360 } 4361 4362 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4363 assert(N->getOpcode() == ISD::TRUNCATE); 4364 assert(N->getOperand(0).getOpcode() == ISD::AND); 4365 4366 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4367 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4368 SDValue N01 = N->getOperand(0).getOperand(1); 4369 4370 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4371 if (!N01C->isOpaque()) { 4372 EVT TruncVT = N->getValueType(0); 4373 SDValue N00 = N->getOperand(0).getOperand(0); 4374 APInt TruncC = N01C->getAPIntValue(); 4375 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4376 SDLoc DL(N); 4377 4378 return DAG.getNode(ISD::AND, DL, TruncVT, 4379 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4380 DAG.getConstant(TruncC, DL, TruncVT)); 4381 } 4382 } 4383 } 4384 4385 return SDValue(); 4386 } 4387 4388 SDValue DAGCombiner::visitRotate(SDNode *N) { 4389 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4390 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4391 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4392 if (SDValue NewOp1 = 4393 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 4394 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4395 N->getOperand(0), NewOp1); 4396 } 4397 return SDValue(); 4398 } 4399 4400 SDValue DAGCombiner::visitSHL(SDNode *N) { 4401 SDValue N0 = N->getOperand(0); 4402 SDValue N1 = N->getOperand(1); 4403 EVT VT = N0.getValueType(); 4404 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4405 4406 // fold vector ops 4407 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4408 if (VT.isVector()) { 4409 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4410 return FoldedVOp; 4411 4412 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4413 // If setcc produces all-one true value then: 4414 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4415 if (N1CV && N1CV->isConstant()) { 4416 if (N0.getOpcode() == ISD::AND) { 4417 SDValue N00 = N0->getOperand(0); 4418 SDValue N01 = N0->getOperand(1); 4419 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4420 4421 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4422 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4423 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4424 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4425 N01CV, N1CV)) 4426 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4427 } 4428 } else { 4429 N1C = isConstOrConstSplat(N1); 4430 } 4431 } 4432 } 4433 4434 // fold (shl c1, c2) -> c1<<c2 4435 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4436 if (N0C && N1C && !N1C->isOpaque()) 4437 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4438 // fold (shl 0, x) -> 0 4439 if (isNullConstant(N0)) 4440 return N0; 4441 // fold (shl x, c >= size(x)) -> undef 4442 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4443 return DAG.getUNDEF(VT); 4444 // fold (shl x, 0) -> x 4445 if (N1C && N1C->isNullValue()) 4446 return N0; 4447 // fold (shl undef, x) -> 0 4448 if (N0.isUndef()) 4449 return DAG.getConstant(0, SDLoc(N), VT); 4450 // if (shl x, c) is known to be zero, return 0 4451 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4452 APInt::getAllOnesValue(OpSizeInBits))) 4453 return DAG.getConstant(0, SDLoc(N), VT); 4454 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4455 if (N1.getOpcode() == ISD::TRUNCATE && 4456 N1.getOperand(0).getOpcode() == ISD::AND) { 4457 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4458 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4459 } 4460 4461 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4462 return SDValue(N, 0); 4463 4464 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4465 if (N1C && N0.getOpcode() == ISD::SHL) { 4466 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4467 uint64_t c1 = N0C1->getZExtValue(); 4468 uint64_t c2 = N1C->getZExtValue(); 4469 SDLoc DL(N); 4470 if (c1 + c2 >= OpSizeInBits) 4471 return DAG.getConstant(0, DL, VT); 4472 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4473 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4474 } 4475 } 4476 4477 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4478 // For this to be valid, the second form must not preserve any of the bits 4479 // that are shifted out by the inner shift in the first form. This means 4480 // the outer shift size must be >= the number of bits added by the ext. 4481 // As a corollary, we don't care what kind of ext it is. 4482 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4483 N0.getOpcode() == ISD::ANY_EXTEND || 4484 N0.getOpcode() == ISD::SIGN_EXTEND) && 4485 N0.getOperand(0).getOpcode() == ISD::SHL) { 4486 SDValue N0Op0 = N0.getOperand(0); 4487 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4488 uint64_t c1 = N0Op0C1->getZExtValue(); 4489 uint64_t c2 = N1C->getZExtValue(); 4490 EVT InnerShiftVT = N0Op0.getValueType(); 4491 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4492 if (c2 >= OpSizeInBits - InnerShiftSize) { 4493 SDLoc DL(N0); 4494 if (c1 + c2 >= OpSizeInBits) 4495 return DAG.getConstant(0, DL, VT); 4496 return DAG.getNode(ISD::SHL, DL, VT, 4497 DAG.getNode(N0.getOpcode(), DL, VT, 4498 N0Op0->getOperand(0)), 4499 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4500 } 4501 } 4502 } 4503 4504 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4505 // Only fold this if the inner zext has no other uses to avoid increasing 4506 // the total number of instructions. 4507 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4508 N0.getOperand(0).getOpcode() == ISD::SRL) { 4509 SDValue N0Op0 = N0.getOperand(0); 4510 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4511 uint64_t c1 = N0Op0C1->getZExtValue(); 4512 if (c1 < VT.getScalarSizeInBits()) { 4513 uint64_t c2 = N1C->getZExtValue(); 4514 if (c1 == c2) { 4515 SDValue NewOp0 = N0.getOperand(0); 4516 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4517 SDLoc DL(N); 4518 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4519 NewOp0, 4520 DAG.getConstant(c2, DL, CountVT)); 4521 AddToWorklist(NewSHL.getNode()); 4522 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4523 } 4524 } 4525 } 4526 } 4527 4528 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4529 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4530 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4531 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4532 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4533 uint64_t C1 = N0C1->getZExtValue(); 4534 uint64_t C2 = N1C->getZExtValue(); 4535 SDLoc DL(N); 4536 if (C1 <= C2) 4537 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4538 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4539 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4540 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4541 } 4542 } 4543 4544 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4545 // (and (srl x, (sub c1, c2), MASK) 4546 // Only fold this if the inner shift has no other uses -- if it does, folding 4547 // this will increase the total number of instructions. 4548 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4549 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4550 uint64_t c1 = N0C1->getZExtValue(); 4551 if (c1 < OpSizeInBits) { 4552 uint64_t c2 = N1C->getZExtValue(); 4553 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4554 SDValue Shift; 4555 if (c2 > c1) { 4556 Mask = Mask.shl(c2 - c1); 4557 SDLoc DL(N); 4558 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4559 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4560 } else { 4561 Mask = Mask.lshr(c1 - c2); 4562 SDLoc DL(N); 4563 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4564 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4565 } 4566 SDLoc DL(N0); 4567 return DAG.getNode(ISD::AND, DL, VT, Shift, 4568 DAG.getConstant(Mask, DL, VT)); 4569 } 4570 } 4571 } 4572 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4573 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4574 unsigned BitSize = VT.getScalarSizeInBits(); 4575 SDLoc DL(N); 4576 SDValue HiBitsMask = 4577 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4578 BitSize - N1C->getZExtValue()), 4579 DL, VT); 4580 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4581 HiBitsMask); 4582 } 4583 4584 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4585 // Variant of version done on multiply, except mul by a power of 2 is turned 4586 // into a shift. 4587 APInt Val; 4588 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4589 (isa<ConstantSDNode>(N0.getOperand(1)) || 4590 ISD::isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4591 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4592 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4593 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4594 } 4595 4596 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4597 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4598 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4599 if (SDValue Folded = 4600 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4601 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4602 } 4603 } 4604 4605 if (N1C && !N1C->isOpaque()) 4606 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4607 return NewSHL; 4608 4609 return SDValue(); 4610 } 4611 4612 SDValue DAGCombiner::visitSRA(SDNode *N) { 4613 SDValue N0 = N->getOperand(0); 4614 SDValue N1 = N->getOperand(1); 4615 EVT VT = N0.getValueType(); 4616 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4617 4618 // fold vector ops 4619 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4620 if (VT.isVector()) { 4621 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4622 return FoldedVOp; 4623 4624 N1C = isConstOrConstSplat(N1); 4625 } 4626 4627 // fold (sra c1, c2) -> (sra c1, c2) 4628 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4629 if (N0C && N1C && !N1C->isOpaque()) 4630 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4631 // fold (sra 0, x) -> 0 4632 if (isNullConstant(N0)) 4633 return N0; 4634 // fold (sra -1, x) -> -1 4635 if (isAllOnesConstant(N0)) 4636 return N0; 4637 // fold (sra x, c >= size(x)) -> undef 4638 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4639 return DAG.getUNDEF(VT); 4640 // fold (sra x, 0) -> x 4641 if (N1C && N1C->isNullValue()) 4642 return N0; 4643 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4644 // sext_inreg. 4645 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4646 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4647 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4648 if (VT.isVector()) 4649 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4650 ExtVT, VT.getVectorNumElements()); 4651 if ((!LegalOperations || 4652 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4653 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4654 N0.getOperand(0), DAG.getValueType(ExtVT)); 4655 } 4656 4657 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4658 if (N1C && N0.getOpcode() == ISD::SRA) { 4659 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4660 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4661 if (Sum >= OpSizeInBits) 4662 Sum = OpSizeInBits - 1; 4663 SDLoc DL(N); 4664 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4665 DAG.getConstant(Sum, DL, N1.getValueType())); 4666 } 4667 } 4668 4669 // fold (sra (shl X, m), (sub result_size, n)) 4670 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4671 // result_size - n != m. 4672 // If truncate is free for the target sext(shl) is likely to result in better 4673 // code. 4674 if (N0.getOpcode() == ISD::SHL && N1C) { 4675 // Get the two constanst of the shifts, CN0 = m, CN = n. 4676 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4677 if (N01C) { 4678 LLVMContext &Ctx = *DAG.getContext(); 4679 // Determine what the truncate's result bitsize and type would be. 4680 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4681 4682 if (VT.isVector()) 4683 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4684 4685 // Determine the residual right-shift amount. 4686 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4687 4688 // If the shift is not a no-op (in which case this should be just a sign 4689 // extend already), the truncated to type is legal, sign_extend is legal 4690 // on that type, and the truncate to that type is both legal and free, 4691 // perform the transform. 4692 if ((ShiftAmt > 0) && 4693 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4694 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4695 TLI.isTruncateFree(VT, TruncVT)) { 4696 4697 SDLoc DL(N); 4698 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4699 getShiftAmountTy(N0.getOperand(0).getValueType())); 4700 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4701 N0.getOperand(0), Amt); 4702 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4703 Shift); 4704 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4705 N->getValueType(0), Trunc); 4706 } 4707 } 4708 } 4709 4710 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4711 if (N1.getOpcode() == ISD::TRUNCATE && 4712 N1.getOperand(0).getOpcode() == ISD::AND) { 4713 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4714 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4715 } 4716 4717 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4718 // if c1 is equal to the number of bits the trunc removes 4719 if (N0.getOpcode() == ISD::TRUNCATE && 4720 (N0.getOperand(0).getOpcode() == ISD::SRL || 4721 N0.getOperand(0).getOpcode() == ISD::SRA) && 4722 N0.getOperand(0).hasOneUse() && 4723 N0.getOperand(0).getOperand(1).hasOneUse() && 4724 N1C) { 4725 SDValue N0Op0 = N0.getOperand(0); 4726 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4727 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4728 EVT LargeVT = N0Op0.getValueType(); 4729 4730 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4731 SDLoc DL(N); 4732 SDValue Amt = 4733 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4734 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4735 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4736 N0Op0.getOperand(0), Amt); 4737 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4738 } 4739 } 4740 } 4741 4742 // Simplify, based on bits shifted out of the LHS. 4743 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4744 return SDValue(N, 0); 4745 4746 4747 // If the sign bit is known to be zero, switch this to a SRL. 4748 if (DAG.SignBitIsZero(N0)) 4749 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4750 4751 if (N1C && !N1C->isOpaque()) 4752 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4753 return NewSRA; 4754 4755 return SDValue(); 4756 } 4757 4758 SDValue DAGCombiner::visitSRL(SDNode *N) { 4759 SDValue N0 = N->getOperand(0); 4760 SDValue N1 = N->getOperand(1); 4761 EVT VT = N0.getValueType(); 4762 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4763 4764 // fold vector ops 4765 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4766 if (VT.isVector()) { 4767 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4768 return FoldedVOp; 4769 4770 N1C = isConstOrConstSplat(N1); 4771 } 4772 4773 // fold (srl c1, c2) -> c1 >>u c2 4774 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4775 if (N0C && N1C && !N1C->isOpaque()) 4776 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4777 // fold (srl 0, x) -> 0 4778 if (isNullConstant(N0)) 4779 return N0; 4780 // fold (srl x, c >= size(x)) -> undef 4781 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4782 return DAG.getUNDEF(VT); 4783 // fold (srl x, 0) -> x 4784 if (N1C && N1C->isNullValue()) 4785 return N0; 4786 // if (srl x, c) is known to be zero, return 0 4787 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4788 APInt::getAllOnesValue(OpSizeInBits))) 4789 return DAG.getConstant(0, SDLoc(N), VT); 4790 4791 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4792 if (N1C && N0.getOpcode() == ISD::SRL) { 4793 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4794 uint64_t c1 = N01C->getZExtValue(); 4795 uint64_t c2 = N1C->getZExtValue(); 4796 SDLoc DL(N); 4797 if (c1 + c2 >= OpSizeInBits) 4798 return DAG.getConstant(0, DL, VT); 4799 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4800 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4801 } 4802 } 4803 4804 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4805 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4806 N0.getOperand(0).getOpcode() == ISD::SRL && 4807 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4808 uint64_t c1 = 4809 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4810 uint64_t c2 = N1C->getZExtValue(); 4811 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4812 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4813 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4814 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4815 if (c1 + OpSizeInBits == InnerShiftSize) { 4816 SDLoc DL(N0); 4817 if (c1 + c2 >= InnerShiftSize) 4818 return DAG.getConstant(0, DL, VT); 4819 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4820 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4821 N0.getOperand(0)->getOperand(0), 4822 DAG.getConstant(c1 + c2, DL, 4823 ShiftCountVT))); 4824 } 4825 } 4826 4827 // fold (srl (shl x, c), c) -> (and x, cst2) 4828 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4829 unsigned BitSize = N0.getScalarValueSizeInBits(); 4830 if (BitSize <= 64) { 4831 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4832 SDLoc DL(N); 4833 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4834 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4835 } 4836 } 4837 4838 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4839 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4840 // Shifting in all undef bits? 4841 EVT SmallVT = N0.getOperand(0).getValueType(); 4842 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4843 if (N1C->getZExtValue() >= BitSize) 4844 return DAG.getUNDEF(VT); 4845 4846 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4847 uint64_t ShiftAmt = N1C->getZExtValue(); 4848 SDLoc DL0(N0); 4849 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4850 N0.getOperand(0), 4851 DAG.getConstant(ShiftAmt, DL0, 4852 getShiftAmountTy(SmallVT))); 4853 AddToWorklist(SmallShift.getNode()); 4854 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4855 SDLoc DL(N); 4856 return DAG.getNode(ISD::AND, DL, VT, 4857 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4858 DAG.getConstant(Mask, DL, VT)); 4859 } 4860 } 4861 4862 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4863 // bit, which is unmodified by sra. 4864 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4865 if (N0.getOpcode() == ISD::SRA) 4866 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4867 } 4868 4869 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4870 if (N1C && N0.getOpcode() == ISD::CTLZ && 4871 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4872 APInt KnownZero, KnownOne; 4873 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4874 4875 // If any of the input bits are KnownOne, then the input couldn't be all 4876 // zeros, thus the result of the srl will always be zero. 4877 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4878 4879 // If all of the bits input the to ctlz node are known to be zero, then 4880 // the result of the ctlz is "32" and the result of the shift is one. 4881 APInt UnknownBits = ~KnownZero; 4882 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4883 4884 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4885 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4886 // Okay, we know that only that the single bit specified by UnknownBits 4887 // could be set on input to the CTLZ node. If this bit is set, the SRL 4888 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4889 // to an SRL/XOR pair, which is likely to simplify more. 4890 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4891 SDValue Op = N0.getOperand(0); 4892 4893 if (ShAmt) { 4894 SDLoc DL(N0); 4895 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4896 DAG.getConstant(ShAmt, DL, 4897 getShiftAmountTy(Op.getValueType()))); 4898 AddToWorklist(Op.getNode()); 4899 } 4900 4901 SDLoc DL(N); 4902 return DAG.getNode(ISD::XOR, DL, VT, 4903 Op, DAG.getConstant(1, DL, VT)); 4904 } 4905 } 4906 4907 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4908 if (N1.getOpcode() == ISD::TRUNCATE && 4909 N1.getOperand(0).getOpcode() == ISD::AND) { 4910 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4911 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4912 } 4913 4914 // fold operands of srl based on knowledge that the low bits are not 4915 // demanded. 4916 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4917 return SDValue(N, 0); 4918 4919 if (N1C && !N1C->isOpaque()) 4920 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4921 return NewSRL; 4922 4923 // Attempt to convert a srl of a load into a narrower zero-extending load. 4924 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4925 return NarrowLoad; 4926 4927 // Here is a common situation. We want to optimize: 4928 // 4929 // %a = ... 4930 // %b = and i32 %a, 2 4931 // %c = srl i32 %b, 1 4932 // brcond i32 %c ... 4933 // 4934 // into 4935 // 4936 // %a = ... 4937 // %b = and %a, 2 4938 // %c = setcc eq %b, 0 4939 // brcond %c ... 4940 // 4941 // However when after the source operand of SRL is optimized into AND, the SRL 4942 // itself may not be optimized further. Look for it and add the BRCOND into 4943 // the worklist. 4944 if (N->hasOneUse()) { 4945 SDNode *Use = *N->use_begin(); 4946 if (Use->getOpcode() == ISD::BRCOND) 4947 AddToWorklist(Use); 4948 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4949 // Also look pass the truncate. 4950 Use = *Use->use_begin(); 4951 if (Use->getOpcode() == ISD::BRCOND) 4952 AddToWorklist(Use); 4953 } 4954 } 4955 4956 return SDValue(); 4957 } 4958 4959 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4960 SDValue N0 = N->getOperand(0); 4961 EVT VT = N->getValueType(0); 4962 4963 // fold (bswap c1) -> c2 4964 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4965 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4966 // fold (bswap (bswap x)) -> x 4967 if (N0.getOpcode() == ISD::BSWAP) 4968 return N0->getOperand(0); 4969 return SDValue(); 4970 } 4971 4972 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 4973 SDValue N0 = N->getOperand(0); 4974 4975 // fold (bitreverse (bitreverse x)) -> x 4976 if (N0.getOpcode() == ISD::BITREVERSE) 4977 return N0.getOperand(0); 4978 return SDValue(); 4979 } 4980 4981 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4982 SDValue N0 = N->getOperand(0); 4983 EVT VT = N->getValueType(0); 4984 4985 // fold (ctlz c1) -> c2 4986 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4987 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4988 return SDValue(); 4989 } 4990 4991 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4992 SDValue N0 = N->getOperand(0); 4993 EVT VT = N->getValueType(0); 4994 4995 // fold (ctlz_zero_undef c1) -> c2 4996 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4997 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4998 return SDValue(); 4999 } 5000 5001 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5002 SDValue N0 = N->getOperand(0); 5003 EVT VT = N->getValueType(0); 5004 5005 // fold (cttz c1) -> c2 5006 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5007 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5008 return SDValue(); 5009 } 5010 5011 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5012 SDValue N0 = N->getOperand(0); 5013 EVT VT = N->getValueType(0); 5014 5015 // fold (cttz_zero_undef c1) -> c2 5016 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5017 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5018 return SDValue(); 5019 } 5020 5021 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5022 SDValue N0 = N->getOperand(0); 5023 EVT VT = N->getValueType(0); 5024 5025 // fold (ctpop c1) -> c2 5026 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5027 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5028 return SDValue(); 5029 } 5030 5031 5032 /// \brief Generate Min/Max node 5033 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 5034 SDValue RHS, SDValue True, SDValue False, 5035 ISD::CondCode CC, const TargetLowering &TLI, 5036 SelectionDAG &DAG) { 5037 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5038 return SDValue(); 5039 5040 switch (CC) { 5041 case ISD::SETOLT: 5042 case ISD::SETOLE: 5043 case ISD::SETLT: 5044 case ISD::SETLE: 5045 case ISD::SETULT: 5046 case ISD::SETULE: { 5047 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5048 if (TLI.isOperationLegal(Opcode, VT)) 5049 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5050 return SDValue(); 5051 } 5052 case ISD::SETOGT: 5053 case ISD::SETOGE: 5054 case ISD::SETGT: 5055 case ISD::SETGE: 5056 case ISD::SETUGT: 5057 case ISD::SETUGE: { 5058 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5059 if (TLI.isOperationLegal(Opcode, VT)) 5060 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5061 return SDValue(); 5062 } 5063 default: 5064 return SDValue(); 5065 } 5066 } 5067 5068 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5069 SDValue N0 = N->getOperand(0); 5070 SDValue N1 = N->getOperand(1); 5071 SDValue N2 = N->getOperand(2); 5072 EVT VT = N->getValueType(0); 5073 EVT VT0 = N0.getValueType(); 5074 5075 // fold (select C, X, X) -> X 5076 if (N1 == N2) 5077 return N1; 5078 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5079 // fold (select true, X, Y) -> X 5080 // fold (select false, X, Y) -> Y 5081 return !N0C->isNullValue() ? N1 : N2; 5082 } 5083 // fold (select C, 1, X) -> (or C, X) 5084 if (VT == MVT::i1 && isOneConstant(N1)) 5085 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5086 // fold (select C, 0, 1) -> (xor C, 1) 5087 // We can't do this reliably if integer based booleans have different contents 5088 // to floating point based booleans. This is because we can't tell whether we 5089 // have an integer-based boolean or a floating-point-based boolean unless we 5090 // can find the SETCC that produced it and inspect its operands. This is 5091 // fairly easy if C is the SETCC node, but it can potentially be 5092 // undiscoverable (or not reasonably discoverable). For example, it could be 5093 // in another basic block or it could require searching a complicated 5094 // expression. 5095 if (VT.isInteger() && 5096 (VT0 == MVT::i1 || (VT0.isInteger() && 5097 TLI.getBooleanContents(false, false) == 5098 TLI.getBooleanContents(false, true) && 5099 TLI.getBooleanContents(false, false) == 5100 TargetLowering::ZeroOrOneBooleanContent)) && 5101 isNullConstant(N1) && isOneConstant(N2)) { 5102 SDValue XORNode; 5103 if (VT == VT0) { 5104 SDLoc DL(N); 5105 return DAG.getNode(ISD::XOR, DL, VT0, 5106 N0, DAG.getConstant(1, DL, VT0)); 5107 } 5108 SDLoc DL0(N0); 5109 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5110 N0, DAG.getConstant(1, DL0, VT0)); 5111 AddToWorklist(XORNode.getNode()); 5112 if (VT.bitsGT(VT0)) 5113 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5114 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5115 } 5116 // fold (select C, 0, X) -> (and (not C), X) 5117 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5118 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5119 AddToWorklist(NOTNode.getNode()); 5120 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5121 } 5122 // fold (select C, X, 1) -> (or (not C), X) 5123 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5124 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5125 AddToWorklist(NOTNode.getNode()); 5126 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5127 } 5128 // fold (select C, X, 0) -> (and C, X) 5129 if (VT == MVT::i1 && isNullConstant(N2)) 5130 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5131 // fold (select X, X, Y) -> (or X, Y) 5132 // fold (select X, 1, Y) -> (or X, Y) 5133 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5134 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5135 // fold (select X, Y, X) -> (and X, Y) 5136 // fold (select X, Y, 0) -> (and X, Y) 5137 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5138 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5139 5140 // If we can fold this based on the true/false value, do so. 5141 if (SimplifySelectOps(N, N1, N2)) 5142 return SDValue(N, 0); // Don't revisit N. 5143 5144 if (VT0 == MVT::i1) { 5145 // The code in this block deals with the following 2 equivalences: 5146 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5147 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5148 // The target can specify its prefered form with the 5149 // shouldNormalizeToSelectSequence() callback. However we always transform 5150 // to the right anyway if we find the inner select exists in the DAG anyway 5151 // and we always transform to the left side if we know that we can further 5152 // optimize the combination of the conditions. 5153 bool normalizeToSequence 5154 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5155 // select (and Cond0, Cond1), X, Y 5156 // -> select Cond0, (select Cond1, X, Y), Y 5157 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5158 SDValue Cond0 = N0->getOperand(0); 5159 SDValue Cond1 = N0->getOperand(1); 5160 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5161 N1.getValueType(), Cond1, N1, N2); 5162 if (normalizeToSequence || !InnerSelect.use_empty()) 5163 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5164 InnerSelect, N2); 5165 } 5166 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5167 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5168 SDValue Cond0 = N0->getOperand(0); 5169 SDValue Cond1 = N0->getOperand(1); 5170 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5171 N1.getValueType(), Cond1, N1, N2); 5172 if (normalizeToSequence || !InnerSelect.use_empty()) 5173 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5174 InnerSelect); 5175 } 5176 5177 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5178 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5179 SDValue N1_0 = N1->getOperand(0); 5180 SDValue N1_1 = N1->getOperand(1); 5181 SDValue N1_2 = N1->getOperand(2); 5182 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5183 // Create the actual and node if we can generate good code for it. 5184 if (!normalizeToSequence) { 5185 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5186 N0, N1_0); 5187 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5188 N1_1, N2); 5189 } 5190 // Otherwise see if we can optimize the "and" to a better pattern. 5191 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5192 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5193 N1_1, N2); 5194 } 5195 } 5196 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5197 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5198 SDValue N2_0 = N2->getOperand(0); 5199 SDValue N2_1 = N2->getOperand(1); 5200 SDValue N2_2 = N2->getOperand(2); 5201 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5202 // Create the actual or node if we can generate good code for it. 5203 if (!normalizeToSequence) { 5204 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5205 N0, N2_0); 5206 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5207 N1, N2_2); 5208 } 5209 // Otherwise see if we can optimize to a better pattern. 5210 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5211 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5212 N1, N2_2); 5213 } 5214 } 5215 } 5216 5217 // fold selects based on a setcc into other things, such as min/max/abs 5218 if (N0.getOpcode() == ISD::SETCC) { 5219 // select x, y (fcmp lt x, y) -> fminnum x, y 5220 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5221 // 5222 // This is OK if we don't care about what happens if either operand is a 5223 // NaN. 5224 // 5225 5226 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5227 // no signed zeros as well as no nans. 5228 const TargetOptions &Options = DAG.getTarget().Options; 5229 if (Options.UnsafeFPMath && 5230 VT.isFloatingPoint() && N0.hasOneUse() && 5231 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5232 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5233 5234 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5235 N0.getOperand(1), N1, N2, CC, 5236 TLI, DAG)) 5237 return FMinMax; 5238 } 5239 5240 if ((!LegalOperations && 5241 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5242 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5243 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5244 N0.getOperand(0), N0.getOperand(1), 5245 N1, N2, N0.getOperand(2)); 5246 return SimplifySelect(SDLoc(N), N0, N1, N2); 5247 } 5248 5249 return SDValue(); 5250 } 5251 5252 static 5253 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5254 SDLoc DL(N); 5255 EVT LoVT, HiVT; 5256 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5257 5258 // Split the inputs. 5259 SDValue Lo, Hi, LL, LH, RL, RH; 5260 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5261 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5262 5263 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5264 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5265 5266 return std::make_pair(Lo, Hi); 5267 } 5268 5269 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5270 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5271 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5272 SDLoc dl(N); 5273 SDValue Cond = N->getOperand(0); 5274 SDValue LHS = N->getOperand(1); 5275 SDValue RHS = N->getOperand(2); 5276 EVT VT = N->getValueType(0); 5277 int NumElems = VT.getVectorNumElements(); 5278 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5279 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5280 Cond.getOpcode() == ISD::BUILD_VECTOR); 5281 5282 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5283 // binary ones here. 5284 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5285 return SDValue(); 5286 5287 // We're sure we have an even number of elements due to the 5288 // concat_vectors we have as arguments to vselect. 5289 // Skip BV elements until we find one that's not an UNDEF 5290 // After we find an UNDEF element, keep looping until we get to half the 5291 // length of the BV and see if all the non-undef nodes are the same. 5292 ConstantSDNode *BottomHalf = nullptr; 5293 for (int i = 0; i < NumElems / 2; ++i) { 5294 if (Cond->getOperand(i)->isUndef()) 5295 continue; 5296 5297 if (BottomHalf == nullptr) 5298 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5299 else if (Cond->getOperand(i).getNode() != BottomHalf) 5300 return SDValue(); 5301 } 5302 5303 // Do the same for the second half of the BuildVector 5304 ConstantSDNode *TopHalf = nullptr; 5305 for (int i = NumElems / 2; i < NumElems; ++i) { 5306 if (Cond->getOperand(i)->isUndef()) 5307 continue; 5308 5309 if (TopHalf == nullptr) 5310 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5311 else if (Cond->getOperand(i).getNode() != TopHalf) 5312 return SDValue(); 5313 } 5314 5315 assert(TopHalf && BottomHalf && 5316 "One half of the selector was all UNDEFs and the other was all the " 5317 "same value. This should have been addressed before this function."); 5318 return DAG.getNode( 5319 ISD::CONCAT_VECTORS, dl, VT, 5320 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5321 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5322 } 5323 5324 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5325 5326 if (Level >= AfterLegalizeTypes) 5327 return SDValue(); 5328 5329 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5330 SDValue Mask = MSC->getMask(); 5331 SDValue Data = MSC->getValue(); 5332 SDLoc DL(N); 5333 5334 // If the MSCATTER data type requires splitting and the mask is provided by a 5335 // SETCC, then split both nodes and its operands before legalization. This 5336 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5337 // and enables future optimizations (e.g. min/max pattern matching on X86). 5338 if (Mask.getOpcode() != ISD::SETCC) 5339 return SDValue(); 5340 5341 // Check if any splitting is required. 5342 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5343 TargetLowering::TypeSplitVector) 5344 return SDValue(); 5345 SDValue MaskLo, MaskHi, Lo, Hi; 5346 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5347 5348 EVT LoVT, HiVT; 5349 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5350 5351 SDValue Chain = MSC->getChain(); 5352 5353 EVT MemoryVT = MSC->getMemoryVT(); 5354 unsigned Alignment = MSC->getOriginalAlignment(); 5355 5356 EVT LoMemVT, HiMemVT; 5357 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5358 5359 SDValue DataLo, DataHi; 5360 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5361 5362 SDValue BasePtr = MSC->getBasePtr(); 5363 SDValue IndexLo, IndexHi; 5364 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5365 5366 MachineMemOperand *MMO = DAG.getMachineFunction(). 5367 getMachineMemOperand(MSC->getPointerInfo(), 5368 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5369 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5370 5371 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5372 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5373 DL, OpsLo, MMO); 5374 5375 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5376 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5377 DL, OpsHi, MMO); 5378 5379 AddToWorklist(Lo.getNode()); 5380 AddToWorklist(Hi.getNode()); 5381 5382 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5383 } 5384 5385 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5386 5387 if (Level >= AfterLegalizeTypes) 5388 return SDValue(); 5389 5390 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5391 SDValue Mask = MST->getMask(); 5392 SDValue Data = MST->getValue(); 5393 SDLoc DL(N); 5394 5395 // If the MSTORE data type requires splitting and the mask is provided by a 5396 // SETCC, then split both nodes and its operands before legalization. This 5397 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5398 // and enables future optimizations (e.g. min/max pattern matching on X86). 5399 if (Mask.getOpcode() == ISD::SETCC) { 5400 5401 // Check if any splitting is required. 5402 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5403 TargetLowering::TypeSplitVector) 5404 return SDValue(); 5405 5406 SDValue MaskLo, MaskHi, Lo, Hi; 5407 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5408 5409 EVT LoVT, HiVT; 5410 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5411 5412 SDValue Chain = MST->getChain(); 5413 SDValue Ptr = MST->getBasePtr(); 5414 5415 EVT MemoryVT = MST->getMemoryVT(); 5416 unsigned Alignment = MST->getOriginalAlignment(); 5417 5418 // if Alignment is equal to the vector size, 5419 // take the half of it for the second part 5420 unsigned SecondHalfAlignment = 5421 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5422 Alignment/2 : Alignment; 5423 5424 EVT LoMemVT, HiMemVT; 5425 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5426 5427 SDValue DataLo, DataHi; 5428 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5429 5430 MachineMemOperand *MMO = DAG.getMachineFunction(). 5431 getMachineMemOperand(MST->getPointerInfo(), 5432 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5433 Alignment, MST->getAAInfo(), MST->getRanges()); 5434 5435 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5436 MST->isTruncatingStore()); 5437 5438 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5439 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5440 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5441 5442 MMO = DAG.getMachineFunction(). 5443 getMachineMemOperand(MST->getPointerInfo(), 5444 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5445 SecondHalfAlignment, MST->getAAInfo(), 5446 MST->getRanges()); 5447 5448 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5449 MST->isTruncatingStore()); 5450 5451 AddToWorklist(Lo.getNode()); 5452 AddToWorklist(Hi.getNode()); 5453 5454 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5455 } 5456 return SDValue(); 5457 } 5458 5459 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5460 5461 if (Level >= AfterLegalizeTypes) 5462 return SDValue(); 5463 5464 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5465 SDValue Mask = MGT->getMask(); 5466 SDLoc DL(N); 5467 5468 // If the MGATHER result requires splitting and the mask is provided by a 5469 // SETCC, then split both nodes and its operands before legalization. This 5470 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5471 // and enables future optimizations (e.g. min/max pattern matching on X86). 5472 5473 if (Mask.getOpcode() != ISD::SETCC) 5474 return SDValue(); 5475 5476 EVT VT = N->getValueType(0); 5477 5478 // Check if any splitting is required. 5479 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5480 TargetLowering::TypeSplitVector) 5481 return SDValue(); 5482 5483 SDValue MaskLo, MaskHi, Lo, Hi; 5484 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5485 5486 SDValue Src0 = MGT->getValue(); 5487 SDValue Src0Lo, Src0Hi; 5488 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5489 5490 EVT LoVT, HiVT; 5491 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5492 5493 SDValue Chain = MGT->getChain(); 5494 EVT MemoryVT = MGT->getMemoryVT(); 5495 unsigned Alignment = MGT->getOriginalAlignment(); 5496 5497 EVT LoMemVT, HiMemVT; 5498 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5499 5500 SDValue BasePtr = MGT->getBasePtr(); 5501 SDValue Index = MGT->getIndex(); 5502 SDValue IndexLo, IndexHi; 5503 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5504 5505 MachineMemOperand *MMO = DAG.getMachineFunction(). 5506 getMachineMemOperand(MGT->getPointerInfo(), 5507 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5508 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5509 5510 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5511 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5512 MMO); 5513 5514 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5515 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5516 MMO); 5517 5518 AddToWorklist(Lo.getNode()); 5519 AddToWorklist(Hi.getNode()); 5520 5521 // Build a factor node to remember that this load is independent of the 5522 // other one. 5523 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5524 Hi.getValue(1)); 5525 5526 // Legalized the chain result - switch anything that used the old chain to 5527 // use the new one. 5528 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5529 5530 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5531 5532 SDValue RetOps[] = { GatherRes, Chain }; 5533 return DAG.getMergeValues(RetOps, DL); 5534 } 5535 5536 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5537 5538 if (Level >= AfterLegalizeTypes) 5539 return SDValue(); 5540 5541 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5542 SDValue Mask = MLD->getMask(); 5543 SDLoc DL(N); 5544 5545 // If the MLOAD result requires splitting and the mask is provided by a 5546 // SETCC, then split both nodes and its operands before legalization. This 5547 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5548 // and enables future optimizations (e.g. min/max pattern matching on X86). 5549 5550 if (Mask.getOpcode() == ISD::SETCC) { 5551 EVT VT = N->getValueType(0); 5552 5553 // Check if any splitting is required. 5554 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5555 TargetLowering::TypeSplitVector) 5556 return SDValue(); 5557 5558 SDValue MaskLo, MaskHi, Lo, Hi; 5559 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5560 5561 SDValue Src0 = MLD->getSrc0(); 5562 SDValue Src0Lo, Src0Hi; 5563 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5564 5565 EVT LoVT, HiVT; 5566 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5567 5568 SDValue Chain = MLD->getChain(); 5569 SDValue Ptr = MLD->getBasePtr(); 5570 EVT MemoryVT = MLD->getMemoryVT(); 5571 unsigned Alignment = MLD->getOriginalAlignment(); 5572 5573 // if Alignment is equal to the vector size, 5574 // take the half of it for the second part 5575 unsigned SecondHalfAlignment = 5576 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5577 Alignment/2 : Alignment; 5578 5579 EVT LoMemVT, HiMemVT; 5580 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5581 5582 MachineMemOperand *MMO = DAG.getMachineFunction(). 5583 getMachineMemOperand(MLD->getPointerInfo(), 5584 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5585 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5586 5587 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5588 ISD::NON_EXTLOAD); 5589 5590 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5591 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5592 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5593 5594 MMO = DAG.getMachineFunction(). 5595 getMachineMemOperand(MLD->getPointerInfo(), 5596 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5597 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5598 5599 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5600 ISD::NON_EXTLOAD); 5601 5602 AddToWorklist(Lo.getNode()); 5603 AddToWorklist(Hi.getNode()); 5604 5605 // Build a factor node to remember that this load is independent of the 5606 // other one. 5607 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5608 Hi.getValue(1)); 5609 5610 // Legalized the chain result - switch anything that used the old chain to 5611 // use the new one. 5612 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5613 5614 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5615 5616 SDValue RetOps[] = { LoadRes, Chain }; 5617 return DAG.getMergeValues(RetOps, DL); 5618 } 5619 return SDValue(); 5620 } 5621 5622 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5623 SDValue N0 = N->getOperand(0); 5624 SDValue N1 = N->getOperand(1); 5625 SDValue N2 = N->getOperand(2); 5626 SDLoc DL(N); 5627 5628 // Canonicalize integer abs. 5629 // vselect (setg[te] X, 0), X, -X -> 5630 // vselect (setgt X, -1), X, -X -> 5631 // vselect (setl[te] X, 0), -X, X -> 5632 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5633 if (N0.getOpcode() == ISD::SETCC) { 5634 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5635 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5636 bool isAbs = false; 5637 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5638 5639 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5640 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5641 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5642 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5643 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5644 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5645 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5646 5647 if (isAbs) { 5648 EVT VT = LHS.getValueType(); 5649 SDValue Shift = DAG.getNode( 5650 ISD::SRA, DL, VT, LHS, 5651 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5652 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5653 AddToWorklist(Shift.getNode()); 5654 AddToWorklist(Add.getNode()); 5655 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5656 } 5657 } 5658 5659 if (SimplifySelectOps(N, N1, N2)) 5660 return SDValue(N, 0); // Don't revisit N. 5661 5662 // If the VSELECT result requires splitting and the mask is provided by a 5663 // SETCC, then split both nodes and its operands before legalization. This 5664 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5665 // and enables future optimizations (e.g. min/max pattern matching on X86). 5666 if (N0.getOpcode() == ISD::SETCC) { 5667 EVT VT = N->getValueType(0); 5668 5669 // Check if any splitting is required. 5670 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5671 TargetLowering::TypeSplitVector) 5672 return SDValue(); 5673 5674 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5675 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5676 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5677 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5678 5679 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5680 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5681 5682 // Add the new VSELECT nodes to the work list in case they need to be split 5683 // again. 5684 AddToWorklist(Lo.getNode()); 5685 AddToWorklist(Hi.getNode()); 5686 5687 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5688 } 5689 5690 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5691 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5692 return N1; 5693 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5694 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5695 return N2; 5696 5697 // The ConvertSelectToConcatVector function is assuming both the above 5698 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5699 // and addressed. 5700 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5701 N2.getOpcode() == ISD::CONCAT_VECTORS && 5702 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5703 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5704 return CV; 5705 } 5706 5707 return SDValue(); 5708 } 5709 5710 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5711 SDValue N0 = N->getOperand(0); 5712 SDValue N1 = N->getOperand(1); 5713 SDValue N2 = N->getOperand(2); 5714 SDValue N3 = N->getOperand(3); 5715 SDValue N4 = N->getOperand(4); 5716 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5717 5718 // fold select_cc lhs, rhs, x, x, cc -> x 5719 if (N2 == N3) 5720 return N2; 5721 5722 // Determine if the condition we're dealing with is constant 5723 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 5724 CC, SDLoc(N), false)) { 5725 AddToWorklist(SCC.getNode()); 5726 5727 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5728 if (!SCCC->isNullValue()) 5729 return N2; // cond always true -> true val 5730 else 5731 return N3; // cond always false -> false val 5732 } else if (SCC->isUndef()) { 5733 // When the condition is UNDEF, just return the first operand. This is 5734 // coherent the DAG creation, no setcc node is created in this case 5735 return N2; 5736 } else if (SCC.getOpcode() == ISD::SETCC) { 5737 // Fold to a simpler select_cc 5738 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5739 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5740 SCC.getOperand(2)); 5741 } 5742 } 5743 5744 // If we can fold this based on the true/false value, do so. 5745 if (SimplifySelectOps(N, N2, N3)) 5746 return SDValue(N, 0); // Don't revisit N. 5747 5748 // fold select_cc into other things, such as min/max/abs 5749 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5750 } 5751 5752 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5753 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5754 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5755 SDLoc(N)); 5756 } 5757 5758 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5759 SDValue LHS = N->getOperand(0); 5760 SDValue RHS = N->getOperand(1); 5761 SDValue Carry = N->getOperand(2); 5762 SDValue Cond = N->getOperand(3); 5763 5764 // If Carry is false, fold to a regular SETCC. 5765 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5766 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5767 5768 return SDValue(); 5769 } 5770 5771 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5772 /// a build_vector of constants. 5773 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5774 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5775 /// Vector extends are not folded if operations are legal; this is to 5776 /// avoid introducing illegal build_vector dag nodes. 5777 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5778 SelectionDAG &DAG, bool LegalTypes, 5779 bool LegalOperations) { 5780 unsigned Opcode = N->getOpcode(); 5781 SDValue N0 = N->getOperand(0); 5782 EVT VT = N->getValueType(0); 5783 5784 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5785 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 5786 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 5787 && "Expected EXTEND dag node in input!"); 5788 5789 // fold (sext c1) -> c1 5790 // fold (zext c1) -> c1 5791 // fold (aext c1) -> c1 5792 if (isa<ConstantSDNode>(N0)) 5793 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5794 5795 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5796 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5797 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5798 EVT SVT = VT.getScalarType(); 5799 if (!(VT.isVector() && 5800 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5801 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5802 return nullptr; 5803 5804 // We can fold this node into a build_vector. 5805 unsigned VTBits = SVT.getSizeInBits(); 5806 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5807 SmallVector<SDValue, 8> Elts; 5808 unsigned NumElts = VT.getVectorNumElements(); 5809 SDLoc DL(N); 5810 5811 for (unsigned i=0; i != NumElts; ++i) { 5812 SDValue Op = N0->getOperand(i); 5813 if (Op->isUndef()) { 5814 Elts.push_back(DAG.getUNDEF(SVT)); 5815 continue; 5816 } 5817 5818 SDLoc DL(Op); 5819 // Get the constant value and if needed trunc it to the size of the type. 5820 // Nodes like build_vector might have constants wider than the scalar type. 5821 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5822 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5823 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5824 else 5825 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5826 } 5827 5828 return DAG.getBuildVector(VT, DL, Elts).getNode(); 5829 } 5830 5831 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5832 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5833 // transformation. Returns true if extension are possible and the above 5834 // mentioned transformation is profitable. 5835 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5836 unsigned ExtOpc, 5837 SmallVectorImpl<SDNode *> &ExtendNodes, 5838 const TargetLowering &TLI) { 5839 bool HasCopyToRegUses = false; 5840 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5841 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5842 UE = N0.getNode()->use_end(); 5843 UI != UE; ++UI) { 5844 SDNode *User = *UI; 5845 if (User == N) 5846 continue; 5847 if (UI.getUse().getResNo() != N0.getResNo()) 5848 continue; 5849 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5850 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5851 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5852 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5853 // Sign bits will be lost after a zext. 5854 return false; 5855 bool Add = false; 5856 for (unsigned i = 0; i != 2; ++i) { 5857 SDValue UseOp = User->getOperand(i); 5858 if (UseOp == N0) 5859 continue; 5860 if (!isa<ConstantSDNode>(UseOp)) 5861 return false; 5862 Add = true; 5863 } 5864 if (Add) 5865 ExtendNodes.push_back(User); 5866 continue; 5867 } 5868 // If truncates aren't free and there are users we can't 5869 // extend, it isn't worthwhile. 5870 if (!isTruncFree) 5871 return false; 5872 // Remember if this value is live-out. 5873 if (User->getOpcode() == ISD::CopyToReg) 5874 HasCopyToRegUses = true; 5875 } 5876 5877 if (HasCopyToRegUses) { 5878 bool BothLiveOut = false; 5879 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5880 UI != UE; ++UI) { 5881 SDUse &Use = UI.getUse(); 5882 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5883 BothLiveOut = true; 5884 break; 5885 } 5886 } 5887 if (BothLiveOut) 5888 // Both unextended and extended values are live out. There had better be 5889 // a good reason for the transformation. 5890 return ExtendNodes.size(); 5891 } 5892 return true; 5893 } 5894 5895 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5896 SDValue Trunc, SDValue ExtLoad, 5897 const SDLoc &DL, ISD::NodeType ExtType) { 5898 // Extend SetCC uses if necessary. 5899 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5900 SDNode *SetCC = SetCCs[i]; 5901 SmallVector<SDValue, 4> Ops; 5902 5903 for (unsigned j = 0; j != 2; ++j) { 5904 SDValue SOp = SetCC->getOperand(j); 5905 if (SOp == Trunc) 5906 Ops.push_back(ExtLoad); 5907 else 5908 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5909 } 5910 5911 Ops.push_back(SetCC->getOperand(2)); 5912 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5913 } 5914 } 5915 5916 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5917 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5918 SDValue N0 = N->getOperand(0); 5919 EVT DstVT = N->getValueType(0); 5920 EVT SrcVT = N0.getValueType(); 5921 5922 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5923 N->getOpcode() == ISD::ZERO_EXTEND) && 5924 "Unexpected node type (not an extend)!"); 5925 5926 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5927 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5928 // (v8i32 (sext (v8i16 (load x)))) 5929 // into: 5930 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5931 // (v4i32 (sextload (x + 16))))) 5932 // Where uses of the original load, i.e.: 5933 // (v8i16 (load x)) 5934 // are replaced with: 5935 // (v8i16 (truncate 5936 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5937 // (v4i32 (sextload (x + 16))))))) 5938 // 5939 // This combine is only applicable to illegal, but splittable, vectors. 5940 // All legal types, and illegal non-vector types, are handled elsewhere. 5941 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5942 // 5943 if (N0->getOpcode() != ISD::LOAD) 5944 return SDValue(); 5945 5946 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5947 5948 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5949 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5950 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5951 return SDValue(); 5952 5953 SmallVector<SDNode *, 4> SetCCs; 5954 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5955 return SDValue(); 5956 5957 ISD::LoadExtType ExtType = 5958 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5959 5960 // Try to split the vector types to get down to legal types. 5961 EVT SplitSrcVT = SrcVT; 5962 EVT SplitDstVT = DstVT; 5963 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5964 SplitSrcVT.getVectorNumElements() > 1) { 5965 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5966 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5967 } 5968 5969 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5970 return SDValue(); 5971 5972 SDLoc DL(N); 5973 const unsigned NumSplits = 5974 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5975 const unsigned Stride = SplitSrcVT.getStoreSize(); 5976 SmallVector<SDValue, 4> Loads; 5977 SmallVector<SDValue, 4> Chains; 5978 5979 SDValue BasePtr = LN0->getBasePtr(); 5980 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5981 const unsigned Offset = Idx * Stride; 5982 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5983 5984 SDValue SplitLoad = DAG.getExtLoad( 5985 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5986 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 5987 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 5988 5989 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5990 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5991 5992 Loads.push_back(SplitLoad.getValue(0)); 5993 Chains.push_back(SplitLoad.getValue(1)); 5994 } 5995 5996 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5997 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5998 5999 CombineTo(N, NewValue); 6000 6001 // Replace uses of the original load (before extension) 6002 // with a truncate of the concatenated sextloaded vectors. 6003 SDValue Trunc = 6004 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6005 CombineTo(N0.getNode(), Trunc, NewChain); 6006 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6007 (ISD::NodeType)N->getOpcode()); 6008 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6009 } 6010 6011 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 6012 SDValue N0 = N->getOperand(0); 6013 EVT VT = N->getValueType(0); 6014 6015 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6016 LegalOperations)) 6017 return SDValue(Res, 0); 6018 6019 // fold (sext (sext x)) -> (sext x) 6020 // fold (sext (aext x)) -> (sext x) 6021 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6022 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 6023 N0.getOperand(0)); 6024 6025 if (N0.getOpcode() == ISD::TRUNCATE) { 6026 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 6027 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 6028 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6029 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6030 if (NarrowLoad.getNode() != N0.getNode()) { 6031 CombineTo(N0.getNode(), NarrowLoad); 6032 // CombineTo deleted the truncate, if needed, but not what's under it. 6033 AddToWorklist(oye); 6034 } 6035 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6036 } 6037 6038 // See if the value being truncated is already sign extended. If so, just 6039 // eliminate the trunc/sext pair. 6040 SDValue Op = N0.getOperand(0); 6041 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 6042 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 6043 unsigned DestBits = VT.getScalarType().getSizeInBits(); 6044 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6045 6046 if (OpBits == DestBits) { 6047 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6048 // bits, it is already ready. 6049 if (NumSignBits > DestBits-MidBits) 6050 return Op; 6051 } else if (OpBits < DestBits) { 6052 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6053 // bits, just sext from i32. 6054 if (NumSignBits > OpBits-MidBits) 6055 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 6056 } else { 6057 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6058 // bits, just truncate to i32. 6059 if (NumSignBits > OpBits-MidBits) 6060 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6061 } 6062 6063 // fold (sext (truncate x)) -> (sextinreg x). 6064 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6065 N0.getValueType())) { 6066 if (OpBits < DestBits) 6067 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6068 else if (OpBits > DestBits) 6069 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6070 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6071 DAG.getValueType(N0.getValueType())); 6072 } 6073 } 6074 6075 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6076 // Only generate vector extloads when 1) they're legal, and 2) they are 6077 // deemed desirable by the target. 6078 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6079 ((!LegalOperations && !VT.isVector() && 6080 !cast<LoadSDNode>(N0)->isVolatile()) || 6081 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6082 bool DoXform = true; 6083 SmallVector<SDNode*, 4> SetCCs; 6084 if (!N0.hasOneUse()) 6085 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6086 if (VT.isVector()) 6087 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6088 if (DoXform) { 6089 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6090 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6091 LN0->getChain(), 6092 LN0->getBasePtr(), N0.getValueType(), 6093 LN0->getMemOperand()); 6094 CombineTo(N, ExtLoad); 6095 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6096 N0.getValueType(), ExtLoad); 6097 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6098 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6099 ISD::SIGN_EXTEND); 6100 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6101 } 6102 } 6103 6104 // fold (sext (load x)) to multiple smaller sextloads. 6105 // Only on illegal but splittable vectors. 6106 if (SDValue ExtLoad = CombineExtLoad(N)) 6107 return ExtLoad; 6108 6109 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6110 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6111 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6112 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6113 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6114 EVT MemVT = LN0->getMemoryVT(); 6115 if ((!LegalOperations && !LN0->isVolatile()) || 6116 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6117 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6118 LN0->getChain(), 6119 LN0->getBasePtr(), MemVT, 6120 LN0->getMemOperand()); 6121 CombineTo(N, ExtLoad); 6122 CombineTo(N0.getNode(), 6123 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6124 N0.getValueType(), ExtLoad), 6125 ExtLoad.getValue(1)); 6126 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6127 } 6128 } 6129 6130 // fold (sext (and/or/xor (load x), cst)) -> 6131 // (and/or/xor (sextload x), (sext cst)) 6132 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6133 N0.getOpcode() == ISD::XOR) && 6134 isa<LoadSDNode>(N0.getOperand(0)) && 6135 N0.getOperand(1).getOpcode() == ISD::Constant && 6136 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6137 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6138 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6139 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6140 bool DoXform = true; 6141 SmallVector<SDNode*, 4> SetCCs; 6142 if (!N0.hasOneUse()) 6143 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6144 SetCCs, TLI); 6145 if (DoXform) { 6146 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6147 LN0->getChain(), LN0->getBasePtr(), 6148 LN0->getMemoryVT(), 6149 LN0->getMemOperand()); 6150 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6151 Mask = Mask.sext(VT.getSizeInBits()); 6152 SDLoc DL(N); 6153 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6154 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6155 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6156 SDLoc(N0.getOperand(0)), 6157 N0.getOperand(0).getValueType(), ExtLoad); 6158 CombineTo(N, And); 6159 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6160 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6161 ISD::SIGN_EXTEND); 6162 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6163 } 6164 } 6165 } 6166 6167 if (N0.getOpcode() == ISD::SETCC) { 6168 EVT N0VT = N0.getOperand(0).getValueType(); 6169 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6170 // Only do this before legalize for now. 6171 if (VT.isVector() && !LegalOperations && 6172 TLI.getBooleanContents(N0VT) == 6173 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6174 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6175 // of the same size as the compared operands. Only optimize sext(setcc()) 6176 // if this is the case. 6177 EVT SVT = getSetCCResultType(N0VT); 6178 6179 // We know that the # elements of the results is the same as the 6180 // # elements of the compare (and the # elements of the compare result 6181 // for that matter). Check to see that they are the same size. If so, 6182 // we know that the element size of the sext'd result matches the 6183 // element size of the compare operands. 6184 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6185 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6186 N0.getOperand(1), 6187 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6188 6189 // If the desired elements are smaller or larger than the source 6190 // elements we can use a matching integer vector type and then 6191 // truncate/sign extend 6192 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6193 if (SVT == MatchingVectorType) { 6194 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6195 N0.getOperand(0), N0.getOperand(1), 6196 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6197 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6198 } 6199 } 6200 6201 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 6202 // Here, T can be 1 or -1, depending on the type of the setcc and 6203 // getBooleanContents(). 6204 unsigned SetCCWidth = N0.getValueType().getScalarSizeInBits(); 6205 6206 SDLoc DL(N); 6207 // To determine the "true" side of the select, we need to know the high bit 6208 // of the value returned by the setcc if it evaluates to true. 6209 // If the type of the setcc is i1, then the true case of the select is just 6210 // sext(i1 1), that is, -1. 6211 // If the type of the setcc is larger (say, i8) then the value of the high 6212 // bit depends on getBooleanContents(). So, ask TLI for a real "true" value 6213 // of the appropriate width. 6214 SDValue ExtTrueVal = 6215 (SetCCWidth == 1) 6216 ? DAG.getConstant(APInt::getAllOnesValue(VT.getScalarSizeInBits()), 6217 DL, VT) 6218 : TLI.getConstTrueVal(DAG, VT, DL); 6219 6220 if (SDValue SCC = SimplifySelectCC( 6221 DL, N0.getOperand(0), N0.getOperand(1), ExtTrueVal, 6222 DAG.getConstant(0, DL, VT), 6223 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6224 return SCC; 6225 6226 if (!VT.isVector()) { 6227 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6228 if (!LegalOperations || 6229 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6230 SDLoc DL(N); 6231 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6232 SDValue SetCC = 6233 DAG.getSetCC(DL, SetCCVT, N0.getOperand(0), N0.getOperand(1), CC); 6234 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, 6235 DAG.getConstant(0, DL, VT)); 6236 } 6237 } 6238 } 6239 6240 // fold (sext x) -> (zext x) if the sign bit is known zero. 6241 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6242 DAG.SignBitIsZero(N0)) 6243 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6244 6245 return SDValue(); 6246 } 6247 6248 // isTruncateOf - If N is a truncate of some other value, return true, record 6249 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6250 // This function computes KnownZero to avoid a duplicated call to 6251 // computeKnownBits in the caller. 6252 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6253 APInt &KnownZero) { 6254 APInt KnownOne; 6255 if (N->getOpcode() == ISD::TRUNCATE) { 6256 Op = N->getOperand(0); 6257 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6258 return true; 6259 } 6260 6261 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6262 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6263 return false; 6264 6265 SDValue Op0 = N->getOperand(0); 6266 SDValue Op1 = N->getOperand(1); 6267 assert(Op0.getValueType() == Op1.getValueType()); 6268 6269 if (isNullConstant(Op0)) 6270 Op = Op1; 6271 else if (isNullConstant(Op1)) 6272 Op = Op0; 6273 else 6274 return false; 6275 6276 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6277 6278 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6279 return false; 6280 6281 return true; 6282 } 6283 6284 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6285 SDValue N0 = N->getOperand(0); 6286 EVT VT = N->getValueType(0); 6287 6288 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6289 LegalOperations)) 6290 return SDValue(Res, 0); 6291 6292 // fold (zext (zext x)) -> (zext x) 6293 // fold (zext (aext x)) -> (zext x) 6294 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6295 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6296 N0.getOperand(0)); 6297 6298 // fold (zext (truncate x)) -> (zext x) or 6299 // (zext (truncate x)) -> (truncate x) 6300 // This is valid when the truncated bits of x are already zero. 6301 // FIXME: We should extend this to work for vectors too. 6302 SDValue Op; 6303 APInt KnownZero; 6304 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6305 APInt TruncatedBits = 6306 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6307 APInt(Op.getValueSizeInBits(), 0) : 6308 APInt::getBitsSet(Op.getValueSizeInBits(), 6309 N0.getValueSizeInBits(), 6310 std::min(Op.getValueSizeInBits(), 6311 VT.getSizeInBits())); 6312 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6313 if (VT.bitsGT(Op.getValueType())) 6314 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6315 if (VT.bitsLT(Op.getValueType())) 6316 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6317 6318 return Op; 6319 } 6320 } 6321 6322 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6323 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6324 if (N0.getOpcode() == ISD::TRUNCATE) { 6325 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6326 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6327 if (NarrowLoad.getNode() != N0.getNode()) { 6328 CombineTo(N0.getNode(), NarrowLoad); 6329 // CombineTo deleted the truncate, if needed, but not what's under it. 6330 AddToWorklist(oye); 6331 } 6332 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6333 } 6334 } 6335 6336 // fold (zext (truncate x)) -> (and x, mask) 6337 if (N0.getOpcode() == ISD::TRUNCATE) { 6338 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6339 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6340 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6341 SDNode *oye = N0.getNode()->getOperand(0).getNode(); 6342 if (NarrowLoad.getNode() != N0.getNode()) { 6343 CombineTo(N0.getNode(), NarrowLoad); 6344 // CombineTo deleted the truncate, if needed, but not what's under it. 6345 AddToWorklist(oye); 6346 } 6347 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6348 } 6349 6350 EVT SrcVT = N0.getOperand(0).getValueType(); 6351 EVT MinVT = N0.getValueType(); 6352 6353 // Try to mask before the extension to avoid having to generate a larger mask, 6354 // possibly over several sub-vectors. 6355 if (SrcVT.bitsLT(VT)) { 6356 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6357 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6358 SDValue Op = N0.getOperand(0); 6359 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6360 AddToWorklist(Op.getNode()); 6361 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6362 } 6363 } 6364 6365 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6366 SDValue Op = N0.getOperand(0); 6367 if (SrcVT.bitsLT(VT)) { 6368 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6369 AddToWorklist(Op.getNode()); 6370 } else if (SrcVT.bitsGT(VT)) { 6371 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6372 AddToWorklist(Op.getNode()); 6373 } 6374 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6375 } 6376 } 6377 6378 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6379 // if either of the casts is not free. 6380 if (N0.getOpcode() == ISD::AND && 6381 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6382 N0.getOperand(1).getOpcode() == ISD::Constant && 6383 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6384 N0.getValueType()) || 6385 !TLI.isZExtFree(N0.getValueType(), VT))) { 6386 SDValue X = N0.getOperand(0).getOperand(0); 6387 if (X.getValueType().bitsLT(VT)) { 6388 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6389 } else if (X.getValueType().bitsGT(VT)) { 6390 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6391 } 6392 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6393 Mask = Mask.zext(VT.getSizeInBits()); 6394 SDLoc DL(N); 6395 return DAG.getNode(ISD::AND, DL, VT, 6396 X, DAG.getConstant(Mask, DL, VT)); 6397 } 6398 6399 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6400 // Only generate vector extloads when 1) they're legal, and 2) they are 6401 // deemed desirable by the target. 6402 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6403 ((!LegalOperations && !VT.isVector() && 6404 !cast<LoadSDNode>(N0)->isVolatile()) || 6405 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6406 bool DoXform = true; 6407 SmallVector<SDNode*, 4> SetCCs; 6408 if (!N0.hasOneUse()) 6409 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6410 if (VT.isVector()) 6411 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6412 if (DoXform) { 6413 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6414 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6415 LN0->getChain(), 6416 LN0->getBasePtr(), N0.getValueType(), 6417 LN0->getMemOperand()); 6418 CombineTo(N, ExtLoad); 6419 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6420 N0.getValueType(), ExtLoad); 6421 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6422 6423 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6424 ISD::ZERO_EXTEND); 6425 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6426 } 6427 } 6428 6429 // fold (zext (load x)) to multiple smaller zextloads. 6430 // Only on illegal but splittable vectors. 6431 if (SDValue ExtLoad = CombineExtLoad(N)) 6432 return ExtLoad; 6433 6434 // fold (zext (and/or/xor (load x), cst)) -> 6435 // (and/or/xor (zextload x), (zext cst)) 6436 // Unless (and (load x) cst) will match as a zextload already and has 6437 // additional users. 6438 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6439 N0.getOpcode() == ISD::XOR) && 6440 isa<LoadSDNode>(N0.getOperand(0)) && 6441 N0.getOperand(1).getOpcode() == ISD::Constant && 6442 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6443 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6444 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6445 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6446 bool DoXform = true; 6447 SmallVector<SDNode*, 4> SetCCs; 6448 if (!N0.hasOneUse()) { 6449 if (N0.getOpcode() == ISD::AND) { 6450 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6451 auto NarrowLoad = false; 6452 EVT LoadResultTy = AndC->getValueType(0); 6453 EVT ExtVT, LoadedVT; 6454 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6455 NarrowLoad)) 6456 DoXform = false; 6457 } 6458 if (DoXform) 6459 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6460 ISD::ZERO_EXTEND, SetCCs, TLI); 6461 } 6462 if (DoXform) { 6463 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6464 LN0->getChain(), LN0->getBasePtr(), 6465 LN0->getMemoryVT(), 6466 LN0->getMemOperand()); 6467 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6468 Mask = Mask.zext(VT.getSizeInBits()); 6469 SDLoc DL(N); 6470 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6471 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6472 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6473 SDLoc(N0.getOperand(0)), 6474 N0.getOperand(0).getValueType(), ExtLoad); 6475 CombineTo(N, And); 6476 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6477 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6478 ISD::ZERO_EXTEND); 6479 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6480 } 6481 } 6482 } 6483 6484 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6485 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6486 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6487 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6488 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6489 EVT MemVT = LN0->getMemoryVT(); 6490 if ((!LegalOperations && !LN0->isVolatile()) || 6491 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6492 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6493 LN0->getChain(), 6494 LN0->getBasePtr(), MemVT, 6495 LN0->getMemOperand()); 6496 CombineTo(N, ExtLoad); 6497 CombineTo(N0.getNode(), 6498 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6499 ExtLoad), 6500 ExtLoad.getValue(1)); 6501 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6502 } 6503 } 6504 6505 if (N0.getOpcode() == ISD::SETCC) { 6506 // Only do this before legalize for now. 6507 if (!LegalOperations && VT.isVector() && 6508 N0.getValueType().getVectorElementType() == MVT::i1) { 6509 EVT N00VT = N0.getOperand(0).getValueType(); 6510 if (getSetCCResultType(N00VT) == N0.getValueType()) 6511 return SDValue(); 6512 6513 // We know that the # elements of the results is the same as the # 6514 // elements of the compare (and the # elements of the compare result for 6515 // that matter). Check to see that they are the same size. If so, we know 6516 // that the element size of the sext'd result matches the element size of 6517 // the compare operands. 6518 SDLoc DL(N); 6519 SDValue VecOnes = DAG.getConstant(1, DL, VT); 6520 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 6521 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6522 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 6523 N0.getOperand(1), N0.getOperand(2)); 6524 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 6525 } 6526 6527 // If the desired elements are smaller or larger than the source 6528 // elements we can use a matching integer vector type and then 6529 // truncate/sign extend. 6530 EVT MatchingElementType = EVT::getIntegerVT( 6531 *DAG.getContext(), N00VT.getScalarType().getSizeInBits()); 6532 EVT MatchingVectorType = EVT::getVectorVT( 6533 *DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements()); 6534 SDValue VsetCC = 6535 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 6536 N0.getOperand(1), N0.getOperand(2)); 6537 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 6538 VecOnes); 6539 } 6540 6541 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6542 SDLoc DL(N); 6543 if (SDValue SCC = SimplifySelectCC( 6544 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6545 DAG.getConstant(0, DL, VT), 6546 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6547 return SCC; 6548 } 6549 6550 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6551 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6552 isa<ConstantSDNode>(N0.getOperand(1)) && 6553 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6554 N0.hasOneUse()) { 6555 SDValue ShAmt = N0.getOperand(1); 6556 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6557 if (N0.getOpcode() == ISD::SHL) { 6558 SDValue InnerZExt = N0.getOperand(0); 6559 // If the original shl may be shifting out bits, do not perform this 6560 // transformation. 6561 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6562 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6563 if (ShAmtVal > KnownZeroBits) 6564 return SDValue(); 6565 } 6566 6567 SDLoc DL(N); 6568 6569 // Ensure that the shift amount is wide enough for the shifted value. 6570 if (VT.getSizeInBits() >= 256) 6571 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6572 6573 return DAG.getNode(N0.getOpcode(), DL, VT, 6574 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6575 ShAmt); 6576 } 6577 6578 return SDValue(); 6579 } 6580 6581 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6582 SDValue N0 = N->getOperand(0); 6583 EVT VT = N->getValueType(0); 6584 6585 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6586 LegalOperations)) 6587 return SDValue(Res, 0); 6588 6589 // fold (aext (aext x)) -> (aext x) 6590 // fold (aext (zext x)) -> (zext x) 6591 // fold (aext (sext x)) -> (sext x) 6592 if (N0.getOpcode() == ISD::ANY_EXTEND || 6593 N0.getOpcode() == ISD::ZERO_EXTEND || 6594 N0.getOpcode() == ISD::SIGN_EXTEND) 6595 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6596 6597 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6598 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6599 if (N0.getOpcode() == ISD::TRUNCATE) { 6600 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6601 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6602 if (NarrowLoad.getNode() != N0.getNode()) { 6603 CombineTo(N0.getNode(), NarrowLoad); 6604 // CombineTo deleted the truncate, if needed, but not what's under it. 6605 AddToWorklist(oye); 6606 } 6607 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6608 } 6609 } 6610 6611 // fold (aext (truncate x)) 6612 if (N0.getOpcode() == ISD::TRUNCATE) { 6613 SDValue TruncOp = N0.getOperand(0); 6614 if (TruncOp.getValueType() == VT) 6615 return TruncOp; // x iff x size == zext size. 6616 if (TruncOp.getValueType().bitsGT(VT)) 6617 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6618 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6619 } 6620 6621 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6622 // if the trunc is not free. 6623 if (N0.getOpcode() == ISD::AND && 6624 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6625 N0.getOperand(1).getOpcode() == ISD::Constant && 6626 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6627 N0.getValueType())) { 6628 SDValue X = N0.getOperand(0).getOperand(0); 6629 if (X.getValueType().bitsLT(VT)) { 6630 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6631 } else if (X.getValueType().bitsGT(VT)) { 6632 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6633 } 6634 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6635 Mask = Mask.zext(VT.getSizeInBits()); 6636 SDLoc DL(N); 6637 return DAG.getNode(ISD::AND, DL, VT, 6638 X, DAG.getConstant(Mask, DL, VT)); 6639 } 6640 6641 // fold (aext (load x)) -> (aext (truncate (extload x))) 6642 // None of the supported targets knows how to perform load and any_ext 6643 // on vectors in one instruction. We only perform this transformation on 6644 // scalars. 6645 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6646 ISD::isUNINDEXEDLoad(N0.getNode()) && 6647 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6648 bool DoXform = true; 6649 SmallVector<SDNode*, 4> SetCCs; 6650 if (!N0.hasOneUse()) 6651 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6652 if (DoXform) { 6653 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6654 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6655 LN0->getChain(), 6656 LN0->getBasePtr(), N0.getValueType(), 6657 LN0->getMemOperand()); 6658 CombineTo(N, ExtLoad); 6659 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6660 N0.getValueType(), ExtLoad); 6661 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6662 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6663 ISD::ANY_EXTEND); 6664 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6665 } 6666 } 6667 6668 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6669 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6670 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6671 if (N0.getOpcode() == ISD::LOAD && 6672 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6673 N0.hasOneUse()) { 6674 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6675 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6676 EVT MemVT = LN0->getMemoryVT(); 6677 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6678 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6679 VT, LN0->getChain(), LN0->getBasePtr(), 6680 MemVT, LN0->getMemOperand()); 6681 CombineTo(N, ExtLoad); 6682 CombineTo(N0.getNode(), 6683 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6684 N0.getValueType(), ExtLoad), 6685 ExtLoad.getValue(1)); 6686 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6687 } 6688 } 6689 6690 if (N0.getOpcode() == ISD::SETCC) { 6691 // For vectors: 6692 // aext(setcc) -> vsetcc 6693 // aext(setcc) -> truncate(vsetcc) 6694 // aext(setcc) -> aext(vsetcc) 6695 // Only do this before legalize for now. 6696 if (VT.isVector() && !LegalOperations) { 6697 EVT N0VT = N0.getOperand(0).getValueType(); 6698 // We know that the # elements of the results is the same as the 6699 // # elements of the compare (and the # elements of the compare result 6700 // for that matter). Check to see that they are the same size. If so, 6701 // we know that the element size of the sext'd result matches the 6702 // element size of the compare operands. 6703 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6704 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6705 N0.getOperand(1), 6706 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6707 // If the desired elements are smaller or larger than the source 6708 // elements we can use a matching integer vector type and then 6709 // truncate/any extend 6710 else { 6711 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6712 SDValue VsetCC = 6713 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6714 N0.getOperand(1), 6715 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6716 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6717 } 6718 } 6719 6720 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6721 SDLoc DL(N); 6722 if (SDValue SCC = SimplifySelectCC( 6723 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6724 DAG.getConstant(0, DL, VT), 6725 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6726 return SCC; 6727 } 6728 6729 return SDValue(); 6730 } 6731 6732 /// See if the specified operand can be simplified with the knowledge that only 6733 /// the bits specified by Mask are used. If so, return the simpler operand, 6734 /// otherwise return a null SDValue. 6735 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6736 switch (V.getOpcode()) { 6737 default: break; 6738 case ISD::Constant: { 6739 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6740 assert(CV && "Const value should be ConstSDNode."); 6741 const APInt &CVal = CV->getAPIntValue(); 6742 APInt NewVal = CVal & Mask; 6743 if (NewVal != CVal) 6744 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6745 break; 6746 } 6747 case ISD::OR: 6748 case ISD::XOR: 6749 // If the LHS or RHS don't contribute bits to the or, drop them. 6750 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6751 return V.getOperand(1); 6752 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6753 return V.getOperand(0); 6754 break; 6755 case ISD::SRL: 6756 // Only look at single-use SRLs. 6757 if (!V.getNode()->hasOneUse()) 6758 break; 6759 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6760 // See if we can recursively simplify the LHS. 6761 unsigned Amt = RHSC->getZExtValue(); 6762 6763 // Watch out for shift count overflow though. 6764 if (Amt >= Mask.getBitWidth()) break; 6765 APInt NewMask = Mask << Amt; 6766 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6767 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6768 SimplifyLHS, V.getOperand(1)); 6769 } 6770 } 6771 return SDValue(); 6772 } 6773 6774 /// If the result of a wider load is shifted to right of N bits and then 6775 /// truncated to a narrower type and where N is a multiple of number of bits of 6776 /// the narrower type, transform it to a narrower load from address + N / num of 6777 /// bits of new type. If the result is to be extended, also fold the extension 6778 /// to form a extending load. 6779 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6780 unsigned Opc = N->getOpcode(); 6781 6782 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6783 SDValue N0 = N->getOperand(0); 6784 EVT VT = N->getValueType(0); 6785 EVT ExtVT = VT; 6786 6787 // This transformation isn't valid for vector loads. 6788 if (VT.isVector()) 6789 return SDValue(); 6790 6791 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6792 // extended to VT. 6793 if (Opc == ISD::SIGN_EXTEND_INREG) { 6794 ExtType = ISD::SEXTLOAD; 6795 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6796 } else if (Opc == ISD::SRL) { 6797 // Another special-case: SRL is basically zero-extending a narrower value. 6798 ExtType = ISD::ZEXTLOAD; 6799 N0 = SDValue(N, 0); 6800 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6801 if (!N01) return SDValue(); 6802 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6803 VT.getSizeInBits() - N01->getZExtValue()); 6804 } 6805 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6806 return SDValue(); 6807 6808 unsigned EVTBits = ExtVT.getSizeInBits(); 6809 6810 // Do not generate loads of non-round integer types since these can 6811 // be expensive (and would be wrong if the type is not byte sized). 6812 if (!ExtVT.isRound()) 6813 return SDValue(); 6814 6815 unsigned ShAmt = 0; 6816 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6817 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6818 ShAmt = N01->getZExtValue(); 6819 // Is the shift amount a multiple of size of VT? 6820 if ((ShAmt & (EVTBits-1)) == 0) { 6821 N0 = N0.getOperand(0); 6822 // Is the load width a multiple of size of VT? 6823 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6824 return SDValue(); 6825 } 6826 6827 // At this point, we must have a load or else we can't do the transform. 6828 if (!isa<LoadSDNode>(N0)) return SDValue(); 6829 6830 // Because a SRL must be assumed to *need* to zero-extend the high bits 6831 // (as opposed to anyext the high bits), we can't combine the zextload 6832 // lowering of SRL and an sextload. 6833 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6834 return SDValue(); 6835 6836 // If the shift amount is larger than the input type then we're not 6837 // accessing any of the loaded bytes. If the load was a zextload/extload 6838 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6839 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6840 return SDValue(); 6841 } 6842 } 6843 6844 // If the load is shifted left (and the result isn't shifted back right), 6845 // we can fold the truncate through the shift. 6846 unsigned ShLeftAmt = 0; 6847 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6848 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6849 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6850 ShLeftAmt = N01->getZExtValue(); 6851 N0 = N0.getOperand(0); 6852 } 6853 } 6854 6855 // If we haven't found a load, we can't narrow it. Don't transform one with 6856 // multiple uses, this would require adding a new load. 6857 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6858 return SDValue(); 6859 6860 // Don't change the width of a volatile load. 6861 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6862 if (LN0->isVolatile()) 6863 return SDValue(); 6864 6865 // Verify that we are actually reducing a load width here. 6866 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6867 return SDValue(); 6868 6869 // For the transform to be legal, the load must produce only two values 6870 // (the value loaded and the chain). Don't transform a pre-increment 6871 // load, for example, which produces an extra value. Otherwise the 6872 // transformation is not equivalent, and the downstream logic to replace 6873 // uses gets things wrong. 6874 if (LN0->getNumValues() > 2) 6875 return SDValue(); 6876 6877 // If the load that we're shrinking is an extload and we're not just 6878 // discarding the extension we can't simply shrink the load. Bail. 6879 // TODO: It would be possible to merge the extensions in some cases. 6880 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6881 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6882 return SDValue(); 6883 6884 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6885 return SDValue(); 6886 6887 EVT PtrType = N0.getOperand(1).getValueType(); 6888 6889 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6890 // It's not possible to generate a constant of extended or untyped type. 6891 return SDValue(); 6892 6893 // For big endian targets, we need to adjust the offset to the pointer to 6894 // load the correct bytes. 6895 if (DAG.getDataLayout().isBigEndian()) { 6896 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6897 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6898 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6899 } 6900 6901 uint64_t PtrOff = ShAmt / 8; 6902 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6903 SDLoc DL(LN0); 6904 // The original load itself didn't wrap, so an offset within it doesn't. 6905 SDNodeFlags Flags; 6906 Flags.setNoUnsignedWrap(true); 6907 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6908 PtrType, LN0->getBasePtr(), 6909 DAG.getConstant(PtrOff, DL, PtrType), 6910 &Flags); 6911 AddToWorklist(NewPtr.getNode()); 6912 6913 SDValue Load; 6914 if (ExtType == ISD::NON_EXTLOAD) 6915 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6916 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 6917 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 6918 else 6919 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 6920 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 6921 NewAlign, LN0->getMemOperand()->getFlags(), 6922 LN0->getAAInfo()); 6923 6924 // Replace the old load's chain with the new load's chain. 6925 WorklistRemover DeadNodes(*this); 6926 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6927 6928 // Shift the result left, if we've swallowed a left shift. 6929 SDValue Result = Load; 6930 if (ShLeftAmt != 0) { 6931 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6932 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6933 ShImmTy = VT; 6934 // If the shift amount is as large as the result size (but, presumably, 6935 // no larger than the source) then the useful bits of the result are 6936 // zero; we can't simply return the shortened shift, because the result 6937 // of that operation is undefined. 6938 SDLoc DL(N0); 6939 if (ShLeftAmt >= VT.getSizeInBits()) 6940 Result = DAG.getConstant(0, DL, VT); 6941 else 6942 Result = DAG.getNode(ISD::SHL, DL, VT, 6943 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6944 } 6945 6946 // Return the new loaded value. 6947 return Result; 6948 } 6949 6950 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6951 SDValue N0 = N->getOperand(0); 6952 SDValue N1 = N->getOperand(1); 6953 EVT VT = N->getValueType(0); 6954 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6955 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6956 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6957 6958 if (N0.isUndef()) 6959 return DAG.getUNDEF(VT); 6960 6961 // fold (sext_in_reg c1) -> c1 6962 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6963 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6964 6965 // If the input is already sign extended, just drop the extension. 6966 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6967 return N0; 6968 6969 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6970 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6971 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6972 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6973 N0.getOperand(0), N1); 6974 6975 // fold (sext_in_reg (sext x)) -> (sext x) 6976 // fold (sext_in_reg (aext x)) -> (sext x) 6977 // if x is small enough. 6978 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6979 SDValue N00 = N0.getOperand(0); 6980 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6981 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6982 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6983 } 6984 6985 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6986 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6987 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6988 6989 // fold operands of sext_in_reg based on knowledge that the top bits are not 6990 // demanded. 6991 if (SimplifyDemandedBits(SDValue(N, 0))) 6992 return SDValue(N, 0); 6993 6994 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6995 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6996 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6997 return NarrowLoad; 6998 6999 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 7000 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 7001 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 7002 if (N0.getOpcode() == ISD::SRL) { 7003 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 7004 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 7005 // We can turn this into an SRA iff the input to the SRL is already sign 7006 // extended enough. 7007 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 7008 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 7009 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 7010 N0.getOperand(0), N0.getOperand(1)); 7011 } 7012 } 7013 7014 // fold (sext_inreg (extload x)) -> (sextload x) 7015 if (ISD::isEXTLoad(N0.getNode()) && 7016 ISD::isUNINDEXEDLoad(N0.getNode()) && 7017 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7018 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7019 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7020 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7021 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7022 LN0->getChain(), 7023 LN0->getBasePtr(), EVT, 7024 LN0->getMemOperand()); 7025 CombineTo(N, ExtLoad); 7026 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7027 AddToWorklist(ExtLoad.getNode()); 7028 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7029 } 7030 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 7031 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7032 N0.hasOneUse() && 7033 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7034 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7035 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7036 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7037 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7038 LN0->getChain(), 7039 LN0->getBasePtr(), EVT, 7040 LN0->getMemOperand()); 7041 CombineTo(N, ExtLoad); 7042 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7043 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7044 } 7045 7046 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7047 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7048 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7049 N0.getOperand(1), false)) 7050 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7051 BSwap, N1); 7052 } 7053 7054 return SDValue(); 7055 } 7056 7057 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7058 SDValue N0 = N->getOperand(0); 7059 EVT VT = N->getValueType(0); 7060 7061 if (N0.isUndef()) 7062 return DAG.getUNDEF(VT); 7063 7064 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7065 LegalOperations)) 7066 return SDValue(Res, 0); 7067 7068 return SDValue(); 7069 } 7070 7071 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7072 SDValue N0 = N->getOperand(0); 7073 EVT VT = N->getValueType(0); 7074 7075 if (N0.isUndef()) 7076 return DAG.getUNDEF(VT); 7077 7078 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7079 LegalOperations)) 7080 return SDValue(Res, 0); 7081 7082 return SDValue(); 7083 } 7084 7085 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7086 SDValue N0 = N->getOperand(0); 7087 EVT VT = N->getValueType(0); 7088 bool isLE = DAG.getDataLayout().isLittleEndian(); 7089 7090 // noop truncate 7091 if (N0.getValueType() == N->getValueType(0)) 7092 return N0; 7093 // fold (truncate c1) -> c1 7094 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7095 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7096 // fold (truncate (truncate x)) -> (truncate x) 7097 if (N0.getOpcode() == ISD::TRUNCATE) 7098 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7099 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7100 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7101 N0.getOpcode() == ISD::SIGN_EXTEND || 7102 N0.getOpcode() == ISD::ANY_EXTEND) { 7103 // if the source is smaller than the dest, we still need an extend. 7104 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7105 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7106 // if the source is larger than the dest, than we just need the truncate. 7107 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7108 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7109 // if the source and dest are the same type, we can drop both the extend 7110 // and the truncate. 7111 return N0.getOperand(0); 7112 } 7113 7114 // Fold extract-and-trunc into a narrow extract. For example: 7115 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7116 // i32 y = TRUNCATE(i64 x) 7117 // -- becomes -- 7118 // v16i8 b = BITCAST (v2i64 val) 7119 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7120 // 7121 // Note: We only run this optimization after type legalization (which often 7122 // creates this pattern) and before operation legalization after which 7123 // we need to be more careful about the vector instructions that we generate. 7124 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7125 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7126 7127 EVT VecTy = N0.getOperand(0).getValueType(); 7128 EVT ExTy = N0.getValueType(); 7129 EVT TrTy = N->getValueType(0); 7130 7131 unsigned NumElem = VecTy.getVectorNumElements(); 7132 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7133 7134 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7135 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7136 7137 SDValue EltNo = N0->getOperand(1); 7138 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7139 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7140 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7141 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7142 7143 SDLoc DL(N); 7144 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7145 DAG.getBitcast(NVT, N0.getOperand(0)), 7146 DAG.getConstant(Index, DL, IndexTy)); 7147 } 7148 } 7149 7150 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7151 if (N0.getOpcode() == ISD::SELECT) { 7152 EVT SrcVT = N0.getValueType(); 7153 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7154 TLI.isTruncateFree(SrcVT, VT)) { 7155 SDLoc SL(N0); 7156 SDValue Cond = N0.getOperand(0); 7157 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7158 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7159 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7160 } 7161 } 7162 7163 // trunc (shl x, K) -> shl (trunc x), K => K < vt.size / 2 7164 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 7165 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 7166 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 7167 if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) { 7168 uint64_t Amt = CAmt->getZExtValue(); 7169 unsigned Size = VT.getSizeInBits(); 7170 7171 if (Amt < Size / 2) { 7172 SDLoc SL(N); 7173 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 7174 7175 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 7176 return DAG.getNode(ISD::SHL, SL, VT, Trunc, 7177 DAG.getConstant(Amt, SL, AmtVT)); 7178 } 7179 } 7180 } 7181 7182 // Fold a series of buildvector, bitcast, and truncate if possible. 7183 // For example fold 7184 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7185 // (2xi32 (buildvector x, y)). 7186 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7187 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7188 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7189 N0.getOperand(0).hasOneUse()) { 7190 7191 SDValue BuildVect = N0.getOperand(0); 7192 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7193 EVT TruncVecEltTy = VT.getVectorElementType(); 7194 7195 // Check that the element types match. 7196 if (BuildVectEltTy == TruncVecEltTy) { 7197 // Now we only need to compute the offset of the truncated elements. 7198 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7199 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7200 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7201 7202 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7203 "Invalid number of elements"); 7204 7205 SmallVector<SDValue, 8> Opnds; 7206 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7207 Opnds.push_back(BuildVect.getOperand(i)); 7208 7209 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 7210 } 7211 } 7212 7213 // See if we can simplify the input to this truncate through knowledge that 7214 // only the low bits are being used. 7215 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7216 // Currently we only perform this optimization on scalars because vectors 7217 // may have different active low bits. 7218 if (!VT.isVector()) { 7219 if (SDValue Shorter = 7220 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7221 VT.getSizeInBits()))) 7222 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7223 } 7224 // fold (truncate (load x)) -> (smaller load x) 7225 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7226 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7227 if (SDValue Reduced = ReduceLoadWidth(N)) 7228 return Reduced; 7229 7230 // Handle the case where the load remains an extending load even 7231 // after truncation. 7232 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7233 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7234 if (!LN0->isVolatile() && 7235 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7236 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7237 VT, LN0->getChain(), LN0->getBasePtr(), 7238 LN0->getMemoryVT(), 7239 LN0->getMemOperand()); 7240 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7241 return NewLoad; 7242 } 7243 } 7244 } 7245 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7246 // where ... are all 'undef'. 7247 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7248 SmallVector<EVT, 8> VTs; 7249 SDValue V; 7250 unsigned Idx = 0; 7251 unsigned NumDefs = 0; 7252 7253 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7254 SDValue X = N0.getOperand(i); 7255 if (!X.isUndef()) { 7256 V = X; 7257 Idx = i; 7258 NumDefs++; 7259 } 7260 // Stop if more than one members are non-undef. 7261 if (NumDefs > 1) 7262 break; 7263 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7264 VT.getVectorElementType(), 7265 X.getValueType().getVectorNumElements())); 7266 } 7267 7268 if (NumDefs == 0) 7269 return DAG.getUNDEF(VT); 7270 7271 if (NumDefs == 1) { 7272 assert(V.getNode() && "The single defined operand is empty!"); 7273 SmallVector<SDValue, 8> Opnds; 7274 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7275 if (i != Idx) { 7276 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7277 continue; 7278 } 7279 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7280 AddToWorklist(NV.getNode()); 7281 Opnds.push_back(NV); 7282 } 7283 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7284 } 7285 } 7286 7287 // Fold truncate of a bitcast of a vector to an extract of the low vector 7288 // element. 7289 // 7290 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 7291 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 7292 SDValue VecSrc = N0.getOperand(0); 7293 EVT SrcVT = VecSrc.getValueType(); 7294 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 7295 (!LegalOperations || 7296 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 7297 SDLoc SL(N); 7298 7299 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 7300 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 7301 VecSrc, DAG.getConstant(0, SL, IdxVT)); 7302 } 7303 } 7304 7305 // Simplify the operands using demanded-bits information. 7306 if (!VT.isVector() && 7307 SimplifyDemandedBits(SDValue(N, 0))) 7308 return SDValue(N, 0); 7309 7310 return SDValue(); 7311 } 7312 7313 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7314 SDValue Elt = N->getOperand(i); 7315 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7316 return Elt.getNode(); 7317 return Elt.getOperand(Elt.getResNo()).getNode(); 7318 } 7319 7320 /// build_pair (load, load) -> load 7321 /// if load locations are consecutive. 7322 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7323 assert(N->getOpcode() == ISD::BUILD_PAIR); 7324 7325 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7326 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7327 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7328 LD1->getAddressSpace() != LD2->getAddressSpace()) 7329 return SDValue(); 7330 EVT LD1VT = LD1->getValueType(0); 7331 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 7332 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 7333 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 7334 unsigned Align = LD1->getAlignment(); 7335 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7336 VT.getTypeForEVT(*DAG.getContext())); 7337 7338 if (NewAlign <= Align && 7339 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7340 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 7341 LD1->getPointerInfo(), Align); 7342 } 7343 7344 return SDValue(); 7345 } 7346 7347 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7348 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7349 // and Lo parts; on big-endian machines it doesn't. 7350 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7351 } 7352 7353 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 7354 const TargetLowering &TLI) { 7355 // If this is not a bitcast to an FP type or if the target doesn't have 7356 // IEEE754-compliant FP logic, we're done. 7357 EVT VT = N->getValueType(0); 7358 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 7359 return SDValue(); 7360 7361 // TODO: Use splat values for the constant-checking below and remove this 7362 // restriction. 7363 SDValue N0 = N->getOperand(0); 7364 EVT SourceVT = N0.getValueType(); 7365 if (SourceVT.isVector()) 7366 return SDValue(); 7367 7368 unsigned FPOpcode; 7369 APInt SignMask; 7370 switch (N0.getOpcode()) { 7371 case ISD::AND: 7372 FPOpcode = ISD::FABS; 7373 SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits()); 7374 break; 7375 case ISD::XOR: 7376 FPOpcode = ISD::FNEG; 7377 SignMask = APInt::getSignBit(SourceVT.getSizeInBits()); 7378 break; 7379 // TODO: ISD::OR --> ISD::FNABS? 7380 default: 7381 return SDValue(); 7382 } 7383 7384 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 7385 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 7386 SDValue LogicOp0 = N0.getOperand(0); 7387 ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7388 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 7389 LogicOp0.getOpcode() == ISD::BITCAST && 7390 LogicOp0->getOperand(0).getValueType() == VT) 7391 return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0)); 7392 7393 return SDValue(); 7394 } 7395 7396 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7397 SDValue N0 = N->getOperand(0); 7398 EVT VT = N->getValueType(0); 7399 7400 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7401 // Only do this before legalize, since afterward the target may be depending 7402 // on the bitconvert. 7403 // First check to see if this is all constant. 7404 if (!LegalTypes && 7405 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7406 VT.isVector()) { 7407 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7408 7409 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7410 assert(!DestEltVT.isVector() && 7411 "Element type of vector ValueType must not be vector!"); 7412 if (isSimple) 7413 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7414 } 7415 7416 // If the input is a constant, let getNode fold it. 7417 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7418 // If we can't allow illegal operations, we need to check that this is just 7419 // a fp -> int or int -> conversion and that the resulting operation will 7420 // be legal. 7421 if (!LegalOperations || 7422 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7423 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7424 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7425 TLI.isOperationLegal(ISD::Constant, VT))) 7426 return DAG.getBitcast(VT, N0); 7427 } 7428 7429 // (conv (conv x, t1), t2) -> (conv x, t2) 7430 if (N0.getOpcode() == ISD::BITCAST) 7431 return DAG.getBitcast(VT, N0.getOperand(0)); 7432 7433 // fold (conv (load x)) -> (load (conv*)x) 7434 // If the resultant load doesn't need a higher alignment than the original! 7435 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7436 // Do not change the width of a volatile load. 7437 !cast<LoadSDNode>(N0)->isVolatile() && 7438 // Do not remove the cast if the types differ in endian layout. 7439 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7440 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7441 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7442 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7443 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7444 unsigned OrigAlign = LN0->getAlignment(); 7445 7446 bool Fast = false; 7447 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7448 LN0->getAddressSpace(), OrigAlign, &Fast) && 7449 Fast) { 7450 SDValue Load = 7451 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 7452 LN0->getPointerInfo(), OrigAlign, 7453 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 7454 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7455 return Load; 7456 } 7457 } 7458 7459 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 7460 return V; 7461 7462 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7463 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7464 // 7465 // For ppc_fp128: 7466 // fold (bitcast (fneg x)) -> 7467 // flipbit = signbit 7468 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7469 // 7470 // fold (bitcast (fabs x)) -> 7471 // flipbit = (and (extract_element (bitcast x), 0), signbit) 7472 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7473 // This often reduces constant pool loads. 7474 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7475 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7476 N0.getNode()->hasOneUse() && VT.isInteger() && 7477 !VT.isVector() && !N0.getValueType().isVector()) { 7478 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 7479 AddToWorklist(NewConv.getNode()); 7480 7481 SDLoc DL(N); 7482 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7483 assert(VT.getSizeInBits() == 128); 7484 SDValue SignBit = DAG.getConstant( 7485 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 7486 SDValue FlipBit; 7487 if (N0.getOpcode() == ISD::FNEG) { 7488 FlipBit = SignBit; 7489 AddToWorklist(FlipBit.getNode()); 7490 } else { 7491 assert(N0.getOpcode() == ISD::FABS); 7492 SDValue Hi = 7493 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 7494 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7495 SDLoc(NewConv))); 7496 AddToWorklist(Hi.getNode()); 7497 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 7498 AddToWorklist(FlipBit.getNode()); 7499 } 7500 SDValue FlipBits = 7501 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7502 AddToWorklist(FlipBits.getNode()); 7503 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 7504 } 7505 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7506 if (N0.getOpcode() == ISD::FNEG) 7507 return DAG.getNode(ISD::XOR, DL, VT, 7508 NewConv, DAG.getConstant(SignBit, DL, VT)); 7509 assert(N0.getOpcode() == ISD::FABS); 7510 return DAG.getNode(ISD::AND, DL, VT, 7511 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7512 } 7513 7514 // fold (bitconvert (fcopysign cst, x)) -> 7515 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7516 // Note that we don't handle (copysign x, cst) because this can always be 7517 // folded to an fneg or fabs. 7518 // 7519 // For ppc_fp128: 7520 // fold (bitcast (fcopysign cst, x)) -> 7521 // flipbit = (and (extract_element 7522 // (xor (bitcast cst), (bitcast x)), 0), 7523 // signbit) 7524 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 7525 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7526 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7527 VT.isInteger() && !VT.isVector()) { 7528 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7529 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7530 if (isTypeLegal(IntXVT)) { 7531 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 7532 AddToWorklist(X.getNode()); 7533 7534 // If X has a different width than the result/lhs, sext it or truncate it. 7535 unsigned VTWidth = VT.getSizeInBits(); 7536 if (OrigXWidth < VTWidth) { 7537 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7538 AddToWorklist(X.getNode()); 7539 } else if (OrigXWidth > VTWidth) { 7540 // To get the sign bit in the right place, we have to shift it right 7541 // before truncating. 7542 SDLoc DL(X); 7543 X = DAG.getNode(ISD::SRL, DL, 7544 X.getValueType(), X, 7545 DAG.getConstant(OrigXWidth-VTWidth, DL, 7546 X.getValueType())); 7547 AddToWorklist(X.getNode()); 7548 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7549 AddToWorklist(X.getNode()); 7550 } 7551 7552 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7553 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 7554 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7555 AddToWorklist(Cst.getNode()); 7556 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 7557 AddToWorklist(X.getNode()); 7558 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 7559 AddToWorklist(XorResult.getNode()); 7560 SDValue XorResult64 = DAG.getNode( 7561 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 7562 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7563 SDLoc(XorResult))); 7564 AddToWorklist(XorResult64.getNode()); 7565 SDValue FlipBit = 7566 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 7567 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 7568 AddToWorklist(FlipBit.getNode()); 7569 SDValue FlipBits = 7570 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7571 AddToWorklist(FlipBits.getNode()); 7572 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 7573 } 7574 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7575 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7576 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7577 AddToWorklist(X.getNode()); 7578 7579 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7580 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7581 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7582 AddToWorklist(Cst.getNode()); 7583 7584 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7585 } 7586 } 7587 7588 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7589 if (N0.getOpcode() == ISD::BUILD_PAIR) 7590 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7591 return CombineLD; 7592 7593 // Remove double bitcasts from shuffles - this is often a legacy of 7594 // XformToShuffleWithZero being used to combine bitmaskings (of 7595 // float vectors bitcast to integer vectors) into shuffles. 7596 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7597 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7598 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7599 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7600 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7601 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7602 7603 // If operands are a bitcast, peek through if it casts the original VT. 7604 // If operands are a constant, just bitcast back to original VT. 7605 auto PeekThroughBitcast = [&](SDValue Op) { 7606 if (Op.getOpcode() == ISD::BITCAST && 7607 Op.getOperand(0).getValueType() == VT) 7608 return SDValue(Op.getOperand(0)); 7609 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7610 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7611 return DAG.getBitcast(VT, Op); 7612 return SDValue(); 7613 }; 7614 7615 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7616 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7617 if (!(SV0 && SV1)) 7618 return SDValue(); 7619 7620 int MaskScale = 7621 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7622 SmallVector<int, 8> NewMask; 7623 for (int M : SVN->getMask()) 7624 for (int i = 0; i != MaskScale; ++i) 7625 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7626 7627 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7628 if (!LegalMask) { 7629 std::swap(SV0, SV1); 7630 ShuffleVectorSDNode::commuteMask(NewMask); 7631 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7632 } 7633 7634 if (LegalMask) 7635 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7636 } 7637 7638 return SDValue(); 7639 } 7640 7641 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7642 EVT VT = N->getValueType(0); 7643 return CombineConsecutiveLoads(N, VT); 7644 } 7645 7646 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7647 /// operands. DstEltVT indicates the destination element value type. 7648 SDValue DAGCombiner:: 7649 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7650 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7651 7652 // If this is already the right type, we're done. 7653 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7654 7655 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7656 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7657 7658 // If this is a conversion of N elements of one type to N elements of another 7659 // type, convert each element. This handles FP<->INT cases. 7660 if (SrcBitSize == DstBitSize) { 7661 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7662 BV->getValueType(0).getVectorNumElements()); 7663 7664 // Due to the FP element handling below calling this routine recursively, 7665 // we can end up with a scalar-to-vector node here. 7666 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7667 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7668 DAG.getBitcast(DstEltVT, BV->getOperand(0))); 7669 7670 SmallVector<SDValue, 8> Ops; 7671 for (SDValue Op : BV->op_values()) { 7672 // If the vector element type is not legal, the BUILD_VECTOR operands 7673 // are promoted and implicitly truncated. Make that explicit here. 7674 if (Op.getValueType() != SrcEltVT) 7675 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7676 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 7677 AddToWorklist(Ops.back().getNode()); 7678 } 7679 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 7680 } 7681 7682 // Otherwise, we're growing or shrinking the elements. To avoid having to 7683 // handle annoying details of growing/shrinking FP values, we convert them to 7684 // int first. 7685 if (SrcEltVT.isFloatingPoint()) { 7686 // Convert the input float vector to a int vector where the elements are the 7687 // same sizes. 7688 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7689 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7690 SrcEltVT = IntVT; 7691 } 7692 7693 // Now we know the input is an integer vector. If the output is a FP type, 7694 // convert to integer first, then to FP of the right size. 7695 if (DstEltVT.isFloatingPoint()) { 7696 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7697 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7698 7699 // Next, convert to FP elements of the same size. 7700 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7701 } 7702 7703 SDLoc DL(BV); 7704 7705 // Okay, we know the src/dst types are both integers of differing types. 7706 // Handling growing first. 7707 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7708 if (SrcBitSize < DstBitSize) { 7709 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7710 7711 SmallVector<SDValue, 8> Ops; 7712 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7713 i += NumInputsPerOutput) { 7714 bool isLE = DAG.getDataLayout().isLittleEndian(); 7715 APInt NewBits = APInt(DstBitSize, 0); 7716 bool EltIsUndef = true; 7717 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7718 // Shift the previously computed bits over. 7719 NewBits <<= SrcBitSize; 7720 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7721 if (Op.isUndef()) continue; 7722 EltIsUndef = false; 7723 7724 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7725 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7726 } 7727 7728 if (EltIsUndef) 7729 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7730 else 7731 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7732 } 7733 7734 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7735 return DAG.getBuildVector(VT, DL, Ops); 7736 } 7737 7738 // Finally, this must be the case where we are shrinking elements: each input 7739 // turns into multiple outputs. 7740 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7741 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7742 NumOutputsPerInput*BV->getNumOperands()); 7743 SmallVector<SDValue, 8> Ops; 7744 7745 for (const SDValue &Op : BV->op_values()) { 7746 if (Op.isUndef()) { 7747 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7748 continue; 7749 } 7750 7751 APInt OpVal = cast<ConstantSDNode>(Op)-> 7752 getAPIntValue().zextOrTrunc(SrcBitSize); 7753 7754 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7755 APInt ThisVal = OpVal.trunc(DstBitSize); 7756 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7757 OpVal = OpVal.lshr(DstBitSize); 7758 } 7759 7760 // For big endian targets, swap the order of the pieces of each element. 7761 if (DAG.getDataLayout().isBigEndian()) 7762 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7763 } 7764 7765 return DAG.getBuildVector(VT, DL, Ops); 7766 } 7767 7768 /// Try to perform FMA combining on a given FADD node. 7769 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7770 SDValue N0 = N->getOperand(0); 7771 SDValue N1 = N->getOperand(1); 7772 EVT VT = N->getValueType(0); 7773 SDLoc SL(N); 7774 7775 const TargetOptions &Options = DAG.getTarget().Options; 7776 bool AllowFusion = 7777 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7778 7779 // Floating-point multiply-add with intermediate rounding. 7780 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7781 7782 // Floating-point multiply-add without intermediate rounding. 7783 bool HasFMA = 7784 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7785 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7786 7787 // No valid opcode, do not combine. 7788 if (!HasFMAD && !HasFMA) 7789 return SDValue(); 7790 7791 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7792 ; 7793 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7794 return SDValue(); 7795 7796 // Always prefer FMAD to FMA for precision. 7797 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7798 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7799 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7800 7801 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7802 // prefer to fold the multiply with fewer uses. 7803 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7804 N1.getOpcode() == ISD::FMUL) { 7805 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7806 std::swap(N0, N1); 7807 } 7808 7809 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7810 if (N0.getOpcode() == ISD::FMUL && 7811 (Aggressive || N0->hasOneUse())) { 7812 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7813 N0.getOperand(0), N0.getOperand(1), N1); 7814 } 7815 7816 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7817 // Note: Commutes FADD operands. 7818 if (N1.getOpcode() == ISD::FMUL && 7819 (Aggressive || N1->hasOneUse())) { 7820 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7821 N1.getOperand(0), N1.getOperand(1), N0); 7822 } 7823 7824 // Look through FP_EXTEND nodes to do more combining. 7825 if (AllowFusion && LookThroughFPExt) { 7826 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7827 if (N0.getOpcode() == ISD::FP_EXTEND) { 7828 SDValue N00 = N0.getOperand(0); 7829 if (N00.getOpcode() == ISD::FMUL) 7830 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7831 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7832 N00.getOperand(0)), 7833 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7834 N00.getOperand(1)), N1); 7835 } 7836 7837 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7838 // Note: Commutes FADD operands. 7839 if (N1.getOpcode() == ISD::FP_EXTEND) { 7840 SDValue N10 = N1.getOperand(0); 7841 if (N10.getOpcode() == ISD::FMUL) 7842 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7843 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7844 N10.getOperand(0)), 7845 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7846 N10.getOperand(1)), N0); 7847 } 7848 } 7849 7850 // More folding opportunities when target permits. 7851 if ((AllowFusion || HasFMAD) && Aggressive) { 7852 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7853 if (N0.getOpcode() == PreferredFusedOpcode && 7854 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7855 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7856 N0.getOperand(0), N0.getOperand(1), 7857 DAG.getNode(PreferredFusedOpcode, SL, VT, 7858 N0.getOperand(2).getOperand(0), 7859 N0.getOperand(2).getOperand(1), 7860 N1)); 7861 } 7862 7863 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7864 if (N1->getOpcode() == PreferredFusedOpcode && 7865 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7866 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7867 N1.getOperand(0), N1.getOperand(1), 7868 DAG.getNode(PreferredFusedOpcode, SL, VT, 7869 N1.getOperand(2).getOperand(0), 7870 N1.getOperand(2).getOperand(1), 7871 N0)); 7872 } 7873 7874 if (AllowFusion && LookThroughFPExt) { 7875 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7876 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7877 auto FoldFAddFMAFPExtFMul = [&] ( 7878 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7879 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7880 DAG.getNode(PreferredFusedOpcode, SL, VT, 7881 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7882 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7883 Z)); 7884 }; 7885 if (N0.getOpcode() == PreferredFusedOpcode) { 7886 SDValue N02 = N0.getOperand(2); 7887 if (N02.getOpcode() == ISD::FP_EXTEND) { 7888 SDValue N020 = N02.getOperand(0); 7889 if (N020.getOpcode() == ISD::FMUL) 7890 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7891 N020.getOperand(0), N020.getOperand(1), 7892 N1); 7893 } 7894 } 7895 7896 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7897 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7898 // FIXME: This turns two single-precision and one double-precision 7899 // operation into two double-precision operations, which might not be 7900 // interesting for all targets, especially GPUs. 7901 auto FoldFAddFPExtFMAFMul = [&] ( 7902 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7903 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7904 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7905 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7906 DAG.getNode(PreferredFusedOpcode, SL, VT, 7907 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7908 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7909 Z)); 7910 }; 7911 if (N0.getOpcode() == ISD::FP_EXTEND) { 7912 SDValue N00 = N0.getOperand(0); 7913 if (N00.getOpcode() == PreferredFusedOpcode) { 7914 SDValue N002 = N00.getOperand(2); 7915 if (N002.getOpcode() == ISD::FMUL) 7916 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7917 N002.getOperand(0), N002.getOperand(1), 7918 N1); 7919 } 7920 } 7921 7922 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7923 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7924 if (N1.getOpcode() == PreferredFusedOpcode) { 7925 SDValue N12 = N1.getOperand(2); 7926 if (N12.getOpcode() == ISD::FP_EXTEND) { 7927 SDValue N120 = N12.getOperand(0); 7928 if (N120.getOpcode() == ISD::FMUL) 7929 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7930 N120.getOperand(0), N120.getOperand(1), 7931 N0); 7932 } 7933 } 7934 7935 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7936 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7937 // FIXME: This turns two single-precision and one double-precision 7938 // operation into two double-precision operations, which might not be 7939 // interesting for all targets, especially GPUs. 7940 if (N1.getOpcode() == ISD::FP_EXTEND) { 7941 SDValue N10 = N1.getOperand(0); 7942 if (N10.getOpcode() == PreferredFusedOpcode) { 7943 SDValue N102 = N10.getOperand(2); 7944 if (N102.getOpcode() == ISD::FMUL) 7945 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7946 N102.getOperand(0), N102.getOperand(1), 7947 N0); 7948 } 7949 } 7950 } 7951 } 7952 7953 return SDValue(); 7954 } 7955 7956 /// Try to perform FMA combining on a given FSUB node. 7957 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7958 SDValue N0 = N->getOperand(0); 7959 SDValue N1 = N->getOperand(1); 7960 EVT VT = N->getValueType(0); 7961 SDLoc SL(N); 7962 7963 const TargetOptions &Options = DAG.getTarget().Options; 7964 bool AllowFusion = 7965 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7966 7967 // Floating-point multiply-add with intermediate rounding. 7968 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7969 7970 // Floating-point multiply-add without intermediate rounding. 7971 bool HasFMA = 7972 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7973 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7974 7975 // No valid opcode, do not combine. 7976 if (!HasFMAD && !HasFMA) 7977 return SDValue(); 7978 7979 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7980 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7981 return SDValue(); 7982 7983 // Always prefer FMAD to FMA for precision. 7984 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7985 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7986 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7987 7988 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7989 if (N0.getOpcode() == ISD::FMUL && 7990 (Aggressive || N0->hasOneUse())) { 7991 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7992 N0.getOperand(0), N0.getOperand(1), 7993 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7994 } 7995 7996 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7997 // Note: Commutes FSUB operands. 7998 if (N1.getOpcode() == ISD::FMUL && 7999 (Aggressive || N1->hasOneUse())) 8000 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8001 DAG.getNode(ISD::FNEG, SL, VT, 8002 N1.getOperand(0)), 8003 N1.getOperand(1), N0); 8004 8005 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 8006 if (N0.getOpcode() == ISD::FNEG && 8007 N0.getOperand(0).getOpcode() == ISD::FMUL && 8008 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 8009 SDValue N00 = N0.getOperand(0).getOperand(0); 8010 SDValue N01 = N0.getOperand(0).getOperand(1); 8011 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8012 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 8013 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8014 } 8015 8016 // Look through FP_EXTEND nodes to do more combining. 8017 if (AllowFusion && LookThroughFPExt) { 8018 // fold (fsub (fpext (fmul x, y)), z) 8019 // -> (fma (fpext x), (fpext y), (fneg z)) 8020 if (N0.getOpcode() == ISD::FP_EXTEND) { 8021 SDValue N00 = N0.getOperand(0); 8022 if (N00.getOpcode() == ISD::FMUL) 8023 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8024 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8025 N00.getOperand(0)), 8026 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8027 N00.getOperand(1)), 8028 DAG.getNode(ISD::FNEG, SL, VT, N1)); 8029 } 8030 8031 // fold (fsub x, (fpext (fmul y, z))) 8032 // -> (fma (fneg (fpext y)), (fpext z), x) 8033 // Note: Commutes FSUB operands. 8034 if (N1.getOpcode() == ISD::FP_EXTEND) { 8035 SDValue N10 = N1.getOperand(0); 8036 if (N10.getOpcode() == ISD::FMUL) 8037 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8038 DAG.getNode(ISD::FNEG, SL, VT, 8039 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8040 N10.getOperand(0))), 8041 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8042 N10.getOperand(1)), 8043 N0); 8044 } 8045 8046 // fold (fsub (fpext (fneg (fmul, x, y))), z) 8047 // -> (fneg (fma (fpext x), (fpext y), z)) 8048 // Note: This could be removed with appropriate canonicalization of the 8049 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8050 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8051 // from implementing the canonicalization in visitFSUB. 8052 if (N0.getOpcode() == ISD::FP_EXTEND) { 8053 SDValue N00 = N0.getOperand(0); 8054 if (N00.getOpcode() == ISD::FNEG) { 8055 SDValue N000 = N00.getOperand(0); 8056 if (N000.getOpcode() == ISD::FMUL) { 8057 return DAG.getNode(ISD::FNEG, SL, VT, 8058 DAG.getNode(PreferredFusedOpcode, SL, VT, 8059 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8060 N000.getOperand(0)), 8061 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8062 N000.getOperand(1)), 8063 N1)); 8064 } 8065 } 8066 } 8067 8068 // fold (fsub (fneg (fpext (fmul, x, y))), z) 8069 // -> (fneg (fma (fpext x)), (fpext y), z) 8070 // Note: This could be removed with appropriate canonicalization of the 8071 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8072 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8073 // from implementing the canonicalization in visitFSUB. 8074 if (N0.getOpcode() == ISD::FNEG) { 8075 SDValue N00 = N0.getOperand(0); 8076 if (N00.getOpcode() == ISD::FP_EXTEND) { 8077 SDValue N000 = N00.getOperand(0); 8078 if (N000.getOpcode() == ISD::FMUL) { 8079 return DAG.getNode(ISD::FNEG, SL, VT, 8080 DAG.getNode(PreferredFusedOpcode, SL, VT, 8081 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8082 N000.getOperand(0)), 8083 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8084 N000.getOperand(1)), 8085 N1)); 8086 } 8087 } 8088 } 8089 8090 } 8091 8092 // More folding opportunities when target permits. 8093 if ((AllowFusion || HasFMAD) && Aggressive) { 8094 // fold (fsub (fma x, y, (fmul u, v)), z) 8095 // -> (fma x, y (fma u, v, (fneg z))) 8096 if (N0.getOpcode() == PreferredFusedOpcode && 8097 N0.getOperand(2).getOpcode() == ISD::FMUL) { 8098 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8099 N0.getOperand(0), N0.getOperand(1), 8100 DAG.getNode(PreferredFusedOpcode, SL, VT, 8101 N0.getOperand(2).getOperand(0), 8102 N0.getOperand(2).getOperand(1), 8103 DAG.getNode(ISD::FNEG, SL, VT, 8104 N1))); 8105 } 8106 8107 // fold (fsub x, (fma y, z, (fmul u, v))) 8108 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 8109 if (N1.getOpcode() == PreferredFusedOpcode && 8110 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8111 SDValue N20 = N1.getOperand(2).getOperand(0); 8112 SDValue N21 = N1.getOperand(2).getOperand(1); 8113 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8114 DAG.getNode(ISD::FNEG, SL, VT, 8115 N1.getOperand(0)), 8116 N1.getOperand(1), 8117 DAG.getNode(PreferredFusedOpcode, SL, VT, 8118 DAG.getNode(ISD::FNEG, SL, VT, N20), 8119 8120 N21, N0)); 8121 } 8122 8123 if (AllowFusion && LookThroughFPExt) { 8124 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 8125 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8126 if (N0.getOpcode() == PreferredFusedOpcode) { 8127 SDValue N02 = N0.getOperand(2); 8128 if (N02.getOpcode() == ISD::FP_EXTEND) { 8129 SDValue N020 = N02.getOperand(0); 8130 if (N020.getOpcode() == ISD::FMUL) 8131 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8132 N0.getOperand(0), N0.getOperand(1), 8133 DAG.getNode(PreferredFusedOpcode, SL, VT, 8134 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8135 N020.getOperand(0)), 8136 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8137 N020.getOperand(1)), 8138 DAG.getNode(ISD::FNEG, SL, VT, 8139 N1))); 8140 } 8141 } 8142 8143 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8144 // -> (fma (fpext x), (fpext y), 8145 // (fma (fpext u), (fpext v), (fneg z))) 8146 // FIXME: This turns two single-precision and one double-precision 8147 // operation into two double-precision operations, which might not be 8148 // interesting for all targets, especially GPUs. 8149 if (N0.getOpcode() == ISD::FP_EXTEND) { 8150 SDValue N00 = N0.getOperand(0); 8151 if (N00.getOpcode() == PreferredFusedOpcode) { 8152 SDValue N002 = N00.getOperand(2); 8153 if (N002.getOpcode() == ISD::FMUL) 8154 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8155 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8156 N00.getOperand(0)), 8157 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8158 N00.getOperand(1)), 8159 DAG.getNode(PreferredFusedOpcode, SL, VT, 8160 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8161 N002.getOperand(0)), 8162 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8163 N002.getOperand(1)), 8164 DAG.getNode(ISD::FNEG, SL, VT, 8165 N1))); 8166 } 8167 } 8168 8169 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8170 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8171 if (N1.getOpcode() == PreferredFusedOpcode && 8172 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8173 SDValue N120 = N1.getOperand(2).getOperand(0); 8174 if (N120.getOpcode() == ISD::FMUL) { 8175 SDValue N1200 = N120.getOperand(0); 8176 SDValue N1201 = N120.getOperand(1); 8177 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8178 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8179 N1.getOperand(1), 8180 DAG.getNode(PreferredFusedOpcode, SL, VT, 8181 DAG.getNode(ISD::FNEG, SL, VT, 8182 DAG.getNode(ISD::FP_EXTEND, SL, 8183 VT, N1200)), 8184 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8185 N1201), 8186 N0)); 8187 } 8188 } 8189 8190 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8191 // -> (fma (fneg (fpext y)), (fpext z), 8192 // (fma (fneg (fpext u)), (fpext v), x)) 8193 // FIXME: This turns two single-precision and one double-precision 8194 // operation into two double-precision operations, which might not be 8195 // interesting for all targets, especially GPUs. 8196 if (N1.getOpcode() == ISD::FP_EXTEND && 8197 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8198 SDValue N100 = N1.getOperand(0).getOperand(0); 8199 SDValue N101 = N1.getOperand(0).getOperand(1); 8200 SDValue N102 = N1.getOperand(0).getOperand(2); 8201 if (N102.getOpcode() == ISD::FMUL) { 8202 SDValue N1020 = N102.getOperand(0); 8203 SDValue N1021 = N102.getOperand(1); 8204 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8205 DAG.getNode(ISD::FNEG, SL, VT, 8206 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8207 N100)), 8208 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8209 DAG.getNode(PreferredFusedOpcode, SL, VT, 8210 DAG.getNode(ISD::FNEG, SL, VT, 8211 DAG.getNode(ISD::FP_EXTEND, SL, 8212 VT, N1020)), 8213 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8214 N1021), 8215 N0)); 8216 } 8217 } 8218 } 8219 } 8220 8221 return SDValue(); 8222 } 8223 8224 /// Try to perform FMA combining on a given FMUL node. 8225 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 8226 SDValue N0 = N->getOperand(0); 8227 SDValue N1 = N->getOperand(1); 8228 EVT VT = N->getValueType(0); 8229 SDLoc SL(N); 8230 8231 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8232 8233 const TargetOptions &Options = DAG.getTarget().Options; 8234 bool AllowFusion = 8235 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8236 8237 // Floating-point multiply-add with intermediate rounding. 8238 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8239 8240 // Floating-point multiply-add without intermediate rounding. 8241 bool HasFMA = 8242 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8243 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8244 8245 // No valid opcode, do not combine. 8246 if (!HasFMAD && !HasFMA) 8247 return SDValue(); 8248 8249 // Always prefer FMAD to FMA for precision. 8250 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8251 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8252 8253 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8254 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8255 auto FuseFADD = [&](SDValue X, SDValue Y) { 8256 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8257 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8258 if (XC1 && XC1->isExactlyValue(+1.0)) 8259 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8260 if (XC1 && XC1->isExactlyValue(-1.0)) 8261 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8262 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8263 } 8264 return SDValue(); 8265 }; 8266 8267 if (SDValue FMA = FuseFADD(N0, N1)) 8268 return FMA; 8269 if (SDValue FMA = FuseFADD(N1, N0)) 8270 return FMA; 8271 8272 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8273 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8274 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8275 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8276 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8277 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8278 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8279 if (XC0 && XC0->isExactlyValue(+1.0)) 8280 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8281 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8282 Y); 8283 if (XC0 && XC0->isExactlyValue(-1.0)) 8284 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8285 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8286 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8287 8288 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8289 if (XC1 && XC1->isExactlyValue(+1.0)) 8290 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8291 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8292 if (XC1 && XC1->isExactlyValue(-1.0)) 8293 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8294 } 8295 return SDValue(); 8296 }; 8297 8298 if (SDValue FMA = FuseFSUB(N0, N1)) 8299 return FMA; 8300 if (SDValue FMA = FuseFSUB(N1, N0)) 8301 return FMA; 8302 8303 return SDValue(); 8304 } 8305 8306 SDValue DAGCombiner::visitFADD(SDNode *N) { 8307 SDValue N0 = N->getOperand(0); 8308 SDValue N1 = N->getOperand(1); 8309 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8310 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8311 EVT VT = N->getValueType(0); 8312 SDLoc DL(N); 8313 const TargetOptions &Options = DAG.getTarget().Options; 8314 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8315 8316 // fold vector ops 8317 if (VT.isVector()) 8318 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8319 return FoldedVOp; 8320 8321 // fold (fadd c1, c2) -> c1 + c2 8322 if (N0CFP && N1CFP) 8323 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8324 8325 // canonicalize constant to RHS 8326 if (N0CFP && !N1CFP) 8327 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8328 8329 // fold (fadd A, (fneg B)) -> (fsub A, B) 8330 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8331 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8332 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8333 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8334 8335 // fold (fadd (fneg A), B) -> (fsub B, A) 8336 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8337 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8338 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8339 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8340 8341 // If 'unsafe math' is enabled, fold lots of things. 8342 if (Options.UnsafeFPMath) { 8343 // No FP constant should be created after legalization as Instruction 8344 // Selection pass has a hard time dealing with FP constants. 8345 bool AllowNewConst = (Level < AfterLegalizeDAG); 8346 8347 // fold (fadd A, 0) -> A 8348 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8349 if (N1C->isZero()) 8350 return N0; 8351 8352 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8353 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8354 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8355 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8356 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8357 Flags), 8358 Flags); 8359 8360 // If allowed, fold (fadd (fneg x), x) -> 0.0 8361 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8362 return DAG.getConstantFP(0.0, DL, VT); 8363 8364 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8365 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8366 return DAG.getConstantFP(0.0, DL, VT); 8367 8368 // We can fold chains of FADD's of the same value into multiplications. 8369 // This transform is not safe in general because we are reducing the number 8370 // of rounding steps. 8371 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8372 if (N0.getOpcode() == ISD::FMUL) { 8373 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8374 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8375 8376 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8377 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8378 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8379 DAG.getConstantFP(1.0, DL, VT), Flags); 8380 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8381 } 8382 8383 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8384 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8385 N1.getOperand(0) == N1.getOperand(1) && 8386 N0.getOperand(0) == N1.getOperand(0)) { 8387 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8388 DAG.getConstantFP(2.0, DL, VT), Flags); 8389 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8390 } 8391 } 8392 8393 if (N1.getOpcode() == ISD::FMUL) { 8394 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8395 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8396 8397 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8398 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8399 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8400 DAG.getConstantFP(1.0, DL, VT), Flags); 8401 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8402 } 8403 8404 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8405 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8406 N0.getOperand(0) == N0.getOperand(1) && 8407 N1.getOperand(0) == N0.getOperand(0)) { 8408 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8409 DAG.getConstantFP(2.0, DL, VT), Flags); 8410 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8411 } 8412 } 8413 8414 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8415 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8416 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8417 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8418 (N0.getOperand(0) == N1)) { 8419 return DAG.getNode(ISD::FMUL, DL, VT, 8420 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8421 } 8422 } 8423 8424 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8425 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8426 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8427 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8428 N1.getOperand(0) == N0) { 8429 return DAG.getNode(ISD::FMUL, DL, VT, 8430 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8431 } 8432 } 8433 8434 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8435 if (AllowNewConst && 8436 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8437 N0.getOperand(0) == N0.getOperand(1) && 8438 N1.getOperand(0) == N1.getOperand(1) && 8439 N0.getOperand(0) == N1.getOperand(0)) { 8440 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8441 DAG.getConstantFP(4.0, DL, VT), Flags); 8442 } 8443 } 8444 } // enable-unsafe-fp-math 8445 8446 // FADD -> FMA combines: 8447 if (SDValue Fused = visitFADDForFMACombine(N)) { 8448 AddToWorklist(Fused.getNode()); 8449 return Fused; 8450 } 8451 return SDValue(); 8452 } 8453 8454 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8455 SDValue N0 = N->getOperand(0); 8456 SDValue N1 = N->getOperand(1); 8457 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8458 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8459 EVT VT = N->getValueType(0); 8460 SDLoc dl(N); 8461 const TargetOptions &Options = DAG.getTarget().Options; 8462 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8463 8464 // fold vector ops 8465 if (VT.isVector()) 8466 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8467 return FoldedVOp; 8468 8469 // fold (fsub c1, c2) -> c1-c2 8470 if (N0CFP && N1CFP) 8471 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8472 8473 // fold (fsub A, (fneg B)) -> (fadd A, B) 8474 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8475 return DAG.getNode(ISD::FADD, dl, VT, N0, 8476 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8477 8478 // If 'unsafe math' is enabled, fold lots of things. 8479 if (Options.UnsafeFPMath) { 8480 // (fsub A, 0) -> A 8481 if (N1CFP && N1CFP->isZero()) 8482 return N0; 8483 8484 // (fsub 0, B) -> -B 8485 if (N0CFP && N0CFP->isZero()) { 8486 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8487 return GetNegatedExpression(N1, DAG, LegalOperations); 8488 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8489 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8490 } 8491 8492 // (fsub x, x) -> 0.0 8493 if (N0 == N1) 8494 return DAG.getConstantFP(0.0f, dl, VT); 8495 8496 // (fsub x, (fadd x, y)) -> (fneg y) 8497 // (fsub x, (fadd y, x)) -> (fneg y) 8498 if (N1.getOpcode() == ISD::FADD) { 8499 SDValue N10 = N1->getOperand(0); 8500 SDValue N11 = N1->getOperand(1); 8501 8502 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8503 return GetNegatedExpression(N11, DAG, LegalOperations); 8504 8505 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8506 return GetNegatedExpression(N10, DAG, LegalOperations); 8507 } 8508 } 8509 8510 // FSUB -> FMA combines: 8511 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8512 AddToWorklist(Fused.getNode()); 8513 return Fused; 8514 } 8515 8516 return SDValue(); 8517 } 8518 8519 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8520 SDValue N0 = N->getOperand(0); 8521 SDValue N1 = N->getOperand(1); 8522 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8523 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8524 EVT VT = N->getValueType(0); 8525 SDLoc DL(N); 8526 const TargetOptions &Options = DAG.getTarget().Options; 8527 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8528 8529 // fold vector ops 8530 if (VT.isVector()) { 8531 // This just handles C1 * C2 for vectors. Other vector folds are below. 8532 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8533 return FoldedVOp; 8534 } 8535 8536 // fold (fmul c1, c2) -> c1*c2 8537 if (N0CFP && N1CFP) 8538 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8539 8540 // canonicalize constant to RHS 8541 if (isConstantFPBuildVectorOrConstantFP(N0) && 8542 !isConstantFPBuildVectorOrConstantFP(N1)) 8543 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8544 8545 // fold (fmul A, 1.0) -> A 8546 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8547 return N0; 8548 8549 if (Options.UnsafeFPMath) { 8550 // fold (fmul A, 0) -> 0 8551 if (N1CFP && N1CFP->isZero()) 8552 return N1; 8553 8554 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8555 if (N0.getOpcode() == ISD::FMUL) { 8556 // Fold scalars or any vector constants (not just splats). 8557 // This fold is done in general by InstCombine, but extra fmul insts 8558 // may have been generated during lowering. 8559 SDValue N00 = N0.getOperand(0); 8560 SDValue N01 = N0.getOperand(1); 8561 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8562 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8563 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8564 8565 // Check 1: Make sure that the first operand of the inner multiply is NOT 8566 // a constant. Otherwise, we may induce infinite looping. 8567 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8568 // Check 2: Make sure that the second operand of the inner multiply and 8569 // the second operand of the outer multiply are constants. 8570 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8571 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8572 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8573 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8574 } 8575 } 8576 } 8577 8578 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8579 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8580 // during an early run of DAGCombiner can prevent folding with fmuls 8581 // inserted during lowering. 8582 if (N0.getOpcode() == ISD::FADD && 8583 (N0.getOperand(0) == N0.getOperand(1)) && 8584 N0.hasOneUse()) { 8585 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8586 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8587 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8588 } 8589 } 8590 8591 // fold (fmul X, 2.0) -> (fadd X, X) 8592 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8593 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8594 8595 // fold (fmul X, -1.0) -> (fneg X) 8596 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8597 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8598 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8599 8600 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8601 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8602 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8603 // Both can be negated for free, check to see if at least one is cheaper 8604 // negated. 8605 if (LHSNeg == 2 || RHSNeg == 2) 8606 return DAG.getNode(ISD::FMUL, DL, VT, 8607 GetNegatedExpression(N0, DAG, LegalOperations), 8608 GetNegatedExpression(N1, DAG, LegalOperations), 8609 Flags); 8610 } 8611 } 8612 8613 // FMUL -> FMA combines: 8614 if (SDValue Fused = visitFMULForFMACombine(N)) { 8615 AddToWorklist(Fused.getNode()); 8616 return Fused; 8617 } 8618 8619 return SDValue(); 8620 } 8621 8622 SDValue DAGCombiner::visitFMA(SDNode *N) { 8623 SDValue N0 = N->getOperand(0); 8624 SDValue N1 = N->getOperand(1); 8625 SDValue N2 = N->getOperand(2); 8626 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8627 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8628 EVT VT = N->getValueType(0); 8629 SDLoc dl(N); 8630 const TargetOptions &Options = DAG.getTarget().Options; 8631 8632 // Constant fold FMA. 8633 if (isa<ConstantFPSDNode>(N0) && 8634 isa<ConstantFPSDNode>(N1) && 8635 isa<ConstantFPSDNode>(N2)) { 8636 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8637 } 8638 8639 if (Options.UnsafeFPMath) { 8640 if (N0CFP && N0CFP->isZero()) 8641 return N2; 8642 if (N1CFP && N1CFP->isZero()) 8643 return N2; 8644 } 8645 // TODO: The FMA node should have flags that propagate to these nodes. 8646 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8647 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8648 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8649 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8650 8651 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8652 if (isConstantFPBuildVectorOrConstantFP(N0) && 8653 !isConstantFPBuildVectorOrConstantFP(N1)) 8654 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8655 8656 // TODO: FMA nodes should have flags that propagate to the created nodes. 8657 // For now, create a Flags object for use with all unsafe math transforms. 8658 SDNodeFlags Flags; 8659 Flags.setUnsafeAlgebra(true); 8660 8661 if (Options.UnsafeFPMath) { 8662 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8663 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8664 isConstantFPBuildVectorOrConstantFP(N1) && 8665 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8666 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8667 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8668 &Flags), &Flags); 8669 } 8670 8671 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8672 if (N0.getOpcode() == ISD::FMUL && 8673 isConstantFPBuildVectorOrConstantFP(N1) && 8674 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8675 return DAG.getNode(ISD::FMA, dl, VT, 8676 N0.getOperand(0), 8677 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8678 &Flags), 8679 N2); 8680 } 8681 } 8682 8683 // (fma x, 1, y) -> (fadd x, y) 8684 // (fma x, -1, y) -> (fadd (fneg x), y) 8685 if (N1CFP) { 8686 if (N1CFP->isExactlyValue(1.0)) 8687 // TODO: The FMA node should have flags that propagate to this node. 8688 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8689 8690 if (N1CFP->isExactlyValue(-1.0) && 8691 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8692 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8693 AddToWorklist(RHSNeg.getNode()); 8694 // TODO: The FMA node should have flags that propagate to this node. 8695 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8696 } 8697 } 8698 8699 if (Options.UnsafeFPMath) { 8700 // (fma x, c, x) -> (fmul x, (c+1)) 8701 if (N1CFP && N0 == N2) { 8702 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8703 DAG.getNode(ISD::FADD, dl, VT, 8704 N1, DAG.getConstantFP(1.0, dl, VT), 8705 &Flags), &Flags); 8706 } 8707 8708 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8709 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8710 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8711 DAG.getNode(ISD::FADD, dl, VT, 8712 N1, DAG.getConstantFP(-1.0, dl, VT), 8713 &Flags), &Flags); 8714 } 8715 } 8716 8717 return SDValue(); 8718 } 8719 8720 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8721 // reciprocal. 8722 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8723 // Notice that this is not always beneficial. One reason is different target 8724 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8725 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8726 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8727 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8728 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8729 const SDNodeFlags *Flags = N->getFlags(); 8730 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8731 return SDValue(); 8732 8733 // Skip if current node is a reciprocal. 8734 SDValue N0 = N->getOperand(0); 8735 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8736 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8737 return SDValue(); 8738 8739 // Exit early if the target does not want this transform or if there can't 8740 // possibly be enough uses of the divisor to make the transform worthwhile. 8741 SDValue N1 = N->getOperand(1); 8742 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8743 if (!MinUses || N1->use_size() < MinUses) 8744 return SDValue(); 8745 8746 // Find all FDIV users of the same divisor. 8747 // Use a set because duplicates may be present in the user list. 8748 SetVector<SDNode *> Users; 8749 for (auto *U : N1->uses()) { 8750 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8751 // This division is eligible for optimization only if global unsafe math 8752 // is enabled or if this division allows reciprocal formation. 8753 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8754 Users.insert(U); 8755 } 8756 } 8757 8758 // Now that we have the actual number of divisor uses, make sure it meets 8759 // the minimum threshold specified by the target. 8760 if (Users.size() < MinUses) 8761 return SDValue(); 8762 8763 EVT VT = N->getValueType(0); 8764 SDLoc DL(N); 8765 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8766 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8767 8768 // Dividend / Divisor -> Dividend * Reciprocal 8769 for (auto *U : Users) { 8770 SDValue Dividend = U->getOperand(0); 8771 if (Dividend != FPOne) { 8772 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8773 Reciprocal, Flags); 8774 CombineTo(U, NewNode); 8775 } else if (U != Reciprocal.getNode()) { 8776 // In the absence of fast-math-flags, this user node is always the 8777 // same node as Reciprocal, but with FMF they may be different nodes. 8778 CombineTo(U, Reciprocal); 8779 } 8780 } 8781 return SDValue(N, 0); // N was replaced. 8782 } 8783 8784 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8785 SDValue N0 = N->getOperand(0); 8786 SDValue N1 = N->getOperand(1); 8787 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8788 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8789 EVT VT = N->getValueType(0); 8790 SDLoc DL(N); 8791 const TargetOptions &Options = DAG.getTarget().Options; 8792 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8793 8794 // fold vector ops 8795 if (VT.isVector()) 8796 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8797 return FoldedVOp; 8798 8799 // fold (fdiv c1, c2) -> c1/c2 8800 if (N0CFP && N1CFP) 8801 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8802 8803 if (Options.UnsafeFPMath) { 8804 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8805 if (N1CFP) { 8806 // Compute the reciprocal 1.0 / c2. 8807 const APFloat &N1APF = N1CFP->getValueAPF(); 8808 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8809 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8810 // Only do the transform if the reciprocal is a legal fp immediate that 8811 // isn't too nasty (eg NaN, denormal, ...). 8812 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8813 (!LegalOperations || 8814 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8815 // backend)... we should handle this gracefully after Legalize. 8816 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8817 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8818 TLI.isFPImmLegal(Recip, VT))) 8819 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8820 DAG.getConstantFP(Recip, DL, VT), Flags); 8821 } 8822 8823 // If this FDIV is part of a reciprocal square root, it may be folded 8824 // into a target-specific square root estimate instruction. 8825 if (N1.getOpcode() == ISD::FSQRT) { 8826 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 8827 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8828 } 8829 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8830 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8831 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8832 Flags)) { 8833 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8834 AddToWorklist(RV.getNode()); 8835 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8836 } 8837 } else if (N1.getOpcode() == ISD::FP_ROUND && 8838 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8839 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8840 Flags)) { 8841 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8842 AddToWorklist(RV.getNode()); 8843 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8844 } 8845 } else if (N1.getOpcode() == ISD::FMUL) { 8846 // Look through an FMUL. Even though this won't remove the FDIV directly, 8847 // it's still worthwhile to get rid of the FSQRT if possible. 8848 SDValue SqrtOp; 8849 SDValue OtherOp; 8850 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8851 SqrtOp = N1.getOperand(0); 8852 OtherOp = N1.getOperand(1); 8853 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8854 SqrtOp = N1.getOperand(1); 8855 OtherOp = N1.getOperand(0); 8856 } 8857 if (SqrtOp.getNode()) { 8858 // We found a FSQRT, so try to make this fold: 8859 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8860 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8861 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8862 AddToWorklist(RV.getNode()); 8863 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8864 } 8865 } 8866 } 8867 8868 // Fold into a reciprocal estimate and multiply instead of a real divide. 8869 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8870 AddToWorklist(RV.getNode()); 8871 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8872 } 8873 } 8874 8875 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8876 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8877 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8878 // Both can be negated for free, check to see if at least one is cheaper 8879 // negated. 8880 if (LHSNeg == 2 || RHSNeg == 2) 8881 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8882 GetNegatedExpression(N0, DAG, LegalOperations), 8883 GetNegatedExpression(N1, DAG, LegalOperations), 8884 Flags); 8885 } 8886 } 8887 8888 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8889 return CombineRepeatedDivisors; 8890 8891 return SDValue(); 8892 } 8893 8894 SDValue DAGCombiner::visitFREM(SDNode *N) { 8895 SDValue N0 = N->getOperand(0); 8896 SDValue N1 = N->getOperand(1); 8897 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8898 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8899 EVT VT = N->getValueType(0); 8900 8901 // fold (frem c1, c2) -> fmod(c1,c2) 8902 if (N0CFP && N1CFP) 8903 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8904 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8905 8906 return SDValue(); 8907 } 8908 8909 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8910 if (!DAG.getTarget().Options.UnsafeFPMath) 8911 return SDValue(); 8912 8913 SDValue N0 = N->getOperand(0); 8914 if (TLI.isFsqrtCheap(N0, DAG)) 8915 return SDValue(); 8916 8917 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8918 // For now, create a Flags object for use with all unsafe math transforms. 8919 SDNodeFlags Flags; 8920 Flags.setUnsafeAlgebra(true); 8921 return buildSqrtEstimate(N0, &Flags); 8922 } 8923 8924 /// copysign(x, fp_extend(y)) -> copysign(x, y) 8925 /// copysign(x, fp_round(y)) -> copysign(x, y) 8926 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 8927 SDValue N1 = N->getOperand(1); 8928 if ((N1.getOpcode() == ISD::FP_EXTEND || 8929 N1.getOpcode() == ISD::FP_ROUND)) { 8930 // Do not optimize out type conversion of f128 type yet. 8931 // For some targets like x86_64, configuration is changed to keep one f128 8932 // value in one SSE register, but instruction selection cannot handle 8933 // FCOPYSIGN on SSE registers yet. 8934 EVT N1VT = N1->getValueType(0); 8935 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 8936 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 8937 } 8938 return false; 8939 } 8940 8941 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8942 SDValue N0 = N->getOperand(0); 8943 SDValue N1 = N->getOperand(1); 8944 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8945 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8946 EVT VT = N->getValueType(0); 8947 8948 if (N0CFP && N1CFP) // Constant fold 8949 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8950 8951 if (N1CFP) { 8952 const APFloat& V = N1CFP->getValueAPF(); 8953 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8954 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8955 if (!V.isNegative()) { 8956 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8957 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8958 } else { 8959 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8960 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8961 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8962 } 8963 } 8964 8965 // copysign(fabs(x), y) -> copysign(x, y) 8966 // copysign(fneg(x), y) -> copysign(x, y) 8967 // copysign(copysign(x,z), y) -> copysign(x, y) 8968 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8969 N0.getOpcode() == ISD::FCOPYSIGN) 8970 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8971 N0.getOperand(0), N1); 8972 8973 // copysign(x, abs(y)) -> abs(x) 8974 if (N1.getOpcode() == ISD::FABS) 8975 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8976 8977 // copysign(x, copysign(y,z)) -> copysign(x, z) 8978 if (N1.getOpcode() == ISD::FCOPYSIGN) 8979 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8980 N0, N1.getOperand(1)); 8981 8982 // copysign(x, fp_extend(y)) -> copysign(x, y) 8983 // copysign(x, fp_round(y)) -> copysign(x, y) 8984 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 8985 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8986 N0, N1.getOperand(0)); 8987 8988 return SDValue(); 8989 } 8990 8991 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8992 SDValue N0 = N->getOperand(0); 8993 EVT VT = N->getValueType(0); 8994 EVT OpVT = N0.getValueType(); 8995 8996 // fold (sint_to_fp c1) -> c1fp 8997 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 8998 // ...but only if the target supports immediate floating-point values 8999 (!LegalOperations || 9000 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9001 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9002 9003 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 9004 // but UINT_TO_FP is legal on this target, try to convert. 9005 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 9006 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 9007 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 9008 if (DAG.SignBitIsZero(N0)) 9009 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9010 } 9011 9012 // The next optimizations are desirable only if SELECT_CC can be lowered. 9013 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9014 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9015 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 9016 !VT.isVector() && 9017 (!LegalOperations || 9018 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9019 SDLoc DL(N); 9020 SDValue Ops[] = 9021 { N0.getOperand(0), N0.getOperand(1), 9022 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9023 N0.getOperand(2) }; 9024 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9025 } 9026 9027 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 9028 // (select_cc x, y, 1.0, 0.0,, cc) 9029 if (N0.getOpcode() == ISD::ZERO_EXTEND && 9030 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 9031 (!LegalOperations || 9032 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9033 SDLoc DL(N); 9034 SDValue Ops[] = 9035 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 9036 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9037 N0.getOperand(0).getOperand(2) }; 9038 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9039 } 9040 } 9041 9042 return SDValue(); 9043 } 9044 9045 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 9046 SDValue N0 = N->getOperand(0); 9047 EVT VT = N->getValueType(0); 9048 EVT OpVT = N0.getValueType(); 9049 9050 // fold (uint_to_fp c1) -> c1fp 9051 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9052 // ...but only if the target supports immediate floating-point values 9053 (!LegalOperations || 9054 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9055 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9056 9057 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 9058 // but SINT_TO_FP is legal on this target, try to convert. 9059 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 9060 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 9061 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 9062 if (DAG.SignBitIsZero(N0)) 9063 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9064 } 9065 9066 // The next optimizations are desirable only if SELECT_CC can be lowered. 9067 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9068 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9069 9070 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 9071 (!LegalOperations || 9072 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9073 SDLoc DL(N); 9074 SDValue Ops[] = 9075 { N0.getOperand(0), N0.getOperand(1), 9076 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9077 N0.getOperand(2) }; 9078 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9079 } 9080 } 9081 9082 return SDValue(); 9083 } 9084 9085 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 9086 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 9087 SDValue N0 = N->getOperand(0); 9088 EVT VT = N->getValueType(0); 9089 9090 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 9091 return SDValue(); 9092 9093 SDValue Src = N0.getOperand(0); 9094 EVT SrcVT = Src.getValueType(); 9095 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 9096 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 9097 9098 // We can safely assume the conversion won't overflow the output range, 9099 // because (for example) (uint8_t)18293.f is undefined behavior. 9100 9101 // Since we can assume the conversion won't overflow, our decision as to 9102 // whether the input will fit in the float should depend on the minimum 9103 // of the input range and output range. 9104 9105 // This means this is also safe for a signed input and unsigned output, since 9106 // a negative input would lead to undefined behavior. 9107 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 9108 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9109 unsigned ActualSize = std::min(InputSize, OutputSize); 9110 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9111 9112 // We can only fold away the float conversion if the input range can be 9113 // represented exactly in the float range. 9114 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9115 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9116 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9117 : ISD::ZERO_EXTEND; 9118 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9119 } 9120 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9121 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9122 return DAG.getBitcast(VT, Src); 9123 } 9124 return SDValue(); 9125 } 9126 9127 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9128 SDValue N0 = N->getOperand(0); 9129 EVT VT = N->getValueType(0); 9130 9131 // fold (fp_to_sint c1fp) -> c1 9132 if (isConstantFPBuildVectorOrConstantFP(N0)) 9133 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9134 9135 return FoldIntToFPToInt(N, DAG); 9136 } 9137 9138 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9139 SDValue N0 = N->getOperand(0); 9140 EVT VT = N->getValueType(0); 9141 9142 // fold (fp_to_uint c1fp) -> c1 9143 if (isConstantFPBuildVectorOrConstantFP(N0)) 9144 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9145 9146 return FoldIntToFPToInt(N, DAG); 9147 } 9148 9149 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9150 SDValue N0 = N->getOperand(0); 9151 SDValue N1 = N->getOperand(1); 9152 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9153 EVT VT = N->getValueType(0); 9154 9155 // fold (fp_round c1fp) -> c1fp 9156 if (N0CFP) 9157 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9158 9159 // fold (fp_round (fp_extend x)) -> x 9160 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9161 return N0.getOperand(0); 9162 9163 // fold (fp_round (fp_round x)) -> (fp_round x) 9164 if (N0.getOpcode() == ISD::FP_ROUND) { 9165 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9166 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 9167 9168 // Skip this folding if it results in an fp_round from f80 to f16. 9169 // 9170 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9171 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9172 // instructions from f32 or f64. Moreover, the first (value-preserving) 9173 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9174 // x86. 9175 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9176 return SDValue(); 9177 9178 // If the first fp_round isn't a value preserving truncation, it might 9179 // introduce a tie in the second fp_round, that wouldn't occur in the 9180 // single-step fp_round we want to fold to. 9181 // In other words, double rounding isn't the same as rounding. 9182 // Also, this is a value preserving truncation iff both fp_round's are. 9183 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9184 SDLoc DL(N); 9185 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9186 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9187 } 9188 } 9189 9190 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9191 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9192 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9193 N0.getOperand(0), N1); 9194 AddToWorklist(Tmp.getNode()); 9195 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9196 Tmp, N0.getOperand(1)); 9197 } 9198 9199 return SDValue(); 9200 } 9201 9202 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9203 SDValue N0 = N->getOperand(0); 9204 EVT VT = N->getValueType(0); 9205 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9206 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9207 9208 // fold (fp_round_inreg c1fp) -> c1fp 9209 if (N0CFP && isTypeLegal(EVT)) { 9210 SDLoc DL(N); 9211 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9212 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9213 } 9214 9215 return SDValue(); 9216 } 9217 9218 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9219 SDValue N0 = N->getOperand(0); 9220 EVT VT = N->getValueType(0); 9221 9222 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9223 if (N->hasOneUse() && 9224 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9225 return SDValue(); 9226 9227 // fold (fp_extend c1fp) -> c1fp 9228 if (isConstantFPBuildVectorOrConstantFP(N0)) 9229 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9230 9231 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9232 if (N0.getOpcode() == ISD::FP16_TO_FP && 9233 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9234 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9235 9236 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9237 // value of X. 9238 if (N0.getOpcode() == ISD::FP_ROUND 9239 && N0.getNode()->getConstantOperandVal(1) == 1) { 9240 SDValue In = N0.getOperand(0); 9241 if (In.getValueType() == VT) return In; 9242 if (VT.bitsLT(In.getValueType())) 9243 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9244 In, N0.getOperand(1)); 9245 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9246 } 9247 9248 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9249 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9250 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9251 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9252 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9253 LN0->getChain(), 9254 LN0->getBasePtr(), N0.getValueType(), 9255 LN0->getMemOperand()); 9256 CombineTo(N, ExtLoad); 9257 CombineTo(N0.getNode(), 9258 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9259 N0.getValueType(), ExtLoad, 9260 DAG.getIntPtrConstant(1, SDLoc(N0))), 9261 ExtLoad.getValue(1)); 9262 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9263 } 9264 9265 return SDValue(); 9266 } 9267 9268 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9269 SDValue N0 = N->getOperand(0); 9270 EVT VT = N->getValueType(0); 9271 9272 // fold (fceil c1) -> fceil(c1) 9273 if (isConstantFPBuildVectorOrConstantFP(N0)) 9274 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9275 9276 return SDValue(); 9277 } 9278 9279 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9280 SDValue N0 = N->getOperand(0); 9281 EVT VT = N->getValueType(0); 9282 9283 // fold (ftrunc c1) -> ftrunc(c1) 9284 if (isConstantFPBuildVectorOrConstantFP(N0)) 9285 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9286 9287 return SDValue(); 9288 } 9289 9290 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9291 SDValue N0 = N->getOperand(0); 9292 EVT VT = N->getValueType(0); 9293 9294 // fold (ffloor c1) -> ffloor(c1) 9295 if (isConstantFPBuildVectorOrConstantFP(N0)) 9296 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9297 9298 return SDValue(); 9299 } 9300 9301 // FIXME: FNEG and FABS have a lot in common; refactor. 9302 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9303 SDValue N0 = N->getOperand(0); 9304 EVT VT = N->getValueType(0); 9305 9306 // Constant fold FNEG. 9307 if (isConstantFPBuildVectorOrConstantFP(N0)) 9308 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9309 9310 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9311 &DAG.getTarget().Options)) 9312 return GetNegatedExpression(N0, DAG, LegalOperations); 9313 9314 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9315 // constant pool values. 9316 if (!TLI.isFNegFree(VT) && 9317 N0.getOpcode() == ISD::BITCAST && 9318 N0.getNode()->hasOneUse()) { 9319 SDValue Int = N0.getOperand(0); 9320 EVT IntVT = Int.getValueType(); 9321 if (IntVT.isInteger() && !IntVT.isVector()) { 9322 APInt SignMask; 9323 if (N0.getValueType().isVector()) { 9324 // For a vector, get a mask such as 0x80... per scalar element 9325 // and splat it. 9326 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9327 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9328 } else { 9329 // For a scalar, just generate 0x80... 9330 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9331 } 9332 SDLoc DL0(N0); 9333 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9334 DAG.getConstant(SignMask, DL0, IntVT)); 9335 AddToWorklist(Int.getNode()); 9336 return DAG.getBitcast(VT, Int); 9337 } 9338 } 9339 9340 // (fneg (fmul c, x)) -> (fmul -c, x) 9341 if (N0.getOpcode() == ISD::FMUL && 9342 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9343 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9344 if (CFP1) { 9345 APFloat CVal = CFP1->getValueAPF(); 9346 CVal.changeSign(); 9347 if (Level >= AfterLegalizeDAG && 9348 (TLI.isFPImmLegal(CVal, VT) || 9349 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9350 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9351 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9352 N0.getOperand(1)), 9353 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9354 } 9355 } 9356 9357 return SDValue(); 9358 } 9359 9360 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9361 SDValue N0 = N->getOperand(0); 9362 SDValue N1 = N->getOperand(1); 9363 EVT VT = N->getValueType(0); 9364 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9365 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9366 9367 if (N0CFP && N1CFP) { 9368 const APFloat &C0 = N0CFP->getValueAPF(); 9369 const APFloat &C1 = N1CFP->getValueAPF(); 9370 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9371 } 9372 9373 // Canonicalize to constant on RHS. 9374 if (isConstantFPBuildVectorOrConstantFP(N0) && 9375 !isConstantFPBuildVectorOrConstantFP(N1)) 9376 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9377 9378 return SDValue(); 9379 } 9380 9381 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9382 SDValue N0 = N->getOperand(0); 9383 SDValue N1 = N->getOperand(1); 9384 EVT VT = N->getValueType(0); 9385 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9386 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9387 9388 if (N0CFP && N1CFP) { 9389 const APFloat &C0 = N0CFP->getValueAPF(); 9390 const APFloat &C1 = N1CFP->getValueAPF(); 9391 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9392 } 9393 9394 // Canonicalize to constant on RHS. 9395 if (isConstantFPBuildVectorOrConstantFP(N0) && 9396 !isConstantFPBuildVectorOrConstantFP(N1)) 9397 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9398 9399 return SDValue(); 9400 } 9401 9402 SDValue DAGCombiner::visitFABS(SDNode *N) { 9403 SDValue N0 = N->getOperand(0); 9404 EVT VT = N->getValueType(0); 9405 9406 // fold (fabs c1) -> fabs(c1) 9407 if (isConstantFPBuildVectorOrConstantFP(N0)) 9408 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9409 9410 // fold (fabs (fabs x)) -> (fabs x) 9411 if (N0.getOpcode() == ISD::FABS) 9412 return N->getOperand(0); 9413 9414 // fold (fabs (fneg x)) -> (fabs x) 9415 // fold (fabs (fcopysign x, y)) -> (fabs x) 9416 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9417 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9418 9419 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9420 // constant pool values. 9421 if (!TLI.isFAbsFree(VT) && 9422 N0.getOpcode() == ISD::BITCAST && 9423 N0.getNode()->hasOneUse()) { 9424 SDValue Int = N0.getOperand(0); 9425 EVT IntVT = Int.getValueType(); 9426 if (IntVT.isInteger() && !IntVT.isVector()) { 9427 APInt SignMask; 9428 if (N0.getValueType().isVector()) { 9429 // For a vector, get a mask such as 0x7f... per scalar element 9430 // and splat it. 9431 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9432 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9433 } else { 9434 // For a scalar, just generate 0x7f... 9435 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9436 } 9437 SDLoc DL(N0); 9438 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9439 DAG.getConstant(SignMask, DL, IntVT)); 9440 AddToWorklist(Int.getNode()); 9441 return DAG.getBitcast(N->getValueType(0), Int); 9442 } 9443 } 9444 9445 return SDValue(); 9446 } 9447 9448 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9449 SDValue Chain = N->getOperand(0); 9450 SDValue N1 = N->getOperand(1); 9451 SDValue N2 = N->getOperand(2); 9452 9453 // If N is a constant we could fold this into a fallthrough or unconditional 9454 // branch. However that doesn't happen very often in normal code, because 9455 // Instcombine/SimplifyCFG should have handled the available opportunities. 9456 // If we did this folding here, it would be necessary to update the 9457 // MachineBasicBlock CFG, which is awkward. 9458 9459 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9460 // on the target. 9461 if (N1.getOpcode() == ISD::SETCC && 9462 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9463 N1.getOperand(0).getValueType())) { 9464 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9465 Chain, N1.getOperand(2), 9466 N1.getOperand(0), N1.getOperand(1), N2); 9467 } 9468 9469 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9470 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9471 (N1.getOperand(0).hasOneUse() && 9472 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9473 SDNode *Trunc = nullptr; 9474 if (N1.getOpcode() == ISD::TRUNCATE) { 9475 // Look pass the truncate. 9476 Trunc = N1.getNode(); 9477 N1 = N1.getOperand(0); 9478 } 9479 9480 // Match this pattern so that we can generate simpler code: 9481 // 9482 // %a = ... 9483 // %b = and i32 %a, 2 9484 // %c = srl i32 %b, 1 9485 // brcond i32 %c ... 9486 // 9487 // into 9488 // 9489 // %a = ... 9490 // %b = and i32 %a, 2 9491 // %c = setcc eq %b, 0 9492 // brcond %c ... 9493 // 9494 // This applies only when the AND constant value has one bit set and the 9495 // SRL constant is equal to the log2 of the AND constant. The back-end is 9496 // smart enough to convert the result into a TEST/JMP sequence. 9497 SDValue Op0 = N1.getOperand(0); 9498 SDValue Op1 = N1.getOperand(1); 9499 9500 if (Op0.getOpcode() == ISD::AND && 9501 Op1.getOpcode() == ISD::Constant) { 9502 SDValue AndOp1 = Op0.getOperand(1); 9503 9504 if (AndOp1.getOpcode() == ISD::Constant) { 9505 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9506 9507 if (AndConst.isPowerOf2() && 9508 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9509 SDLoc DL(N); 9510 SDValue SetCC = 9511 DAG.getSetCC(DL, 9512 getSetCCResultType(Op0.getValueType()), 9513 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9514 ISD::SETNE); 9515 9516 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9517 MVT::Other, Chain, SetCC, N2); 9518 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9519 // will convert it back to (X & C1) >> C2. 9520 CombineTo(N, NewBRCond, false); 9521 // Truncate is dead. 9522 if (Trunc) 9523 deleteAndRecombine(Trunc); 9524 // Replace the uses of SRL with SETCC 9525 WorklistRemover DeadNodes(*this); 9526 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9527 deleteAndRecombine(N1.getNode()); 9528 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9529 } 9530 } 9531 } 9532 9533 if (Trunc) 9534 // Restore N1 if the above transformation doesn't match. 9535 N1 = N->getOperand(1); 9536 } 9537 9538 // Transform br(xor(x, y)) -> br(x != y) 9539 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9540 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9541 SDNode *TheXor = N1.getNode(); 9542 SDValue Op0 = TheXor->getOperand(0); 9543 SDValue Op1 = TheXor->getOperand(1); 9544 if (Op0.getOpcode() == Op1.getOpcode()) { 9545 // Avoid missing important xor optimizations. 9546 if (SDValue Tmp = visitXOR(TheXor)) { 9547 if (Tmp.getNode() != TheXor) { 9548 DEBUG(dbgs() << "\nReplacing.8 "; 9549 TheXor->dump(&DAG); 9550 dbgs() << "\nWith: "; 9551 Tmp.getNode()->dump(&DAG); 9552 dbgs() << '\n'); 9553 WorklistRemover DeadNodes(*this); 9554 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9555 deleteAndRecombine(TheXor); 9556 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9557 MVT::Other, Chain, Tmp, N2); 9558 } 9559 9560 // visitXOR has changed XOR's operands or replaced the XOR completely, 9561 // bail out. 9562 return SDValue(N, 0); 9563 } 9564 } 9565 9566 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9567 bool Equal = false; 9568 if (isOneConstant(Op0) && Op0.hasOneUse() && 9569 Op0.getOpcode() == ISD::XOR) { 9570 TheXor = Op0.getNode(); 9571 Equal = true; 9572 } 9573 9574 EVT SetCCVT = N1.getValueType(); 9575 if (LegalTypes) 9576 SetCCVT = getSetCCResultType(SetCCVT); 9577 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9578 SetCCVT, 9579 Op0, Op1, 9580 Equal ? ISD::SETEQ : ISD::SETNE); 9581 // Replace the uses of XOR with SETCC 9582 WorklistRemover DeadNodes(*this); 9583 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9584 deleteAndRecombine(N1.getNode()); 9585 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9586 MVT::Other, Chain, SetCC, N2); 9587 } 9588 } 9589 9590 return SDValue(); 9591 } 9592 9593 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9594 // 9595 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9596 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9597 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9598 9599 // If N is a constant we could fold this into a fallthrough or unconditional 9600 // branch. However that doesn't happen very often in normal code, because 9601 // Instcombine/SimplifyCFG should have handled the available opportunities. 9602 // If we did this folding here, it would be necessary to update the 9603 // MachineBasicBlock CFG, which is awkward. 9604 9605 // Use SimplifySetCC to simplify SETCC's. 9606 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9607 CondLHS, CondRHS, CC->get(), SDLoc(N), 9608 false); 9609 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9610 9611 // fold to a simpler setcc 9612 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9613 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9614 N->getOperand(0), Simp.getOperand(2), 9615 Simp.getOperand(0), Simp.getOperand(1), 9616 N->getOperand(4)); 9617 9618 return SDValue(); 9619 } 9620 9621 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9622 /// and that N may be folded in the load / store addressing mode. 9623 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9624 SelectionDAG &DAG, 9625 const TargetLowering &TLI) { 9626 EVT VT; 9627 unsigned AS; 9628 9629 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9630 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9631 return false; 9632 VT = LD->getMemoryVT(); 9633 AS = LD->getAddressSpace(); 9634 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9635 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9636 return false; 9637 VT = ST->getMemoryVT(); 9638 AS = ST->getAddressSpace(); 9639 } else 9640 return false; 9641 9642 TargetLowering::AddrMode AM; 9643 if (N->getOpcode() == ISD::ADD) { 9644 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9645 if (Offset) 9646 // [reg +/- imm] 9647 AM.BaseOffs = Offset->getSExtValue(); 9648 else 9649 // [reg +/- reg] 9650 AM.Scale = 1; 9651 } else if (N->getOpcode() == ISD::SUB) { 9652 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9653 if (Offset) 9654 // [reg +/- imm] 9655 AM.BaseOffs = -Offset->getSExtValue(); 9656 else 9657 // [reg +/- reg] 9658 AM.Scale = 1; 9659 } else 9660 return false; 9661 9662 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9663 VT.getTypeForEVT(*DAG.getContext()), AS); 9664 } 9665 9666 /// Try turning a load/store into a pre-indexed load/store when the base 9667 /// pointer is an add or subtract and it has other uses besides the load/store. 9668 /// After the transformation, the new indexed load/store has effectively folded 9669 /// the add/subtract in and all of its other uses are redirected to the 9670 /// new load/store. 9671 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9672 if (Level < AfterLegalizeDAG) 9673 return false; 9674 9675 bool isLoad = true; 9676 SDValue Ptr; 9677 EVT VT; 9678 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9679 if (LD->isIndexed()) 9680 return false; 9681 VT = LD->getMemoryVT(); 9682 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9683 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9684 return false; 9685 Ptr = LD->getBasePtr(); 9686 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9687 if (ST->isIndexed()) 9688 return false; 9689 VT = ST->getMemoryVT(); 9690 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9691 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9692 return false; 9693 Ptr = ST->getBasePtr(); 9694 isLoad = false; 9695 } else { 9696 return false; 9697 } 9698 9699 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9700 // out. There is no reason to make this a preinc/predec. 9701 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9702 Ptr.getNode()->hasOneUse()) 9703 return false; 9704 9705 // Ask the target to do addressing mode selection. 9706 SDValue BasePtr; 9707 SDValue Offset; 9708 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9709 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9710 return false; 9711 9712 // Backends without true r+i pre-indexed forms may need to pass a 9713 // constant base with a variable offset so that constant coercion 9714 // will work with the patterns in canonical form. 9715 bool Swapped = false; 9716 if (isa<ConstantSDNode>(BasePtr)) { 9717 std::swap(BasePtr, Offset); 9718 Swapped = true; 9719 } 9720 9721 // Don't create a indexed load / store with zero offset. 9722 if (isNullConstant(Offset)) 9723 return false; 9724 9725 // Try turning it into a pre-indexed load / store except when: 9726 // 1) The new base ptr is a frame index. 9727 // 2) If N is a store and the new base ptr is either the same as or is a 9728 // predecessor of the value being stored. 9729 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9730 // that would create a cycle. 9731 // 4) All uses are load / store ops that use it as old base ptr. 9732 9733 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9734 // (plus the implicit offset) to a register to preinc anyway. 9735 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9736 return false; 9737 9738 // Check #2. 9739 if (!isLoad) { 9740 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9741 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9742 return false; 9743 } 9744 9745 // Caches for hasPredecessorHelper. 9746 SmallPtrSet<const SDNode *, 32> Visited; 9747 SmallVector<const SDNode *, 16> Worklist; 9748 Worklist.push_back(N); 9749 9750 // If the offset is a constant, there may be other adds of constants that 9751 // can be folded with this one. We should do this to avoid having to keep 9752 // a copy of the original base pointer. 9753 SmallVector<SDNode *, 16> OtherUses; 9754 if (isa<ConstantSDNode>(Offset)) 9755 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9756 UE = BasePtr.getNode()->use_end(); 9757 UI != UE; ++UI) { 9758 SDUse &Use = UI.getUse(); 9759 // Skip the use that is Ptr and uses of other results from BasePtr's 9760 // node (important for nodes that return multiple results). 9761 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9762 continue; 9763 9764 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 9765 continue; 9766 9767 if (Use.getUser()->getOpcode() != ISD::ADD && 9768 Use.getUser()->getOpcode() != ISD::SUB) { 9769 OtherUses.clear(); 9770 break; 9771 } 9772 9773 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9774 if (!isa<ConstantSDNode>(Op1)) { 9775 OtherUses.clear(); 9776 break; 9777 } 9778 9779 // FIXME: In some cases, we can be smarter about this. 9780 if (Op1.getValueType() != Offset.getValueType()) { 9781 OtherUses.clear(); 9782 break; 9783 } 9784 9785 OtherUses.push_back(Use.getUser()); 9786 } 9787 9788 if (Swapped) 9789 std::swap(BasePtr, Offset); 9790 9791 // Now check for #3 and #4. 9792 bool RealUse = false; 9793 9794 for (SDNode *Use : Ptr.getNode()->uses()) { 9795 if (Use == N) 9796 continue; 9797 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 9798 return false; 9799 9800 // If Ptr may be folded in addressing mode of other use, then it's 9801 // not profitable to do this transformation. 9802 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9803 RealUse = true; 9804 } 9805 9806 if (!RealUse) 9807 return false; 9808 9809 SDValue Result; 9810 if (isLoad) 9811 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9812 BasePtr, Offset, AM); 9813 else 9814 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9815 BasePtr, Offset, AM); 9816 ++PreIndexedNodes; 9817 ++NodesCombined; 9818 DEBUG(dbgs() << "\nReplacing.4 "; 9819 N->dump(&DAG); 9820 dbgs() << "\nWith: "; 9821 Result.getNode()->dump(&DAG); 9822 dbgs() << '\n'); 9823 WorklistRemover DeadNodes(*this); 9824 if (isLoad) { 9825 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9826 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9827 } else { 9828 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9829 } 9830 9831 // Finally, since the node is now dead, remove it from the graph. 9832 deleteAndRecombine(N); 9833 9834 if (Swapped) 9835 std::swap(BasePtr, Offset); 9836 9837 // Replace other uses of BasePtr that can be updated to use Ptr 9838 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9839 unsigned OffsetIdx = 1; 9840 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9841 OffsetIdx = 0; 9842 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9843 BasePtr.getNode() && "Expected BasePtr operand"); 9844 9845 // We need to replace ptr0 in the following expression: 9846 // x0 * offset0 + y0 * ptr0 = t0 9847 // knowing that 9848 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9849 // 9850 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9851 // indexed load/store and the expresion that needs to be re-written. 9852 // 9853 // Therefore, we have: 9854 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9855 9856 ConstantSDNode *CN = 9857 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9858 int X0, X1, Y0, Y1; 9859 const APInt &Offset0 = CN->getAPIntValue(); 9860 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9861 9862 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9863 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9864 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9865 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9866 9867 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9868 9869 APInt CNV = Offset0; 9870 if (X0 < 0) CNV = -CNV; 9871 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9872 else CNV = CNV - Offset1; 9873 9874 SDLoc DL(OtherUses[i]); 9875 9876 // We can now generate the new expression. 9877 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9878 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9879 9880 SDValue NewUse = DAG.getNode(Opcode, 9881 DL, 9882 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9883 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9884 deleteAndRecombine(OtherUses[i]); 9885 } 9886 9887 // Replace the uses of Ptr with uses of the updated base value. 9888 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9889 deleteAndRecombine(Ptr.getNode()); 9890 9891 return true; 9892 } 9893 9894 /// Try to combine a load/store with a add/sub of the base pointer node into a 9895 /// post-indexed load/store. The transformation folded the add/subtract into the 9896 /// new indexed load/store effectively and all of its uses are redirected to the 9897 /// new load/store. 9898 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9899 if (Level < AfterLegalizeDAG) 9900 return false; 9901 9902 bool isLoad = true; 9903 SDValue Ptr; 9904 EVT VT; 9905 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9906 if (LD->isIndexed()) 9907 return false; 9908 VT = LD->getMemoryVT(); 9909 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9910 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9911 return false; 9912 Ptr = LD->getBasePtr(); 9913 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9914 if (ST->isIndexed()) 9915 return false; 9916 VT = ST->getMemoryVT(); 9917 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9918 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9919 return false; 9920 Ptr = ST->getBasePtr(); 9921 isLoad = false; 9922 } else { 9923 return false; 9924 } 9925 9926 if (Ptr.getNode()->hasOneUse()) 9927 return false; 9928 9929 for (SDNode *Op : Ptr.getNode()->uses()) { 9930 if (Op == N || 9931 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9932 continue; 9933 9934 SDValue BasePtr; 9935 SDValue Offset; 9936 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9937 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9938 // Don't create a indexed load / store with zero offset. 9939 if (isNullConstant(Offset)) 9940 continue; 9941 9942 // Try turning it into a post-indexed load / store except when 9943 // 1) All uses are load / store ops that use it as base ptr (and 9944 // it may be folded as addressing mmode). 9945 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9946 // nor a successor of N. Otherwise, if Op is folded that would 9947 // create a cycle. 9948 9949 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9950 continue; 9951 9952 // Check for #1. 9953 bool TryNext = false; 9954 for (SDNode *Use : BasePtr.getNode()->uses()) { 9955 if (Use == Ptr.getNode()) 9956 continue; 9957 9958 // If all the uses are load / store addresses, then don't do the 9959 // transformation. 9960 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9961 bool RealUse = false; 9962 for (SDNode *UseUse : Use->uses()) { 9963 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9964 RealUse = true; 9965 } 9966 9967 if (!RealUse) { 9968 TryNext = true; 9969 break; 9970 } 9971 } 9972 } 9973 9974 if (TryNext) 9975 continue; 9976 9977 // Check for #2 9978 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9979 SDValue Result = isLoad 9980 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9981 BasePtr, Offset, AM) 9982 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9983 BasePtr, Offset, AM); 9984 ++PostIndexedNodes; 9985 ++NodesCombined; 9986 DEBUG(dbgs() << "\nReplacing.5 "; 9987 N->dump(&DAG); 9988 dbgs() << "\nWith: "; 9989 Result.getNode()->dump(&DAG); 9990 dbgs() << '\n'); 9991 WorklistRemover DeadNodes(*this); 9992 if (isLoad) { 9993 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9994 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9995 } else { 9996 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9997 } 9998 9999 // Finally, since the node is now dead, remove it from the graph. 10000 deleteAndRecombine(N); 10001 10002 // Replace the uses of Use with uses of the updated base value. 10003 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 10004 Result.getValue(isLoad ? 1 : 0)); 10005 deleteAndRecombine(Op); 10006 return true; 10007 } 10008 } 10009 } 10010 10011 return false; 10012 } 10013 10014 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 10015 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 10016 ISD::MemIndexedMode AM = LD->getAddressingMode(); 10017 assert(AM != ISD::UNINDEXED); 10018 SDValue BP = LD->getOperand(1); 10019 SDValue Inc = LD->getOperand(2); 10020 10021 // Some backends use TargetConstants for load offsets, but don't expect 10022 // TargetConstants in general ADD nodes. We can convert these constants into 10023 // regular Constants (if the constant is not opaque). 10024 assert((Inc.getOpcode() != ISD::TargetConstant || 10025 !cast<ConstantSDNode>(Inc)->isOpaque()) && 10026 "Cannot split out indexing using opaque target constants"); 10027 if (Inc.getOpcode() == ISD::TargetConstant) { 10028 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 10029 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 10030 ConstInc->getValueType(0)); 10031 } 10032 10033 unsigned Opc = 10034 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 10035 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 10036 } 10037 10038 SDValue DAGCombiner::visitLOAD(SDNode *N) { 10039 LoadSDNode *LD = cast<LoadSDNode>(N); 10040 SDValue Chain = LD->getChain(); 10041 SDValue Ptr = LD->getBasePtr(); 10042 10043 // If load is not volatile and there are no uses of the loaded value (and 10044 // the updated indexed value in case of indexed loads), change uses of the 10045 // chain value into uses of the chain input (i.e. delete the dead load). 10046 if (!LD->isVolatile()) { 10047 if (N->getValueType(1) == MVT::Other) { 10048 // Unindexed loads. 10049 if (!N->hasAnyUseOfValue(0)) { 10050 // It's not safe to use the two value CombineTo variant here. e.g. 10051 // v1, chain2 = load chain1, loc 10052 // v2, chain3 = load chain2, loc 10053 // v3 = add v2, c 10054 // Now we replace use of chain2 with chain1. This makes the second load 10055 // isomorphic to the one we are deleting, and thus makes this load live. 10056 DEBUG(dbgs() << "\nReplacing.6 "; 10057 N->dump(&DAG); 10058 dbgs() << "\nWith chain: "; 10059 Chain.getNode()->dump(&DAG); 10060 dbgs() << "\n"); 10061 WorklistRemover DeadNodes(*this); 10062 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10063 10064 if (N->use_empty()) 10065 deleteAndRecombine(N); 10066 10067 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10068 } 10069 } else { 10070 // Indexed loads. 10071 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 10072 10073 // If this load has an opaque TargetConstant offset, then we cannot split 10074 // the indexing into an add/sub directly (that TargetConstant may not be 10075 // valid for a different type of node, and we cannot convert an opaque 10076 // target constant into a regular constant). 10077 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 10078 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 10079 10080 if (!N->hasAnyUseOfValue(0) && 10081 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 10082 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 10083 SDValue Index; 10084 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 10085 Index = SplitIndexingFromLoad(LD); 10086 // Try to fold the base pointer arithmetic into subsequent loads and 10087 // stores. 10088 AddUsersToWorklist(N); 10089 } else 10090 Index = DAG.getUNDEF(N->getValueType(1)); 10091 DEBUG(dbgs() << "\nReplacing.7 "; 10092 N->dump(&DAG); 10093 dbgs() << "\nWith: "; 10094 Undef.getNode()->dump(&DAG); 10095 dbgs() << " and 2 other values\n"); 10096 WorklistRemover DeadNodes(*this); 10097 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 10098 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 10099 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 10100 deleteAndRecombine(N); 10101 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10102 } 10103 } 10104 } 10105 10106 // If this load is directly stored, replace the load value with the stored 10107 // value. 10108 // TODO: Handle store large -> read small portion. 10109 // TODO: Handle TRUNCSTORE/LOADEXT 10110 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 10111 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10112 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10113 if (PrevST->getBasePtr() == Ptr && 10114 PrevST->getValue().getValueType() == N->getValueType(0)) 10115 return CombineTo(N, Chain.getOperand(1), Chain); 10116 } 10117 } 10118 10119 // Try to infer better alignment information than the load already has. 10120 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10121 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10122 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10123 SDValue NewLoad = DAG.getExtLoad( 10124 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 10125 LD->getPointerInfo(), LD->getMemoryVT(), Align, 10126 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10127 if (NewLoad.getNode() != N) 10128 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10129 } 10130 } 10131 } 10132 10133 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10134 : DAG.getSubtarget().useAA(); 10135 #ifndef NDEBUG 10136 if (CombinerAAOnlyFunc.getNumOccurrences() && 10137 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10138 UseAA = false; 10139 #endif 10140 if (UseAA && LD->isUnindexed()) { 10141 // Walk up chain skipping non-aliasing memory nodes. 10142 SDValue BetterChain = FindBetterChain(N, Chain); 10143 10144 // If there is a better chain. 10145 if (Chain != BetterChain) { 10146 SDValue ReplLoad; 10147 10148 // Replace the chain to void dependency. 10149 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10150 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10151 BetterChain, Ptr, LD->getMemOperand()); 10152 } else { 10153 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10154 LD->getValueType(0), 10155 BetterChain, Ptr, LD->getMemoryVT(), 10156 LD->getMemOperand()); 10157 } 10158 10159 // Create token factor to keep old chain connected. 10160 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10161 MVT::Other, Chain, ReplLoad.getValue(1)); 10162 10163 // Make sure the new and old chains are cleaned up. 10164 AddToWorklist(Token.getNode()); 10165 10166 // Replace uses with load result and token factor. Don't add users 10167 // to work list. 10168 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10169 } 10170 } 10171 10172 // Try transforming N to an indexed load. 10173 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10174 return SDValue(N, 0); 10175 10176 // Try to slice up N to more direct loads if the slices are mapped to 10177 // different register banks or pairing can take place. 10178 if (SliceUpLoad(N)) 10179 return SDValue(N, 0); 10180 10181 return SDValue(); 10182 } 10183 10184 namespace { 10185 /// \brief Helper structure used to slice a load in smaller loads. 10186 /// Basically a slice is obtained from the following sequence: 10187 /// Origin = load Ty1, Base 10188 /// Shift = srl Ty1 Origin, CstTy Amount 10189 /// Inst = trunc Shift to Ty2 10190 /// 10191 /// Then, it will be rewriten into: 10192 /// Slice = load SliceTy, Base + SliceOffset 10193 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10194 /// 10195 /// SliceTy is deduced from the number of bits that are actually used to 10196 /// build Inst. 10197 struct LoadedSlice { 10198 /// \brief Helper structure used to compute the cost of a slice. 10199 struct Cost { 10200 /// Are we optimizing for code size. 10201 bool ForCodeSize; 10202 /// Various cost. 10203 unsigned Loads; 10204 unsigned Truncates; 10205 unsigned CrossRegisterBanksCopies; 10206 unsigned ZExts; 10207 unsigned Shift; 10208 10209 Cost(bool ForCodeSize = false) 10210 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10211 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10212 10213 /// \brief Get the cost of one isolated slice. 10214 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10215 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10216 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10217 EVT TruncType = LS.Inst->getValueType(0); 10218 EVT LoadedType = LS.getLoadedType(); 10219 if (TruncType != LoadedType && 10220 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10221 ZExts = 1; 10222 } 10223 10224 /// \brief Account for slicing gain in the current cost. 10225 /// Slicing provide a few gains like removing a shift or a 10226 /// truncate. This method allows to grow the cost of the original 10227 /// load with the gain from this slice. 10228 void addSliceGain(const LoadedSlice &LS) { 10229 // Each slice saves a truncate. 10230 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10231 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10232 LS.Inst->getValueType(0))) 10233 ++Truncates; 10234 // If there is a shift amount, this slice gets rid of it. 10235 if (LS.Shift) 10236 ++Shift; 10237 // If this slice can merge a cross register bank copy, account for it. 10238 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10239 ++CrossRegisterBanksCopies; 10240 } 10241 10242 Cost &operator+=(const Cost &RHS) { 10243 Loads += RHS.Loads; 10244 Truncates += RHS.Truncates; 10245 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10246 ZExts += RHS.ZExts; 10247 Shift += RHS.Shift; 10248 return *this; 10249 } 10250 10251 bool operator==(const Cost &RHS) const { 10252 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10253 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10254 ZExts == RHS.ZExts && Shift == RHS.Shift; 10255 } 10256 10257 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10258 10259 bool operator<(const Cost &RHS) const { 10260 // Assume cross register banks copies are as expensive as loads. 10261 // FIXME: Do we want some more target hooks? 10262 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10263 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10264 // Unless we are optimizing for code size, consider the 10265 // expensive operation first. 10266 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10267 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10268 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10269 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10270 } 10271 10272 bool operator>(const Cost &RHS) const { return RHS < *this; } 10273 10274 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10275 10276 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10277 }; 10278 // The last instruction that represent the slice. This should be a 10279 // truncate instruction. 10280 SDNode *Inst; 10281 // The original load instruction. 10282 LoadSDNode *Origin; 10283 // The right shift amount in bits from the original load. 10284 unsigned Shift; 10285 // The DAG from which Origin came from. 10286 // This is used to get some contextual information about legal types, etc. 10287 SelectionDAG *DAG; 10288 10289 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10290 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10291 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10292 10293 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10294 /// \return Result is \p BitWidth and has used bits set to 1 and 10295 /// not used bits set to 0. 10296 APInt getUsedBits() const { 10297 // Reproduce the trunc(lshr) sequence: 10298 // - Start from the truncated value. 10299 // - Zero extend to the desired bit width. 10300 // - Shift left. 10301 assert(Origin && "No original load to compare against."); 10302 unsigned BitWidth = Origin->getValueSizeInBits(0); 10303 assert(Inst && "This slice is not bound to an instruction"); 10304 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10305 "Extracted slice is bigger than the whole type!"); 10306 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10307 UsedBits.setAllBits(); 10308 UsedBits = UsedBits.zext(BitWidth); 10309 UsedBits <<= Shift; 10310 return UsedBits; 10311 } 10312 10313 /// \brief Get the size of the slice to be loaded in bytes. 10314 unsigned getLoadedSize() const { 10315 unsigned SliceSize = getUsedBits().countPopulation(); 10316 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10317 return SliceSize / 8; 10318 } 10319 10320 /// \brief Get the type that will be loaded for this slice. 10321 /// Note: This may not be the final type for the slice. 10322 EVT getLoadedType() const { 10323 assert(DAG && "Missing context"); 10324 LLVMContext &Ctxt = *DAG->getContext(); 10325 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10326 } 10327 10328 /// \brief Get the alignment of the load used for this slice. 10329 unsigned getAlignment() const { 10330 unsigned Alignment = Origin->getAlignment(); 10331 unsigned Offset = getOffsetFromBase(); 10332 if (Offset != 0) 10333 Alignment = MinAlign(Alignment, Alignment + Offset); 10334 return Alignment; 10335 } 10336 10337 /// \brief Check if this slice can be rewritten with legal operations. 10338 bool isLegal() const { 10339 // An invalid slice is not legal. 10340 if (!Origin || !Inst || !DAG) 10341 return false; 10342 10343 // Offsets are for indexed load only, we do not handle that. 10344 if (!Origin->getOffset().isUndef()) 10345 return false; 10346 10347 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10348 10349 // Check that the type is legal. 10350 EVT SliceType = getLoadedType(); 10351 if (!TLI.isTypeLegal(SliceType)) 10352 return false; 10353 10354 // Check that the load is legal for this type. 10355 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10356 return false; 10357 10358 // Check that the offset can be computed. 10359 // 1. Check its type. 10360 EVT PtrType = Origin->getBasePtr().getValueType(); 10361 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10362 return false; 10363 10364 // 2. Check that it fits in the immediate. 10365 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10366 return false; 10367 10368 // 3. Check that the computation is legal. 10369 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10370 return false; 10371 10372 // Check that the zext is legal if it needs one. 10373 EVT TruncateType = Inst->getValueType(0); 10374 if (TruncateType != SliceType && 10375 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10376 return false; 10377 10378 return true; 10379 } 10380 10381 /// \brief Get the offset in bytes of this slice in the original chunk of 10382 /// bits. 10383 /// \pre DAG != nullptr. 10384 uint64_t getOffsetFromBase() const { 10385 assert(DAG && "Missing context."); 10386 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10387 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10388 uint64_t Offset = Shift / 8; 10389 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10390 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10391 "The size of the original loaded type is not a multiple of a" 10392 " byte."); 10393 // If Offset is bigger than TySizeInBytes, it means we are loading all 10394 // zeros. This should have been optimized before in the process. 10395 assert(TySizeInBytes > Offset && 10396 "Invalid shift amount for given loaded size"); 10397 if (IsBigEndian) 10398 Offset = TySizeInBytes - Offset - getLoadedSize(); 10399 return Offset; 10400 } 10401 10402 /// \brief Generate the sequence of instructions to load the slice 10403 /// represented by this object and redirect the uses of this slice to 10404 /// this new sequence of instructions. 10405 /// \pre this->Inst && this->Origin are valid Instructions and this 10406 /// object passed the legal check: LoadedSlice::isLegal returned true. 10407 /// \return The last instruction of the sequence used to load the slice. 10408 SDValue loadSlice() const { 10409 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10410 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10411 SDValue BaseAddr = OldBaseAddr; 10412 // Get the offset in that chunk of bytes w.r.t. the endianess. 10413 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10414 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10415 if (Offset) { 10416 // BaseAddr = BaseAddr + Offset. 10417 EVT ArithType = BaseAddr.getValueType(); 10418 SDLoc DL(Origin); 10419 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10420 DAG->getConstant(Offset, DL, ArithType)); 10421 } 10422 10423 // Create the type of the loaded slice according to its size. 10424 EVT SliceType = getLoadedType(); 10425 10426 // Create the load for the slice. 10427 SDValue LastInst = 10428 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10429 Origin->getPointerInfo().getWithOffset(Offset), 10430 getAlignment(), Origin->getMemOperand()->getFlags()); 10431 // If the final type is not the same as the loaded type, this means that 10432 // we have to pad with zero. Create a zero extend for that. 10433 EVT FinalType = Inst->getValueType(0); 10434 if (SliceType != FinalType) 10435 LastInst = 10436 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10437 return LastInst; 10438 } 10439 10440 /// \brief Check if this slice can be merged with an expensive cross register 10441 /// bank copy. E.g., 10442 /// i = load i32 10443 /// f = bitcast i32 i to float 10444 bool canMergeExpensiveCrossRegisterBankCopy() const { 10445 if (!Inst || !Inst->hasOneUse()) 10446 return false; 10447 SDNode *Use = *Inst->use_begin(); 10448 if (Use->getOpcode() != ISD::BITCAST) 10449 return false; 10450 assert(DAG && "Missing context"); 10451 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10452 EVT ResVT = Use->getValueType(0); 10453 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10454 const TargetRegisterClass *ArgRC = 10455 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10456 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10457 return false; 10458 10459 // At this point, we know that we perform a cross-register-bank copy. 10460 // Check if it is expensive. 10461 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10462 // Assume bitcasts are cheap, unless both register classes do not 10463 // explicitly share a common sub class. 10464 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10465 return false; 10466 10467 // Check if it will be merged with the load. 10468 // 1. Check the alignment constraint. 10469 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10470 ResVT.getTypeForEVT(*DAG->getContext())); 10471 10472 if (RequiredAlignment > getAlignment()) 10473 return false; 10474 10475 // 2. Check that the load is a legal operation for that type. 10476 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10477 return false; 10478 10479 // 3. Check that we do not have a zext in the way. 10480 if (Inst->getValueType(0) != getLoadedType()) 10481 return false; 10482 10483 return true; 10484 } 10485 }; 10486 } 10487 10488 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10489 /// \p UsedBits looks like 0..0 1..1 0..0. 10490 static bool areUsedBitsDense(const APInt &UsedBits) { 10491 // If all the bits are one, this is dense! 10492 if (UsedBits.isAllOnesValue()) 10493 return true; 10494 10495 // Get rid of the unused bits on the right. 10496 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10497 // Get rid of the unused bits on the left. 10498 if (NarrowedUsedBits.countLeadingZeros()) 10499 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10500 // Check that the chunk of bits is completely used. 10501 return NarrowedUsedBits.isAllOnesValue(); 10502 } 10503 10504 /// \brief Check whether or not \p First and \p Second are next to each other 10505 /// in memory. This means that there is no hole between the bits loaded 10506 /// by \p First and the bits loaded by \p Second. 10507 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10508 const LoadedSlice &Second) { 10509 assert(First.Origin == Second.Origin && First.Origin && 10510 "Unable to match different memory origins."); 10511 APInt UsedBits = First.getUsedBits(); 10512 assert((UsedBits & Second.getUsedBits()) == 0 && 10513 "Slices are not supposed to overlap."); 10514 UsedBits |= Second.getUsedBits(); 10515 return areUsedBitsDense(UsedBits); 10516 } 10517 10518 /// \brief Adjust the \p GlobalLSCost according to the target 10519 /// paring capabilities and the layout of the slices. 10520 /// \pre \p GlobalLSCost should account for at least as many loads as 10521 /// there is in the slices in \p LoadedSlices. 10522 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10523 LoadedSlice::Cost &GlobalLSCost) { 10524 unsigned NumberOfSlices = LoadedSlices.size(); 10525 // If there is less than 2 elements, no pairing is possible. 10526 if (NumberOfSlices < 2) 10527 return; 10528 10529 // Sort the slices so that elements that are likely to be next to each 10530 // other in memory are next to each other in the list. 10531 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10532 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10533 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10534 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10535 }); 10536 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10537 // First (resp. Second) is the first (resp. Second) potentially candidate 10538 // to be placed in a paired load. 10539 const LoadedSlice *First = nullptr; 10540 const LoadedSlice *Second = nullptr; 10541 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10542 // Set the beginning of the pair. 10543 First = Second) { 10544 10545 Second = &LoadedSlices[CurrSlice]; 10546 10547 // If First is NULL, it means we start a new pair. 10548 // Get to the next slice. 10549 if (!First) 10550 continue; 10551 10552 EVT LoadedType = First->getLoadedType(); 10553 10554 // If the types of the slices are different, we cannot pair them. 10555 if (LoadedType != Second->getLoadedType()) 10556 continue; 10557 10558 // Check if the target supplies paired loads for this type. 10559 unsigned RequiredAlignment = 0; 10560 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10561 // move to the next pair, this type is hopeless. 10562 Second = nullptr; 10563 continue; 10564 } 10565 // Check if we meet the alignment requirement. 10566 if (RequiredAlignment > First->getAlignment()) 10567 continue; 10568 10569 // Check that both loads are next to each other in memory. 10570 if (!areSlicesNextToEachOther(*First, *Second)) 10571 continue; 10572 10573 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10574 --GlobalLSCost.Loads; 10575 // Move to the next pair. 10576 Second = nullptr; 10577 } 10578 } 10579 10580 /// \brief Check the profitability of all involved LoadedSlice. 10581 /// Currently, it is considered profitable if there is exactly two 10582 /// involved slices (1) which are (2) next to each other in memory, and 10583 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10584 /// 10585 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10586 /// the elements themselves. 10587 /// 10588 /// FIXME: When the cost model will be mature enough, we can relax 10589 /// constraints (1) and (2). 10590 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10591 const APInt &UsedBits, bool ForCodeSize) { 10592 unsigned NumberOfSlices = LoadedSlices.size(); 10593 if (StressLoadSlicing) 10594 return NumberOfSlices > 1; 10595 10596 // Check (1). 10597 if (NumberOfSlices != 2) 10598 return false; 10599 10600 // Check (2). 10601 if (!areUsedBitsDense(UsedBits)) 10602 return false; 10603 10604 // Check (3). 10605 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10606 // The original code has one big load. 10607 OrigCost.Loads = 1; 10608 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10609 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10610 // Accumulate the cost of all the slices. 10611 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10612 GlobalSlicingCost += SliceCost; 10613 10614 // Account as cost in the original configuration the gain obtained 10615 // with the current slices. 10616 OrigCost.addSliceGain(LS); 10617 } 10618 10619 // If the target supports paired load, adjust the cost accordingly. 10620 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10621 return OrigCost > GlobalSlicingCost; 10622 } 10623 10624 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10625 /// operations, split it in the various pieces being extracted. 10626 /// 10627 /// This sort of thing is introduced by SROA. 10628 /// This slicing takes care not to insert overlapping loads. 10629 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10630 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10631 if (Level < AfterLegalizeDAG) 10632 return false; 10633 10634 LoadSDNode *LD = cast<LoadSDNode>(N); 10635 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10636 !LD->getValueType(0).isInteger()) 10637 return false; 10638 10639 // Keep track of already used bits to detect overlapping values. 10640 // In that case, we will just abort the transformation. 10641 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10642 10643 SmallVector<LoadedSlice, 4> LoadedSlices; 10644 10645 // Check if this load is used as several smaller chunks of bits. 10646 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10647 // of computation for each trunc. 10648 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10649 UI != UIEnd; ++UI) { 10650 // Skip the uses of the chain. 10651 if (UI.getUse().getResNo() != 0) 10652 continue; 10653 10654 SDNode *User = *UI; 10655 unsigned Shift = 0; 10656 10657 // Check if this is a trunc(lshr). 10658 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10659 isa<ConstantSDNode>(User->getOperand(1))) { 10660 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10661 User = *User->use_begin(); 10662 } 10663 10664 // At this point, User is a Truncate, iff we encountered, trunc or 10665 // trunc(lshr). 10666 if (User->getOpcode() != ISD::TRUNCATE) 10667 return false; 10668 10669 // The width of the type must be a power of 2 and greater than 8-bits. 10670 // Otherwise the load cannot be represented in LLVM IR. 10671 // Moreover, if we shifted with a non-8-bits multiple, the slice 10672 // will be across several bytes. We do not support that. 10673 unsigned Width = User->getValueSizeInBits(0); 10674 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10675 return 0; 10676 10677 // Build the slice for this chain of computations. 10678 LoadedSlice LS(User, LD, Shift, &DAG); 10679 APInt CurrentUsedBits = LS.getUsedBits(); 10680 10681 // Check if this slice overlaps with another. 10682 if ((CurrentUsedBits & UsedBits) != 0) 10683 return false; 10684 // Update the bits used globally. 10685 UsedBits |= CurrentUsedBits; 10686 10687 // Check if the new slice would be legal. 10688 if (!LS.isLegal()) 10689 return false; 10690 10691 // Record the slice. 10692 LoadedSlices.push_back(LS); 10693 } 10694 10695 // Abort slicing if it does not seem to be profitable. 10696 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10697 return false; 10698 10699 ++SlicedLoads; 10700 10701 // Rewrite each chain to use an independent load. 10702 // By construction, each chain can be represented by a unique load. 10703 10704 // Prepare the argument for the new token factor for all the slices. 10705 SmallVector<SDValue, 8> ArgChains; 10706 for (SmallVectorImpl<LoadedSlice>::const_iterator 10707 LSIt = LoadedSlices.begin(), 10708 LSItEnd = LoadedSlices.end(); 10709 LSIt != LSItEnd; ++LSIt) { 10710 SDValue SliceInst = LSIt->loadSlice(); 10711 CombineTo(LSIt->Inst, SliceInst, true); 10712 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10713 SliceInst = SliceInst.getOperand(0); 10714 assert(SliceInst->getOpcode() == ISD::LOAD && 10715 "It takes more than a zext to get to the loaded slice!!"); 10716 ArgChains.push_back(SliceInst.getValue(1)); 10717 } 10718 10719 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10720 ArgChains); 10721 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10722 return true; 10723 } 10724 10725 /// Check to see if V is (and load (ptr), imm), where the load is having 10726 /// specific bytes cleared out. If so, return the byte size being masked out 10727 /// and the shift amount. 10728 static std::pair<unsigned, unsigned> 10729 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10730 std::pair<unsigned, unsigned> Result(0, 0); 10731 10732 // Check for the structure we're looking for. 10733 if (V->getOpcode() != ISD::AND || 10734 !isa<ConstantSDNode>(V->getOperand(1)) || 10735 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10736 return Result; 10737 10738 // Check the chain and pointer. 10739 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10740 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10741 10742 // The store should be chained directly to the load or be an operand of a 10743 // tokenfactor. 10744 if (LD == Chain.getNode()) 10745 ; // ok. 10746 else if (Chain->getOpcode() != ISD::TokenFactor) 10747 return Result; // Fail. 10748 else { 10749 bool isOk = false; 10750 for (const SDValue &ChainOp : Chain->op_values()) 10751 if (ChainOp.getNode() == LD) { 10752 isOk = true; 10753 break; 10754 } 10755 if (!isOk) return Result; 10756 } 10757 10758 // This only handles simple types. 10759 if (V.getValueType() != MVT::i16 && 10760 V.getValueType() != MVT::i32 && 10761 V.getValueType() != MVT::i64) 10762 return Result; 10763 10764 // Check the constant mask. Invert it so that the bits being masked out are 10765 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10766 // follow the sign bit for uniformity. 10767 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10768 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10769 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10770 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10771 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10772 if (NotMaskLZ == 64) return Result; // All zero mask. 10773 10774 // See if we have a continuous run of bits. If so, we have 0*1+0* 10775 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10776 return Result; 10777 10778 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10779 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10780 NotMaskLZ -= 64-V.getValueSizeInBits(); 10781 10782 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10783 switch (MaskedBytes) { 10784 case 1: 10785 case 2: 10786 case 4: break; 10787 default: return Result; // All one mask, or 5-byte mask. 10788 } 10789 10790 // Verify that the first bit starts at a multiple of mask so that the access 10791 // is aligned the same as the access width. 10792 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10793 10794 Result.first = MaskedBytes; 10795 Result.second = NotMaskTZ/8; 10796 return Result; 10797 } 10798 10799 10800 /// Check to see if IVal is something that provides a value as specified by 10801 /// MaskInfo. If so, replace the specified store with a narrower store of 10802 /// truncated IVal. 10803 static SDNode * 10804 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10805 SDValue IVal, StoreSDNode *St, 10806 DAGCombiner *DC) { 10807 unsigned NumBytes = MaskInfo.first; 10808 unsigned ByteShift = MaskInfo.second; 10809 SelectionDAG &DAG = DC->getDAG(); 10810 10811 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10812 // that uses this. If not, this is not a replacement. 10813 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10814 ByteShift*8, (ByteShift+NumBytes)*8); 10815 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10816 10817 // Check that it is legal on the target to do this. It is legal if the new 10818 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10819 // legalization. 10820 MVT VT = MVT::getIntegerVT(NumBytes*8); 10821 if (!DC->isTypeLegal(VT)) 10822 return nullptr; 10823 10824 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10825 // shifted by ByteShift and truncated down to NumBytes. 10826 if (ByteShift) { 10827 SDLoc DL(IVal); 10828 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10829 DAG.getConstant(ByteShift*8, DL, 10830 DC->getShiftAmountTy(IVal.getValueType()))); 10831 } 10832 10833 // Figure out the offset for the store and the alignment of the access. 10834 unsigned StOffset; 10835 unsigned NewAlign = St->getAlignment(); 10836 10837 if (DAG.getDataLayout().isLittleEndian()) 10838 StOffset = ByteShift; 10839 else 10840 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10841 10842 SDValue Ptr = St->getBasePtr(); 10843 if (StOffset) { 10844 SDLoc DL(IVal); 10845 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10846 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10847 NewAlign = MinAlign(NewAlign, StOffset); 10848 } 10849 10850 // Truncate down to the new size. 10851 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10852 10853 ++OpsNarrowed; 10854 return DAG 10855 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10856 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 10857 .getNode(); 10858 } 10859 10860 10861 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10862 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10863 /// narrowing the load and store if it would end up being a win for performance 10864 /// or code size. 10865 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10866 StoreSDNode *ST = cast<StoreSDNode>(N); 10867 if (ST->isVolatile()) 10868 return SDValue(); 10869 10870 SDValue Chain = ST->getChain(); 10871 SDValue Value = ST->getValue(); 10872 SDValue Ptr = ST->getBasePtr(); 10873 EVT VT = Value.getValueType(); 10874 10875 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10876 return SDValue(); 10877 10878 unsigned Opc = Value.getOpcode(); 10879 10880 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10881 // is a byte mask indicating a consecutive number of bytes, check to see if 10882 // Y is known to provide just those bytes. If so, we try to replace the 10883 // load + replace + store sequence with a single (narrower) store, which makes 10884 // the load dead. 10885 if (Opc == ISD::OR) { 10886 std::pair<unsigned, unsigned> MaskedLoad; 10887 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10888 if (MaskedLoad.first) 10889 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10890 Value.getOperand(1), ST,this)) 10891 return SDValue(NewST, 0); 10892 10893 // Or is commutative, so try swapping X and Y. 10894 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10895 if (MaskedLoad.first) 10896 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10897 Value.getOperand(0), ST,this)) 10898 return SDValue(NewST, 0); 10899 } 10900 10901 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10902 Value.getOperand(1).getOpcode() != ISD::Constant) 10903 return SDValue(); 10904 10905 SDValue N0 = Value.getOperand(0); 10906 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10907 Chain == SDValue(N0.getNode(), 1)) { 10908 LoadSDNode *LD = cast<LoadSDNode>(N0); 10909 if (LD->getBasePtr() != Ptr || 10910 LD->getPointerInfo().getAddrSpace() != 10911 ST->getPointerInfo().getAddrSpace()) 10912 return SDValue(); 10913 10914 // Find the type to narrow it the load / op / store to. 10915 SDValue N1 = Value.getOperand(1); 10916 unsigned BitWidth = N1.getValueSizeInBits(); 10917 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10918 if (Opc == ISD::AND) 10919 Imm ^= APInt::getAllOnesValue(BitWidth); 10920 if (Imm == 0 || Imm.isAllOnesValue()) 10921 return SDValue(); 10922 unsigned ShAmt = Imm.countTrailingZeros(); 10923 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10924 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10925 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10926 // The narrowing should be profitable, the load/store operation should be 10927 // legal (or custom) and the store size should be equal to the NewVT width. 10928 while (NewBW < BitWidth && 10929 (NewVT.getStoreSizeInBits() != NewBW || 10930 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10931 !TLI.isNarrowingProfitable(VT, NewVT))) { 10932 NewBW = NextPowerOf2(NewBW); 10933 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10934 } 10935 if (NewBW >= BitWidth) 10936 return SDValue(); 10937 10938 // If the lsb changed does not start at the type bitwidth boundary, 10939 // start at the previous one. 10940 if (ShAmt % NewBW) 10941 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10942 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10943 std::min(BitWidth, ShAmt + NewBW)); 10944 if ((Imm & Mask) == Imm) { 10945 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10946 if (Opc == ISD::AND) 10947 NewImm ^= APInt::getAllOnesValue(NewBW); 10948 uint64_t PtrOff = ShAmt / 8; 10949 // For big endian targets, we need to adjust the offset to the pointer to 10950 // load the correct bytes. 10951 if (DAG.getDataLayout().isBigEndian()) 10952 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10953 10954 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10955 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10956 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10957 return SDValue(); 10958 10959 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10960 Ptr.getValueType(), Ptr, 10961 DAG.getConstant(PtrOff, SDLoc(LD), 10962 Ptr.getValueType())); 10963 SDValue NewLD = 10964 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 10965 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 10966 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 10967 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10968 DAG.getConstant(NewImm, SDLoc(Value), 10969 NewVT)); 10970 SDValue NewST = 10971 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 10972 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 10973 10974 AddToWorklist(NewPtr.getNode()); 10975 AddToWorklist(NewLD.getNode()); 10976 AddToWorklist(NewVal.getNode()); 10977 WorklistRemover DeadNodes(*this); 10978 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10979 ++OpsNarrowed; 10980 return NewST; 10981 } 10982 } 10983 10984 return SDValue(); 10985 } 10986 10987 /// For a given floating point load / store pair, if the load value isn't used 10988 /// by any other operations, then consider transforming the pair to integer 10989 /// load / store operations if the target deems the transformation profitable. 10990 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10991 StoreSDNode *ST = cast<StoreSDNode>(N); 10992 SDValue Chain = ST->getChain(); 10993 SDValue Value = ST->getValue(); 10994 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10995 Value.hasOneUse() && 10996 Chain == SDValue(Value.getNode(), 1)) { 10997 LoadSDNode *LD = cast<LoadSDNode>(Value); 10998 EVT VT = LD->getMemoryVT(); 10999 if (!VT.isFloatingPoint() || 11000 VT != ST->getMemoryVT() || 11001 LD->isNonTemporal() || 11002 ST->isNonTemporal() || 11003 LD->getPointerInfo().getAddrSpace() != 0 || 11004 ST->getPointerInfo().getAddrSpace() != 0) 11005 return SDValue(); 11006 11007 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 11008 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 11009 !TLI.isOperationLegal(ISD::STORE, IntVT) || 11010 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 11011 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 11012 return SDValue(); 11013 11014 unsigned LDAlign = LD->getAlignment(); 11015 unsigned STAlign = ST->getAlignment(); 11016 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 11017 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 11018 if (LDAlign < ABIAlign || STAlign < ABIAlign) 11019 return SDValue(); 11020 11021 SDValue NewLD = 11022 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 11023 LD->getPointerInfo(), LDAlign); 11024 11025 SDValue NewST = 11026 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 11027 ST->getPointerInfo(), STAlign); 11028 11029 AddToWorklist(NewLD.getNode()); 11030 AddToWorklist(NewST.getNode()); 11031 WorklistRemover DeadNodes(*this); 11032 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 11033 ++LdStFP2Int; 11034 return NewST; 11035 } 11036 11037 return SDValue(); 11038 } 11039 11040 namespace { 11041 /// Helper struct to parse and store a memory address as base + index + offset. 11042 /// We ignore sign extensions when it is safe to do so. 11043 /// The following two expressions are not equivalent. To differentiate we need 11044 /// to store whether there was a sign extension involved in the index 11045 /// computation. 11046 /// (load (i64 add (i64 copyfromreg %c) 11047 /// (i64 signextend (add (i8 load %index) 11048 /// (i8 1)))) 11049 /// vs 11050 /// 11051 /// (load (i64 add (i64 copyfromreg %c) 11052 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 11053 /// (i32 1))))) 11054 struct BaseIndexOffset { 11055 SDValue Base; 11056 SDValue Index; 11057 int64_t Offset; 11058 bool IsIndexSignExt; 11059 11060 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 11061 11062 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 11063 bool IsIndexSignExt) : 11064 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 11065 11066 bool equalBaseIndex(const BaseIndexOffset &Other) { 11067 return Other.Base == Base && Other.Index == Index && 11068 Other.IsIndexSignExt == IsIndexSignExt; 11069 } 11070 11071 /// Parses tree in Ptr for base, index, offset addresses. 11072 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 11073 bool IsIndexSignExt = false; 11074 11075 // Split up a folded GlobalAddress+Offset into its component parts. 11076 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 11077 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 11078 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 11079 SDLoc(GA), 11080 GA->getValueType(0), 11081 /*Offset=*/0, 11082 /*isTargetGA=*/false, 11083 GA->getTargetFlags()), 11084 SDValue(), 11085 GA->getOffset(), 11086 IsIndexSignExt); 11087 } 11088 11089 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 11090 // instruction, then it could be just the BASE or everything else we don't 11091 // know how to handle. Just use Ptr as BASE and give up. 11092 if (Ptr->getOpcode() != ISD::ADD) 11093 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11094 11095 // We know that we have at least an ADD instruction. Try to pattern match 11096 // the simple case of BASE + OFFSET. 11097 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 11098 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 11099 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 11100 IsIndexSignExt); 11101 } 11102 11103 // Inside a loop the current BASE pointer is calculated using an ADD and a 11104 // MUL instruction. In this case Ptr is the actual BASE pointer. 11105 // (i64 add (i64 %array_ptr) 11106 // (i64 mul (i64 %induction_var) 11107 // (i64 %element_size))) 11108 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 11109 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11110 11111 // Look at Base + Index + Offset cases. 11112 SDValue Base = Ptr->getOperand(0); 11113 SDValue IndexOffset = Ptr->getOperand(1); 11114 11115 // Skip signextends. 11116 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 11117 IndexOffset = IndexOffset->getOperand(0); 11118 IsIndexSignExt = true; 11119 } 11120 11121 // Either the case of Base + Index (no offset) or something else. 11122 if (IndexOffset->getOpcode() != ISD::ADD) 11123 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 11124 11125 // Now we have the case of Base + Index + offset. 11126 SDValue Index = IndexOffset->getOperand(0); 11127 SDValue Offset = IndexOffset->getOperand(1); 11128 11129 if (!isa<ConstantSDNode>(Offset)) 11130 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11131 11132 // Ignore signextends. 11133 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 11134 Index = Index->getOperand(0); 11135 IsIndexSignExt = true; 11136 } else IsIndexSignExt = false; 11137 11138 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 11139 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 11140 } 11141 }; 11142 } // namespace 11143 11144 // This is a helper function for visitMUL to check the profitability 11145 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11146 // MulNode is the original multiply, AddNode is (add x, c1), 11147 // and ConstNode is c2. 11148 // 11149 // If the (add x, c1) has multiple uses, we could increase 11150 // the number of adds if we make this transformation. 11151 // It would only be worth doing this if we can remove a 11152 // multiply in the process. Check for that here. 11153 // To illustrate: 11154 // (A + c1) * c3 11155 // (A + c2) * c3 11156 // We're checking for cases where we have common "c3 * A" expressions. 11157 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11158 SDValue &AddNode, 11159 SDValue &ConstNode) { 11160 APInt Val; 11161 11162 // If the add only has one use, this would be OK to do. 11163 if (AddNode.getNode()->hasOneUse()) 11164 return true; 11165 11166 // Walk all the users of the constant with which we're multiplying. 11167 for (SDNode *Use : ConstNode->uses()) { 11168 11169 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11170 continue; 11171 11172 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11173 SDNode *OtherOp; 11174 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11175 11176 // OtherOp is what we're multiplying against the constant. 11177 if (Use->getOperand(0) == ConstNode) 11178 OtherOp = Use->getOperand(1).getNode(); 11179 else 11180 OtherOp = Use->getOperand(0).getNode(); 11181 11182 // Check to see if multiply is with the same operand of our "add". 11183 // 11184 // ConstNode = CONST 11185 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11186 // ... 11187 // AddNode = (A + c1) <-- MulVar is A. 11188 // = AddNode * ConstNode <-- current visiting instruction. 11189 // 11190 // If we make this transformation, we will have a common 11191 // multiply (ConstNode * A) that we can save. 11192 if (OtherOp == MulVar) 11193 return true; 11194 11195 // Now check to see if a future expansion will give us a common 11196 // multiply. 11197 // 11198 // ConstNode = CONST 11199 // AddNode = (A + c1) 11200 // ... = AddNode * ConstNode <-- current visiting instruction. 11201 // ... 11202 // OtherOp = (A + c2) 11203 // Use = OtherOp * ConstNode <-- visiting Use. 11204 // 11205 // If we make this transformation, we will have a common 11206 // multiply (CONST * A) after we also do the same transformation 11207 // to the "t2" instruction. 11208 if (OtherOp->getOpcode() == ISD::ADD && 11209 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11210 OtherOp->getOperand(0).getNode() == MulVar) 11211 return true; 11212 } 11213 } 11214 11215 // Didn't find a case where this would be profitable. 11216 return false; 11217 } 11218 11219 SDValue DAGCombiner::getMergedConstantVectorStore( 11220 SelectionDAG &DAG, const SDLoc &SL, ArrayRef<MemOpLink> Stores, 11221 SmallVectorImpl<SDValue> &Chains, EVT Ty) const { 11222 SmallVector<SDValue, 8> BuildVector; 11223 11224 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11225 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11226 Chains.push_back(St->getChain()); 11227 BuildVector.push_back(St->getValue()); 11228 } 11229 11230 return DAG.getBuildVector(Ty, SL, BuildVector); 11231 } 11232 11233 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11234 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11235 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11236 // Make sure we have something to merge. 11237 if (NumStores < 2) 11238 return false; 11239 11240 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11241 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11242 unsigned LatestNodeUsed = 0; 11243 11244 for (unsigned i=0; i < NumStores; ++i) { 11245 // Find a chain for the new wide-store operand. Notice that some 11246 // of the store nodes that we found may not be selected for inclusion 11247 // in the wide store. The chain we use needs to be the chain of the 11248 // latest store node which is *used* and replaced by the wide store. 11249 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11250 LatestNodeUsed = i; 11251 } 11252 11253 SmallVector<SDValue, 8> Chains; 11254 11255 // The latest Node in the DAG. 11256 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11257 SDLoc DL(StoreNodes[0].MemNode); 11258 11259 SDValue StoredVal; 11260 if (UseVector) { 11261 bool IsVec = MemVT.isVector(); 11262 unsigned Elts = NumStores; 11263 if (IsVec) { 11264 // When merging vector stores, get the total number of elements. 11265 Elts *= MemVT.getVectorNumElements(); 11266 } 11267 // Get the type for the merged vector store. 11268 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11269 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11270 11271 if (IsConstantSrc) { 11272 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11273 } else { 11274 SmallVector<SDValue, 8> Ops; 11275 for (unsigned i = 0; i < NumStores; ++i) { 11276 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11277 SDValue Val = St->getValue(); 11278 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11279 if (Val.getValueType() != MemVT) 11280 return false; 11281 Ops.push_back(Val); 11282 Chains.push_back(St->getChain()); 11283 } 11284 11285 // Build the extracted vector elements back into a vector. 11286 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11287 DL, Ty, Ops); } 11288 } else { 11289 // We should always use a vector store when merging extracted vector 11290 // elements, so this path implies a store of constants. 11291 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11292 11293 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11294 APInt StoreInt(SizeInBits, 0); 11295 11296 // Construct a single integer constant which is made of the smaller 11297 // constant inputs. 11298 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11299 for (unsigned i = 0; i < NumStores; ++i) { 11300 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11301 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11302 Chains.push_back(St->getChain()); 11303 11304 SDValue Val = St->getValue(); 11305 StoreInt <<= ElementSizeBytes * 8; 11306 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11307 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11308 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11309 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11310 } else { 11311 llvm_unreachable("Invalid constant element type"); 11312 } 11313 } 11314 11315 // Create the new Load and Store operations. 11316 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11317 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11318 } 11319 11320 assert(!Chains.empty()); 11321 11322 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11323 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11324 FirstInChain->getBasePtr(), 11325 FirstInChain->getPointerInfo(), 11326 FirstInChain->getAlignment()); 11327 11328 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11329 : DAG.getSubtarget().useAA(); 11330 if (UseAA) { 11331 // Replace all merged stores with the new store. 11332 for (unsigned i = 0; i < NumStores; ++i) 11333 CombineTo(StoreNodes[i].MemNode, NewStore); 11334 } else { 11335 // Replace the last store with the new store. 11336 CombineTo(LatestOp, NewStore); 11337 // Erase all other stores. 11338 for (unsigned i = 0; i < NumStores; ++i) { 11339 if (StoreNodes[i].MemNode == LatestOp) 11340 continue; 11341 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11342 // ReplaceAllUsesWith will replace all uses that existed when it was 11343 // called, but graph optimizations may cause new ones to appear. For 11344 // example, the case in pr14333 looks like 11345 // 11346 // St's chain -> St -> another store -> X 11347 // 11348 // And the only difference from St to the other store is the chain. 11349 // When we change it's chain to be St's chain they become identical, 11350 // get CSEed and the net result is that X is now a use of St. 11351 // Since we know that St is redundant, just iterate. 11352 while (!St->use_empty()) 11353 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11354 deleteAndRecombine(St); 11355 } 11356 } 11357 11358 return true; 11359 } 11360 11361 void DAGCombiner::getStoreMergeAndAliasCandidates( 11362 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11363 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11364 // This holds the base pointer, index, and the offset in bytes from the base 11365 // pointer. 11366 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11367 11368 // We must have a base and an offset. 11369 if (!BasePtr.Base.getNode()) 11370 return; 11371 11372 // Do not handle stores to undef base pointers. 11373 if (BasePtr.Base.isUndef()) 11374 return; 11375 11376 // Walk up the chain and look for nodes with offsets from the same 11377 // base pointer. Stop when reaching an instruction with a different kind 11378 // or instruction which has a different base pointer. 11379 EVT MemVT = St->getMemoryVT(); 11380 unsigned Seq = 0; 11381 StoreSDNode *Index = St; 11382 11383 11384 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11385 : DAG.getSubtarget().useAA(); 11386 11387 if (UseAA) { 11388 // Look at other users of the same chain. Stores on the same chain do not 11389 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11390 // to be on the same chain, so don't bother looking at adjacent chains. 11391 11392 SDValue Chain = St->getChain(); 11393 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11394 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11395 if (I.getOperandNo() != 0) 11396 continue; 11397 11398 if (OtherST->isVolatile() || OtherST->isIndexed()) 11399 continue; 11400 11401 if (OtherST->getMemoryVT() != MemVT) 11402 continue; 11403 11404 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11405 11406 if (Ptr.equalBaseIndex(BasePtr)) 11407 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11408 } 11409 } 11410 11411 return; 11412 } 11413 11414 while (Index) { 11415 // If the chain has more than one use, then we can't reorder the mem ops. 11416 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11417 break; 11418 11419 // Find the base pointer and offset for this memory node. 11420 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11421 11422 // Check that the base pointer is the same as the original one. 11423 if (!Ptr.equalBaseIndex(BasePtr)) 11424 break; 11425 11426 // The memory operands must not be volatile. 11427 if (Index->isVolatile() || Index->isIndexed()) 11428 break; 11429 11430 // No truncation. 11431 if (Index->isTruncatingStore()) 11432 break; 11433 11434 // The stored memory type must be the same. 11435 if (Index->getMemoryVT() != MemVT) 11436 break; 11437 11438 // We do not allow under-aligned stores in order to prevent 11439 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11440 // be irrelevant here; what MATTERS is that we not move memory 11441 // operations that potentially overlap past each-other. 11442 if (Index->getAlignment() < MemVT.getStoreSize()) 11443 break; 11444 11445 // We found a potential memory operand to merge. 11446 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11447 11448 // Find the next memory operand in the chain. If the next operand in the 11449 // chain is a store then move up and continue the scan with the next 11450 // memory operand. If the next operand is a load save it and use alias 11451 // information to check if it interferes with anything. 11452 SDNode *NextInChain = Index->getChain().getNode(); 11453 while (1) { 11454 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11455 // We found a store node. Use it for the next iteration. 11456 Index = STn; 11457 break; 11458 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11459 if (Ldn->isVolatile()) { 11460 Index = nullptr; 11461 break; 11462 } 11463 11464 // Save the load node for later. Continue the scan. 11465 AliasLoadNodes.push_back(Ldn); 11466 NextInChain = Ldn->getChain().getNode(); 11467 continue; 11468 } else { 11469 Index = nullptr; 11470 break; 11471 } 11472 } 11473 } 11474 } 11475 11476 // We need to check that merging these stores does not cause a loop 11477 // in the DAG. Any store candidate may depend on another candidate 11478 // indirectly through its operand (we already consider dependencies 11479 // through the chain). Check in parallel by searching up from 11480 // non-chain operands of candidates. 11481 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 11482 SmallVectorImpl<MemOpLink> &StoreNodes) { 11483 SmallPtrSet<const SDNode *, 16> Visited; 11484 SmallVector<const SDNode *, 8> Worklist; 11485 // search ops of store candidates 11486 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11487 SDNode *n = StoreNodes[i].MemNode; 11488 // Potential loops may happen only through non-chain operands 11489 for (unsigned j = 1; j < n->getNumOperands(); ++j) 11490 Worklist.push_back(n->getOperand(j).getNode()); 11491 } 11492 // search through DAG. We can stop early if we find a storenode 11493 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11494 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 11495 return false; 11496 } 11497 return true; 11498 } 11499 11500 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11501 if (OptLevel == CodeGenOpt::None) 11502 return false; 11503 11504 EVT MemVT = St->getMemoryVT(); 11505 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11506 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11507 Attribute::NoImplicitFloat); 11508 11509 // This function cannot currently deal with non-byte-sized memory sizes. 11510 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11511 return false; 11512 11513 if (!MemVT.isSimple()) 11514 return false; 11515 11516 // Perform an early exit check. Do not bother looking at stored values that 11517 // are not constants, loads, or extracted vector elements. 11518 SDValue StoredVal = St->getValue(); 11519 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11520 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11521 isa<ConstantFPSDNode>(StoredVal); 11522 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11523 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11524 11525 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11526 return false; 11527 11528 // Don't merge vectors into wider vectors if the source data comes from loads. 11529 // TODO: This restriction can be lifted by using logic similar to the 11530 // ExtractVecSrc case. 11531 if (MemVT.isVector() && IsLoadSrc) 11532 return false; 11533 11534 // Only look at ends of store sequences. 11535 SDValue Chain = SDValue(St, 0); 11536 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11537 return false; 11538 11539 // Save the LoadSDNodes that we find in the chain. 11540 // We need to make sure that these nodes do not interfere with 11541 // any of the store nodes. 11542 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11543 11544 // Save the StoreSDNodes that we find in the chain. 11545 SmallVector<MemOpLink, 8> StoreNodes; 11546 11547 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11548 11549 // Check if there is anything to merge. 11550 if (StoreNodes.size() < 2) 11551 return false; 11552 11553 // only do dependence check in AA case 11554 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11555 : DAG.getSubtarget().useAA(); 11556 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes)) 11557 return false; 11558 11559 // Sort the memory operands according to their distance from the 11560 // base pointer. As a secondary criteria: make sure stores coming 11561 // later in the code come first in the list. This is important for 11562 // the non-UseAA case, because we're merging stores into the FINAL 11563 // store along a chain which potentially contains aliasing stores. 11564 // Thus, if there are multiple stores to the same address, the last 11565 // one can be considered for merging but not the others. 11566 std::sort(StoreNodes.begin(), StoreNodes.end(), 11567 [](MemOpLink LHS, MemOpLink RHS) { 11568 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11569 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11570 LHS.SequenceNum < RHS.SequenceNum); 11571 }); 11572 11573 // Scan the memory operations on the chain and find the first non-consecutive 11574 // store memory address. 11575 unsigned LastConsecutiveStore = 0; 11576 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11577 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11578 11579 // Check that the addresses are consecutive starting from the second 11580 // element in the list of stores. 11581 if (i > 0) { 11582 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11583 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11584 break; 11585 } 11586 11587 // Check if this store interferes with any of the loads that we found. 11588 // If we find a load that alias with this store. Stop the sequence. 11589 if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(), 11590 [&](LSBaseSDNode* Ldn) { 11591 return isAlias(Ldn, StoreNodes[i].MemNode); 11592 })) 11593 break; 11594 11595 // Mark this node as useful. 11596 LastConsecutiveStore = i; 11597 } 11598 11599 // The node with the lowest store address. 11600 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11601 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11602 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11603 LLVMContext &Context = *DAG.getContext(); 11604 const DataLayout &DL = DAG.getDataLayout(); 11605 11606 // Store the constants into memory as one consecutive store. 11607 if (IsConstantSrc) { 11608 unsigned LastLegalType = 0; 11609 unsigned LastLegalVectorType = 0; 11610 bool NonZero = false; 11611 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11612 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11613 SDValue StoredVal = St->getValue(); 11614 11615 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11616 NonZero |= !C->isNullValue(); 11617 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11618 NonZero |= !C->getConstantFPValue()->isNullValue(); 11619 } else { 11620 // Non-constant. 11621 break; 11622 } 11623 11624 // Find a legal type for the constant store. 11625 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11626 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11627 bool IsFast; 11628 if (TLI.isTypeLegal(StoreTy) && 11629 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11630 FirstStoreAlign, &IsFast) && IsFast) { 11631 LastLegalType = i+1; 11632 // Or check whether a truncstore is legal. 11633 } else if (TLI.getTypeAction(Context, StoreTy) == 11634 TargetLowering::TypePromoteInteger) { 11635 EVT LegalizedStoredValueTy = 11636 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11637 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11638 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11639 FirstStoreAS, FirstStoreAlign, &IsFast) && 11640 IsFast) { 11641 LastLegalType = i + 1; 11642 } 11643 } 11644 11645 // We only use vectors if the constant is known to be zero or the target 11646 // allows it and the function is not marked with the noimplicitfloat 11647 // attribute. 11648 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11649 FirstStoreAS)) && 11650 !NoVectors) { 11651 // Find a legal type for the vector store. 11652 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11653 if (TLI.isTypeLegal(Ty) && 11654 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11655 FirstStoreAlign, &IsFast) && IsFast) 11656 LastLegalVectorType = i + 1; 11657 } 11658 } 11659 11660 // Check if we found a legal integer type to store. 11661 if (LastLegalType == 0 && LastLegalVectorType == 0) 11662 return false; 11663 11664 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11665 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11666 11667 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11668 true, UseVector); 11669 } 11670 11671 // When extracting multiple vector elements, try to store them 11672 // in one vector store rather than a sequence of scalar stores. 11673 if (IsExtractVecSrc) { 11674 unsigned NumStoresToMerge = 0; 11675 bool IsVec = MemVT.isVector(); 11676 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11677 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11678 unsigned StoreValOpcode = St->getValue().getOpcode(); 11679 // This restriction could be loosened. 11680 // Bail out if any stored values are not elements extracted from a vector. 11681 // It should be possible to handle mixed sources, but load sources need 11682 // more careful handling (see the block of code below that handles 11683 // consecutive loads). 11684 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11685 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11686 return false; 11687 11688 // Find a legal type for the vector store. 11689 unsigned Elts = i + 1; 11690 if (IsVec) { 11691 // When merging vector stores, get the total number of elements. 11692 Elts *= MemVT.getVectorNumElements(); 11693 } 11694 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11695 bool IsFast; 11696 if (TLI.isTypeLegal(Ty) && 11697 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11698 FirstStoreAlign, &IsFast) && IsFast) 11699 NumStoresToMerge = i + 1; 11700 } 11701 11702 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11703 false, true); 11704 } 11705 11706 // Below we handle the case of multiple consecutive stores that 11707 // come from multiple consecutive loads. We merge them into a single 11708 // wide load and a single wide store. 11709 11710 // Look for load nodes which are used by the stored values. 11711 SmallVector<MemOpLink, 8> LoadNodes; 11712 11713 // Find acceptable loads. Loads need to have the same chain (token factor), 11714 // must not be zext, volatile, indexed, and they must be consecutive. 11715 BaseIndexOffset LdBasePtr; 11716 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11717 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11718 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11719 if (!Ld) break; 11720 11721 // Loads must only have one use. 11722 if (!Ld->hasNUsesOfValue(1, 0)) 11723 break; 11724 11725 // The memory operands must not be volatile. 11726 if (Ld->isVolatile() || Ld->isIndexed()) 11727 break; 11728 11729 // We do not accept ext loads. 11730 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11731 break; 11732 11733 // The stored memory type must be the same. 11734 if (Ld->getMemoryVT() != MemVT) 11735 break; 11736 11737 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 11738 // If this is not the first ptr that we check. 11739 if (LdBasePtr.Base.getNode()) { 11740 // The base ptr must be the same. 11741 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11742 break; 11743 } else { 11744 // Check that all other base pointers are the same as this one. 11745 LdBasePtr = LdPtr; 11746 } 11747 11748 // We found a potential memory operand to merge. 11749 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11750 } 11751 11752 if (LoadNodes.size() < 2) 11753 return false; 11754 11755 // If we have load/store pair instructions and we only have two values, 11756 // don't bother. 11757 unsigned RequiredAlignment; 11758 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11759 St->getAlignment() >= RequiredAlignment) 11760 return false; 11761 11762 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11763 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11764 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11765 11766 // Scan the memory operations on the chain and find the first non-consecutive 11767 // load memory address. These variables hold the index in the store node 11768 // array. 11769 unsigned LastConsecutiveLoad = 0; 11770 // This variable refers to the size and not index in the array. 11771 unsigned LastLegalVectorType = 0; 11772 unsigned LastLegalIntegerType = 0; 11773 StartAddress = LoadNodes[0].OffsetFromBase; 11774 SDValue FirstChain = FirstLoad->getChain(); 11775 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11776 // All loads must share the same chain. 11777 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11778 break; 11779 11780 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11781 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11782 break; 11783 LastConsecutiveLoad = i; 11784 // Find a legal type for the vector store. 11785 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11786 bool IsFastSt, IsFastLd; 11787 if (TLI.isTypeLegal(StoreTy) && 11788 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11789 FirstStoreAlign, &IsFastSt) && IsFastSt && 11790 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11791 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11792 LastLegalVectorType = i + 1; 11793 } 11794 11795 // Find a legal type for the integer store. 11796 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11797 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11798 if (TLI.isTypeLegal(StoreTy) && 11799 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11800 FirstStoreAlign, &IsFastSt) && IsFastSt && 11801 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11802 FirstLoadAlign, &IsFastLd) && IsFastLd) 11803 LastLegalIntegerType = i + 1; 11804 // Or check whether a truncstore and extload is legal. 11805 else if (TLI.getTypeAction(Context, StoreTy) == 11806 TargetLowering::TypePromoteInteger) { 11807 EVT LegalizedStoredValueTy = 11808 TLI.getTypeToTransformTo(Context, StoreTy); 11809 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11810 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11811 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11812 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11813 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11814 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11815 IsFastSt && 11816 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11817 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11818 IsFastLd) 11819 LastLegalIntegerType = i+1; 11820 } 11821 } 11822 11823 // Only use vector types if the vector type is larger than the integer type. 11824 // If they are the same, use integers. 11825 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11826 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11827 11828 // We add +1 here because the LastXXX variables refer to location while 11829 // the NumElem refers to array/index size. 11830 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11831 NumElem = std::min(LastLegalType, NumElem); 11832 11833 if (NumElem < 2) 11834 return false; 11835 11836 // Collect the chains from all merged stores. 11837 SmallVector<SDValue, 8> MergeStoreChains; 11838 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11839 11840 // The latest Node in the DAG. 11841 unsigned LatestNodeUsed = 0; 11842 for (unsigned i=1; i<NumElem; ++i) { 11843 // Find a chain for the new wide-store operand. Notice that some 11844 // of the store nodes that we found may not be selected for inclusion 11845 // in the wide store. The chain we use needs to be the chain of the 11846 // latest store node which is *used* and replaced by the wide store. 11847 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11848 LatestNodeUsed = i; 11849 11850 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11851 } 11852 11853 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11854 11855 // Find if it is better to use vectors or integers to load and store 11856 // to memory. 11857 EVT JointMemOpVT; 11858 if (UseVectorTy) { 11859 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11860 } else { 11861 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11862 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11863 } 11864 11865 SDLoc LoadDL(LoadNodes[0].MemNode); 11866 SDLoc StoreDL(StoreNodes[0].MemNode); 11867 11868 // The merged loads are required to have the same incoming chain, so 11869 // using the first's chain is acceptable. 11870 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 11871 FirstLoad->getBasePtr(), 11872 FirstLoad->getPointerInfo(), FirstLoadAlign); 11873 11874 SDValue NewStoreChain = 11875 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11876 11877 SDValue NewStore = 11878 DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11879 FirstInChain->getPointerInfo(), FirstStoreAlign); 11880 11881 // Transfer chain users from old loads to the new load. 11882 for (unsigned i = 0; i < NumElem; ++i) { 11883 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11884 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11885 SDValue(NewLoad.getNode(), 1)); 11886 } 11887 11888 if (UseAA) { 11889 // Replace the all stores with the new store. 11890 for (unsigned i = 0; i < NumElem; ++i) 11891 CombineTo(StoreNodes[i].MemNode, NewStore); 11892 } else { 11893 // Replace the last store with the new store. 11894 CombineTo(LatestOp, NewStore); 11895 // Erase all other stores. 11896 for (unsigned i = 0; i < NumElem; ++i) { 11897 // Remove all Store nodes. 11898 if (StoreNodes[i].MemNode == LatestOp) 11899 continue; 11900 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11901 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11902 deleteAndRecombine(St); 11903 } 11904 } 11905 11906 return true; 11907 } 11908 11909 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11910 SDLoc SL(ST); 11911 SDValue ReplStore; 11912 11913 // Replace the chain to avoid dependency. 11914 if (ST->isTruncatingStore()) { 11915 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11916 ST->getBasePtr(), ST->getMemoryVT(), 11917 ST->getMemOperand()); 11918 } else { 11919 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11920 ST->getMemOperand()); 11921 } 11922 11923 // Create token to keep both nodes around. 11924 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11925 MVT::Other, ST->getChain(), ReplStore); 11926 11927 // Make sure the new and old chains are cleaned up. 11928 AddToWorklist(Token.getNode()); 11929 11930 // Don't add users to work list. 11931 return CombineTo(ST, Token, false); 11932 } 11933 11934 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11935 SDValue Value = ST->getValue(); 11936 if (Value.getOpcode() == ISD::TargetConstantFP) 11937 return SDValue(); 11938 11939 SDLoc DL(ST); 11940 11941 SDValue Chain = ST->getChain(); 11942 SDValue Ptr = ST->getBasePtr(); 11943 11944 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11945 11946 // NOTE: If the original store is volatile, this transform must not increase 11947 // the number of stores. For example, on x86-32 an f64 can be stored in one 11948 // processor operation but an i64 (which is not legal) requires two. So the 11949 // transform should not be done in this case. 11950 11951 SDValue Tmp; 11952 switch (CFP->getSimpleValueType(0).SimpleTy) { 11953 default: 11954 llvm_unreachable("Unknown FP type"); 11955 case MVT::f16: // We don't do this for these yet. 11956 case MVT::f80: 11957 case MVT::f128: 11958 case MVT::ppcf128: 11959 return SDValue(); 11960 case MVT::f32: 11961 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11962 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11963 ; 11964 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11965 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11966 MVT::i32); 11967 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11968 } 11969 11970 return SDValue(); 11971 case MVT::f64: 11972 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11973 !ST->isVolatile()) || 11974 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11975 ; 11976 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11977 getZExtValue(), SDLoc(CFP), MVT::i64); 11978 return DAG.getStore(Chain, DL, Tmp, 11979 Ptr, ST->getMemOperand()); 11980 } 11981 11982 if (!ST->isVolatile() && 11983 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11984 // Many FP stores are not made apparent until after legalize, e.g. for 11985 // argument passing. Since this is so common, custom legalize the 11986 // 64-bit integer store into two 32-bit stores. 11987 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11988 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11989 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11990 if (DAG.getDataLayout().isBigEndian()) 11991 std::swap(Lo, Hi); 11992 11993 unsigned Alignment = ST->getAlignment(); 11994 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 11995 AAMDNodes AAInfo = ST->getAAInfo(); 11996 11997 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 11998 ST->getAlignment(), MMOFlags, AAInfo); 11999 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 12000 DAG.getConstant(4, DL, Ptr.getValueType())); 12001 Alignment = MinAlign(Alignment, 4U); 12002 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 12003 ST->getPointerInfo().getWithOffset(4), 12004 Alignment, MMOFlags, AAInfo); 12005 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 12006 St0, St1); 12007 } 12008 12009 return SDValue(); 12010 } 12011 } 12012 12013 SDValue DAGCombiner::visitSTORE(SDNode *N) { 12014 StoreSDNode *ST = cast<StoreSDNode>(N); 12015 SDValue Chain = ST->getChain(); 12016 SDValue Value = ST->getValue(); 12017 SDValue Ptr = ST->getBasePtr(); 12018 12019 // If this is a store of a bit convert, store the input value if the 12020 // resultant store does not need a higher alignment than the original. 12021 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 12022 ST->isUnindexed()) { 12023 EVT SVT = Value.getOperand(0).getValueType(); 12024 if (((!LegalOperations && !ST->isVolatile()) || 12025 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 12026 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 12027 unsigned OrigAlign = ST->getAlignment(); 12028 bool Fast = false; 12029 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 12030 ST->getAddressSpace(), OrigAlign, &Fast) && 12031 Fast) { 12032 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 12033 ST->getPointerInfo(), OrigAlign, 12034 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12035 } 12036 } 12037 } 12038 12039 // Turn 'store undef, Ptr' -> nothing. 12040 if (Value.isUndef() && ST->isUnindexed()) 12041 return Chain; 12042 12043 // Try to infer better alignment information than the store already has. 12044 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 12045 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12046 if (Align > ST->getAlignment()) { 12047 SDValue NewStore = 12048 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 12049 ST->getMemoryVT(), Align, 12050 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 12051 if (NewStore.getNode() != N) 12052 return CombineTo(ST, NewStore, true); 12053 } 12054 } 12055 } 12056 12057 // Try transforming a pair floating point load / store ops to integer 12058 // load / store ops. 12059 if (SDValue NewST = TransformFPLoadStorePair(N)) 12060 return NewST; 12061 12062 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12063 : DAG.getSubtarget().useAA(); 12064 #ifndef NDEBUG 12065 if (CombinerAAOnlyFunc.getNumOccurrences() && 12066 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12067 UseAA = false; 12068 #endif 12069 if (UseAA && ST->isUnindexed()) { 12070 // FIXME: We should do this even without AA enabled. AA will just allow 12071 // FindBetterChain to work in more situations. The problem with this is that 12072 // any combine that expects memory operations to be on consecutive chains 12073 // first needs to be updated to look for users of the same chain. 12074 12075 // Walk up chain skipping non-aliasing memory nodes, on this store and any 12076 // adjacent stores. 12077 if (findBetterNeighborChains(ST)) { 12078 // replaceStoreChain uses CombineTo, which handled all of the worklist 12079 // manipulation. Return the original node to not do anything else. 12080 return SDValue(ST, 0); 12081 } 12082 Chain = ST->getChain(); 12083 } 12084 12085 // Try transforming N to an indexed store. 12086 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12087 return SDValue(N, 0); 12088 12089 // FIXME: is there such a thing as a truncating indexed store? 12090 if (ST->isTruncatingStore() && ST->isUnindexed() && 12091 Value.getValueType().isInteger()) { 12092 // See if we can simplify the input to this truncstore with knowledge that 12093 // only the low bits are being used. For example: 12094 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 12095 SDValue Shorter = 12096 GetDemandedBits(Value, 12097 APInt::getLowBitsSet( 12098 Value.getValueType().getScalarType().getSizeInBits(), 12099 ST->getMemoryVT().getScalarType().getSizeInBits())); 12100 AddToWorklist(Value.getNode()); 12101 if (Shorter.getNode()) 12102 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12103 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12104 12105 // Otherwise, see if we can simplify the operation with 12106 // SimplifyDemandedBits, which only works if the value has a single use. 12107 if (SimplifyDemandedBits(Value, 12108 APInt::getLowBitsSet( 12109 Value.getValueType().getScalarType().getSizeInBits(), 12110 ST->getMemoryVT().getScalarType().getSizeInBits()))) 12111 return SDValue(N, 0); 12112 } 12113 12114 // If this is a load followed by a store to the same location, then the store 12115 // is dead/noop. 12116 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12117 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12118 ST->isUnindexed() && !ST->isVolatile() && 12119 // There can't be any side effects between the load and store, such as 12120 // a call or store. 12121 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12122 // The store is dead, remove it. 12123 return Chain; 12124 } 12125 } 12126 12127 // If this is a store followed by a store with the same value to the same 12128 // location, then the store is dead/noop. 12129 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12130 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12131 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12132 ST1->isUnindexed() && !ST1->isVolatile()) { 12133 // The store is dead, remove it. 12134 return Chain; 12135 } 12136 } 12137 12138 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12139 // truncating store. We can do this even if this is already a truncstore. 12140 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12141 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12142 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12143 ST->getMemoryVT())) { 12144 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12145 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12146 } 12147 12148 // Only perform this optimization before the types are legal, because we 12149 // don't want to perform this optimization on every DAGCombine invocation. 12150 if (!LegalTypes) { 12151 bool EverChanged = false; 12152 12153 do { 12154 // There can be multiple store sequences on the same chain. 12155 // Keep trying to merge store sequences until we are unable to do so 12156 // or until we merge the last store on the chain. 12157 bool Changed = MergeConsecutiveStores(ST); 12158 EverChanged |= Changed; 12159 if (!Changed) break; 12160 } while (ST->getOpcode() != ISD::DELETED_NODE); 12161 12162 if (EverChanged) 12163 return SDValue(N, 0); 12164 } 12165 12166 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12167 // 12168 // Make sure to do this only after attempting to merge stores in order to 12169 // avoid changing the types of some subset of stores due to visit order, 12170 // preventing their merging. 12171 if (isa<ConstantFPSDNode>(Value)) { 12172 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12173 return NewSt; 12174 } 12175 12176 return ReduceLoadOpStoreWidth(N); 12177 } 12178 12179 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12180 SDValue InVec = N->getOperand(0); 12181 SDValue InVal = N->getOperand(1); 12182 SDValue EltNo = N->getOperand(2); 12183 SDLoc dl(N); 12184 12185 // If the inserted element is an UNDEF, just use the input vector. 12186 if (InVal.isUndef()) 12187 return InVec; 12188 12189 EVT VT = InVec.getValueType(); 12190 12191 // If we can't generate a legal BUILD_VECTOR, exit 12192 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12193 return SDValue(); 12194 12195 // Check that we know which element is being inserted 12196 if (!isa<ConstantSDNode>(EltNo)) 12197 return SDValue(); 12198 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12199 12200 // Canonicalize insert_vector_elt dag nodes. 12201 // Example: 12202 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12203 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12204 // 12205 // Do this only if the child insert_vector node has one use; also 12206 // do this only if indices are both constants and Idx1 < Idx0. 12207 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12208 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12209 unsigned OtherElt = 12210 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12211 if (Elt < OtherElt) { 12212 // Swap nodes. 12213 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 12214 InVec.getOperand(0), InVal, EltNo); 12215 AddToWorklist(NewOp.getNode()); 12216 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12217 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12218 } 12219 } 12220 12221 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12222 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12223 // vector elements. 12224 SmallVector<SDValue, 8> Ops; 12225 // Do not combine these two vectors if the output vector will not replace 12226 // the input vector. 12227 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12228 Ops.append(InVec.getNode()->op_begin(), 12229 InVec.getNode()->op_end()); 12230 } else if (InVec.isUndef()) { 12231 unsigned NElts = VT.getVectorNumElements(); 12232 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12233 } else { 12234 return SDValue(); 12235 } 12236 12237 // Insert the element 12238 if (Elt < Ops.size()) { 12239 // All the operands of BUILD_VECTOR must have the same type; 12240 // we enforce that here. 12241 EVT OpVT = Ops[0].getValueType(); 12242 if (InVal.getValueType() != OpVT) 12243 InVal = OpVT.bitsGT(InVal.getValueType()) ? 12244 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 12245 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 12246 Ops[Elt] = InVal; 12247 } 12248 12249 // Return the new vector 12250 return DAG.getBuildVector(VT, dl, Ops); 12251 } 12252 12253 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12254 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12255 assert(!OriginalLoad->isVolatile()); 12256 12257 EVT ResultVT = EVE->getValueType(0); 12258 EVT VecEltVT = InVecVT.getVectorElementType(); 12259 unsigned Align = OriginalLoad->getAlignment(); 12260 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12261 VecEltVT.getTypeForEVT(*DAG.getContext())); 12262 12263 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12264 return SDValue(); 12265 12266 Align = NewAlign; 12267 12268 SDValue NewPtr = OriginalLoad->getBasePtr(); 12269 SDValue Offset; 12270 EVT PtrType = NewPtr.getValueType(); 12271 MachinePointerInfo MPI; 12272 SDLoc DL(EVE); 12273 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12274 int Elt = ConstEltNo->getZExtValue(); 12275 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12276 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12277 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12278 } else { 12279 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12280 Offset = DAG.getNode( 12281 ISD::MUL, DL, PtrType, Offset, 12282 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12283 MPI = OriginalLoad->getPointerInfo(); 12284 } 12285 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12286 12287 // The replacement we need to do here is a little tricky: we need to 12288 // replace an extractelement of a load with a load. 12289 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12290 // Note that this replacement assumes that the extractvalue is the only 12291 // use of the load; that's okay because we don't want to perform this 12292 // transformation in other cases anyway. 12293 SDValue Load; 12294 SDValue Chain; 12295 if (ResultVT.bitsGT(VecEltVT)) { 12296 // If the result type of vextract is wider than the load, then issue an 12297 // extending load instead. 12298 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12299 VecEltVT) 12300 ? ISD::ZEXTLOAD 12301 : ISD::EXTLOAD; 12302 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 12303 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 12304 Align, OriginalLoad->getMemOperand()->getFlags(), 12305 OriginalLoad->getAAInfo()); 12306 Chain = Load.getValue(1); 12307 } else { 12308 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 12309 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 12310 OriginalLoad->getAAInfo()); 12311 Chain = Load.getValue(1); 12312 if (ResultVT.bitsLT(VecEltVT)) 12313 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12314 else 12315 Load = DAG.getBitcast(ResultVT, Load); 12316 } 12317 WorklistRemover DeadNodes(*this); 12318 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12319 SDValue To[] = { Load, Chain }; 12320 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12321 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12322 // worklist explicitly as well. 12323 AddToWorklist(Load.getNode()); 12324 AddUsersToWorklist(Load.getNode()); // Add users too 12325 // Make sure to revisit this node to clean it up; it will usually be dead. 12326 AddToWorklist(EVE); 12327 ++OpsNarrowed; 12328 return SDValue(EVE, 0); 12329 } 12330 12331 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12332 // (vextract (scalar_to_vector val, 0) -> val 12333 SDValue InVec = N->getOperand(0); 12334 EVT VT = InVec.getValueType(); 12335 EVT NVT = N->getValueType(0); 12336 12337 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12338 // Check if the result type doesn't match the inserted element type. A 12339 // SCALAR_TO_VECTOR may truncate the inserted element and the 12340 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12341 SDValue InOp = InVec.getOperand(0); 12342 if (InOp.getValueType() != NVT) { 12343 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12344 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12345 } 12346 return InOp; 12347 } 12348 12349 SDValue EltNo = N->getOperand(1); 12350 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12351 12352 // extract_vector_elt (build_vector x, y), 1 -> y 12353 if (ConstEltNo && 12354 InVec.getOpcode() == ISD::BUILD_VECTOR && 12355 TLI.isTypeLegal(VT) && 12356 (InVec.hasOneUse() || 12357 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12358 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12359 EVT InEltVT = Elt.getValueType(); 12360 12361 // Sometimes build_vector's scalar input types do not match result type. 12362 if (NVT == InEltVT) 12363 return Elt; 12364 12365 // TODO: It may be useful to truncate if free if the build_vector implicitly 12366 // converts. 12367 } 12368 12369 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 12370 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 12371 ConstEltNo->isNullValue() && VT.isInteger()) { 12372 SDValue BCSrc = InVec.getOperand(0); 12373 if (BCSrc.getValueType().isScalarInteger()) 12374 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 12375 } 12376 12377 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 12378 // 12379 // This only really matters if the index is non-constant since other combines 12380 // on the constant elements already work. 12381 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && 12382 EltNo == InVec.getOperand(2)) { 12383 SDValue Elt = InVec.getOperand(1); 12384 return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt; 12385 } 12386 12387 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12388 // We only perform this optimization before the op legalization phase because 12389 // we may introduce new vector instructions which are not backed by TD 12390 // patterns. For example on AVX, extracting elements from a wide vector 12391 // without using extract_subvector. However, if we can find an underlying 12392 // scalar value, then we can always use that. 12393 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12394 int NumElem = VT.getVectorNumElements(); 12395 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12396 // Find the new index to extract from. 12397 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12398 12399 // Extracting an undef index is undef. 12400 if (OrigElt == -1) 12401 return DAG.getUNDEF(NVT); 12402 12403 // Select the right vector half to extract from. 12404 SDValue SVInVec; 12405 if (OrigElt < NumElem) { 12406 SVInVec = InVec->getOperand(0); 12407 } else { 12408 SVInVec = InVec->getOperand(1); 12409 OrigElt -= NumElem; 12410 } 12411 12412 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12413 SDValue InOp = SVInVec.getOperand(OrigElt); 12414 if (InOp.getValueType() != NVT) { 12415 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12416 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12417 } 12418 12419 return InOp; 12420 } 12421 12422 // FIXME: We should handle recursing on other vector shuffles and 12423 // scalar_to_vector here as well. 12424 12425 if (!LegalOperations) { 12426 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12427 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12428 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12429 } 12430 } 12431 12432 bool BCNumEltsChanged = false; 12433 EVT ExtVT = VT.getVectorElementType(); 12434 EVT LVT = ExtVT; 12435 12436 // If the result of load has to be truncated, then it's not necessarily 12437 // profitable. 12438 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12439 return SDValue(); 12440 12441 if (InVec.getOpcode() == ISD::BITCAST) { 12442 // Don't duplicate a load with other uses. 12443 if (!InVec.hasOneUse()) 12444 return SDValue(); 12445 12446 EVT BCVT = InVec.getOperand(0).getValueType(); 12447 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12448 return SDValue(); 12449 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12450 BCNumEltsChanged = true; 12451 InVec = InVec.getOperand(0); 12452 ExtVT = BCVT.getVectorElementType(); 12453 } 12454 12455 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12456 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12457 ISD::isNormalLoad(InVec.getNode()) && 12458 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12459 SDValue Index = N->getOperand(1); 12460 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) { 12461 if (!OrigLoad->isVolatile()) { 12462 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12463 OrigLoad); 12464 } 12465 } 12466 } 12467 12468 // Perform only after legalization to ensure build_vector / vector_shuffle 12469 // optimizations have already been done. 12470 if (!LegalOperations) return SDValue(); 12471 12472 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12473 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12474 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12475 12476 if (ConstEltNo) { 12477 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12478 12479 LoadSDNode *LN0 = nullptr; 12480 const ShuffleVectorSDNode *SVN = nullptr; 12481 if (ISD::isNormalLoad(InVec.getNode())) { 12482 LN0 = cast<LoadSDNode>(InVec); 12483 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12484 InVec.getOperand(0).getValueType() == ExtVT && 12485 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12486 // Don't duplicate a load with other uses. 12487 if (!InVec.hasOneUse()) 12488 return SDValue(); 12489 12490 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12491 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12492 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12493 // => 12494 // (load $addr+1*size) 12495 12496 // Don't duplicate a load with other uses. 12497 if (!InVec.hasOneUse()) 12498 return SDValue(); 12499 12500 // If the bit convert changed the number of elements, it is unsafe 12501 // to examine the mask. 12502 if (BCNumEltsChanged) 12503 return SDValue(); 12504 12505 // Select the input vector, guarding against out of range extract vector. 12506 unsigned NumElems = VT.getVectorNumElements(); 12507 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12508 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12509 12510 if (InVec.getOpcode() == ISD::BITCAST) { 12511 // Don't duplicate a load with other uses. 12512 if (!InVec.hasOneUse()) 12513 return SDValue(); 12514 12515 InVec = InVec.getOperand(0); 12516 } 12517 if (ISD::isNormalLoad(InVec.getNode())) { 12518 LN0 = cast<LoadSDNode>(InVec); 12519 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12520 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12521 } 12522 } 12523 12524 // Make sure we found a non-volatile load and the extractelement is 12525 // the only use. 12526 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12527 return SDValue(); 12528 12529 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12530 if (Elt == -1) 12531 return DAG.getUNDEF(LVT); 12532 12533 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12534 } 12535 12536 return SDValue(); 12537 } 12538 12539 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12540 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12541 // We perform this optimization post type-legalization because 12542 // the type-legalizer often scalarizes integer-promoted vectors. 12543 // Performing this optimization before may create bit-casts which 12544 // will be type-legalized to complex code sequences. 12545 // We perform this optimization only before the operation legalizer because we 12546 // may introduce illegal operations. 12547 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12548 return SDValue(); 12549 12550 unsigned NumInScalars = N->getNumOperands(); 12551 SDLoc dl(N); 12552 EVT VT = N->getValueType(0); 12553 12554 // Check to see if this is a BUILD_VECTOR of a bunch of values 12555 // which come from any_extend or zero_extend nodes. If so, we can create 12556 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12557 // optimizations. We do not handle sign-extend because we can't fill the sign 12558 // using shuffles. 12559 EVT SourceType = MVT::Other; 12560 bool AllAnyExt = true; 12561 12562 for (unsigned i = 0; i != NumInScalars; ++i) { 12563 SDValue In = N->getOperand(i); 12564 // Ignore undef inputs. 12565 if (In.isUndef()) continue; 12566 12567 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12568 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12569 12570 // Abort if the element is not an extension. 12571 if (!ZeroExt && !AnyExt) { 12572 SourceType = MVT::Other; 12573 break; 12574 } 12575 12576 // The input is a ZeroExt or AnyExt. Check the original type. 12577 EVT InTy = In.getOperand(0).getValueType(); 12578 12579 // Check that all of the widened source types are the same. 12580 if (SourceType == MVT::Other) 12581 // First time. 12582 SourceType = InTy; 12583 else if (InTy != SourceType) { 12584 // Multiple income types. Abort. 12585 SourceType = MVT::Other; 12586 break; 12587 } 12588 12589 // Check if all of the extends are ANY_EXTENDs. 12590 AllAnyExt &= AnyExt; 12591 } 12592 12593 // In order to have valid types, all of the inputs must be extended from the 12594 // same source type and all of the inputs must be any or zero extend. 12595 // Scalar sizes must be a power of two. 12596 EVT OutScalarTy = VT.getScalarType(); 12597 bool ValidTypes = SourceType != MVT::Other && 12598 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12599 isPowerOf2_32(SourceType.getSizeInBits()); 12600 12601 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12602 // turn into a single shuffle instruction. 12603 if (!ValidTypes) 12604 return SDValue(); 12605 12606 bool isLE = DAG.getDataLayout().isLittleEndian(); 12607 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12608 assert(ElemRatio > 1 && "Invalid element size ratio"); 12609 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12610 DAG.getConstant(0, SDLoc(N), SourceType); 12611 12612 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12613 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12614 12615 // Populate the new build_vector 12616 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12617 SDValue Cast = N->getOperand(i); 12618 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12619 Cast.getOpcode() == ISD::ZERO_EXTEND || 12620 Cast.isUndef()) && "Invalid cast opcode"); 12621 SDValue In; 12622 if (Cast.isUndef()) 12623 In = DAG.getUNDEF(SourceType); 12624 else 12625 In = Cast->getOperand(0); 12626 unsigned Index = isLE ? (i * ElemRatio) : 12627 (i * ElemRatio + (ElemRatio - 1)); 12628 12629 assert(Index < Ops.size() && "Invalid index"); 12630 Ops[Index] = In; 12631 } 12632 12633 // The type of the new BUILD_VECTOR node. 12634 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12635 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12636 "Invalid vector size"); 12637 // Check if the new vector type is legal. 12638 if (!isTypeLegal(VecVT)) return SDValue(); 12639 12640 // Make the new BUILD_VECTOR. 12641 SDValue BV = DAG.getBuildVector(VecVT, dl, Ops); 12642 12643 // The new BUILD_VECTOR node has the potential to be further optimized. 12644 AddToWorklist(BV.getNode()); 12645 // Bitcast to the desired type. 12646 return DAG.getBitcast(VT, BV); 12647 } 12648 12649 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12650 EVT VT = N->getValueType(0); 12651 12652 unsigned NumInScalars = N->getNumOperands(); 12653 SDLoc dl(N); 12654 12655 EVT SrcVT = MVT::Other; 12656 unsigned Opcode = ISD::DELETED_NODE; 12657 unsigned NumDefs = 0; 12658 12659 for (unsigned i = 0; i != NumInScalars; ++i) { 12660 SDValue In = N->getOperand(i); 12661 unsigned Opc = In.getOpcode(); 12662 12663 if (Opc == ISD::UNDEF) 12664 continue; 12665 12666 // If all scalar values are floats and converted from integers. 12667 if (Opcode == ISD::DELETED_NODE && 12668 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12669 Opcode = Opc; 12670 } 12671 12672 if (Opc != Opcode) 12673 return SDValue(); 12674 12675 EVT InVT = In.getOperand(0).getValueType(); 12676 12677 // If all scalar values are typed differently, bail out. It's chosen to 12678 // simplify BUILD_VECTOR of integer types. 12679 if (SrcVT == MVT::Other) 12680 SrcVT = InVT; 12681 if (SrcVT != InVT) 12682 return SDValue(); 12683 NumDefs++; 12684 } 12685 12686 // If the vector has just one element defined, it's not worth to fold it into 12687 // a vectorized one. 12688 if (NumDefs < 2) 12689 return SDValue(); 12690 12691 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12692 && "Should only handle conversion from integer to float."); 12693 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12694 12695 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12696 12697 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12698 return SDValue(); 12699 12700 // Just because the floating-point vector type is legal does not necessarily 12701 // mean that the corresponding integer vector type is. 12702 if (!isTypeLegal(NVT)) 12703 return SDValue(); 12704 12705 SmallVector<SDValue, 8> Opnds; 12706 for (unsigned i = 0; i != NumInScalars; ++i) { 12707 SDValue In = N->getOperand(i); 12708 12709 if (In.isUndef()) 12710 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12711 else 12712 Opnds.push_back(In.getOperand(0)); 12713 } 12714 SDValue BV = DAG.getBuildVector(NVT, dl, Opnds); 12715 AddToWorklist(BV.getNode()); 12716 12717 return DAG.getNode(Opcode, dl, VT, BV); 12718 } 12719 12720 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12721 unsigned NumInScalars = N->getNumOperands(); 12722 SDLoc dl(N); 12723 EVT VT = N->getValueType(0); 12724 12725 // A vector built entirely of undefs is undef. 12726 if (ISD::allOperandsUndef(N)) 12727 return DAG.getUNDEF(VT); 12728 12729 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12730 return V; 12731 12732 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12733 return V; 12734 12735 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12736 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12737 // at most two distinct vectors, turn this into a shuffle node. 12738 12739 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12740 if (!isTypeLegal(VT)) 12741 return SDValue(); 12742 12743 // May only combine to shuffle after legalize if shuffle is legal. 12744 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12745 return SDValue(); 12746 12747 SDValue VecIn1, VecIn2; 12748 bool UsesZeroVector = false; 12749 for (unsigned i = 0; i != NumInScalars; ++i) { 12750 SDValue Op = N->getOperand(i); 12751 // Ignore undef inputs. 12752 if (Op.isUndef()) continue; 12753 12754 // See if we can combine this build_vector into a blend with a zero vector. 12755 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12756 UsesZeroVector = true; 12757 continue; 12758 } 12759 12760 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12761 // constant index, bail out. 12762 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12763 !isa<ConstantSDNode>(Op.getOperand(1))) { 12764 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12765 break; 12766 } 12767 12768 // We allow up to two distinct input vectors. 12769 SDValue ExtractedFromVec = Op.getOperand(0); 12770 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12771 continue; 12772 12773 if (!VecIn1.getNode()) { 12774 VecIn1 = ExtractedFromVec; 12775 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12776 VecIn2 = ExtractedFromVec; 12777 } else { 12778 // Too many inputs. 12779 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12780 break; 12781 } 12782 } 12783 12784 // If everything is good, we can make a shuffle operation. 12785 if (VecIn1.getNode()) { 12786 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12787 SmallVector<int, 8> Mask; 12788 for (unsigned i = 0; i != NumInScalars; ++i) { 12789 unsigned Opcode = N->getOperand(i).getOpcode(); 12790 if (Opcode == ISD::UNDEF) { 12791 Mask.push_back(-1); 12792 continue; 12793 } 12794 12795 // Operands can also be zero. 12796 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12797 assert(UsesZeroVector && 12798 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12799 "Unexpected node found!"); 12800 Mask.push_back(NumInScalars+i); 12801 continue; 12802 } 12803 12804 // If extracting from the first vector, just use the index directly. 12805 SDValue Extract = N->getOperand(i); 12806 SDValue ExtVal = Extract.getOperand(1); 12807 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12808 if (Extract.getOperand(0) == VecIn1) { 12809 Mask.push_back(ExtIndex); 12810 continue; 12811 } 12812 12813 // Otherwise, use InIdx + InputVecSize 12814 Mask.push_back(InNumElements + ExtIndex); 12815 } 12816 12817 // Avoid introducing illegal shuffles with zero. 12818 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12819 return SDValue(); 12820 12821 // We can't generate a shuffle node with mismatched input and output types. 12822 // Attempt to transform a single input vector to the correct type. 12823 if ((VT != VecIn1.getValueType())) { 12824 // If the input vector type has a different base type to the output 12825 // vector type, bail out. 12826 EVT VTElemType = VT.getVectorElementType(); 12827 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12828 (VecIn2.getNode() && 12829 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12830 return SDValue(); 12831 12832 // If the input vector is too small, widen it. 12833 // We only support widening of vectors which are half the size of the 12834 // output registers. For example XMM->YMM widening on X86 with AVX. 12835 EVT VecInT = VecIn1.getValueType(); 12836 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12837 // If we only have one small input, widen it by adding undef values. 12838 if (!VecIn2.getNode()) 12839 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12840 DAG.getUNDEF(VecIn1.getValueType())); 12841 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12842 // If we have two small inputs of the same type, try to concat them. 12843 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12844 VecIn2 = SDValue(nullptr, 0); 12845 } else 12846 return SDValue(); 12847 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12848 // If the input vector is too large, try to split it. 12849 // We don't support having two input vectors that are too large. 12850 // If the zero vector was used, we can not split the vector, 12851 // since we'd need 3 inputs. 12852 if (UsesZeroVector || VecIn2.getNode()) 12853 return SDValue(); 12854 12855 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12856 return SDValue(); 12857 12858 // Try to replace VecIn1 with two extract_subvectors 12859 // No need to update the masks, they should still be correct. 12860 VecIn2 = DAG.getNode( 12861 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12862 DAG.getConstant(VT.getVectorNumElements(), dl, 12863 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12864 VecIn1 = DAG.getNode( 12865 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12866 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12867 } else 12868 return SDValue(); 12869 } 12870 12871 if (UsesZeroVector) 12872 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12873 DAG.getConstantFP(0.0, dl, VT); 12874 else 12875 // If VecIn2 is unused then change it to undef. 12876 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12877 12878 // Check that we were able to transform all incoming values to the same 12879 // type. 12880 if (VecIn2.getValueType() != VecIn1.getValueType() || 12881 VecIn1.getValueType() != VT) 12882 return SDValue(); 12883 12884 // Return the new VECTOR_SHUFFLE node. 12885 SDValue Ops[2]; 12886 Ops[0] = VecIn1; 12887 Ops[1] = VecIn2; 12888 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], Mask); 12889 } 12890 12891 return SDValue(); 12892 } 12893 12894 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12895 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12896 EVT OpVT = N->getOperand(0).getValueType(); 12897 12898 // If the operands are legal vectors, leave them alone. 12899 if (TLI.isTypeLegal(OpVT)) 12900 return SDValue(); 12901 12902 SDLoc DL(N); 12903 EVT VT = N->getValueType(0); 12904 SmallVector<SDValue, 8> Ops; 12905 12906 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12907 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12908 12909 // Keep track of what we encounter. 12910 bool AnyInteger = false; 12911 bool AnyFP = false; 12912 for (const SDValue &Op : N->ops()) { 12913 if (ISD::BITCAST == Op.getOpcode() && 12914 !Op.getOperand(0).getValueType().isVector()) 12915 Ops.push_back(Op.getOperand(0)); 12916 else if (ISD::UNDEF == Op.getOpcode()) 12917 Ops.push_back(ScalarUndef); 12918 else 12919 return SDValue(); 12920 12921 // Note whether we encounter an integer or floating point scalar. 12922 // If it's neither, bail out, it could be something weird like x86mmx. 12923 EVT LastOpVT = Ops.back().getValueType(); 12924 if (LastOpVT.isFloatingPoint()) 12925 AnyFP = true; 12926 else if (LastOpVT.isInteger()) 12927 AnyInteger = true; 12928 else 12929 return SDValue(); 12930 } 12931 12932 // If any of the operands is a floating point scalar bitcast to a vector, 12933 // use floating point types throughout, and bitcast everything. 12934 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12935 if (AnyFP) { 12936 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12937 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12938 if (AnyInteger) { 12939 for (SDValue &Op : Ops) { 12940 if (Op.getValueType() == SVT) 12941 continue; 12942 if (Op.isUndef()) 12943 Op = ScalarUndef; 12944 else 12945 Op = DAG.getBitcast(SVT, Op); 12946 } 12947 } 12948 } 12949 12950 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12951 VT.getSizeInBits() / SVT.getSizeInBits()); 12952 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 12953 } 12954 12955 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12956 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12957 // most two distinct vectors the same size as the result, attempt to turn this 12958 // into a legal shuffle. 12959 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12960 EVT VT = N->getValueType(0); 12961 EVT OpVT = N->getOperand(0).getValueType(); 12962 int NumElts = VT.getVectorNumElements(); 12963 int NumOpElts = OpVT.getVectorNumElements(); 12964 12965 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12966 SmallVector<int, 8> Mask; 12967 12968 for (SDValue Op : N->ops()) { 12969 // Peek through any bitcast. 12970 while (Op.getOpcode() == ISD::BITCAST) 12971 Op = Op.getOperand(0); 12972 12973 // UNDEF nodes convert to UNDEF shuffle mask values. 12974 if (Op.isUndef()) { 12975 Mask.append((unsigned)NumOpElts, -1); 12976 continue; 12977 } 12978 12979 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12980 return SDValue(); 12981 12982 // What vector are we extracting the subvector from and at what index? 12983 SDValue ExtVec = Op.getOperand(0); 12984 12985 // We want the EVT of the original extraction to correctly scale the 12986 // extraction index. 12987 EVT ExtVT = ExtVec.getValueType(); 12988 12989 // Peek through any bitcast. 12990 while (ExtVec.getOpcode() == ISD::BITCAST) 12991 ExtVec = ExtVec.getOperand(0); 12992 12993 // UNDEF nodes convert to UNDEF shuffle mask values. 12994 if (ExtVec.isUndef()) { 12995 Mask.append((unsigned)NumOpElts, -1); 12996 continue; 12997 } 12998 12999 if (!isa<ConstantSDNode>(Op.getOperand(1))) 13000 return SDValue(); 13001 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 13002 13003 // Ensure that we are extracting a subvector from a vector the same 13004 // size as the result. 13005 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 13006 return SDValue(); 13007 13008 // Scale the subvector index to account for any bitcast. 13009 int NumExtElts = ExtVT.getVectorNumElements(); 13010 if (0 == (NumExtElts % NumElts)) 13011 ExtIdx /= (NumExtElts / NumElts); 13012 else if (0 == (NumElts % NumExtElts)) 13013 ExtIdx *= (NumElts / NumExtElts); 13014 else 13015 return SDValue(); 13016 13017 // At most we can reference 2 inputs in the final shuffle. 13018 if (SV0.isUndef() || SV0 == ExtVec) { 13019 SV0 = ExtVec; 13020 for (int i = 0; i != NumOpElts; ++i) 13021 Mask.push_back(i + ExtIdx); 13022 } else if (SV1.isUndef() || SV1 == ExtVec) { 13023 SV1 = ExtVec; 13024 for (int i = 0; i != NumOpElts; ++i) 13025 Mask.push_back(i + ExtIdx + NumElts); 13026 } else { 13027 return SDValue(); 13028 } 13029 } 13030 13031 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 13032 return SDValue(); 13033 13034 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 13035 DAG.getBitcast(VT, SV1), Mask); 13036 } 13037 13038 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 13039 // If we only have one input vector, we don't need to do any concatenation. 13040 if (N->getNumOperands() == 1) 13041 return N->getOperand(0); 13042 13043 // Check if all of the operands are undefs. 13044 EVT VT = N->getValueType(0); 13045 if (ISD::allOperandsUndef(N)) 13046 return DAG.getUNDEF(VT); 13047 13048 // Optimize concat_vectors where all but the first of the vectors are undef. 13049 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 13050 return Op.isUndef(); 13051 })) { 13052 SDValue In = N->getOperand(0); 13053 assert(In.getValueType().isVector() && "Must concat vectors"); 13054 13055 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 13056 if (In->getOpcode() == ISD::BITCAST && 13057 !In->getOperand(0)->getValueType(0).isVector()) { 13058 SDValue Scalar = In->getOperand(0); 13059 13060 // If the bitcast type isn't legal, it might be a trunc of a legal type; 13061 // look through the trunc so we can still do the transform: 13062 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 13063 if (Scalar->getOpcode() == ISD::TRUNCATE && 13064 !TLI.isTypeLegal(Scalar.getValueType()) && 13065 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 13066 Scalar = Scalar->getOperand(0); 13067 13068 EVT SclTy = Scalar->getValueType(0); 13069 13070 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 13071 return SDValue(); 13072 13073 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 13074 VT.getSizeInBits() / SclTy.getSizeInBits()); 13075 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 13076 return SDValue(); 13077 13078 SDLoc dl = SDLoc(N); 13079 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 13080 return DAG.getBitcast(VT, Res); 13081 } 13082 } 13083 13084 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 13085 // We have already tested above for an UNDEF only concatenation. 13086 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 13087 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 13088 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 13089 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 13090 }; 13091 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 13092 SmallVector<SDValue, 8> Opnds; 13093 EVT SVT = VT.getScalarType(); 13094 13095 EVT MinVT = SVT; 13096 if (!SVT.isFloatingPoint()) { 13097 // If BUILD_VECTOR are from built from integer, they may have different 13098 // operand types. Get the smallest type and truncate all operands to it. 13099 bool FoundMinVT = false; 13100 for (const SDValue &Op : N->ops()) 13101 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13102 EVT OpSVT = Op.getOperand(0)->getValueType(0); 13103 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 13104 FoundMinVT = true; 13105 } 13106 assert(FoundMinVT && "Concat vector type mismatch"); 13107 } 13108 13109 for (const SDValue &Op : N->ops()) { 13110 EVT OpVT = Op.getValueType(); 13111 unsigned NumElts = OpVT.getVectorNumElements(); 13112 13113 if (ISD::UNDEF == Op.getOpcode()) 13114 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 13115 13116 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13117 if (SVT.isFloatingPoint()) { 13118 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 13119 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 13120 } else { 13121 for (unsigned i = 0; i != NumElts; ++i) 13122 Opnds.push_back( 13123 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 13124 } 13125 } 13126 } 13127 13128 assert(VT.getVectorNumElements() == Opnds.size() && 13129 "Concat vector type mismatch"); 13130 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 13131 } 13132 13133 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 13134 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 13135 return V; 13136 13137 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 13138 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 13139 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 13140 return V; 13141 13142 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 13143 // nodes often generate nop CONCAT_VECTOR nodes. 13144 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 13145 // place the incoming vectors at the exact same location. 13146 SDValue SingleSource = SDValue(); 13147 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 13148 13149 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13150 SDValue Op = N->getOperand(i); 13151 13152 if (Op.isUndef()) 13153 continue; 13154 13155 // Check if this is the identity extract: 13156 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13157 return SDValue(); 13158 13159 // Find the single incoming vector for the extract_subvector. 13160 if (SingleSource.getNode()) { 13161 if (Op.getOperand(0) != SingleSource) 13162 return SDValue(); 13163 } else { 13164 SingleSource = Op.getOperand(0); 13165 13166 // Check the source type is the same as the type of the result. 13167 // If not, this concat may extend the vector, so we can not 13168 // optimize it away. 13169 if (SingleSource.getValueType() != N->getValueType(0)) 13170 return SDValue(); 13171 } 13172 13173 unsigned IdentityIndex = i * PartNumElem; 13174 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13175 // The extract index must be constant. 13176 if (!CS) 13177 return SDValue(); 13178 13179 // Check that we are reading from the identity index. 13180 if (CS->getZExtValue() != IdentityIndex) 13181 return SDValue(); 13182 } 13183 13184 if (SingleSource.getNode()) 13185 return SingleSource; 13186 13187 return SDValue(); 13188 } 13189 13190 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 13191 EVT NVT = N->getValueType(0); 13192 SDValue V = N->getOperand(0); 13193 13194 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 13195 // Combine: 13196 // (extract_subvec (concat V1, V2, ...), i) 13197 // Into: 13198 // Vi if possible 13199 // Only operand 0 is checked as 'concat' assumes all inputs of the same 13200 // type. 13201 if (V->getOperand(0).getValueType() != NVT) 13202 return SDValue(); 13203 unsigned Idx = N->getConstantOperandVal(1); 13204 unsigned NumElems = NVT.getVectorNumElements(); 13205 assert((Idx % NumElems) == 0 && 13206 "IDX in concat is not a multiple of the result vector length."); 13207 return V->getOperand(Idx / NumElems); 13208 } 13209 13210 // Skip bitcasting 13211 if (V->getOpcode() == ISD::BITCAST) 13212 V = V.getOperand(0); 13213 13214 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13215 SDLoc dl(N); 13216 // Handle only simple case where vector being inserted and vector 13217 // being extracted are of same type, and are half size of larger vectors. 13218 EVT BigVT = V->getOperand(0).getValueType(); 13219 EVT SmallVT = V->getOperand(1).getValueType(); 13220 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 13221 return SDValue(); 13222 13223 // Only handle cases where both indexes are constants with the same type. 13224 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13225 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13226 13227 if (InsIdx && ExtIdx && 13228 InsIdx->getValueType(0).getSizeInBits() <= 64 && 13229 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 13230 // Combine: 13231 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 13232 // Into: 13233 // indices are equal or bit offsets are equal => V1 13234 // otherwise => (extract_subvec V1, ExtIdx) 13235 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 13236 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 13237 return DAG.getBitcast(NVT, V->getOperand(1)); 13238 return DAG.getNode( 13239 ISD::EXTRACT_SUBVECTOR, dl, NVT, 13240 DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)), 13241 N->getOperand(1)); 13242 } 13243 } 13244 13245 return SDValue(); 13246 } 13247 13248 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 13249 SDValue V, SelectionDAG &DAG) { 13250 SDLoc DL(V); 13251 EVT VT = V.getValueType(); 13252 13253 switch (V.getOpcode()) { 13254 default: 13255 return V; 13256 13257 case ISD::CONCAT_VECTORS: { 13258 EVT OpVT = V->getOperand(0).getValueType(); 13259 int OpSize = OpVT.getVectorNumElements(); 13260 SmallBitVector OpUsedElements(OpSize, false); 13261 bool FoundSimplification = false; 13262 SmallVector<SDValue, 4> NewOps; 13263 NewOps.reserve(V->getNumOperands()); 13264 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 13265 SDValue Op = V->getOperand(i); 13266 bool OpUsed = false; 13267 for (int j = 0; j < OpSize; ++j) 13268 if (UsedElements[i * OpSize + j]) { 13269 OpUsedElements[j] = true; 13270 OpUsed = true; 13271 } 13272 NewOps.push_back( 13273 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13274 : DAG.getUNDEF(OpVT)); 13275 FoundSimplification |= Op == NewOps.back(); 13276 OpUsedElements.reset(); 13277 } 13278 if (FoundSimplification) 13279 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13280 return V; 13281 } 13282 13283 case ISD::INSERT_SUBVECTOR: { 13284 SDValue BaseV = V->getOperand(0); 13285 SDValue SubV = V->getOperand(1); 13286 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13287 if (!IdxN) 13288 return V; 13289 13290 int SubSize = SubV.getValueType().getVectorNumElements(); 13291 int Idx = IdxN->getZExtValue(); 13292 bool SubVectorUsed = false; 13293 SmallBitVector SubUsedElements(SubSize, false); 13294 for (int i = 0; i < SubSize; ++i) 13295 if (UsedElements[i + Idx]) { 13296 SubVectorUsed = true; 13297 SubUsedElements[i] = true; 13298 UsedElements[i + Idx] = false; 13299 } 13300 13301 // Now recurse on both the base and sub vectors. 13302 SDValue SimplifiedSubV = 13303 SubVectorUsed 13304 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13305 : DAG.getUNDEF(SubV.getValueType()); 13306 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13307 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13308 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13309 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13310 return V; 13311 } 13312 } 13313 } 13314 13315 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13316 SDValue N1, SelectionDAG &DAG) { 13317 EVT VT = SVN->getValueType(0); 13318 int NumElts = VT.getVectorNumElements(); 13319 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13320 for (int M : SVN->getMask()) 13321 if (M >= 0 && M < NumElts) 13322 N0UsedElements[M] = true; 13323 else if (M >= NumElts) 13324 N1UsedElements[M - NumElts] = true; 13325 13326 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13327 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13328 if (S0 == N0 && S1 == N1) 13329 return SDValue(); 13330 13331 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13332 } 13333 13334 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13335 // or turn a shuffle of a single concat into simpler shuffle then concat. 13336 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13337 EVT VT = N->getValueType(0); 13338 unsigned NumElts = VT.getVectorNumElements(); 13339 13340 SDValue N0 = N->getOperand(0); 13341 SDValue N1 = N->getOperand(1); 13342 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13343 13344 SmallVector<SDValue, 4> Ops; 13345 EVT ConcatVT = N0.getOperand(0).getValueType(); 13346 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13347 unsigned NumConcats = NumElts / NumElemsPerConcat; 13348 13349 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13350 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13351 // half vector elements. 13352 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 13353 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13354 SVN->getMask().end(), [](int i) { return i == -1; })) { 13355 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13356 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13357 N1 = DAG.getUNDEF(ConcatVT); 13358 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13359 } 13360 13361 // Look at every vector that's inserted. We're looking for exact 13362 // subvector-sized copies from a concatenated vector 13363 for (unsigned I = 0; I != NumConcats; ++I) { 13364 // Make sure we're dealing with a copy. 13365 unsigned Begin = I * NumElemsPerConcat; 13366 bool AllUndef = true, NoUndef = true; 13367 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13368 if (SVN->getMaskElt(J) >= 0) 13369 AllUndef = false; 13370 else 13371 NoUndef = false; 13372 } 13373 13374 if (NoUndef) { 13375 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13376 return SDValue(); 13377 13378 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13379 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13380 return SDValue(); 13381 13382 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13383 if (FirstElt < N0.getNumOperands()) 13384 Ops.push_back(N0.getOperand(FirstElt)); 13385 else 13386 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13387 13388 } else if (AllUndef) { 13389 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13390 } else { // Mixed with general masks and undefs, can't do optimization. 13391 return SDValue(); 13392 } 13393 } 13394 13395 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13396 } 13397 13398 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13399 EVT VT = N->getValueType(0); 13400 unsigned NumElts = VT.getVectorNumElements(); 13401 13402 SDValue N0 = N->getOperand(0); 13403 SDValue N1 = N->getOperand(1); 13404 13405 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13406 13407 // Canonicalize shuffle undef, undef -> undef 13408 if (N0.isUndef() && N1.isUndef()) 13409 return DAG.getUNDEF(VT); 13410 13411 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13412 13413 // Canonicalize shuffle v, v -> v, undef 13414 if (N0 == N1) { 13415 SmallVector<int, 8> NewMask; 13416 for (unsigned i = 0; i != NumElts; ++i) { 13417 int Idx = SVN->getMaskElt(i); 13418 if (Idx >= (int)NumElts) Idx -= NumElts; 13419 NewMask.push_back(Idx); 13420 } 13421 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 13422 } 13423 13424 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13425 if (N0.isUndef()) 13426 return DAG.getCommutedVectorShuffle(*SVN); 13427 13428 // Remove references to rhs if it is undef 13429 if (N1.isUndef()) { 13430 bool Changed = false; 13431 SmallVector<int, 8> NewMask; 13432 for (unsigned i = 0; i != NumElts; ++i) { 13433 int Idx = SVN->getMaskElt(i); 13434 if (Idx >= (int)NumElts) { 13435 Idx = -1; 13436 Changed = true; 13437 } 13438 NewMask.push_back(Idx); 13439 } 13440 if (Changed) 13441 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 13442 } 13443 13444 // If it is a splat, check if the argument vector is another splat or a 13445 // build_vector. 13446 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13447 SDNode *V = N0.getNode(); 13448 13449 // If this is a bit convert that changes the element type of the vector but 13450 // not the number of vector elements, look through it. Be careful not to 13451 // look though conversions that change things like v4f32 to v2f64. 13452 if (V->getOpcode() == ISD::BITCAST) { 13453 SDValue ConvInput = V->getOperand(0); 13454 if (ConvInput.getValueType().isVector() && 13455 ConvInput.getValueType().getVectorNumElements() == NumElts) 13456 V = ConvInput.getNode(); 13457 } 13458 13459 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13460 assert(V->getNumOperands() == NumElts && 13461 "BUILD_VECTOR has wrong number of operands"); 13462 SDValue Base; 13463 bool AllSame = true; 13464 for (unsigned i = 0; i != NumElts; ++i) { 13465 if (!V->getOperand(i).isUndef()) { 13466 Base = V->getOperand(i); 13467 break; 13468 } 13469 } 13470 // Splat of <u, u, u, u>, return <u, u, u, u> 13471 if (!Base.getNode()) 13472 return N0; 13473 for (unsigned i = 0; i != NumElts; ++i) { 13474 if (V->getOperand(i) != Base) { 13475 AllSame = false; 13476 break; 13477 } 13478 } 13479 // Splat of <x, x, x, x>, return <x, x, x, x> 13480 if (AllSame) 13481 return N0; 13482 13483 // Canonicalize any other splat as a build_vector. 13484 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13485 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13486 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 13487 13488 // We may have jumped through bitcasts, so the type of the 13489 // BUILD_VECTOR may not match the type of the shuffle. 13490 if (V->getValueType(0) != VT) 13491 NewBV = DAG.getBitcast(VT, NewBV); 13492 return NewBV; 13493 } 13494 } 13495 13496 // There are various patterns used to build up a vector from smaller vectors, 13497 // subvectors, or elements. Scan chains of these and replace unused insertions 13498 // or components with undef. 13499 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13500 return S; 13501 13502 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13503 Level < AfterLegalizeVectorOps && 13504 (N1.isUndef() || 13505 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13506 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13507 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 13508 return V; 13509 } 13510 13511 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13512 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13513 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13514 SmallVector<SDValue, 8> Ops; 13515 for (int M : SVN->getMask()) { 13516 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13517 if (M >= 0) { 13518 int Idx = M % NumElts; 13519 SDValue &S = (M < (int)NumElts ? N0 : N1); 13520 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13521 Op = S.getOperand(Idx); 13522 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13523 if (Idx == 0) 13524 Op = S.getOperand(0); 13525 } else { 13526 // Operand can't be combined - bail out. 13527 break; 13528 } 13529 } 13530 Ops.push_back(Op); 13531 } 13532 if (Ops.size() == VT.getVectorNumElements()) { 13533 // BUILD_VECTOR requires all inputs to be of the same type, find the 13534 // maximum type and extend them all. 13535 EVT SVT = VT.getScalarType(); 13536 if (SVT.isInteger()) 13537 for (SDValue &Op : Ops) 13538 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13539 if (SVT != VT.getScalarType()) 13540 for (SDValue &Op : Ops) 13541 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13542 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13543 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13544 return DAG.getBuildVector(VT, SDLoc(N), Ops); 13545 } 13546 } 13547 13548 // If this shuffle only has a single input that is a bitcasted shuffle, 13549 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13550 // back to their original types. 13551 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13552 N1.isUndef() && Level < AfterLegalizeVectorOps && 13553 TLI.isTypeLegal(VT)) { 13554 13555 // Peek through the bitcast only if there is one user. 13556 SDValue BC0 = N0; 13557 while (BC0.getOpcode() == ISD::BITCAST) { 13558 if (!BC0.hasOneUse()) 13559 break; 13560 BC0 = BC0.getOperand(0); 13561 } 13562 13563 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13564 if (Scale == 1) 13565 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13566 13567 SmallVector<int, 8> NewMask; 13568 for (int M : Mask) 13569 for (int s = 0; s != Scale; ++s) 13570 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13571 return NewMask; 13572 }; 13573 13574 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13575 EVT SVT = VT.getScalarType(); 13576 EVT InnerVT = BC0->getValueType(0); 13577 EVT InnerSVT = InnerVT.getScalarType(); 13578 13579 // Determine which shuffle works with the smaller scalar type. 13580 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13581 EVT ScaleSVT = ScaleVT.getScalarType(); 13582 13583 if (TLI.isTypeLegal(ScaleVT) && 13584 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13585 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13586 13587 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13588 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13589 13590 // Scale the shuffle masks to the smaller scalar type. 13591 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13592 SmallVector<int, 8> InnerMask = 13593 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13594 SmallVector<int, 8> OuterMask = 13595 ScaleShuffleMask(SVN->getMask(), OuterScale); 13596 13597 // Merge the shuffle masks. 13598 SmallVector<int, 8> NewMask; 13599 for (int M : OuterMask) 13600 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13601 13602 // Test for shuffle mask legality over both commutations. 13603 SDValue SV0 = BC0->getOperand(0); 13604 SDValue SV1 = BC0->getOperand(1); 13605 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13606 if (!LegalMask) { 13607 std::swap(SV0, SV1); 13608 ShuffleVectorSDNode::commuteMask(NewMask); 13609 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13610 } 13611 13612 if (LegalMask) { 13613 SV0 = DAG.getBitcast(ScaleVT, SV0); 13614 SV1 = DAG.getBitcast(ScaleVT, SV1); 13615 return DAG.getBitcast( 13616 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13617 } 13618 } 13619 } 13620 } 13621 13622 // Canonicalize shuffles according to rules: 13623 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13624 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13625 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13626 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13627 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13628 TLI.isTypeLegal(VT)) { 13629 // The incoming shuffle must be of the same type as the result of the 13630 // current shuffle. 13631 assert(N1->getOperand(0).getValueType() == VT && 13632 "Shuffle types don't match"); 13633 13634 SDValue SV0 = N1->getOperand(0); 13635 SDValue SV1 = N1->getOperand(1); 13636 bool HasSameOp0 = N0 == SV0; 13637 bool IsSV1Undef = SV1.isUndef(); 13638 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13639 // Commute the operands of this shuffle so that next rule 13640 // will trigger. 13641 return DAG.getCommutedVectorShuffle(*SVN); 13642 } 13643 13644 // Try to fold according to rules: 13645 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13646 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13647 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13648 // Don't try to fold shuffles with illegal type. 13649 // Only fold if this shuffle is the only user of the other shuffle. 13650 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13651 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13652 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13653 13654 // The incoming shuffle must be of the same type as the result of the 13655 // current shuffle. 13656 assert(OtherSV->getOperand(0).getValueType() == VT && 13657 "Shuffle types don't match"); 13658 13659 SDValue SV0, SV1; 13660 SmallVector<int, 4> Mask; 13661 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13662 // operand, and SV1 as the second operand. 13663 for (unsigned i = 0; i != NumElts; ++i) { 13664 int Idx = SVN->getMaskElt(i); 13665 if (Idx < 0) { 13666 // Propagate Undef. 13667 Mask.push_back(Idx); 13668 continue; 13669 } 13670 13671 SDValue CurrentVec; 13672 if (Idx < (int)NumElts) { 13673 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13674 // shuffle mask to identify which vector is actually referenced. 13675 Idx = OtherSV->getMaskElt(Idx); 13676 if (Idx < 0) { 13677 // Propagate Undef. 13678 Mask.push_back(Idx); 13679 continue; 13680 } 13681 13682 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13683 : OtherSV->getOperand(1); 13684 } else { 13685 // This shuffle index references an element within N1. 13686 CurrentVec = N1; 13687 } 13688 13689 // Simple case where 'CurrentVec' is UNDEF. 13690 if (CurrentVec.isUndef()) { 13691 Mask.push_back(-1); 13692 continue; 13693 } 13694 13695 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13696 // will be the first or second operand of the combined shuffle. 13697 Idx = Idx % NumElts; 13698 if (!SV0.getNode() || SV0 == CurrentVec) { 13699 // Ok. CurrentVec is the left hand side. 13700 // Update the mask accordingly. 13701 SV0 = CurrentVec; 13702 Mask.push_back(Idx); 13703 continue; 13704 } 13705 13706 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13707 if (SV1.getNode() && SV1 != CurrentVec) 13708 return SDValue(); 13709 13710 // Ok. CurrentVec is the right hand side. 13711 // Update the mask accordingly. 13712 SV1 = CurrentVec; 13713 Mask.push_back(Idx + NumElts); 13714 } 13715 13716 // Check if all indices in Mask are Undef. In case, propagate Undef. 13717 bool isUndefMask = true; 13718 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13719 isUndefMask &= Mask[i] < 0; 13720 13721 if (isUndefMask) 13722 return DAG.getUNDEF(VT); 13723 13724 if (!SV0.getNode()) 13725 SV0 = DAG.getUNDEF(VT); 13726 if (!SV1.getNode()) 13727 SV1 = DAG.getUNDEF(VT); 13728 13729 // Avoid introducing shuffles with illegal mask. 13730 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13731 ShuffleVectorSDNode::commuteMask(Mask); 13732 13733 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13734 return SDValue(); 13735 13736 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13737 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13738 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13739 std::swap(SV0, SV1); 13740 } 13741 13742 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13743 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13744 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13745 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 13746 } 13747 13748 return SDValue(); 13749 } 13750 13751 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13752 SDValue InVal = N->getOperand(0); 13753 EVT VT = N->getValueType(0); 13754 13755 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13756 // with a VECTOR_SHUFFLE. 13757 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13758 SDValue InVec = InVal->getOperand(0); 13759 SDValue EltNo = InVal->getOperand(1); 13760 13761 // FIXME: We could support implicit truncation if the shuffle can be 13762 // scaled to a smaller vector scalar type. 13763 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13764 if (C0 && VT == InVec.getValueType() && 13765 VT.getScalarType() == InVal.getValueType()) { 13766 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13767 int Elt = C0->getZExtValue(); 13768 NewMask[0] = Elt; 13769 13770 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13771 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13772 NewMask); 13773 } 13774 } 13775 13776 return SDValue(); 13777 } 13778 13779 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13780 SDValue N0 = N->getOperand(0); 13781 SDValue N1 = N->getOperand(1); 13782 SDValue N2 = N->getOperand(2); 13783 13784 if (N0.getValueType() != N1.getValueType()) 13785 return SDValue(); 13786 13787 // If the input vector is a concatenation, and the insert replaces 13788 // one of the halves, we can optimize into a single concat_vectors. 13789 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0->getNumOperands() == 2 && 13790 N2.getOpcode() == ISD::Constant) { 13791 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13792 EVT VT = N->getValueType(0); 13793 13794 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13795 // (concat_vectors Z, Y) 13796 if (InsIdx == 0) 13797 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N1, 13798 N0.getOperand(1)); 13799 13800 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13801 // (concat_vectors X, Z) 13802 if (InsIdx == VT.getVectorNumElements() / 2) 13803 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0.getOperand(0), 13804 N1); 13805 } 13806 13807 return SDValue(); 13808 } 13809 13810 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13811 SDValue N0 = N->getOperand(0); 13812 13813 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13814 if (N0->getOpcode() == ISD::FP16_TO_FP) 13815 return N0->getOperand(0); 13816 13817 return SDValue(); 13818 } 13819 13820 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13821 SDValue N0 = N->getOperand(0); 13822 13823 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13824 if (N0->getOpcode() == ISD::AND) { 13825 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13826 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13827 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13828 N0.getOperand(0)); 13829 } 13830 } 13831 13832 return SDValue(); 13833 } 13834 13835 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13836 /// with the destination vector and a zero vector. 13837 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13838 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13839 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13840 EVT VT = N->getValueType(0); 13841 SDValue LHS = N->getOperand(0); 13842 SDValue RHS = N->getOperand(1); 13843 SDLoc dl(N); 13844 13845 // Make sure we're not running after operation legalization where it 13846 // may have custom lowered the vector shuffles. 13847 if (LegalOperations) 13848 return SDValue(); 13849 13850 if (N->getOpcode() != ISD::AND) 13851 return SDValue(); 13852 13853 if (RHS.getOpcode() == ISD::BITCAST) 13854 RHS = RHS.getOperand(0); 13855 13856 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13857 return SDValue(); 13858 13859 EVT RVT = RHS.getValueType(); 13860 unsigned NumElts = RHS.getNumOperands(); 13861 13862 // Attempt to create a valid clear mask, splitting the mask into 13863 // sub elements and checking to see if each is 13864 // all zeros or all ones - suitable for shuffle masking. 13865 auto BuildClearMask = [&](int Split) { 13866 int NumSubElts = NumElts * Split; 13867 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13868 13869 SmallVector<int, 8> Indices; 13870 for (int i = 0; i != NumSubElts; ++i) { 13871 int EltIdx = i / Split; 13872 int SubIdx = i % Split; 13873 SDValue Elt = RHS.getOperand(EltIdx); 13874 if (Elt.isUndef()) { 13875 Indices.push_back(-1); 13876 continue; 13877 } 13878 13879 APInt Bits; 13880 if (isa<ConstantSDNode>(Elt)) 13881 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13882 else if (isa<ConstantFPSDNode>(Elt)) 13883 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13884 else 13885 return SDValue(); 13886 13887 // Extract the sub element from the constant bit mask. 13888 if (DAG.getDataLayout().isBigEndian()) { 13889 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13890 } else { 13891 Bits = Bits.lshr(SubIdx * NumSubBits); 13892 } 13893 13894 if (Split > 1) 13895 Bits = Bits.trunc(NumSubBits); 13896 13897 if (Bits.isAllOnesValue()) 13898 Indices.push_back(i); 13899 else if (Bits == 0) 13900 Indices.push_back(i + NumSubElts); 13901 else 13902 return SDValue(); 13903 } 13904 13905 // Let's see if the target supports this vector_shuffle. 13906 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13907 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13908 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13909 return SDValue(); 13910 13911 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13912 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13913 DAG.getBitcast(ClearVT, LHS), 13914 Zero, Indices)); 13915 }; 13916 13917 // Determine maximum split level (byte level masking). 13918 int MaxSplit = 1; 13919 if (RVT.getScalarSizeInBits() % 8 == 0) 13920 MaxSplit = RVT.getScalarSizeInBits() / 8; 13921 13922 for (int Split = 1; Split <= MaxSplit; ++Split) 13923 if (RVT.getScalarSizeInBits() % Split == 0) 13924 if (SDValue S = BuildClearMask(Split)) 13925 return S; 13926 13927 return SDValue(); 13928 } 13929 13930 /// Visit a binary vector operation, like ADD. 13931 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13932 assert(N->getValueType(0).isVector() && 13933 "SimplifyVBinOp only works on vectors!"); 13934 13935 SDValue LHS = N->getOperand(0); 13936 SDValue RHS = N->getOperand(1); 13937 SDValue Ops[] = {LHS, RHS}; 13938 13939 // See if we can constant fold the vector operation. 13940 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 13941 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 13942 return Fold; 13943 13944 // Try to convert a constant mask AND into a shuffle clear mask. 13945 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13946 return Shuffle; 13947 13948 // Type legalization might introduce new shuffles in the DAG. 13949 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13950 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13951 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13952 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13953 LHS.getOperand(1).isUndef() && 13954 RHS.getOperand(1).isUndef()) { 13955 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13956 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13957 13958 if (SVN0->getMask().equals(SVN1->getMask())) { 13959 EVT VT = N->getValueType(0); 13960 SDValue UndefVector = LHS.getOperand(1); 13961 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13962 LHS.getOperand(0), RHS.getOperand(0), 13963 N->getFlags()); 13964 AddUsersToWorklist(N); 13965 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13966 SVN0->getMask()); 13967 } 13968 } 13969 13970 return SDValue(); 13971 } 13972 13973 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 13974 SDValue N2) { 13975 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13976 13977 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13978 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13979 13980 // If we got a simplified select_cc node back from SimplifySelectCC, then 13981 // break it down into a new SETCC node, and a new SELECT node, and then return 13982 // the SELECT node, since we were called with a SELECT node. 13983 if (SCC.getNode()) { 13984 // Check to see if we got a select_cc back (to turn into setcc/select). 13985 // Otherwise, just return whatever node we got back, like fabs. 13986 if (SCC.getOpcode() == ISD::SELECT_CC) { 13987 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13988 N0.getValueType(), 13989 SCC.getOperand(0), SCC.getOperand(1), 13990 SCC.getOperand(4)); 13991 AddToWorklist(SETCC.getNode()); 13992 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13993 SCC.getOperand(2), SCC.getOperand(3)); 13994 } 13995 13996 return SCC; 13997 } 13998 return SDValue(); 13999 } 14000 14001 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 14002 /// being selected between, see if we can simplify the select. Callers of this 14003 /// should assume that TheSelect is deleted if this returns true. As such, they 14004 /// should return the appropriate thing (e.g. the node) back to the top-level of 14005 /// the DAG combiner loop to avoid it being looked at. 14006 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 14007 SDValue RHS) { 14008 14009 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14010 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 14011 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 14012 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 14013 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 14014 SDValue Sqrt = RHS; 14015 ISD::CondCode CC; 14016 SDValue CmpLHS; 14017 const ConstantFPSDNode *Zero = nullptr; 14018 14019 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 14020 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 14021 CmpLHS = TheSelect->getOperand(0); 14022 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 14023 } else { 14024 // SELECT or VSELECT 14025 SDValue Cmp = TheSelect->getOperand(0); 14026 if (Cmp.getOpcode() == ISD::SETCC) { 14027 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 14028 CmpLHS = Cmp.getOperand(0); 14029 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 14030 } 14031 } 14032 if (Zero && Zero->isZero() && 14033 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 14034 CC == ISD::SETULT || CC == ISD::SETLT)) { 14035 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14036 CombineTo(TheSelect, Sqrt); 14037 return true; 14038 } 14039 } 14040 } 14041 // Cannot simplify select with vector condition 14042 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 14043 14044 // If this is a select from two identical things, try to pull the operation 14045 // through the select. 14046 if (LHS.getOpcode() != RHS.getOpcode() || 14047 !LHS.hasOneUse() || !RHS.hasOneUse()) 14048 return false; 14049 14050 // If this is a load and the token chain is identical, replace the select 14051 // of two loads with a load through a select of the address to load from. 14052 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 14053 // constants have been dropped into the constant pool. 14054 if (LHS.getOpcode() == ISD::LOAD) { 14055 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 14056 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 14057 14058 // Token chains must be identical. 14059 if (LHS.getOperand(0) != RHS.getOperand(0) || 14060 // Do not let this transformation reduce the number of volatile loads. 14061 LLD->isVolatile() || RLD->isVolatile() || 14062 // FIXME: If either is a pre/post inc/dec load, 14063 // we'd need to split out the address adjustment. 14064 LLD->isIndexed() || RLD->isIndexed() || 14065 // If this is an EXTLOAD, the VT's must match. 14066 LLD->getMemoryVT() != RLD->getMemoryVT() || 14067 // If this is an EXTLOAD, the kind of extension must match. 14068 (LLD->getExtensionType() != RLD->getExtensionType() && 14069 // The only exception is if one of the extensions is anyext. 14070 LLD->getExtensionType() != ISD::EXTLOAD && 14071 RLD->getExtensionType() != ISD::EXTLOAD) || 14072 // FIXME: this discards src value information. This is 14073 // over-conservative. It would be beneficial to be able to remember 14074 // both potential memory locations. Since we are discarding 14075 // src value info, don't do the transformation if the memory 14076 // locations are not in the default address space. 14077 LLD->getPointerInfo().getAddrSpace() != 0 || 14078 RLD->getPointerInfo().getAddrSpace() != 0 || 14079 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 14080 LLD->getBasePtr().getValueType())) 14081 return false; 14082 14083 // Check that the select condition doesn't reach either load. If so, 14084 // folding this will induce a cycle into the DAG. If not, this is safe to 14085 // xform, so create a select of the addresses. 14086 SDValue Addr; 14087 if (TheSelect->getOpcode() == ISD::SELECT) { 14088 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 14089 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 14090 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 14091 return false; 14092 // The loads must not depend on one another. 14093 if (LLD->isPredecessorOf(RLD) || 14094 RLD->isPredecessorOf(LLD)) 14095 return false; 14096 Addr = DAG.getSelect(SDLoc(TheSelect), 14097 LLD->getBasePtr().getValueType(), 14098 TheSelect->getOperand(0), LLD->getBasePtr(), 14099 RLD->getBasePtr()); 14100 } else { // Otherwise SELECT_CC 14101 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 14102 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 14103 14104 if ((LLD->hasAnyUseOfValue(1) && 14105 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 14106 (RLD->hasAnyUseOfValue(1) && 14107 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 14108 return false; 14109 14110 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 14111 LLD->getBasePtr().getValueType(), 14112 TheSelect->getOperand(0), 14113 TheSelect->getOperand(1), 14114 LLD->getBasePtr(), RLD->getBasePtr(), 14115 TheSelect->getOperand(4)); 14116 } 14117 14118 SDValue Load; 14119 // It is safe to replace the two loads if they have different alignments, 14120 // but the new load must be the minimum (most restrictive) alignment of the 14121 // inputs. 14122 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 14123 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 14124 if (!RLD->isInvariant()) 14125 MMOFlags &= ~MachineMemOperand::MOInvariant; 14126 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 14127 // FIXME: Discards pointer and AA info. 14128 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 14129 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 14130 MMOFlags); 14131 } else { 14132 // FIXME: Discards pointer and AA info. 14133 Load = DAG.getExtLoad( 14134 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 14135 : LLD->getExtensionType(), 14136 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 14137 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 14138 } 14139 14140 // Users of the select now use the result of the load. 14141 CombineTo(TheSelect, Load); 14142 14143 // Users of the old loads now use the new load's chain. We know the 14144 // old-load value is dead now. 14145 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 14146 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 14147 return true; 14148 } 14149 14150 return false; 14151 } 14152 14153 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 14154 /// where 'cond' is the comparison specified by CC. 14155 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 14156 SDValue N2, SDValue N3, ISD::CondCode CC, 14157 bool NotExtCompare) { 14158 // (x ? y : y) -> y. 14159 if (N2 == N3) return N2; 14160 14161 EVT VT = N2.getValueType(); 14162 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 14163 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 14164 14165 // Determine if the condition we're dealing with is constant 14166 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 14167 N0, N1, CC, DL, false); 14168 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 14169 14170 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 14171 // fold select_cc true, x, y -> x 14172 // fold select_cc false, x, y -> y 14173 return !SCCC->isNullValue() ? N2 : N3; 14174 } 14175 14176 // Check to see if we can simplify the select into an fabs node 14177 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 14178 // Allow either -0.0 or 0.0 14179 if (CFP->isZero()) { 14180 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 14181 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 14182 N0 == N2 && N3.getOpcode() == ISD::FNEG && 14183 N2 == N3.getOperand(0)) 14184 return DAG.getNode(ISD::FABS, DL, VT, N0); 14185 14186 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 14187 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 14188 N0 == N3 && N2.getOpcode() == ISD::FNEG && 14189 N2.getOperand(0) == N3) 14190 return DAG.getNode(ISD::FABS, DL, VT, N3); 14191 } 14192 } 14193 14194 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 14195 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 14196 // in it. This is a win when the constant is not otherwise available because 14197 // it replaces two constant pool loads with one. We only do this if the FP 14198 // type is known to be legal, because if it isn't, then we are before legalize 14199 // types an we want the other legalization to happen first (e.g. to avoid 14200 // messing with soft float) and if the ConstantFP is not legal, because if 14201 // it is legal, we may not need to store the FP constant in a constant pool. 14202 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 14203 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 14204 if (TLI.isTypeLegal(N2.getValueType()) && 14205 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 14206 TargetLowering::Legal && 14207 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 14208 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 14209 // If both constants have multiple uses, then we won't need to do an 14210 // extra load, they are likely around in registers for other users. 14211 (TV->hasOneUse() || FV->hasOneUse())) { 14212 Constant *Elts[] = { 14213 const_cast<ConstantFP*>(FV->getConstantFPValue()), 14214 const_cast<ConstantFP*>(TV->getConstantFPValue()) 14215 }; 14216 Type *FPTy = Elts[0]->getType(); 14217 const DataLayout &TD = DAG.getDataLayout(); 14218 14219 // Create a ConstantArray of the two constants. 14220 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 14221 SDValue CPIdx = 14222 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 14223 TD.getPrefTypeAlignment(FPTy)); 14224 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 14225 14226 // Get the offsets to the 0 and 1 element of the array so that we can 14227 // select between them. 14228 SDValue Zero = DAG.getIntPtrConstant(0, DL); 14229 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 14230 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 14231 14232 SDValue Cond = DAG.getSetCC(DL, 14233 getSetCCResultType(N0.getValueType()), 14234 N0, N1, CC); 14235 AddToWorklist(Cond.getNode()); 14236 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 14237 Cond, One, Zero); 14238 AddToWorklist(CstOffset.getNode()); 14239 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 14240 CstOffset); 14241 AddToWorklist(CPIdx.getNode()); 14242 return DAG.getLoad( 14243 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 14244 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 14245 Alignment); 14246 } 14247 } 14248 14249 // Check to see if we can perform the "gzip trick", transforming 14250 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 14251 if (isNullConstant(N3) && CC == ISD::SETLT && 14252 (isNullConstant(N1) || // (a < 0) ? b : 0 14253 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 14254 EVT XType = N0.getValueType(); 14255 EVT AType = N2.getValueType(); 14256 if (XType.bitsGE(AType)) { 14257 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 14258 // single-bit constant. 14259 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14260 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 14261 ShCtV = XType.getSizeInBits() - ShCtV - 1; 14262 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 14263 getShiftAmountTy(N0.getValueType())); 14264 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 14265 XType, N0, ShCt); 14266 AddToWorklist(Shift.getNode()); 14267 14268 if (XType.bitsGT(AType)) { 14269 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14270 AddToWorklist(Shift.getNode()); 14271 } 14272 14273 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14274 } 14275 14276 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 14277 XType, N0, 14278 DAG.getConstant(XType.getSizeInBits() - 1, 14279 SDLoc(N0), 14280 getShiftAmountTy(N0.getValueType()))); 14281 AddToWorklist(Shift.getNode()); 14282 14283 if (XType.bitsGT(AType)) { 14284 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14285 AddToWorklist(Shift.getNode()); 14286 } 14287 14288 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14289 } 14290 } 14291 14292 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14293 // where y is has a single bit set. 14294 // A plaintext description would be, we can turn the SELECT_CC into an AND 14295 // when the condition can be materialized as an all-ones register. Any 14296 // single bit-test can be materialized as an all-ones register with 14297 // shift-left and shift-right-arith. 14298 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14299 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14300 SDValue AndLHS = N0->getOperand(0); 14301 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14302 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14303 // Shift the tested bit over the sign bit. 14304 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 14305 SDValue ShlAmt = 14306 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14307 getShiftAmountTy(AndLHS.getValueType())); 14308 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14309 14310 // Now arithmetic right shift it all the way over, so the result is either 14311 // all-ones, or zero. 14312 SDValue ShrAmt = 14313 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14314 getShiftAmountTy(Shl.getValueType())); 14315 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14316 14317 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14318 } 14319 } 14320 14321 // fold select C, 16, 0 -> shl C, 4 14322 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14323 TLI.getBooleanContents(N0.getValueType()) == 14324 TargetLowering::ZeroOrOneBooleanContent) { 14325 14326 // If the caller doesn't want us to simplify this into a zext of a compare, 14327 // don't do it. 14328 if (NotExtCompare && N2C->isOne()) 14329 return SDValue(); 14330 14331 // Get a SetCC of the condition 14332 // NOTE: Don't create a SETCC if it's not legal on this target. 14333 if (!LegalOperations || 14334 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14335 SDValue Temp, SCC; 14336 // cast from setcc result type to select result type 14337 if (LegalTypes) { 14338 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14339 N0, N1, CC); 14340 if (N2.getValueType().bitsLT(SCC.getValueType())) 14341 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14342 N2.getValueType()); 14343 else 14344 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14345 N2.getValueType(), SCC); 14346 } else { 14347 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14348 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14349 N2.getValueType(), SCC); 14350 } 14351 14352 AddToWorklist(SCC.getNode()); 14353 AddToWorklist(Temp.getNode()); 14354 14355 if (N2C->isOne()) 14356 return Temp; 14357 14358 // shl setcc result by log2 n2c 14359 return DAG.getNode( 14360 ISD::SHL, DL, N2.getValueType(), Temp, 14361 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14362 getShiftAmountTy(Temp.getValueType()))); 14363 } 14364 } 14365 14366 // Check to see if this is an integer abs. 14367 // select_cc setg[te] X, 0, X, -X -> 14368 // select_cc setgt X, -1, X, -X -> 14369 // select_cc setl[te] X, 0, -X, X -> 14370 // select_cc setlt X, 1, -X, X -> 14371 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14372 if (N1C) { 14373 ConstantSDNode *SubC = nullptr; 14374 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14375 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14376 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14377 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14378 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14379 (N1C->isOne() && CC == ISD::SETLT)) && 14380 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14381 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14382 14383 EVT XType = N0.getValueType(); 14384 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14385 SDLoc DL(N0); 14386 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14387 N0, 14388 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14389 getShiftAmountTy(N0.getValueType()))); 14390 SDValue Add = DAG.getNode(ISD::ADD, DL, 14391 XType, N0, Shift); 14392 AddToWorklist(Shift.getNode()); 14393 AddToWorklist(Add.getNode()); 14394 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14395 } 14396 } 14397 14398 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 14399 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 14400 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 14401 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 14402 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 14403 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 14404 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 14405 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 14406 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 14407 SDValue ValueOnZero = N2; 14408 SDValue Count = N3; 14409 // If the condition is NE instead of E, swap the operands. 14410 if (CC == ISD::SETNE) 14411 std::swap(ValueOnZero, Count); 14412 // Check if the value on zero is a constant equal to the bits in the type. 14413 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 14414 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 14415 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 14416 // legal, combine to just cttz. 14417 if ((Count.getOpcode() == ISD::CTTZ || 14418 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 14419 N0 == Count.getOperand(0) && 14420 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 14421 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 14422 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 14423 // legal, combine to just ctlz. 14424 if ((Count.getOpcode() == ISD::CTLZ || 14425 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 14426 N0 == Count.getOperand(0) && 14427 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 14428 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 14429 } 14430 } 14431 } 14432 14433 return SDValue(); 14434 } 14435 14436 /// This is a stub for TargetLowering::SimplifySetCC. 14437 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 14438 ISD::CondCode Cond, const SDLoc &DL, 14439 bool foldBooleans) { 14440 TargetLowering::DAGCombinerInfo 14441 DagCombineInfo(DAG, Level, false, this); 14442 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14443 } 14444 14445 /// Given an ISD::SDIV node expressing a divide by constant, return 14446 /// a DAG expression to select that will generate the same value by multiplying 14447 /// by a magic number. 14448 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14449 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14450 // when optimising for minimum size, we don't want to expand a div to a mul 14451 // and a shift. 14452 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 14453 return SDValue(); 14454 14455 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14456 if (!C) 14457 return SDValue(); 14458 14459 // Avoid division by zero. 14460 if (C->isNullValue()) 14461 return SDValue(); 14462 14463 std::vector<SDNode*> Built; 14464 SDValue S = 14465 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14466 14467 for (SDNode *N : Built) 14468 AddToWorklist(N); 14469 return S; 14470 } 14471 14472 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14473 /// DAG expression that will generate the same value by right shifting. 14474 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14475 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14476 if (!C) 14477 return SDValue(); 14478 14479 // Avoid division by zero. 14480 if (C->isNullValue()) 14481 return SDValue(); 14482 14483 std::vector<SDNode *> Built; 14484 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14485 14486 for (SDNode *N : Built) 14487 AddToWorklist(N); 14488 return S; 14489 } 14490 14491 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14492 /// expression that will generate the same value by multiplying by a magic 14493 /// number. 14494 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14495 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14496 // when optimising for minimum size, we don't want to expand a div to a mul 14497 // and a shift. 14498 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 14499 return SDValue(); 14500 14501 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14502 if (!C) 14503 return SDValue(); 14504 14505 // Avoid division by zero. 14506 if (C->isNullValue()) 14507 return SDValue(); 14508 14509 std::vector<SDNode*> Built; 14510 SDValue S = 14511 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14512 14513 for (SDNode *N : Built) 14514 AddToWorklist(N); 14515 return S; 14516 } 14517 14518 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14519 if (Level >= AfterLegalizeDAG) 14520 return SDValue(); 14521 14522 // Expose the DAG combiner to the target combiner implementations. 14523 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14524 14525 unsigned Iterations = 0; 14526 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14527 if (Iterations) { 14528 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14529 // For the reciprocal, we need to find the zero of the function: 14530 // F(X) = A X - 1 [which has a zero at X = 1/A] 14531 // => 14532 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14533 // does not require additional intermediate precision] 14534 EVT VT = Op.getValueType(); 14535 SDLoc DL(Op); 14536 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14537 14538 AddToWorklist(Est.getNode()); 14539 14540 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14541 for (unsigned i = 0; i < Iterations; ++i) { 14542 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14543 AddToWorklist(NewEst.getNode()); 14544 14545 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14546 AddToWorklist(NewEst.getNode()); 14547 14548 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14549 AddToWorklist(NewEst.getNode()); 14550 14551 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14552 AddToWorklist(Est.getNode()); 14553 } 14554 } 14555 return Est; 14556 } 14557 14558 return SDValue(); 14559 } 14560 14561 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14562 /// For the reciprocal sqrt, we need to find the zero of the function: 14563 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14564 /// => 14565 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14566 /// As a result, we precompute A/2 prior to the iteration loop. 14567 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 14568 unsigned Iterations, 14569 SDNodeFlags *Flags, bool Reciprocal) { 14570 EVT VT = Arg.getValueType(); 14571 SDLoc DL(Arg); 14572 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14573 14574 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14575 // this entire sequence requires only one FP constant. 14576 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14577 AddToWorklist(HalfArg.getNode()); 14578 14579 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14580 AddToWorklist(HalfArg.getNode()); 14581 14582 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14583 for (unsigned i = 0; i < Iterations; ++i) { 14584 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14585 AddToWorklist(NewEst.getNode()); 14586 14587 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14588 AddToWorklist(NewEst.getNode()); 14589 14590 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14591 AddToWorklist(NewEst.getNode()); 14592 14593 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14594 AddToWorklist(Est.getNode()); 14595 } 14596 14597 // If non-reciprocal square root is requested, multiply the result by Arg. 14598 if (!Reciprocal) { 14599 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14600 AddToWorklist(Est.getNode()); 14601 } 14602 14603 return Est; 14604 } 14605 14606 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14607 /// For the reciprocal sqrt, we need to find the zero of the function: 14608 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14609 /// => 14610 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14611 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 14612 unsigned Iterations, 14613 SDNodeFlags *Flags, bool Reciprocal) { 14614 EVT VT = Arg.getValueType(); 14615 SDLoc DL(Arg); 14616 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14617 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14618 14619 // This routine must enter the loop below to work correctly 14620 // when (Reciprocal == false). 14621 assert(Iterations > 0); 14622 14623 // Newton iterations for reciprocal square root: 14624 // E = (E * -0.5) * ((A * E) * E + -3.0) 14625 for (unsigned i = 0; i < Iterations; ++i) { 14626 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 14627 AddToWorklist(AE.getNode()); 14628 14629 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 14630 AddToWorklist(AEE.getNode()); 14631 14632 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 14633 AddToWorklist(RHS.getNode()); 14634 14635 // When calculating a square root at the last iteration build: 14636 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 14637 // (notice a common subexpression) 14638 SDValue LHS; 14639 if (Reciprocal || (i + 1) < Iterations) { 14640 // RSQRT: LHS = (E * -0.5) 14641 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14642 } else { 14643 // SQRT: LHS = (A * E) * -0.5 14644 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 14645 } 14646 AddToWorklist(LHS.getNode()); 14647 14648 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 14649 AddToWorklist(Est.getNode()); 14650 } 14651 14652 return Est; 14653 } 14654 14655 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 14656 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 14657 /// Op can be zero. 14658 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, 14659 bool Reciprocal) { 14660 if (Level >= AfterLegalizeDAG) 14661 return SDValue(); 14662 14663 // Expose the DAG combiner to the target combiner implementations. 14664 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14665 unsigned Iterations = 0; 14666 bool UseOneConstNR = false; 14667 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14668 AddToWorklist(Est.getNode()); 14669 if (Iterations) { 14670 Est = UseOneConstNR 14671 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 14672 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 14673 } 14674 return Est; 14675 } 14676 14677 return SDValue(); 14678 } 14679 14680 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14681 return buildSqrtEstimateImpl(Op, Flags, true); 14682 } 14683 14684 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14685 SDValue Est = buildSqrtEstimateImpl(Op, Flags, false); 14686 if (!Est) 14687 return SDValue(); 14688 14689 // Unfortunately, Est is now NaN if the input was exactly 0. 14690 // Select out this case and force the answer to 0. 14691 EVT VT = Est.getValueType(); 14692 SDLoc DL(Op); 14693 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 14694 EVT CCVT = getSetCCResultType(VT); 14695 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, Zero, ISD::SETEQ); 14696 AddToWorklist(ZeroCmp.getNode()); 14697 14698 Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, ZeroCmp, 14699 Zero, Est); 14700 AddToWorklist(Est.getNode()); 14701 return Est; 14702 } 14703 14704 /// Return true if base is a frame index, which is known not to alias with 14705 /// anything but itself. Provides base object and offset as results. 14706 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14707 const GlobalValue *&GV, const void *&CV) { 14708 // Assume it is a primitive operation. 14709 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14710 14711 // If it's an adding a simple constant then integrate the offset. 14712 if (Base.getOpcode() == ISD::ADD) { 14713 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14714 Base = Base.getOperand(0); 14715 Offset += C->getZExtValue(); 14716 } 14717 } 14718 14719 // Return the underlying GlobalValue, and update the Offset. Return false 14720 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14721 // by multiple nodes with different offsets. 14722 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14723 GV = G->getGlobal(); 14724 Offset += G->getOffset(); 14725 return false; 14726 } 14727 14728 // Return the underlying Constant value, and update the Offset. Return false 14729 // for ConstantSDNodes since the same constant pool entry may be represented 14730 // by multiple nodes with different offsets. 14731 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14732 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14733 : (const void *)C->getConstVal(); 14734 Offset += C->getOffset(); 14735 return false; 14736 } 14737 // If it's any of the following then it can't alias with anything but itself. 14738 return isa<FrameIndexSDNode>(Base); 14739 } 14740 14741 /// Return true if there is any possibility that the two addresses overlap. 14742 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14743 // If they are the same then they must be aliases. 14744 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14745 14746 // If they are both volatile then they cannot be reordered. 14747 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14748 14749 // If one operation reads from invariant memory, and the other may store, they 14750 // cannot alias. These should really be checking the equivalent of mayWrite, 14751 // but it only matters for memory nodes other than load /store. 14752 if (Op0->isInvariant() && Op1->writeMem()) 14753 return false; 14754 14755 if (Op1->isInvariant() && Op0->writeMem()) 14756 return false; 14757 14758 // Gather base node and offset information. 14759 SDValue Base1, Base2; 14760 int64_t Offset1, Offset2; 14761 const GlobalValue *GV1, *GV2; 14762 const void *CV1, *CV2; 14763 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14764 Base1, Offset1, GV1, CV1); 14765 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14766 Base2, Offset2, GV2, CV2); 14767 14768 // If they have a same base address then check to see if they overlap. 14769 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14770 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14771 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14772 14773 // It is possible for different frame indices to alias each other, mostly 14774 // when tail call optimization reuses return address slots for arguments. 14775 // To catch this case, look up the actual index of frame indices to compute 14776 // the real alias relationship. 14777 if (isFrameIndex1 && isFrameIndex2) { 14778 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 14779 Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14780 Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14781 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14782 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14783 } 14784 14785 // Otherwise, if we know what the bases are, and they aren't identical, then 14786 // we know they cannot alias. 14787 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14788 return false; 14789 14790 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14791 // compared to the size and offset of the access, we may be able to prove they 14792 // do not alias. This check is conservative for now to catch cases created by 14793 // splitting vector types. 14794 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14795 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14796 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14797 Op1->getMemoryVT().getSizeInBits() >> 3) && 14798 (Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) { 14799 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14800 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14801 14802 // There is no overlap between these relatively aligned accesses of similar 14803 // size, return no alias. 14804 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14805 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14806 return false; 14807 } 14808 14809 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14810 ? CombinerGlobalAA 14811 : DAG.getSubtarget().useAA(); 14812 #ifndef NDEBUG 14813 if (CombinerAAOnlyFunc.getNumOccurrences() && 14814 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14815 UseAA = false; 14816 #endif 14817 if (UseAA && 14818 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14819 // Use alias analysis information. 14820 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14821 Op1->getSrcValueOffset()); 14822 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14823 Op0->getSrcValueOffset() - MinOffset; 14824 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14825 Op1->getSrcValueOffset() - MinOffset; 14826 AliasResult AAResult = 14827 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14828 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14829 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14830 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14831 if (AAResult == NoAlias) 14832 return false; 14833 } 14834 14835 // Otherwise we have to assume they alias. 14836 return true; 14837 } 14838 14839 /// Walk up chain skipping non-aliasing memory nodes, 14840 /// looking for aliasing nodes and adding them to the Aliases vector. 14841 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14842 SmallVectorImpl<SDValue> &Aliases) { 14843 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14844 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14845 14846 // Get alias information for node. 14847 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14848 14849 // Starting off. 14850 Chains.push_back(OriginalChain); 14851 unsigned Depth = 0; 14852 14853 // Look at each chain and determine if it is an alias. If so, add it to the 14854 // aliases list. If not, then continue up the chain looking for the next 14855 // candidate. 14856 while (!Chains.empty()) { 14857 SDValue Chain = Chains.pop_back_val(); 14858 14859 // For TokenFactor nodes, look at each operand and only continue up the 14860 // chain until we reach the depth limit. 14861 // 14862 // FIXME: The depth check could be made to return the last non-aliasing 14863 // chain we found before we hit a tokenfactor rather than the original 14864 // chain. 14865 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 14866 Aliases.clear(); 14867 Aliases.push_back(OriginalChain); 14868 return; 14869 } 14870 14871 // Don't bother if we've been before. 14872 if (!Visited.insert(Chain.getNode()).second) 14873 continue; 14874 14875 switch (Chain.getOpcode()) { 14876 case ISD::EntryToken: 14877 // Entry token is ideal chain operand, but handled in FindBetterChain. 14878 break; 14879 14880 case ISD::LOAD: 14881 case ISD::STORE: { 14882 // Get alias information for Chain. 14883 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14884 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14885 14886 // If chain is alias then stop here. 14887 if (!(IsLoad && IsOpLoad) && 14888 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14889 Aliases.push_back(Chain); 14890 } else { 14891 // Look further up the chain. 14892 Chains.push_back(Chain.getOperand(0)); 14893 ++Depth; 14894 } 14895 break; 14896 } 14897 14898 case ISD::TokenFactor: 14899 // We have to check each of the operands of the token factor for "small" 14900 // token factors, so we queue them up. Adding the operands to the queue 14901 // (stack) in reverse order maintains the original order and increases the 14902 // likelihood that getNode will find a matching token factor (CSE.) 14903 if (Chain.getNumOperands() > 16) { 14904 Aliases.push_back(Chain); 14905 break; 14906 } 14907 for (unsigned n = Chain.getNumOperands(); n;) 14908 Chains.push_back(Chain.getOperand(--n)); 14909 ++Depth; 14910 break; 14911 14912 default: 14913 // For all other instructions we will just have to take what we can get. 14914 Aliases.push_back(Chain); 14915 break; 14916 } 14917 } 14918 } 14919 14920 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14921 /// (aliasing node.) 14922 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14923 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14924 14925 // Accumulate all the aliases to this node. 14926 GatherAllAliases(N, OldChain, Aliases); 14927 14928 // If no operands then chain to entry token. 14929 if (Aliases.size() == 0) 14930 return DAG.getEntryNode(); 14931 14932 // If a single operand then chain to it. We don't need to revisit it. 14933 if (Aliases.size() == 1) 14934 return Aliases[0]; 14935 14936 // Construct a custom tailored token factor. 14937 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14938 } 14939 14940 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 14941 // This holds the base pointer, index, and the offset in bytes from the base 14942 // pointer. 14943 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 14944 14945 // We must have a base and an offset. 14946 if (!BasePtr.Base.getNode()) 14947 return false; 14948 14949 // Do not handle stores to undef base pointers. 14950 if (BasePtr.Base.isUndef()) 14951 return false; 14952 14953 SmallVector<StoreSDNode *, 8> ChainedStores; 14954 ChainedStores.push_back(St); 14955 14956 // Walk up the chain and look for nodes with offsets from the same 14957 // base pointer. Stop when reaching an instruction with a different kind 14958 // or instruction which has a different base pointer. 14959 StoreSDNode *Index = St; 14960 while (Index) { 14961 // If the chain has more than one use, then we can't reorder the mem ops. 14962 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14963 break; 14964 14965 if (Index->isVolatile() || Index->isIndexed()) 14966 break; 14967 14968 // Find the base pointer and offset for this memory node. 14969 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 14970 14971 // Check that the base pointer is the same as the original one. 14972 if (!Ptr.equalBaseIndex(BasePtr)) 14973 break; 14974 14975 // Find the next memory operand in the chain. If the next operand in the 14976 // chain is a store then move up and continue the scan with the next 14977 // memory operand. If the next operand is a load save it and use alias 14978 // information to check if it interferes with anything. 14979 SDNode *NextInChain = Index->getChain().getNode(); 14980 while (true) { 14981 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14982 // We found a store node. Use it for the next iteration. 14983 if (STn->isVolatile() || STn->isIndexed()) { 14984 Index = nullptr; 14985 break; 14986 } 14987 ChainedStores.push_back(STn); 14988 Index = STn; 14989 break; 14990 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14991 NextInChain = Ldn->getChain().getNode(); 14992 continue; 14993 } else { 14994 Index = nullptr; 14995 break; 14996 } 14997 } 14998 } 14999 15000 bool MadeChangeToSt = false; 15001 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 15002 15003 for (StoreSDNode *ChainedStore : ChainedStores) { 15004 SDValue Chain = ChainedStore->getChain(); 15005 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 15006 15007 if (Chain != BetterChain) { 15008 if (ChainedStore == St) 15009 MadeChangeToSt = true; 15010 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 15011 } 15012 } 15013 15014 // Do all replacements after finding the replacements to make to avoid making 15015 // the chains more complicated by introducing new TokenFactors. 15016 for (auto Replacement : BetterChains) 15017 replaceStoreChain(Replacement.first, Replacement.second); 15018 15019 return MadeChangeToSt; 15020 } 15021 15022 /// This is the entry point for the file. 15023 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 15024 CodeGenOpt::Level OptLevel) { 15025 /// This is the main entry point to this class. 15026 DAGCombiner(*this, AA, OptLevel).Run(Level); 15027 } 15028