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, 216 SDValue Trunc, SDValue ExtLoad, 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 visitCTLZ(SDNode *N); 263 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 264 SDValue visitCTTZ(SDNode *N); 265 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 266 SDValue visitCTPOP(SDNode *N); 267 SDValue visitSELECT(SDNode *N); 268 SDValue visitVSELECT(SDNode *N); 269 SDValue visitSELECT_CC(SDNode *N); 270 SDValue visitSETCC(SDNode *N); 271 SDValue visitSETCCE(SDNode *N); 272 SDValue visitSIGN_EXTEND(SDNode *N); 273 SDValue visitZERO_EXTEND(SDNode *N); 274 SDValue visitANY_EXTEND(SDNode *N); 275 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 276 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 277 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 278 SDValue visitTRUNCATE(SDNode *N); 279 SDValue visitBITCAST(SDNode *N); 280 SDValue visitBUILD_PAIR(SDNode *N); 281 SDValue visitFADD(SDNode *N); 282 SDValue visitFSUB(SDNode *N); 283 SDValue visitFMUL(SDNode *N); 284 SDValue visitFMA(SDNode *N); 285 SDValue visitFDIV(SDNode *N); 286 SDValue visitFREM(SDNode *N); 287 SDValue visitFSQRT(SDNode *N); 288 SDValue visitFCOPYSIGN(SDNode *N); 289 SDValue visitSINT_TO_FP(SDNode *N); 290 SDValue visitUINT_TO_FP(SDNode *N); 291 SDValue visitFP_TO_SINT(SDNode *N); 292 SDValue visitFP_TO_UINT(SDNode *N); 293 SDValue visitFP_ROUND(SDNode *N); 294 SDValue visitFP_ROUND_INREG(SDNode *N); 295 SDValue visitFP_EXTEND(SDNode *N); 296 SDValue visitFNEG(SDNode *N); 297 SDValue visitFABS(SDNode *N); 298 SDValue visitFCEIL(SDNode *N); 299 SDValue visitFTRUNC(SDNode *N); 300 SDValue visitFFLOOR(SDNode *N); 301 SDValue visitFMINNUM(SDNode *N); 302 SDValue visitFMAXNUM(SDNode *N); 303 SDValue visitBRCOND(SDNode *N); 304 SDValue visitBR_CC(SDNode *N); 305 SDValue visitLOAD(SDNode *N); 306 307 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 308 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 309 310 SDValue visitSTORE(SDNode *N); 311 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 312 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 313 SDValue visitBUILD_VECTOR(SDNode *N); 314 SDValue visitCONCAT_VECTORS(SDNode *N); 315 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 316 SDValue visitVECTOR_SHUFFLE(SDNode *N); 317 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 318 SDValue visitINSERT_SUBVECTOR(SDNode *N); 319 SDValue visitMLOAD(SDNode *N); 320 SDValue visitMSTORE(SDNode *N); 321 SDValue visitMGATHER(SDNode *N); 322 SDValue visitMSCATTER(SDNode *N); 323 SDValue visitFP_TO_FP16(SDNode *N); 324 SDValue visitFP16_TO_FP(SDNode *N); 325 326 SDValue visitFADDForFMACombine(SDNode *N); 327 SDValue visitFSUBForFMACombine(SDNode *N); 328 SDValue visitFMULForFMACombine(SDNode *N); 329 330 SDValue XformToShuffleWithZero(SDNode *N); 331 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 332 333 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 334 335 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 336 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 337 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 338 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 339 SDValue N3, ISD::CondCode CC, 340 bool NotExtCompare = false); 341 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 342 SDLoc DL, bool foldBooleans = true); 343 344 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 345 SDValue &CC) const; 346 bool isOneUseSetCC(SDValue N) const; 347 348 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 349 unsigned HiOp); 350 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 351 SDValue CombineExtLoad(SDNode *N); 352 SDValue combineRepeatedFPDivisors(SDNode *N); 353 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 354 SDValue BuildSDIV(SDNode *N); 355 SDValue BuildSDIVPow2(SDNode *N); 356 SDValue BuildUDIV(SDNode *N); 357 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags); 358 SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags); 359 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations, 360 SDNodeFlags *Flags); 361 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations, 362 SDNodeFlags *Flags); 363 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 364 bool DemandHighBits = true); 365 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 366 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 367 SDValue InnerPos, SDValue InnerNeg, 368 unsigned PosOpcode, unsigned NegOpcode, 369 SDLoc DL); 370 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 371 SDValue ReduceLoadWidth(SDNode *N); 372 SDValue ReduceLoadOpStoreWidth(SDNode *N); 373 SDValue TransformFPLoadStorePair(SDNode *N); 374 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 375 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 376 377 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 378 379 /// Walk up chain skipping non-aliasing memory nodes, 380 /// looking for aliasing nodes and adding them to the Aliases vector. 381 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 382 SmallVectorImpl<SDValue> &Aliases); 383 384 /// Return true if there is any possibility that the two addresses overlap. 385 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 386 387 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 388 /// chain (aliasing node.) 389 SDValue FindBetterChain(SDNode *N, SDValue Chain); 390 391 /// Do FindBetterChain for a store and any possibly adjacent stores on 392 /// consecutive chains. 393 bool findBetterNeighborChains(StoreSDNode *St); 394 395 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 396 bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask); 397 398 /// Holds a pointer to an LSBaseSDNode as well as information on where it 399 /// is located in a sequence of memory operations connected by a chain. 400 struct MemOpLink { 401 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 402 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 403 // Ptr to the mem node. 404 LSBaseSDNode *MemNode; 405 // Offset from the base ptr. 406 int64_t OffsetFromBase; 407 // What is the sequence number of this mem node. 408 // Lowest mem operand in the DAG starts at zero. 409 unsigned SequenceNum; 410 }; 411 412 /// This is a helper function for visitMUL to check the profitability 413 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 414 /// MulNode is the original multiply, AddNode is (add x, c1), 415 /// and ConstNode is c2. 416 bool isMulAddWithConstProfitable(SDNode *MulNode, 417 SDValue &AddNode, 418 SDValue &ConstNode); 419 420 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a 421 /// constant build_vector of the stored constant values in Stores. 422 SDValue getMergedConstantVectorStore(SelectionDAG &DAG, 423 SDLoc SL, 424 ArrayRef<MemOpLink> Stores, 425 SmallVectorImpl<SDValue> &Chains, 426 EVT Ty) const; 427 428 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 429 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 430 /// the type of the loaded value to be extended. LoadedVT returns the type 431 /// of the original loaded value. NarrowLoad returns whether the load would 432 /// need to be narrowed in order to match. 433 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 434 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 435 bool &NarrowLoad); 436 437 /// This is a helper function for MergeConsecutiveStores. When the source 438 /// elements of the consecutive stores are all constants or all extracted 439 /// vector elements, try to merge them into one larger store. 440 /// \return True if a merged store was created. 441 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 442 EVT MemVT, unsigned NumStores, 443 bool IsConstantSrc, bool UseVector); 444 445 /// This is a helper function for MergeConsecutiveStores. 446 /// Stores that may be merged are placed in StoreNodes. 447 /// Loads that may alias with those stores are placed in AliasLoadNodes. 448 void getStoreMergeAndAliasCandidates( 449 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 450 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes); 451 452 /// Helper function for MergeConsecutiveStores. Checks if 453 /// Candidate stores have indirect dependency through their 454 /// operands. \return True if safe to merge 455 bool checkMergeStoreCandidatesForDependencies( 456 SmallVectorImpl<MemOpLink> &StoreNodes); 457 458 /// Merge consecutive store operations into a wide store. 459 /// This optimization uses wide integers or vectors when possible. 460 /// \return True if some memory operations were changed. 461 bool MergeConsecutiveStores(StoreSDNode *N); 462 463 /// \brief Try to transform a truncation where C is a constant: 464 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 465 /// 466 /// \p N needs to be a truncation and its first operand an AND. Other 467 /// requirements are checked by the function (e.g. that trunc is 468 /// single-use) and if missed an empty SDValue is returned. 469 SDValue distributeTruncateThroughAnd(SDNode *N); 470 471 public: 472 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 473 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 474 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 475 ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize(); 476 } 477 478 /// Runs the dag combiner on all nodes in the work list 479 void Run(CombineLevel AtLevel); 480 481 SelectionDAG &getDAG() const { return DAG; } 482 483 /// Returns a type large enough to hold any valid shift amount - before type 484 /// legalization these can be huge. 485 EVT getShiftAmountTy(EVT LHSTy) { 486 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 487 if (LHSTy.isVector()) 488 return LHSTy; 489 auto &DL = DAG.getDataLayout(); 490 return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy) 491 : TLI.getPointerTy(DL); 492 } 493 494 /// This method returns true if we are running before type legalization or 495 /// if the specified VT is legal. 496 bool isTypeLegal(const EVT &VT) { 497 if (!LegalTypes) return true; 498 return TLI.isTypeLegal(VT); 499 } 500 501 /// Convenience wrapper around TargetLowering::getSetCCResultType 502 EVT getSetCCResultType(EVT VT) const { 503 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 504 } 505 }; 506 } 507 508 509 namespace { 510 /// This class is a DAGUpdateListener that removes any deleted 511 /// nodes from the worklist. 512 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 513 DAGCombiner &DC; 514 public: 515 explicit WorklistRemover(DAGCombiner &dc) 516 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 517 518 void NodeDeleted(SDNode *N, SDNode *E) override { 519 DC.removeFromWorklist(N); 520 } 521 }; 522 } 523 524 //===----------------------------------------------------------------------===// 525 // TargetLowering::DAGCombinerInfo implementation 526 //===----------------------------------------------------------------------===// 527 528 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 529 ((DAGCombiner*)DC)->AddToWorklist(N); 530 } 531 532 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 533 ((DAGCombiner*)DC)->removeFromWorklist(N); 534 } 535 536 SDValue TargetLowering::DAGCombinerInfo:: 537 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 538 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 539 } 540 541 SDValue TargetLowering::DAGCombinerInfo:: 542 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 543 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 544 } 545 546 547 SDValue TargetLowering::DAGCombinerInfo:: 548 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 549 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 550 } 551 552 void TargetLowering::DAGCombinerInfo:: 553 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 554 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 555 } 556 557 //===----------------------------------------------------------------------===// 558 // Helper Functions 559 //===----------------------------------------------------------------------===// 560 561 void DAGCombiner::deleteAndRecombine(SDNode *N) { 562 removeFromWorklist(N); 563 564 // If the operands of this node are only used by the node, they will now be 565 // dead. Make sure to re-visit them and recursively delete dead nodes. 566 for (const SDValue &Op : N->ops()) 567 // For an operand generating multiple values, one of the values may 568 // become dead allowing further simplification (e.g. split index 569 // arithmetic from an indexed load). 570 if (Op->hasOneUse() || Op->getNumValues() > 1) 571 AddToWorklist(Op.getNode()); 572 573 DAG.DeleteNode(N); 574 } 575 576 /// Return 1 if we can compute the negated form of the specified expression for 577 /// the same cost as the expression itself, or 2 if we can compute the negated 578 /// form more cheaply than the expression itself. 579 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 580 const TargetLowering &TLI, 581 const TargetOptions *Options, 582 unsigned Depth = 0) { 583 // fneg is removable even if it has multiple uses. 584 if (Op.getOpcode() == ISD::FNEG) return 2; 585 586 // Don't allow anything with multiple uses. 587 if (!Op.hasOneUse()) return 0; 588 589 // Don't recurse exponentially. 590 if (Depth > 6) return 0; 591 592 switch (Op.getOpcode()) { 593 default: return false; 594 case ISD::ConstantFP: 595 // Don't invert constant FP values after legalize. The negated constant 596 // isn't necessarily legal. 597 return LegalOperations ? 0 : 1; 598 case ISD::FADD: 599 // FIXME: determine better conditions for this xform. 600 if (!Options->UnsafeFPMath) return 0; 601 602 // After operation legalization, it might not be legal to create new FSUBs. 603 if (LegalOperations && 604 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 605 return 0; 606 607 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 608 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 609 Options, Depth + 1)) 610 return V; 611 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 612 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 613 Depth + 1); 614 case ISD::FSUB: 615 // We can't turn -(A-B) into B-A when we honor signed zeros. 616 if (!Options->UnsafeFPMath) return 0; 617 618 // fold (fneg (fsub A, B)) -> (fsub B, A) 619 return 1; 620 621 case ISD::FMUL: 622 case ISD::FDIV: 623 if (Options->HonorSignDependentRoundingFPMath()) return 0; 624 625 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 626 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 627 Options, Depth + 1)) 628 return V; 629 630 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 631 Depth + 1); 632 633 case ISD::FP_EXTEND: 634 case ISD::FP_ROUND: 635 case ISD::FSIN: 636 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 637 Depth + 1); 638 } 639 } 640 641 /// If isNegatibleForFree returns true, return the newly negated expression. 642 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 643 bool LegalOperations, unsigned Depth = 0) { 644 const TargetOptions &Options = DAG.getTarget().Options; 645 // fneg is removable even if it has multiple uses. 646 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 647 648 // Don't allow anything with multiple uses. 649 assert(Op.hasOneUse() && "Unknown reuse!"); 650 651 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 652 653 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 654 655 switch (Op.getOpcode()) { 656 default: llvm_unreachable("Unknown code"); 657 case ISD::ConstantFP: { 658 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 659 V.changeSign(); 660 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 661 } 662 case ISD::FADD: 663 // FIXME: determine better conditions for this xform. 664 assert(Options.UnsafeFPMath); 665 666 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 667 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 668 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 669 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 670 GetNegatedExpression(Op.getOperand(0), DAG, 671 LegalOperations, Depth+1), 672 Op.getOperand(1), Flags); 673 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 674 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 675 GetNegatedExpression(Op.getOperand(1), DAG, 676 LegalOperations, Depth+1), 677 Op.getOperand(0), Flags); 678 case ISD::FSUB: 679 // We can't turn -(A-B) into B-A when we honor signed zeros. 680 assert(Options.UnsafeFPMath); 681 682 // fold (fneg (fsub 0, B)) -> B 683 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 684 if (N0CFP->isZero()) 685 return Op.getOperand(1); 686 687 // fold (fneg (fsub A, B)) -> (fsub B, A) 688 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 689 Op.getOperand(1), Op.getOperand(0), Flags); 690 691 case ISD::FMUL: 692 case ISD::FDIV: 693 assert(!Options.HonorSignDependentRoundingFPMath()); 694 695 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 696 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 697 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 698 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 699 GetNegatedExpression(Op.getOperand(0), DAG, 700 LegalOperations, Depth+1), 701 Op.getOperand(1), Flags); 702 703 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 704 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 705 Op.getOperand(0), 706 GetNegatedExpression(Op.getOperand(1), DAG, 707 LegalOperations, Depth+1), Flags); 708 709 case ISD::FP_EXTEND: 710 case ISD::FSIN: 711 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 712 GetNegatedExpression(Op.getOperand(0), DAG, 713 LegalOperations, Depth+1)); 714 case ISD::FP_ROUND: 715 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 716 GetNegatedExpression(Op.getOperand(0), DAG, 717 LegalOperations, Depth+1), 718 Op.getOperand(1)); 719 } 720 } 721 722 // Return true if this node is a setcc, or is a select_cc 723 // that selects between the target values used for true and false, making it 724 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 725 // the appropriate nodes based on the type of node we are checking. This 726 // simplifies life a bit for the callers. 727 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 728 SDValue &CC) const { 729 if (N.getOpcode() == ISD::SETCC) { 730 LHS = N.getOperand(0); 731 RHS = N.getOperand(1); 732 CC = N.getOperand(2); 733 return true; 734 } 735 736 if (N.getOpcode() != ISD::SELECT_CC || 737 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 738 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 739 return false; 740 741 if (TLI.getBooleanContents(N.getValueType()) == 742 TargetLowering::UndefinedBooleanContent) 743 return false; 744 745 LHS = N.getOperand(0); 746 RHS = N.getOperand(1); 747 CC = N.getOperand(4); 748 return true; 749 } 750 751 /// Return true if this is a SetCC-equivalent operation with only one use. 752 /// If this is true, it allows the users to invert the operation for free when 753 /// it is profitable to do so. 754 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 755 SDValue N0, N1, N2; 756 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 757 return true; 758 return false; 759 } 760 761 /// Returns true if N is a BUILD_VECTOR node whose 762 /// elements are all the same constant or undefined. 763 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 764 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 765 if (!C) 766 return false; 767 768 APInt SplatUndef; 769 unsigned SplatBitSize; 770 bool HasAnyUndefs; 771 EVT EltVT = N->getValueType(0).getVectorElementType(); 772 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 773 HasAnyUndefs) && 774 EltVT.getSizeInBits() >= SplatBitSize); 775 } 776 777 // \brief Returns the SDNode if it is a constant float BuildVector 778 // or constant float. 779 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 780 if (isa<ConstantFPSDNode>(N)) 781 return N.getNode(); 782 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 783 return N.getNode(); 784 return nullptr; 785 } 786 787 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 788 // int. 789 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 790 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 791 return CN; 792 793 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 794 BitVector UndefElements; 795 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 796 797 // BuildVectors can truncate their operands. Ignore that case here. 798 // FIXME: We blindly ignore splats which include undef which is overly 799 // pessimistic. 800 if (CN && UndefElements.none() && 801 CN->getValueType(0) == N.getValueType().getScalarType()) 802 return CN; 803 } 804 805 return nullptr; 806 } 807 808 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 809 // float. 810 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 811 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 812 return CN; 813 814 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 815 BitVector UndefElements; 816 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 817 818 if (CN && UndefElements.none()) 819 return CN; 820 } 821 822 return nullptr; 823 } 824 825 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 826 SDValue N0, SDValue N1) { 827 EVT VT = N0.getValueType(); 828 if (N0.getOpcode() == Opc) { 829 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 830 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 831 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 832 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 833 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 834 return SDValue(); 835 } 836 if (N0.hasOneUse()) { 837 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 838 // use 839 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 840 if (!OpNode.getNode()) 841 return SDValue(); 842 AddToWorklist(OpNode.getNode()); 843 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 844 } 845 } 846 } 847 848 if (N1.getOpcode() == Opc) { 849 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 850 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 851 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 852 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 853 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 854 return SDValue(); 855 } 856 if (N1.hasOneUse()) { 857 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 858 // use 859 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 860 if (!OpNode.getNode()) 861 return SDValue(); 862 AddToWorklist(OpNode.getNode()); 863 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 864 } 865 } 866 } 867 868 return SDValue(); 869 } 870 871 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 872 bool AddTo) { 873 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 874 ++NodesCombined; 875 DEBUG(dbgs() << "\nReplacing.1 "; 876 N->dump(&DAG); 877 dbgs() << "\nWith: "; 878 To[0].getNode()->dump(&DAG); 879 dbgs() << " and " << NumTo-1 << " other values\n"); 880 for (unsigned i = 0, e = NumTo; i != e; ++i) 881 assert((!To[i].getNode() || 882 N->getValueType(i) == To[i].getValueType()) && 883 "Cannot combine value to value of different type!"); 884 885 WorklistRemover DeadNodes(*this); 886 DAG.ReplaceAllUsesWith(N, To); 887 if (AddTo) { 888 // Push the new nodes and any users onto the worklist 889 for (unsigned i = 0, e = NumTo; i != e; ++i) { 890 if (To[i].getNode()) { 891 AddToWorklist(To[i].getNode()); 892 AddUsersToWorklist(To[i].getNode()); 893 } 894 } 895 } 896 897 // Finally, if the node is now dead, remove it from the graph. The node 898 // may not be dead if the replacement process recursively simplified to 899 // something else needing this node. 900 if (N->use_empty()) 901 deleteAndRecombine(N); 902 return SDValue(N, 0); 903 } 904 905 void DAGCombiner:: 906 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 907 // Replace all uses. If any nodes become isomorphic to other nodes and 908 // are deleted, make sure to remove them from our worklist. 909 WorklistRemover DeadNodes(*this); 910 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 911 912 // Push the new node and any (possibly new) users onto the worklist. 913 AddToWorklist(TLO.New.getNode()); 914 AddUsersToWorklist(TLO.New.getNode()); 915 916 // Finally, if the node is now dead, remove it from the graph. The node 917 // may not be dead if the replacement process recursively simplified to 918 // something else needing this node. 919 if (TLO.Old.getNode()->use_empty()) 920 deleteAndRecombine(TLO.Old.getNode()); 921 } 922 923 /// Check the specified integer node value to see if it can be simplified or if 924 /// things it uses can be simplified by bit propagation. If so, return true. 925 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 926 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 927 APInt KnownZero, KnownOne; 928 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 929 return false; 930 931 // Revisit the node. 932 AddToWorklist(Op.getNode()); 933 934 // Replace the old value with the new one. 935 ++NodesCombined; 936 DEBUG(dbgs() << "\nReplacing.2 "; 937 TLO.Old.getNode()->dump(&DAG); 938 dbgs() << "\nWith: "; 939 TLO.New.getNode()->dump(&DAG); 940 dbgs() << '\n'); 941 942 CommitTargetLoweringOpt(TLO); 943 return true; 944 } 945 946 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 947 SDLoc dl(Load); 948 EVT VT = Load->getValueType(0); 949 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 950 951 DEBUG(dbgs() << "\nReplacing.9 "; 952 Load->dump(&DAG); 953 dbgs() << "\nWith: "; 954 Trunc.getNode()->dump(&DAG); 955 dbgs() << '\n'); 956 WorklistRemover DeadNodes(*this); 957 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 958 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 959 deleteAndRecombine(Load); 960 AddToWorklist(Trunc.getNode()); 961 } 962 963 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 964 Replace = false; 965 SDLoc dl(Op); 966 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 967 LoadSDNode *LD = cast<LoadSDNode>(Op); 968 EVT MemVT = LD->getMemoryVT(); 969 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 970 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 971 : ISD::EXTLOAD) 972 : LD->getExtensionType(); 973 Replace = true; 974 return DAG.getExtLoad(ExtType, dl, PVT, 975 LD->getChain(), LD->getBasePtr(), 976 MemVT, LD->getMemOperand()); 977 } 978 979 unsigned Opc = Op.getOpcode(); 980 switch (Opc) { 981 default: break; 982 case ISD::AssertSext: 983 return DAG.getNode(ISD::AssertSext, dl, PVT, 984 SExtPromoteOperand(Op.getOperand(0), PVT), 985 Op.getOperand(1)); 986 case ISD::AssertZext: 987 return DAG.getNode(ISD::AssertZext, dl, PVT, 988 ZExtPromoteOperand(Op.getOperand(0), PVT), 989 Op.getOperand(1)); 990 case ISD::Constant: { 991 unsigned ExtOpc = 992 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 993 return DAG.getNode(ExtOpc, dl, PVT, Op); 994 } 995 } 996 997 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 998 return SDValue(); 999 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 1000 } 1001 1002 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1003 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1004 return SDValue(); 1005 EVT OldVT = Op.getValueType(); 1006 SDLoc dl(Op); 1007 bool Replace = false; 1008 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1009 if (!NewOp.getNode()) 1010 return SDValue(); 1011 AddToWorklist(NewOp.getNode()); 1012 1013 if (Replace) 1014 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1015 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 1016 DAG.getValueType(OldVT)); 1017 } 1018 1019 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1020 EVT OldVT = Op.getValueType(); 1021 SDLoc dl(Op); 1022 bool Replace = false; 1023 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1024 if (!NewOp.getNode()) 1025 return SDValue(); 1026 AddToWorklist(NewOp.getNode()); 1027 1028 if (Replace) 1029 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1030 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 1031 } 1032 1033 /// Promote the specified integer binary operation if the target indicates it is 1034 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1035 /// i32 since i16 instructions are longer. 1036 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1037 if (!LegalOperations) 1038 return SDValue(); 1039 1040 EVT VT = Op.getValueType(); 1041 if (VT.isVector() || !VT.isInteger()) 1042 return SDValue(); 1043 1044 // If operation type is 'undesirable', e.g. i16 on x86, consider 1045 // promoting it. 1046 unsigned Opc = Op.getOpcode(); 1047 if (TLI.isTypeDesirableForOp(Opc, VT)) 1048 return SDValue(); 1049 1050 EVT PVT = VT; 1051 // Consult target whether it is a good idea to promote this operation and 1052 // what's the right type to promote it to. 1053 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1054 assert(PVT != VT && "Don't know what type to promote to!"); 1055 1056 bool Replace0 = false; 1057 SDValue N0 = Op.getOperand(0); 1058 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1059 if (!NN0.getNode()) 1060 return SDValue(); 1061 1062 bool Replace1 = false; 1063 SDValue N1 = Op.getOperand(1); 1064 SDValue NN1; 1065 if (N0 == N1) 1066 NN1 = NN0; 1067 else { 1068 NN1 = PromoteOperand(N1, PVT, Replace1); 1069 if (!NN1.getNode()) 1070 return SDValue(); 1071 } 1072 1073 AddToWorklist(NN0.getNode()); 1074 if (NN1.getNode()) 1075 AddToWorklist(NN1.getNode()); 1076 1077 if (Replace0) 1078 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1079 if (Replace1) 1080 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1081 1082 DEBUG(dbgs() << "\nPromoting "; 1083 Op.getNode()->dump(&DAG)); 1084 SDLoc dl(Op); 1085 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1086 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1087 } 1088 return SDValue(); 1089 } 1090 1091 /// Promote the specified integer shift operation if the target indicates it is 1092 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1093 /// i32 since i16 instructions are longer. 1094 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1095 if (!LegalOperations) 1096 return SDValue(); 1097 1098 EVT VT = Op.getValueType(); 1099 if (VT.isVector() || !VT.isInteger()) 1100 return SDValue(); 1101 1102 // If operation type is 'undesirable', e.g. i16 on x86, consider 1103 // promoting it. 1104 unsigned Opc = Op.getOpcode(); 1105 if (TLI.isTypeDesirableForOp(Opc, VT)) 1106 return SDValue(); 1107 1108 EVT PVT = VT; 1109 // Consult target whether it is a good idea to promote this operation and 1110 // what's the right type to promote it to. 1111 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1112 assert(PVT != VT && "Don't know what type to promote to!"); 1113 1114 bool Replace = false; 1115 SDValue N0 = Op.getOperand(0); 1116 if (Opc == ISD::SRA) 1117 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1118 else if (Opc == ISD::SRL) 1119 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1120 else 1121 N0 = PromoteOperand(N0, PVT, Replace); 1122 if (!N0.getNode()) 1123 return SDValue(); 1124 1125 AddToWorklist(N0.getNode()); 1126 if (Replace) 1127 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1128 1129 DEBUG(dbgs() << "\nPromoting "; 1130 Op.getNode()->dump(&DAG)); 1131 SDLoc dl(Op); 1132 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1133 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1134 } 1135 return SDValue(); 1136 } 1137 1138 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1139 if (!LegalOperations) 1140 return SDValue(); 1141 1142 EVT VT = Op.getValueType(); 1143 if (VT.isVector() || !VT.isInteger()) 1144 return SDValue(); 1145 1146 // If operation type is 'undesirable', e.g. i16 on x86, consider 1147 // promoting it. 1148 unsigned Opc = Op.getOpcode(); 1149 if (TLI.isTypeDesirableForOp(Opc, VT)) 1150 return SDValue(); 1151 1152 EVT PVT = VT; 1153 // Consult target whether it is a good idea to promote this operation and 1154 // what's the right type to promote it to. 1155 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1156 assert(PVT != VT && "Don't know what type to promote to!"); 1157 // fold (aext (aext x)) -> (aext x) 1158 // fold (aext (zext x)) -> (zext x) 1159 // fold (aext (sext x)) -> (sext x) 1160 DEBUG(dbgs() << "\nPromoting "; 1161 Op.getNode()->dump(&DAG)); 1162 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1163 } 1164 return SDValue(); 1165 } 1166 1167 bool DAGCombiner::PromoteLoad(SDValue Op) { 1168 if (!LegalOperations) 1169 return false; 1170 1171 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1172 return false; 1173 1174 EVT VT = Op.getValueType(); 1175 if (VT.isVector() || !VT.isInteger()) 1176 return false; 1177 1178 // If operation type is 'undesirable', e.g. i16 on x86, consider 1179 // promoting it. 1180 unsigned Opc = Op.getOpcode(); 1181 if (TLI.isTypeDesirableForOp(Opc, VT)) 1182 return false; 1183 1184 EVT PVT = VT; 1185 // Consult target whether it is a good idea to promote this operation and 1186 // what's the right type to promote it to. 1187 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1188 assert(PVT != VT && "Don't know what type to promote to!"); 1189 1190 SDLoc dl(Op); 1191 SDNode *N = Op.getNode(); 1192 LoadSDNode *LD = cast<LoadSDNode>(N); 1193 EVT MemVT = LD->getMemoryVT(); 1194 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1195 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1196 : ISD::EXTLOAD) 1197 : LD->getExtensionType(); 1198 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1199 LD->getChain(), LD->getBasePtr(), 1200 MemVT, LD->getMemOperand()); 1201 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1202 1203 DEBUG(dbgs() << "\nPromoting "; 1204 N->dump(&DAG); 1205 dbgs() << "\nTo: "; 1206 Result.getNode()->dump(&DAG); 1207 dbgs() << '\n'); 1208 WorklistRemover DeadNodes(*this); 1209 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1210 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1211 deleteAndRecombine(N); 1212 AddToWorklist(Result.getNode()); 1213 return true; 1214 } 1215 return false; 1216 } 1217 1218 /// \brief Recursively delete a node which has no uses and any operands for 1219 /// which it is the only use. 1220 /// 1221 /// Note that this both deletes the nodes and removes them from the worklist. 1222 /// It also adds any nodes who have had a user deleted to the worklist as they 1223 /// may now have only one use and subject to other combines. 1224 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1225 if (!N->use_empty()) 1226 return false; 1227 1228 SmallSetVector<SDNode *, 16> Nodes; 1229 Nodes.insert(N); 1230 do { 1231 N = Nodes.pop_back_val(); 1232 if (!N) 1233 continue; 1234 1235 if (N->use_empty()) { 1236 for (const SDValue &ChildN : N->op_values()) 1237 Nodes.insert(ChildN.getNode()); 1238 1239 removeFromWorklist(N); 1240 DAG.DeleteNode(N); 1241 } else { 1242 AddToWorklist(N); 1243 } 1244 } while (!Nodes.empty()); 1245 return true; 1246 } 1247 1248 //===----------------------------------------------------------------------===// 1249 // Main DAG Combiner implementation 1250 //===----------------------------------------------------------------------===// 1251 1252 void DAGCombiner::Run(CombineLevel AtLevel) { 1253 // set the instance variables, so that the various visit routines may use it. 1254 Level = AtLevel; 1255 LegalOperations = Level >= AfterLegalizeVectorOps; 1256 LegalTypes = Level >= AfterLegalizeTypes; 1257 1258 // Add all the dag nodes to the worklist. 1259 for (SDNode &Node : DAG.allnodes()) 1260 AddToWorklist(&Node); 1261 1262 // Create a dummy node (which is not added to allnodes), that adds a reference 1263 // to the root node, preventing it from being deleted, and tracking any 1264 // changes of the root. 1265 HandleSDNode Dummy(DAG.getRoot()); 1266 1267 // While the worklist isn't empty, find a node and try to combine it. 1268 while (!WorklistMap.empty()) { 1269 SDNode *N; 1270 // The Worklist holds the SDNodes in order, but it may contain null entries. 1271 do { 1272 N = Worklist.pop_back_val(); 1273 } while (!N); 1274 1275 bool GoodWorklistEntry = WorklistMap.erase(N); 1276 (void)GoodWorklistEntry; 1277 assert(GoodWorklistEntry && 1278 "Found a worklist entry without a corresponding map entry!"); 1279 1280 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1281 // N is deleted from the DAG, since they too may now be dead or may have a 1282 // reduced number of uses, allowing other xforms. 1283 if (recursivelyDeleteUnusedNodes(N)) 1284 continue; 1285 1286 WorklistRemover DeadNodes(*this); 1287 1288 // If this combine is running after legalizing the DAG, re-legalize any 1289 // nodes pulled off the worklist. 1290 if (Level == AfterLegalizeDAG) { 1291 SmallSetVector<SDNode *, 16> UpdatedNodes; 1292 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1293 1294 for (SDNode *LN : UpdatedNodes) { 1295 AddToWorklist(LN); 1296 AddUsersToWorklist(LN); 1297 } 1298 if (!NIsValid) 1299 continue; 1300 } 1301 1302 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1303 1304 // Add any operands of the new node which have not yet been combined to the 1305 // worklist as well. Because the worklist uniques things already, this 1306 // won't repeatedly process the same operand. 1307 CombinedNodes.insert(N); 1308 for (const SDValue &ChildN : N->op_values()) 1309 if (!CombinedNodes.count(ChildN.getNode())) 1310 AddToWorklist(ChildN.getNode()); 1311 1312 SDValue RV = combine(N); 1313 1314 if (!RV.getNode()) 1315 continue; 1316 1317 ++NodesCombined; 1318 1319 // If we get back the same node we passed in, rather than a new node or 1320 // zero, we know that the node must have defined multiple values and 1321 // CombineTo was used. Since CombineTo takes care of the worklist 1322 // mechanics for us, we have no work to do in this case. 1323 if (RV.getNode() == N) 1324 continue; 1325 1326 assert(N->getOpcode() != ISD::DELETED_NODE && 1327 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1328 "Node was deleted but visit returned new node!"); 1329 1330 DEBUG(dbgs() << " ... into: "; 1331 RV.getNode()->dump(&DAG)); 1332 1333 // Transfer debug value. 1334 DAG.TransferDbgValues(SDValue(N, 0), RV); 1335 if (N->getNumValues() == RV.getNode()->getNumValues()) 1336 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1337 else { 1338 assert(N->getValueType(0) == RV.getValueType() && 1339 N->getNumValues() == 1 && "Type mismatch"); 1340 SDValue OpV = RV; 1341 DAG.ReplaceAllUsesWith(N, &OpV); 1342 } 1343 1344 // Push the new node and any users onto the worklist 1345 AddToWorklist(RV.getNode()); 1346 AddUsersToWorklist(RV.getNode()); 1347 1348 // Finally, if the node is now dead, remove it from the graph. The node 1349 // may not be dead if the replacement process recursively simplified to 1350 // something else needing this node. This will also take care of adding any 1351 // operands which have lost a user to the worklist. 1352 recursivelyDeleteUnusedNodes(N); 1353 } 1354 1355 // If the root changed (e.g. it was a dead load, update the root). 1356 DAG.setRoot(Dummy.getValue()); 1357 DAG.RemoveDeadNodes(); 1358 } 1359 1360 SDValue DAGCombiner::visit(SDNode *N) { 1361 switch (N->getOpcode()) { 1362 default: break; 1363 case ISD::TokenFactor: return visitTokenFactor(N); 1364 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1365 case ISD::ADD: return visitADD(N); 1366 case ISD::SUB: return visitSUB(N); 1367 case ISD::ADDC: return visitADDC(N); 1368 case ISD::SUBC: return visitSUBC(N); 1369 case ISD::ADDE: return visitADDE(N); 1370 case ISD::SUBE: return visitSUBE(N); 1371 case ISD::MUL: return visitMUL(N); 1372 case ISD::SDIV: return visitSDIV(N); 1373 case ISD::UDIV: return visitUDIV(N); 1374 case ISD::SREM: 1375 case ISD::UREM: return visitREM(N); 1376 case ISD::MULHU: return visitMULHU(N); 1377 case ISD::MULHS: return visitMULHS(N); 1378 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1379 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1380 case ISD::SMULO: return visitSMULO(N); 1381 case ISD::UMULO: return visitUMULO(N); 1382 case ISD::SMIN: 1383 case ISD::SMAX: 1384 case ISD::UMIN: 1385 case ISD::UMAX: return visitIMINMAX(N); 1386 case ISD::AND: return visitAND(N); 1387 case ISD::OR: return visitOR(N); 1388 case ISD::XOR: return visitXOR(N); 1389 case ISD::SHL: return visitSHL(N); 1390 case ISD::SRA: return visitSRA(N); 1391 case ISD::SRL: return visitSRL(N); 1392 case ISD::ROTR: 1393 case ISD::ROTL: return visitRotate(N); 1394 case ISD::BSWAP: return visitBSWAP(N); 1395 case ISD::CTLZ: return visitCTLZ(N); 1396 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1397 case ISD::CTTZ: return visitCTTZ(N); 1398 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1399 case ISD::CTPOP: return visitCTPOP(N); 1400 case ISD::SELECT: return visitSELECT(N); 1401 case ISD::VSELECT: return visitVSELECT(N); 1402 case ISD::SELECT_CC: return visitSELECT_CC(N); 1403 case ISD::SETCC: return visitSETCC(N); 1404 case ISD::SETCCE: return visitSETCCE(N); 1405 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1406 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1407 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1408 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1409 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1410 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1411 case ISD::TRUNCATE: return visitTRUNCATE(N); 1412 case ISD::BITCAST: return visitBITCAST(N); 1413 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1414 case ISD::FADD: return visitFADD(N); 1415 case ISD::FSUB: return visitFSUB(N); 1416 case ISD::FMUL: return visitFMUL(N); 1417 case ISD::FMA: return visitFMA(N); 1418 case ISD::FDIV: return visitFDIV(N); 1419 case ISD::FREM: return visitFREM(N); 1420 case ISD::FSQRT: return visitFSQRT(N); 1421 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1422 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1423 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1424 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1425 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1426 case ISD::FP_ROUND: return visitFP_ROUND(N); 1427 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1428 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1429 case ISD::FNEG: return visitFNEG(N); 1430 case ISD::FABS: return visitFABS(N); 1431 case ISD::FFLOOR: return visitFFLOOR(N); 1432 case ISD::FMINNUM: return visitFMINNUM(N); 1433 case ISD::FMAXNUM: return visitFMAXNUM(N); 1434 case ISD::FCEIL: return visitFCEIL(N); 1435 case ISD::FTRUNC: return visitFTRUNC(N); 1436 case ISD::BRCOND: return visitBRCOND(N); 1437 case ISD::BR_CC: return visitBR_CC(N); 1438 case ISD::LOAD: return visitLOAD(N); 1439 case ISD::STORE: return visitSTORE(N); 1440 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1441 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1442 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1443 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1444 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1445 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1446 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1447 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1448 case ISD::MGATHER: return visitMGATHER(N); 1449 case ISD::MLOAD: return visitMLOAD(N); 1450 case ISD::MSCATTER: return visitMSCATTER(N); 1451 case ISD::MSTORE: return visitMSTORE(N); 1452 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1453 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1454 } 1455 return SDValue(); 1456 } 1457 1458 SDValue DAGCombiner::combine(SDNode *N) { 1459 SDValue RV = visit(N); 1460 1461 // If nothing happened, try a target-specific DAG combine. 1462 if (!RV.getNode()) { 1463 assert(N->getOpcode() != ISD::DELETED_NODE && 1464 "Node was deleted but visit returned NULL!"); 1465 1466 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1467 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1468 1469 // Expose the DAG combiner to the target combiner impls. 1470 TargetLowering::DAGCombinerInfo 1471 DagCombineInfo(DAG, Level, false, this); 1472 1473 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1474 } 1475 } 1476 1477 // If nothing happened still, try promoting the operation. 1478 if (!RV.getNode()) { 1479 switch (N->getOpcode()) { 1480 default: break; 1481 case ISD::ADD: 1482 case ISD::SUB: 1483 case ISD::MUL: 1484 case ISD::AND: 1485 case ISD::OR: 1486 case ISD::XOR: 1487 RV = PromoteIntBinOp(SDValue(N, 0)); 1488 break; 1489 case ISD::SHL: 1490 case ISD::SRA: 1491 case ISD::SRL: 1492 RV = PromoteIntShiftOp(SDValue(N, 0)); 1493 break; 1494 case ISD::SIGN_EXTEND: 1495 case ISD::ZERO_EXTEND: 1496 case ISD::ANY_EXTEND: 1497 RV = PromoteExtend(SDValue(N, 0)); 1498 break; 1499 case ISD::LOAD: 1500 if (PromoteLoad(SDValue(N, 0))) 1501 RV = SDValue(N, 0); 1502 break; 1503 } 1504 } 1505 1506 // If N is a commutative binary node, try commuting it to enable more 1507 // sdisel CSE. 1508 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1509 N->getNumValues() == 1) { 1510 SDValue N0 = N->getOperand(0); 1511 SDValue N1 = N->getOperand(1); 1512 1513 // Constant operands are canonicalized to RHS. 1514 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1515 SDValue Ops[] = {N1, N0}; 1516 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1517 N->getFlags()); 1518 if (CSENode) 1519 return SDValue(CSENode, 0); 1520 } 1521 } 1522 1523 return RV; 1524 } 1525 1526 /// Given a node, return its input chain if it has one, otherwise return a null 1527 /// sd operand. 1528 static SDValue getInputChainForNode(SDNode *N) { 1529 if (unsigned NumOps = N->getNumOperands()) { 1530 if (N->getOperand(0).getValueType() == MVT::Other) 1531 return N->getOperand(0); 1532 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1533 return N->getOperand(NumOps-1); 1534 for (unsigned i = 1; i < NumOps-1; ++i) 1535 if (N->getOperand(i).getValueType() == MVT::Other) 1536 return N->getOperand(i); 1537 } 1538 return SDValue(); 1539 } 1540 1541 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1542 // If N has two operands, where one has an input chain equal to the other, 1543 // the 'other' chain is redundant. 1544 if (N->getNumOperands() == 2) { 1545 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1546 return N->getOperand(0); 1547 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1548 return N->getOperand(1); 1549 } 1550 1551 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1552 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1553 SmallPtrSet<SDNode*, 16> SeenOps; 1554 bool Changed = false; // If we should replace this token factor. 1555 1556 // Start out with this token factor. 1557 TFs.push_back(N); 1558 1559 // Iterate through token factors. The TFs grows when new token factors are 1560 // encountered. 1561 for (unsigned i = 0; i < TFs.size(); ++i) { 1562 SDNode *TF = TFs[i]; 1563 1564 // Check each of the operands. 1565 for (const SDValue &Op : TF->op_values()) { 1566 1567 switch (Op.getOpcode()) { 1568 case ISD::EntryToken: 1569 // Entry tokens don't need to be added to the list. They are 1570 // redundant. 1571 Changed = true; 1572 break; 1573 1574 case ISD::TokenFactor: 1575 if (Op.hasOneUse() && 1576 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1577 // Queue up for processing. 1578 TFs.push_back(Op.getNode()); 1579 // Clean up in case the token factor is removed. 1580 AddToWorklist(Op.getNode()); 1581 Changed = true; 1582 break; 1583 } 1584 // Fall thru 1585 1586 default: 1587 // Only add if it isn't already in the list. 1588 if (SeenOps.insert(Op.getNode()).second) 1589 Ops.push_back(Op); 1590 else 1591 Changed = true; 1592 break; 1593 } 1594 } 1595 } 1596 1597 SDValue Result; 1598 1599 // If we've changed things around then replace token factor. 1600 if (Changed) { 1601 if (Ops.empty()) { 1602 // The entry token is the only possible outcome. 1603 Result = DAG.getEntryNode(); 1604 } else { 1605 // New and improved token factor. 1606 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1607 } 1608 1609 // Add users to worklist if AA is enabled, since it may introduce 1610 // a lot of new chained token factors while removing memory deps. 1611 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1612 : DAG.getSubtarget().useAA(); 1613 return CombineTo(N, Result, UseAA /*add to worklist*/); 1614 } 1615 1616 return Result; 1617 } 1618 1619 /// MERGE_VALUES can always be eliminated. 1620 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1621 WorklistRemover DeadNodes(*this); 1622 // Replacing results may cause a different MERGE_VALUES to suddenly 1623 // be CSE'd with N, and carry its uses with it. Iterate until no 1624 // uses remain, to ensure that the node can be safely deleted. 1625 // First add the users of this node to the work list so that they 1626 // can be tried again once they have new operands. 1627 AddUsersToWorklist(N); 1628 do { 1629 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1630 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1631 } while (!N->use_empty()); 1632 deleteAndRecombine(N); 1633 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1634 } 1635 1636 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1637 /// ConstantSDNode pointer else nullptr. 1638 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1639 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1640 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1641 } 1642 1643 SDValue DAGCombiner::visitADD(SDNode *N) { 1644 SDValue N0 = N->getOperand(0); 1645 SDValue N1 = N->getOperand(1); 1646 EVT VT = N0.getValueType(); 1647 1648 // fold vector ops 1649 if (VT.isVector()) { 1650 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1651 return FoldedVOp; 1652 1653 // fold (add x, 0) -> x, vector edition 1654 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1655 return N0; 1656 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1657 return N1; 1658 } 1659 1660 // fold (add x, undef) -> undef 1661 if (N0.isUndef()) 1662 return N0; 1663 if (N1.isUndef()) 1664 return N1; 1665 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1666 // canonicalize constant to RHS 1667 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 1668 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1669 // fold (add c1, c2) -> c1+c2 1670 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, 1671 N0.getNode(), N1.getNode()); 1672 } 1673 // fold (add x, 0) -> x 1674 if (isNullConstant(N1)) 1675 return N0; 1676 // fold ((c1-A)+c2) -> (c1+c2)-A 1677 if (ConstantSDNode *N1C = getAsNonOpaqueConstant(N1)) { 1678 if (N0.getOpcode() == ISD::SUB) 1679 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) { 1680 SDLoc DL(N); 1681 return DAG.getNode(ISD::SUB, DL, VT, 1682 DAG.getConstant(N1C->getAPIntValue()+ 1683 N0C->getAPIntValue(), DL, VT), 1684 N0.getOperand(1)); 1685 } 1686 } 1687 // reassociate add 1688 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1689 return RADD; 1690 // fold ((0-A) + B) -> B-A 1691 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1692 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1693 // fold (A + (0-B)) -> A-B 1694 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1695 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1696 // fold (A+(B-A)) -> B 1697 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1698 return N1.getOperand(0); 1699 // fold ((B-A)+A) -> B 1700 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1701 return N0.getOperand(0); 1702 // fold (A+(B-(A+C))) to (B-C) 1703 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1704 N0 == N1.getOperand(1).getOperand(0)) 1705 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1706 N1.getOperand(1).getOperand(1)); 1707 // fold (A+(B-(C+A))) to (B-C) 1708 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1709 N0 == N1.getOperand(1).getOperand(1)) 1710 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1711 N1.getOperand(1).getOperand(0)); 1712 // fold (A+((B-A)+or-C)) to (B+or-C) 1713 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1714 N1.getOperand(0).getOpcode() == ISD::SUB && 1715 N0 == N1.getOperand(0).getOperand(1)) 1716 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1717 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1718 1719 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1720 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1721 SDValue N00 = N0.getOperand(0); 1722 SDValue N01 = N0.getOperand(1); 1723 SDValue N10 = N1.getOperand(0); 1724 SDValue N11 = N1.getOperand(1); 1725 1726 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1727 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1728 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1729 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1730 } 1731 1732 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1733 return SDValue(N, 0); 1734 1735 // fold (a+b) -> (a|b) iff a and b share no bits. 1736 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::OR, VT)) && 1737 VT.isInteger() && !VT.isVector() && DAG.haveNoCommonBitsSet(N0, N1)) 1738 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1739 1740 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1741 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1742 isNullConstant(N1.getOperand(0).getOperand(0))) 1743 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1744 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1745 N1.getOperand(0).getOperand(1), 1746 N1.getOperand(1))); 1747 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1748 isNullConstant(N0.getOperand(0).getOperand(0))) 1749 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1750 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1751 N0.getOperand(0).getOperand(1), 1752 N0.getOperand(1))); 1753 1754 if (N1.getOpcode() == ISD::AND) { 1755 SDValue AndOp0 = N1.getOperand(0); 1756 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1757 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1758 1759 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1760 // and similar xforms where the inner op is either ~0 or 0. 1761 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1762 SDLoc DL(N); 1763 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1764 } 1765 } 1766 1767 // add (sext i1), X -> sub X, (zext i1) 1768 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1769 N0.getOperand(0).getValueType() == MVT::i1 && 1770 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1771 SDLoc DL(N); 1772 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1773 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1774 } 1775 1776 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1777 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1778 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1779 if (TN->getVT() == MVT::i1) { 1780 SDLoc DL(N); 1781 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1782 DAG.getConstant(1, DL, VT)); 1783 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1784 } 1785 } 1786 1787 return SDValue(); 1788 } 1789 1790 SDValue DAGCombiner::visitADDC(SDNode *N) { 1791 SDValue N0 = N->getOperand(0); 1792 SDValue N1 = N->getOperand(1); 1793 EVT VT = N0.getValueType(); 1794 1795 // If the flag result is dead, turn this into an ADD. 1796 if (!N->hasAnyUseOfValue(1)) 1797 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1798 DAG.getNode(ISD::CARRY_FALSE, 1799 SDLoc(N), MVT::Glue)); 1800 1801 // canonicalize constant to RHS. 1802 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1803 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1804 if (N0C && !N1C) 1805 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1806 1807 // fold (addc x, 0) -> x + no carry out 1808 if (isNullConstant(N1)) 1809 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1810 SDLoc(N), MVT::Glue)); 1811 1812 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1813 APInt LHSZero, LHSOne; 1814 APInt RHSZero, RHSOne; 1815 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1816 1817 if (LHSZero.getBoolValue()) { 1818 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1819 1820 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1821 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1822 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1823 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1824 DAG.getNode(ISD::CARRY_FALSE, 1825 SDLoc(N), MVT::Glue)); 1826 } 1827 1828 return SDValue(); 1829 } 1830 1831 SDValue DAGCombiner::visitADDE(SDNode *N) { 1832 SDValue N0 = N->getOperand(0); 1833 SDValue N1 = N->getOperand(1); 1834 SDValue CarryIn = N->getOperand(2); 1835 1836 // canonicalize constant to RHS 1837 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1838 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1839 if (N0C && !N1C) 1840 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1841 N1, N0, CarryIn); 1842 1843 // fold (adde x, y, false) -> (addc x, y) 1844 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1845 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1846 1847 return SDValue(); 1848 } 1849 1850 // Since it may not be valid to emit a fold to zero for vector initializers 1851 // check if we can before folding. 1852 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1853 SelectionDAG &DAG, 1854 bool LegalOperations, bool LegalTypes) { 1855 if (!VT.isVector()) 1856 return DAG.getConstant(0, DL, VT); 1857 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1858 return DAG.getConstant(0, DL, VT); 1859 return SDValue(); 1860 } 1861 1862 SDValue DAGCombiner::visitSUB(SDNode *N) { 1863 SDValue N0 = N->getOperand(0); 1864 SDValue N1 = N->getOperand(1); 1865 EVT VT = N0.getValueType(); 1866 1867 // fold vector ops 1868 if (VT.isVector()) { 1869 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1870 return FoldedVOp; 1871 1872 // fold (sub x, 0) -> x, vector edition 1873 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1874 return N0; 1875 } 1876 1877 // fold (sub x, x) -> 0 1878 // FIXME: Refactor this and xor and other similar operations together. 1879 if (N0 == N1) 1880 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1881 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 1882 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1883 // fold (sub c1, c2) -> c1-c2 1884 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, 1885 N0.getNode(), N1.getNode()); 1886 } 1887 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 1888 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 1889 // fold (sub x, c) -> (add x, -c) 1890 if (N1C) { 1891 SDLoc DL(N); 1892 return DAG.getNode(ISD::ADD, DL, VT, N0, 1893 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1894 } 1895 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1896 if (isAllOnesConstant(N0)) 1897 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1898 // fold A-(A-B) -> B 1899 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1900 return N1.getOperand(1); 1901 // fold (A+B)-A -> B 1902 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1903 return N0.getOperand(1); 1904 // fold (A+B)-B -> A 1905 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1906 return N0.getOperand(0); 1907 // fold C2-(A+C1) -> (C2-C1)-A 1908 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1909 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1910 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1911 SDLoc DL(N); 1912 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1913 DL, VT); 1914 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1915 N1.getOperand(0)); 1916 } 1917 // fold ((A+(B+or-C))-B) -> A+or-C 1918 if (N0.getOpcode() == ISD::ADD && 1919 (N0.getOperand(1).getOpcode() == ISD::SUB || 1920 N0.getOperand(1).getOpcode() == ISD::ADD) && 1921 N0.getOperand(1).getOperand(0) == N1) 1922 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1923 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1924 // fold ((A+(C+B))-B) -> A+C 1925 if (N0.getOpcode() == ISD::ADD && 1926 N0.getOperand(1).getOpcode() == ISD::ADD && 1927 N0.getOperand(1).getOperand(1) == N1) 1928 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1929 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1930 // fold ((A-(B-C))-C) -> A-B 1931 if (N0.getOpcode() == ISD::SUB && 1932 N0.getOperand(1).getOpcode() == ISD::SUB && 1933 N0.getOperand(1).getOperand(1) == N1) 1934 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1935 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1936 1937 // If either operand of a sub is undef, the result is undef 1938 if (N0.isUndef()) 1939 return N0; 1940 if (N1.isUndef()) 1941 return N1; 1942 1943 // If the relocation model supports it, consider symbol offsets. 1944 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1945 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1946 // fold (sub Sym, c) -> Sym-c 1947 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1948 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1949 GA->getOffset() - 1950 (uint64_t)N1C->getSExtValue()); 1951 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1952 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1953 if (GA->getGlobal() == GB->getGlobal()) 1954 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1955 SDLoc(N), VT); 1956 } 1957 1958 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1959 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1960 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1961 if (TN->getVT() == MVT::i1) { 1962 SDLoc DL(N); 1963 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1964 DAG.getConstant(1, DL, VT)); 1965 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1966 } 1967 } 1968 1969 return SDValue(); 1970 } 1971 1972 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1973 SDValue N0 = N->getOperand(0); 1974 SDValue N1 = N->getOperand(1); 1975 EVT VT = N0.getValueType(); 1976 SDLoc DL(N); 1977 1978 // If the flag result is dead, turn this into an SUB. 1979 if (!N->hasAnyUseOfValue(1)) 1980 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 1981 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1982 1983 // fold (subc x, x) -> 0 + no borrow 1984 if (N0 == N1) 1985 return CombineTo(N, DAG.getConstant(0, DL, VT), 1986 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1987 1988 // fold (subc x, 0) -> x + no borrow 1989 if (isNullConstant(N1)) 1990 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1991 1992 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1993 if (isAllOnesConstant(N0)) 1994 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 1995 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 1996 1997 return SDValue(); 1998 } 1999 2000 SDValue DAGCombiner::visitSUBE(SDNode *N) { 2001 SDValue N0 = N->getOperand(0); 2002 SDValue N1 = N->getOperand(1); 2003 SDValue CarryIn = N->getOperand(2); 2004 2005 // fold (sube x, y, false) -> (subc x, y) 2006 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2007 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 2008 2009 return SDValue(); 2010 } 2011 2012 SDValue DAGCombiner::visitMUL(SDNode *N) { 2013 SDValue N0 = N->getOperand(0); 2014 SDValue N1 = N->getOperand(1); 2015 EVT VT = N0.getValueType(); 2016 2017 // fold (mul x, undef) -> 0 2018 if (N0.isUndef() || N1.isUndef()) 2019 return DAG.getConstant(0, SDLoc(N), VT); 2020 2021 bool N0IsConst = false; 2022 bool N1IsConst = false; 2023 bool N1IsOpaqueConst = false; 2024 bool N0IsOpaqueConst = false; 2025 APInt ConstValue0, ConstValue1; 2026 // fold vector ops 2027 if (VT.isVector()) { 2028 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2029 return FoldedVOp; 2030 2031 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2032 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2033 } else { 2034 N0IsConst = isa<ConstantSDNode>(N0); 2035 if (N0IsConst) { 2036 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2037 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 2038 } 2039 N1IsConst = isa<ConstantSDNode>(N1); 2040 if (N1IsConst) { 2041 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2042 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 2043 } 2044 } 2045 2046 // fold (mul c1, c2) -> c1*c2 2047 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 2048 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2049 N0.getNode(), N1.getNode()); 2050 2051 // canonicalize constant to RHS (vector doesn't have to splat) 2052 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2053 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2054 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2055 // fold (mul x, 0) -> 0 2056 if (N1IsConst && ConstValue1 == 0) 2057 return N1; 2058 // We require a splat of the entire scalar bit width for non-contiguous 2059 // bit patterns. 2060 bool IsFullSplat = 2061 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2062 // fold (mul x, 1) -> x 2063 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2064 return N0; 2065 // fold (mul x, -1) -> 0-x 2066 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2067 SDLoc DL(N); 2068 return DAG.getNode(ISD::SUB, DL, VT, 2069 DAG.getConstant(0, DL, VT), N0); 2070 } 2071 // fold (mul x, (1 << c)) -> x << c 2072 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() && 2073 IsFullSplat) { 2074 SDLoc DL(N); 2075 return DAG.getNode(ISD::SHL, DL, VT, N0, 2076 DAG.getConstant(ConstValue1.logBase2(), DL, 2077 getShiftAmountTy(N0.getValueType()))); 2078 } 2079 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2080 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() && 2081 IsFullSplat) { 2082 unsigned Log2Val = (-ConstValue1).logBase2(); 2083 SDLoc DL(N); 2084 // FIXME: If the input is something that is easily negated (e.g. a 2085 // single-use add), we should put the negate there. 2086 return DAG.getNode(ISD::SUB, DL, VT, 2087 DAG.getConstant(0, DL, VT), 2088 DAG.getNode(ISD::SHL, DL, VT, N0, 2089 DAG.getConstant(Log2Val, DL, 2090 getShiftAmountTy(N0.getValueType())))); 2091 } 2092 2093 APInt Val; 2094 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2095 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2096 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2097 isa<ConstantSDNode>(N0.getOperand(1)))) { 2098 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2099 N1, N0.getOperand(1)); 2100 AddToWorklist(C3.getNode()); 2101 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2102 N0.getOperand(0), C3); 2103 } 2104 2105 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2106 // use. 2107 { 2108 SDValue Sh(nullptr,0), Y(nullptr,0); 2109 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2110 if (N0.getOpcode() == ISD::SHL && 2111 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2112 isa<ConstantSDNode>(N0.getOperand(1))) && 2113 N0.getNode()->hasOneUse()) { 2114 Sh = N0; Y = N1; 2115 } else if (N1.getOpcode() == ISD::SHL && 2116 isa<ConstantSDNode>(N1.getOperand(1)) && 2117 N1.getNode()->hasOneUse()) { 2118 Sh = N1; Y = N0; 2119 } 2120 2121 if (Sh.getNode()) { 2122 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2123 Sh.getOperand(0), Y); 2124 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2125 Mul, Sh.getOperand(1)); 2126 } 2127 } 2128 2129 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2130 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 2131 N0.getOpcode() == ISD::ADD && 2132 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 2133 isMulAddWithConstProfitable(N, N0, N1)) 2134 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2135 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2136 N0.getOperand(0), N1), 2137 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2138 N0.getOperand(1), N1)); 2139 2140 // reassociate mul 2141 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2142 return RMUL; 2143 2144 return SDValue(); 2145 } 2146 2147 /// Return true if divmod libcall is available. 2148 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 2149 const TargetLowering &TLI) { 2150 RTLIB::Libcall LC; 2151 EVT NodeType = Node->getValueType(0); 2152 if (!NodeType.isSimple()) 2153 return false; 2154 switch (NodeType.getSimpleVT().SimpleTy) { 2155 default: return false; // No libcall for vector types. 2156 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 2157 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 2158 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 2159 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 2160 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 2161 } 2162 2163 return TLI.getLibcallName(LC) != nullptr; 2164 } 2165 2166 /// Issue divrem if both quotient and remainder are needed. 2167 SDValue DAGCombiner::useDivRem(SDNode *Node) { 2168 if (Node->use_empty()) 2169 return SDValue(); // This is a dead node, leave it alone. 2170 2171 unsigned Opcode = Node->getOpcode(); 2172 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 2173 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 2174 2175 // DivMod lib calls can still work on non-legal types if using lib-calls. 2176 EVT VT = Node->getValueType(0); 2177 if (VT.isVector() || !VT.isInteger()) 2178 return SDValue(); 2179 2180 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 2181 return SDValue(); 2182 2183 // If DIVREM is going to get expanded into a libcall, 2184 // but there is no libcall available, then don't combine. 2185 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 2186 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 2187 return SDValue(); 2188 2189 // If div is legal, it's better to do the normal expansion 2190 unsigned OtherOpcode = 0; 2191 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 2192 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 2193 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 2194 return SDValue(); 2195 } else { 2196 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2197 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 2198 return SDValue(); 2199 } 2200 2201 SDValue Op0 = Node->getOperand(0); 2202 SDValue Op1 = Node->getOperand(1); 2203 SDValue combined; 2204 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 2205 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 2206 SDNode *User = *UI; 2207 if (User == Node || User->use_empty()) 2208 continue; 2209 // Convert the other matching node(s), too; 2210 // otherwise, the DIVREM may get target-legalized into something 2211 // target-specific that we won't be able to recognize. 2212 unsigned UserOpc = User->getOpcode(); 2213 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 2214 User->getOperand(0) == Op0 && 2215 User->getOperand(1) == Op1) { 2216 if (!combined) { 2217 if (UserOpc == OtherOpcode) { 2218 SDVTList VTs = DAG.getVTList(VT, VT); 2219 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 2220 } else if (UserOpc == DivRemOpc) { 2221 combined = SDValue(User, 0); 2222 } else { 2223 assert(UserOpc == Opcode); 2224 continue; 2225 } 2226 } 2227 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 2228 CombineTo(User, combined); 2229 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 2230 CombineTo(User, combined.getValue(1)); 2231 } 2232 } 2233 return combined; 2234 } 2235 2236 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2237 SDValue N0 = N->getOperand(0); 2238 SDValue N1 = N->getOperand(1); 2239 EVT VT = N->getValueType(0); 2240 2241 // fold vector ops 2242 if (VT.isVector()) 2243 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2244 return FoldedVOp; 2245 2246 SDLoc DL(N); 2247 2248 // fold (sdiv c1, c2) -> c1/c2 2249 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2250 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2251 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 2252 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 2253 // fold (sdiv X, 1) -> X 2254 if (N1C && N1C->isOne()) 2255 return N0; 2256 // fold (sdiv X, -1) -> 0-X 2257 if (N1C && N1C->isAllOnesValue()) 2258 return DAG.getNode(ISD::SUB, DL, VT, 2259 DAG.getConstant(0, DL, VT), N0); 2260 2261 // If we know the sign bits of both operands are zero, strength reduce to a 2262 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2263 if (!VT.isVector()) { 2264 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2265 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 2266 } 2267 2268 // fold (sdiv X, pow2) -> simple ops after legalize 2269 // FIXME: We check for the exact bit here because the generic lowering gives 2270 // better results in that case. The target-specific lowering should learn how 2271 // to handle exact sdivs efficiently. 2272 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2273 !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() && 2274 (N1C->getAPIntValue().isPowerOf2() || 2275 (-N1C->getAPIntValue()).isPowerOf2())) { 2276 // Target-specific implementation of sdiv x, pow2. 2277 if (SDValue Res = BuildSDIVPow2(N)) 2278 return Res; 2279 2280 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2281 2282 // Splat the sign bit into the register 2283 SDValue SGN = 2284 DAG.getNode(ISD::SRA, DL, VT, N0, 2285 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2286 getShiftAmountTy(N0.getValueType()))); 2287 AddToWorklist(SGN.getNode()); 2288 2289 // Add (N0 < 0) ? abs2 - 1 : 0; 2290 SDValue SRL = 2291 DAG.getNode(ISD::SRL, DL, VT, SGN, 2292 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2293 getShiftAmountTy(SGN.getValueType()))); 2294 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2295 AddToWorklist(SRL.getNode()); 2296 AddToWorklist(ADD.getNode()); // Divide by pow2 2297 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2298 DAG.getConstant(lg2, DL, 2299 getShiftAmountTy(ADD.getValueType()))); 2300 2301 // If we're dividing by a positive value, we're done. Otherwise, we must 2302 // negate the result. 2303 if (N1C->getAPIntValue().isNonNegative()) 2304 return SRA; 2305 2306 AddToWorklist(SRA.getNode()); 2307 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2308 } 2309 2310 // If integer divide is expensive and we satisfy the requirements, emit an 2311 // alternate sequence. Targets may check function attributes for size/speed 2312 // trade-offs. 2313 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2314 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2315 if (SDValue Op = BuildSDIV(N)) 2316 return Op; 2317 2318 // sdiv, srem -> sdivrem 2319 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2320 // Otherwise, we break the simplification logic in visitREM(). 2321 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2322 if (SDValue DivRem = useDivRem(N)) 2323 return DivRem; 2324 2325 // undef / X -> 0 2326 if (N0.isUndef()) 2327 return DAG.getConstant(0, DL, VT); 2328 // X / undef -> undef 2329 if (N1.isUndef()) 2330 return N1; 2331 2332 return SDValue(); 2333 } 2334 2335 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2336 SDValue N0 = N->getOperand(0); 2337 SDValue N1 = N->getOperand(1); 2338 EVT VT = N->getValueType(0); 2339 2340 // fold vector ops 2341 if (VT.isVector()) 2342 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2343 return FoldedVOp; 2344 2345 SDLoc DL(N); 2346 2347 // fold (udiv c1, c2) -> c1/c2 2348 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2349 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2350 if (N0C && N1C) 2351 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 2352 N0C, N1C)) 2353 return Folded; 2354 // fold (udiv x, (1 << c)) -> x >>u c 2355 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) 2356 return DAG.getNode(ISD::SRL, DL, VT, N0, 2357 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2358 getShiftAmountTy(N0.getValueType()))); 2359 2360 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2361 if (N1.getOpcode() == ISD::SHL) { 2362 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2363 if (SHC->getAPIntValue().isPowerOf2()) { 2364 EVT ADDVT = N1.getOperand(1).getValueType(); 2365 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2366 N1.getOperand(1), 2367 DAG.getConstant(SHC->getAPIntValue() 2368 .logBase2(), 2369 DL, ADDVT)); 2370 AddToWorklist(Add.getNode()); 2371 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2372 } 2373 } 2374 } 2375 2376 // fold (udiv x, c) -> alternate 2377 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2378 if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr)) 2379 if (SDValue Op = BuildUDIV(N)) 2380 return Op; 2381 2382 // sdiv, srem -> sdivrem 2383 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is true. 2384 // Otherwise, we break the simplification logic in visitREM(). 2385 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 2386 if (SDValue DivRem = useDivRem(N)) 2387 return DivRem; 2388 2389 // undef / X -> 0 2390 if (N0.isUndef()) 2391 return DAG.getConstant(0, DL, VT); 2392 // X / undef -> undef 2393 if (N1.isUndef()) 2394 return N1; 2395 2396 return SDValue(); 2397 } 2398 2399 // handles ISD::SREM and ISD::UREM 2400 SDValue DAGCombiner::visitREM(SDNode *N) { 2401 unsigned Opcode = N->getOpcode(); 2402 SDValue N0 = N->getOperand(0); 2403 SDValue N1 = N->getOperand(1); 2404 EVT VT = N->getValueType(0); 2405 bool isSigned = (Opcode == ISD::SREM); 2406 SDLoc DL(N); 2407 2408 // fold (rem c1, c2) -> c1%c2 2409 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2410 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2411 if (N0C && N1C) 2412 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 2413 return Folded; 2414 2415 if (isSigned) { 2416 // If we know the sign bits of both operands are zero, strength reduce to a 2417 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2418 if (!VT.isVector()) { 2419 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2420 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 2421 } 2422 } else { 2423 // fold (urem x, pow2) -> (and x, pow2-1) 2424 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() && 2425 N1C->getAPIntValue().isPowerOf2()) { 2426 return DAG.getNode(ISD::AND, DL, VT, N0, 2427 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2428 } 2429 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2430 if (N1.getOpcode() == ISD::SHL) { 2431 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) { 2432 if (SHC->getAPIntValue().isPowerOf2()) { 2433 SDValue Add = 2434 DAG.getNode(ISD::ADD, DL, VT, N1, 2435 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2436 VT)); 2437 AddToWorklist(Add.getNode()); 2438 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2439 } 2440 } 2441 } 2442 } 2443 2444 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2445 2446 // If X/C can be simplified by the division-by-constant logic, lower 2447 // X%C to the equivalent of X-X/C*C. 2448 // To avoid mangling nodes, this simplification requires that the combine() 2449 // call for the speculative DIV must not cause a DIVREM conversion. We guard 2450 // against this by skipping the simplification if isIntDivCheap(). When 2451 // div is not cheap, combine will not return a DIVREM. Regardless, 2452 // checking cheapness here makes sense since the simplification results in 2453 // fatter code. 2454 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) { 2455 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 2456 SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1); 2457 AddToWorklist(Div.getNode()); 2458 SDValue OptimizedDiv = combine(Div.getNode()); 2459 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2460 assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) && 2461 (OptimizedDiv.getOpcode() != ISD::SDIVREM)); 2462 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 2463 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 2464 AddToWorklist(Mul.getNode()); 2465 return Sub; 2466 } 2467 } 2468 2469 // sdiv, srem -> sdivrem 2470 if (SDValue DivRem = useDivRem(N)) 2471 return DivRem.getValue(1); 2472 2473 // undef % X -> 0 2474 if (N0.isUndef()) 2475 return DAG.getConstant(0, DL, VT); 2476 // X % undef -> undef 2477 if (N1.isUndef()) 2478 return N1; 2479 2480 return SDValue(); 2481 } 2482 2483 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2484 SDValue N0 = N->getOperand(0); 2485 SDValue N1 = N->getOperand(1); 2486 EVT VT = N->getValueType(0); 2487 SDLoc DL(N); 2488 2489 // fold (mulhs x, 0) -> 0 2490 if (isNullConstant(N1)) 2491 return N1; 2492 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2493 if (isOneConstant(N1)) { 2494 SDLoc DL(N); 2495 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2496 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2497 DL, 2498 getShiftAmountTy(N0.getValueType()))); 2499 } 2500 // fold (mulhs x, undef) -> 0 2501 if (N0.isUndef() || N1.isUndef()) 2502 return DAG.getConstant(0, SDLoc(N), VT); 2503 2504 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2505 // plus a shift. 2506 if (VT.isSimple() && !VT.isVector()) { 2507 MVT Simple = VT.getSimpleVT(); 2508 unsigned SimpleSize = Simple.getSizeInBits(); 2509 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2510 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2511 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2512 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2513 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2514 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2515 DAG.getConstant(SimpleSize, DL, 2516 getShiftAmountTy(N1.getValueType()))); 2517 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2518 } 2519 } 2520 2521 return SDValue(); 2522 } 2523 2524 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2525 SDValue N0 = N->getOperand(0); 2526 SDValue N1 = N->getOperand(1); 2527 EVT VT = N->getValueType(0); 2528 SDLoc DL(N); 2529 2530 // fold (mulhu x, 0) -> 0 2531 if (isNullConstant(N1)) 2532 return N1; 2533 // fold (mulhu x, 1) -> 0 2534 if (isOneConstant(N1)) 2535 return DAG.getConstant(0, DL, N0.getValueType()); 2536 // fold (mulhu x, undef) -> 0 2537 if (N0.isUndef() || N1.isUndef()) 2538 return DAG.getConstant(0, DL, VT); 2539 2540 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2541 // plus a shift. 2542 if (VT.isSimple() && !VT.isVector()) { 2543 MVT Simple = VT.getSimpleVT(); 2544 unsigned SimpleSize = Simple.getSizeInBits(); 2545 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2546 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2547 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2548 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2549 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2550 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2551 DAG.getConstant(SimpleSize, DL, 2552 getShiftAmountTy(N1.getValueType()))); 2553 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2554 } 2555 } 2556 2557 return SDValue(); 2558 } 2559 2560 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2561 /// give the opcodes for the two computations that are being performed. Return 2562 /// true if a simplification was made. 2563 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2564 unsigned HiOp) { 2565 // If the high half is not needed, just compute the low half. 2566 bool HiExists = N->hasAnyUseOfValue(1); 2567 if (!HiExists && 2568 (!LegalOperations || 2569 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2570 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2571 return CombineTo(N, Res, Res); 2572 } 2573 2574 // If the low half is not needed, just compute the high half. 2575 bool LoExists = N->hasAnyUseOfValue(0); 2576 if (!LoExists && 2577 (!LegalOperations || 2578 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2579 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2580 return CombineTo(N, Res, Res); 2581 } 2582 2583 // If both halves are used, return as it is. 2584 if (LoExists && HiExists) 2585 return SDValue(); 2586 2587 // If the two computed results can be simplified separately, separate them. 2588 if (LoExists) { 2589 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2590 AddToWorklist(Lo.getNode()); 2591 SDValue LoOpt = combine(Lo.getNode()); 2592 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2593 (!LegalOperations || 2594 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2595 return CombineTo(N, LoOpt, LoOpt); 2596 } 2597 2598 if (HiExists) { 2599 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2600 AddToWorklist(Hi.getNode()); 2601 SDValue HiOpt = combine(Hi.getNode()); 2602 if (HiOpt.getNode() && HiOpt != Hi && 2603 (!LegalOperations || 2604 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2605 return CombineTo(N, HiOpt, HiOpt); 2606 } 2607 2608 return SDValue(); 2609 } 2610 2611 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2612 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 2613 return Res; 2614 2615 EVT VT = N->getValueType(0); 2616 SDLoc DL(N); 2617 2618 // If the type is twice as wide is legal, transform the mulhu to a wider 2619 // multiply plus a shift. 2620 if (VT.isSimple() && !VT.isVector()) { 2621 MVT Simple = VT.getSimpleVT(); 2622 unsigned SimpleSize = Simple.getSizeInBits(); 2623 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2624 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2625 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2626 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2627 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2628 // Compute the high part as N1. 2629 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2630 DAG.getConstant(SimpleSize, DL, 2631 getShiftAmountTy(Lo.getValueType()))); 2632 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2633 // Compute the low part as N0. 2634 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2635 return CombineTo(N, Lo, Hi); 2636 } 2637 } 2638 2639 return SDValue(); 2640 } 2641 2642 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2643 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 2644 return Res; 2645 2646 EVT VT = N->getValueType(0); 2647 SDLoc DL(N); 2648 2649 // If the type is twice as wide is legal, transform the mulhu to a wider 2650 // multiply plus a shift. 2651 if (VT.isSimple() && !VT.isVector()) { 2652 MVT Simple = VT.getSimpleVT(); 2653 unsigned SimpleSize = Simple.getSizeInBits(); 2654 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2655 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2656 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2657 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2658 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2659 // Compute the high part as N1. 2660 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2661 DAG.getConstant(SimpleSize, DL, 2662 getShiftAmountTy(Lo.getValueType()))); 2663 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2664 // Compute the low part as N0. 2665 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2666 return CombineTo(N, Lo, Hi); 2667 } 2668 } 2669 2670 return SDValue(); 2671 } 2672 2673 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2674 // (smulo x, 2) -> (saddo x, x) 2675 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2676 if (C2->getAPIntValue() == 2) 2677 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2678 N->getOperand(0), N->getOperand(0)); 2679 2680 return SDValue(); 2681 } 2682 2683 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2684 // (umulo x, 2) -> (uaddo x, x) 2685 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2686 if (C2->getAPIntValue() == 2) 2687 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2688 N->getOperand(0), N->getOperand(0)); 2689 2690 return SDValue(); 2691 } 2692 2693 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 2694 SDValue N0 = N->getOperand(0); 2695 SDValue N1 = N->getOperand(1); 2696 EVT VT = N0.getValueType(); 2697 2698 // fold vector ops 2699 if (VT.isVector()) 2700 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2701 return FoldedVOp; 2702 2703 // fold (add c1, c2) -> c1+c2 2704 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 2705 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2706 if (N0C && N1C) 2707 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 2708 2709 // canonicalize constant to RHS 2710 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2711 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2712 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 2713 2714 return SDValue(); 2715 } 2716 2717 /// If this is a binary operator with two operands of the same opcode, try to 2718 /// simplify it. 2719 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2720 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2721 EVT VT = N0.getValueType(); 2722 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2723 2724 // Bail early if none of these transforms apply. 2725 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2726 2727 // For each of OP in AND/OR/XOR: 2728 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2729 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2730 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2731 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2732 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2733 // 2734 // do not sink logical op inside of a vector extend, since it may combine 2735 // into a vsetcc. 2736 EVT Op0VT = N0.getOperand(0).getValueType(); 2737 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2738 N0.getOpcode() == ISD::SIGN_EXTEND || 2739 N0.getOpcode() == ISD::BSWAP || 2740 // Avoid infinite looping with PromoteIntBinOp. 2741 (N0.getOpcode() == ISD::ANY_EXTEND && 2742 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2743 (N0.getOpcode() == ISD::TRUNCATE && 2744 (!TLI.isZExtFree(VT, Op0VT) || 2745 !TLI.isTruncateFree(Op0VT, VT)) && 2746 TLI.isTypeLegal(Op0VT))) && 2747 !VT.isVector() && 2748 Op0VT == N1.getOperand(0).getValueType() && 2749 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2750 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2751 N0.getOperand(0).getValueType(), 2752 N0.getOperand(0), N1.getOperand(0)); 2753 AddToWorklist(ORNode.getNode()); 2754 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2755 } 2756 2757 // For each of OP in SHL/SRL/SRA/AND... 2758 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2759 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2760 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2761 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2762 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2763 N0.getOperand(1) == N1.getOperand(1)) { 2764 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2765 N0.getOperand(0).getValueType(), 2766 N0.getOperand(0), N1.getOperand(0)); 2767 AddToWorklist(ORNode.getNode()); 2768 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2769 ORNode, N0.getOperand(1)); 2770 } 2771 2772 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2773 // Only perform this optimization up until type legalization, before 2774 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2775 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2776 // we don't want to undo this promotion. 2777 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2778 // on scalars. 2779 if ((N0.getOpcode() == ISD::BITCAST || 2780 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2781 Level <= AfterLegalizeTypes) { 2782 SDValue In0 = N0.getOperand(0); 2783 SDValue In1 = N1.getOperand(0); 2784 EVT In0Ty = In0.getValueType(); 2785 EVT In1Ty = In1.getValueType(); 2786 SDLoc DL(N); 2787 // If both incoming values are integers, and the original types are the 2788 // same. 2789 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2790 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2791 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2792 AddToWorklist(Op.getNode()); 2793 return BC; 2794 } 2795 } 2796 2797 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2798 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2799 // If both shuffles use the same mask, and both shuffle within a single 2800 // vector, then it is worthwhile to move the swizzle after the operation. 2801 // The type-legalizer generates this pattern when loading illegal 2802 // vector types from memory. In many cases this allows additional shuffle 2803 // optimizations. 2804 // There are other cases where moving the shuffle after the xor/and/or 2805 // is profitable even if shuffles don't perform a swizzle. 2806 // If both shuffles use the same mask, and both shuffles have the same first 2807 // or second operand, then it might still be profitable to move the shuffle 2808 // after the xor/and/or operation. 2809 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2810 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2811 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2812 2813 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2814 "Inputs to shuffles are not the same type"); 2815 2816 // Check that both shuffles use the same mask. The masks are known to be of 2817 // the same length because the result vector type is the same. 2818 // Check also that shuffles have only one use to avoid introducing extra 2819 // instructions. 2820 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2821 SVN0->getMask().equals(SVN1->getMask())) { 2822 SDValue ShOp = N0->getOperand(1); 2823 2824 // Don't try to fold this node if it requires introducing a 2825 // build vector of all zeros that might be illegal at this stage. 2826 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2827 if (!LegalTypes) 2828 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2829 else 2830 ShOp = SDValue(); 2831 } 2832 2833 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2834 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2835 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2836 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2837 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2838 N0->getOperand(0), N1->getOperand(0)); 2839 AddToWorklist(NewNode.getNode()); 2840 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2841 &SVN0->getMask()[0]); 2842 } 2843 2844 // Don't try to fold this node if it requires introducing a 2845 // build vector of all zeros that might be illegal at this stage. 2846 ShOp = N0->getOperand(0); 2847 if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) { 2848 if (!LegalTypes) 2849 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2850 else 2851 ShOp = SDValue(); 2852 } 2853 2854 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2855 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2856 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2857 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2858 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2859 N0->getOperand(1), N1->getOperand(1)); 2860 AddToWorklist(NewNode.getNode()); 2861 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2862 &SVN0->getMask()[0]); 2863 } 2864 } 2865 } 2866 2867 return SDValue(); 2868 } 2869 2870 /// This contains all DAGCombine rules which reduce two values combined by 2871 /// an And operation to a single value. This makes them reusable in the context 2872 /// of visitSELECT(). Rules involving constants are not included as 2873 /// visitSELECT() already handles those cases. 2874 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2875 SDNode *LocReference) { 2876 EVT VT = N1.getValueType(); 2877 2878 // fold (and x, undef) -> 0 2879 if (N0.isUndef() || N1.isUndef()) 2880 return DAG.getConstant(0, SDLoc(LocReference), VT); 2881 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2882 SDValue LL, LR, RL, RR, CC0, CC1; 2883 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2884 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2885 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2886 2887 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2888 LL.getValueType().isInteger()) { 2889 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2890 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2891 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2892 LR.getValueType(), LL, RL); 2893 AddToWorklist(ORNode.getNode()); 2894 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2895 } 2896 if (isAllOnesConstant(LR)) { 2897 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2898 if (Op1 == ISD::SETEQ) { 2899 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2900 LR.getValueType(), LL, RL); 2901 AddToWorklist(ANDNode.getNode()); 2902 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2903 } 2904 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2905 if (Op1 == ISD::SETGT) { 2906 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2907 LR.getValueType(), LL, RL); 2908 AddToWorklist(ORNode.getNode()); 2909 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2910 } 2911 } 2912 } 2913 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2914 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2915 Op0 == Op1 && LL.getValueType().isInteger() && 2916 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2917 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2918 SDLoc DL(N0); 2919 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2920 LL, DAG.getConstant(1, DL, 2921 LL.getValueType())); 2922 AddToWorklist(ADDNode.getNode()); 2923 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2924 DAG.getConstant(2, DL, LL.getValueType()), 2925 ISD::SETUGE); 2926 } 2927 // canonicalize equivalent to ll == rl 2928 if (LL == RR && LR == RL) { 2929 Op1 = ISD::getSetCCSwappedOperands(Op1); 2930 std::swap(RL, RR); 2931 } 2932 if (LL == RL && LR == RR) { 2933 bool isInteger = LL.getValueType().isInteger(); 2934 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2935 if (Result != ISD::SETCC_INVALID && 2936 (!LegalOperations || 2937 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2938 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 2939 EVT CCVT = getSetCCResultType(LL.getValueType()); 2940 if (N0.getValueType() == CCVT || 2941 (!LegalOperations && N0.getValueType() == MVT::i1)) 2942 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2943 LL, LR, Result); 2944 } 2945 } 2946 } 2947 2948 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2949 VT.getSizeInBits() <= 64) { 2950 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2951 APInt ADDC = ADDI->getAPIntValue(); 2952 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2953 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2954 // immediate for an add, but it is legal if its top c2 bits are set, 2955 // transform the ADD so the immediate doesn't need to be materialized 2956 // in a register. 2957 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2958 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2959 SRLI->getZExtValue()); 2960 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2961 ADDC |= Mask; 2962 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2963 SDLoc DL(N0); 2964 SDValue NewAdd = 2965 DAG.getNode(ISD::ADD, DL, VT, 2966 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2967 CombineTo(N0.getNode(), NewAdd); 2968 // Return N so it doesn't get rechecked! 2969 return SDValue(LocReference, 0); 2970 } 2971 } 2972 } 2973 } 2974 } 2975 } 2976 2977 // Reduce bit extract of low half of an integer to the narrower type. 2978 // (and (srl i64:x, K), KMask) -> 2979 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 2980 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 2981 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 2982 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2983 unsigned Size = VT.getSizeInBits(); 2984 const APInt &AndMask = CAnd->getAPIntValue(); 2985 unsigned ShiftBits = CShift->getZExtValue(); 2986 unsigned MaskBits = AndMask.countTrailingOnes(); 2987 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 2988 2989 if (APIntOps::isMask(AndMask) && 2990 // Required bits must not span the two halves of the integer and 2991 // must fit in the half size type. 2992 (ShiftBits + MaskBits <= Size / 2) && 2993 TLI.isNarrowingProfitable(VT, HalfVT) && 2994 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 2995 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 2996 TLI.isTruncateFree(VT, HalfVT) && 2997 TLI.isZExtFree(HalfVT, VT)) { 2998 // The isNarrowingProfitable is to avoid regressions on PPC and 2999 // AArch64 which match a few 64-bit bit insert / bit extract patterns 3000 // on downstream users of this. Those patterns could probably be 3001 // extended to handle extensions mixed in. 3002 3003 SDValue SL(N0); 3004 assert(ShiftBits != 0 && MaskBits <= Size); 3005 3006 // Extracting the highest bit of the low half. 3007 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 3008 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 3009 N0.getOperand(0)); 3010 3011 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 3012 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 3013 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 3014 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 3015 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 3016 } 3017 } 3018 } 3019 } 3020 3021 return SDValue(); 3022 } 3023 3024 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 3025 EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT, 3026 bool &NarrowLoad) { 3027 uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits(); 3028 3029 if (ActiveBits == 0 || !APIntOps::isMask(ActiveBits, AndC->getAPIntValue())) 3030 return false; 3031 3032 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3033 LoadedVT = LoadN->getMemoryVT(); 3034 3035 if (ExtVT == LoadedVT && 3036 (!LegalOperations || 3037 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 3038 // ZEXTLOAD will match without needing to change the size of the value being 3039 // loaded. 3040 NarrowLoad = false; 3041 return true; 3042 } 3043 3044 // Do not change the width of a volatile load. 3045 if (LoadN->isVolatile()) 3046 return false; 3047 3048 // Do not generate loads of non-round integer types since these can 3049 // be expensive (and would be wrong if the type is not byte sized). 3050 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 3051 return false; 3052 3053 if (LegalOperations && 3054 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 3055 return false; 3056 3057 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 3058 return false; 3059 3060 NarrowLoad = true; 3061 return true; 3062 } 3063 3064 SDValue DAGCombiner::visitAND(SDNode *N) { 3065 SDValue N0 = N->getOperand(0); 3066 SDValue N1 = N->getOperand(1); 3067 EVT VT = N1.getValueType(); 3068 3069 // fold vector ops 3070 if (VT.isVector()) { 3071 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3072 return FoldedVOp; 3073 3074 // fold (and x, 0) -> 0, vector edition 3075 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3076 // do not return N0, because undef node may exist in N0 3077 return DAG.getConstant( 3078 APInt::getNullValue( 3079 N0.getValueType().getScalarType().getSizeInBits()), 3080 SDLoc(N), N0.getValueType()); 3081 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3082 // do not return N1, because undef node may exist in N1 3083 return DAG.getConstant( 3084 APInt::getNullValue( 3085 N1.getValueType().getScalarType().getSizeInBits()), 3086 SDLoc(N), N1.getValueType()); 3087 3088 // fold (and x, -1) -> x, vector edition 3089 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3090 return N1; 3091 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3092 return N0; 3093 } 3094 3095 // fold (and c1, c2) -> c1&c2 3096 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3097 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3098 if (N0C && N1C && !N1C->isOpaque()) 3099 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 3100 // canonicalize constant to RHS 3101 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3102 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3103 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 3104 // fold (and x, -1) -> x 3105 if (isAllOnesConstant(N1)) 3106 return N0; 3107 // if (and x, c) is known to be zero, return 0 3108 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 3109 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 3110 APInt::getAllOnesValue(BitWidth))) 3111 return DAG.getConstant(0, SDLoc(N), VT); 3112 // reassociate and 3113 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 3114 return RAND; 3115 // fold (and (or x, C), D) -> D if (C & D) == D 3116 if (N1C && N0.getOpcode() == ISD::OR) 3117 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 3118 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 3119 return N1; 3120 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 3121 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 3122 SDValue N0Op0 = N0.getOperand(0); 3123 APInt Mask = ~N1C->getAPIntValue(); 3124 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 3125 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 3126 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 3127 N0.getValueType(), N0Op0); 3128 3129 // Replace uses of the AND with uses of the Zero extend node. 3130 CombineTo(N, Zext); 3131 3132 // We actually want to replace all uses of the any_extend with the 3133 // zero_extend, to avoid duplicating things. This will later cause this 3134 // AND to be folded. 3135 CombineTo(N0.getNode(), Zext); 3136 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3137 } 3138 } 3139 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 3140 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 3141 // already be zero by virtue of the width of the base type of the load. 3142 // 3143 // the 'X' node here can either be nothing or an extract_vector_elt to catch 3144 // more cases. 3145 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 3146 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 3147 N0.getOperand(0).getOpcode() == ISD::LOAD && 3148 N0.getOperand(0).getResNo() == 0) || 3149 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 3150 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 3151 N0 : N0.getOperand(0) ); 3152 3153 // Get the constant (if applicable) the zero'th operand is being ANDed with. 3154 // This can be a pure constant or a vector splat, in which case we treat the 3155 // vector as a scalar and use the splat value. 3156 APInt Constant = APInt::getNullValue(1); 3157 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 3158 Constant = C->getAPIntValue(); 3159 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 3160 APInt SplatValue, SplatUndef; 3161 unsigned SplatBitSize; 3162 bool HasAnyUndefs; 3163 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 3164 SplatBitSize, HasAnyUndefs); 3165 if (IsSplat) { 3166 // Undef bits can contribute to a possible optimisation if set, so 3167 // set them. 3168 SplatValue |= SplatUndef; 3169 3170 // The splat value may be something like "0x00FFFFFF", which means 0 for 3171 // the first vector value and FF for the rest, repeating. We need a mask 3172 // that will apply equally to all members of the vector, so AND all the 3173 // lanes of the constant together. 3174 EVT VT = Vector->getValueType(0); 3175 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 3176 3177 // If the splat value has been compressed to a bitlength lower 3178 // than the size of the vector lane, we need to re-expand it to 3179 // the lane size. 3180 if (BitWidth > SplatBitSize) 3181 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 3182 SplatBitSize < BitWidth; 3183 SplatBitSize = SplatBitSize * 2) 3184 SplatValue |= SplatValue.shl(SplatBitSize); 3185 3186 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 3187 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 3188 if (SplatBitSize % BitWidth == 0) { 3189 Constant = APInt::getAllOnesValue(BitWidth); 3190 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 3191 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 3192 } 3193 } 3194 } 3195 3196 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 3197 // actually legal and isn't going to get expanded, else this is a false 3198 // optimisation. 3199 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 3200 Load->getValueType(0), 3201 Load->getMemoryVT()); 3202 3203 // Resize the constant to the same size as the original memory access before 3204 // extension. If it is still the AllOnesValue then this AND is completely 3205 // unneeded. 3206 Constant = 3207 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 3208 3209 bool B; 3210 switch (Load->getExtensionType()) { 3211 default: B = false; break; 3212 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 3213 case ISD::ZEXTLOAD: 3214 case ISD::NON_EXTLOAD: B = true; break; 3215 } 3216 3217 if (B && Constant.isAllOnesValue()) { 3218 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 3219 // preserve semantics once we get rid of the AND. 3220 SDValue NewLoad(Load, 0); 3221 if (Load->getExtensionType() == ISD::EXTLOAD) { 3222 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3223 Load->getValueType(0), SDLoc(Load), 3224 Load->getChain(), Load->getBasePtr(), 3225 Load->getOffset(), Load->getMemoryVT(), 3226 Load->getMemOperand()); 3227 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3228 if (Load->getNumValues() == 3) { 3229 // PRE/POST_INC loads have 3 values. 3230 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3231 NewLoad.getValue(2) }; 3232 CombineTo(Load, To, 3, true); 3233 } else { 3234 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3235 } 3236 } 3237 3238 // Fold the AND away, taking care not to fold to the old load node if we 3239 // replaced it. 3240 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3241 3242 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3243 } 3244 } 3245 3246 // fold (and (load x), 255) -> (zextload x, i8) 3247 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3248 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3249 if (N1C && (N0.getOpcode() == ISD::LOAD || 3250 (N0.getOpcode() == ISD::ANY_EXTEND && 3251 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3252 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3253 LoadSDNode *LN0 = HasAnyExt 3254 ? cast<LoadSDNode>(N0.getOperand(0)) 3255 : cast<LoadSDNode>(N0); 3256 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3257 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3258 auto NarrowLoad = false; 3259 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3260 EVT ExtVT, LoadedVT; 3261 if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT, 3262 NarrowLoad)) { 3263 if (!NarrowLoad) { 3264 SDValue NewLoad = 3265 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3266 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3267 LN0->getMemOperand()); 3268 AddToWorklist(N); 3269 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3270 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3271 } else { 3272 EVT PtrType = LN0->getOperand(1).getValueType(); 3273 3274 unsigned Alignment = LN0->getAlignment(); 3275 SDValue NewPtr = LN0->getBasePtr(); 3276 3277 // For big endian targets, we need to add an offset to the pointer 3278 // to load the correct bytes. For little endian systems, we merely 3279 // need to read fewer bytes from the same pointer. 3280 if (DAG.getDataLayout().isBigEndian()) { 3281 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3282 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3283 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3284 SDLoc DL(LN0); 3285 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3286 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3287 Alignment = MinAlign(Alignment, PtrOff); 3288 } 3289 3290 AddToWorklist(NewPtr.getNode()); 3291 3292 SDValue Load = 3293 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3294 LN0->getChain(), NewPtr, 3295 LN0->getPointerInfo(), 3296 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3297 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3298 AddToWorklist(N); 3299 CombineTo(LN0, Load, Load.getValue(1)); 3300 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3301 } 3302 } 3303 } 3304 } 3305 3306 if (SDValue Combined = visitANDLike(N0, N1, N)) 3307 return Combined; 3308 3309 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3310 if (N0.getOpcode() == N1.getOpcode()) 3311 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3312 return Tmp; 3313 3314 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3315 // fold (and (sra)) -> (and (srl)) when possible. 3316 if (!VT.isVector() && 3317 SimplifyDemandedBits(SDValue(N, 0))) 3318 return SDValue(N, 0); 3319 3320 // fold (zext_inreg (extload x)) -> (zextload x) 3321 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3322 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3323 EVT MemVT = LN0->getMemoryVT(); 3324 // If we zero all the possible extended bits, then we can turn this into 3325 // a zextload if we are running before legalize or the operation is legal. 3326 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3327 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3328 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3329 ((!LegalOperations && !LN0->isVolatile()) || 3330 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3331 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3332 LN0->getChain(), LN0->getBasePtr(), 3333 MemVT, LN0->getMemOperand()); 3334 AddToWorklist(N); 3335 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3336 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3337 } 3338 } 3339 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3340 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3341 N0.hasOneUse()) { 3342 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3343 EVT MemVT = LN0->getMemoryVT(); 3344 // If we zero all the possible extended bits, then we can turn this into 3345 // a zextload if we are running before legalize or the operation is legal. 3346 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3347 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3348 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3349 ((!LegalOperations && !LN0->isVolatile()) || 3350 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3351 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3352 LN0->getChain(), LN0->getBasePtr(), 3353 MemVT, LN0->getMemOperand()); 3354 AddToWorklist(N); 3355 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3356 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3357 } 3358 } 3359 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3360 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3361 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3362 N0.getOperand(1), false)) 3363 return BSwap; 3364 } 3365 3366 return SDValue(); 3367 } 3368 3369 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3370 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3371 bool DemandHighBits) { 3372 if (!LegalOperations) 3373 return SDValue(); 3374 3375 EVT VT = N->getValueType(0); 3376 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3377 return SDValue(); 3378 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3379 return SDValue(); 3380 3381 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3382 bool LookPassAnd0 = false; 3383 bool LookPassAnd1 = false; 3384 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3385 std::swap(N0, N1); 3386 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3387 std::swap(N0, N1); 3388 if (N0.getOpcode() == ISD::AND) { 3389 if (!N0.getNode()->hasOneUse()) 3390 return SDValue(); 3391 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3392 if (!N01C || N01C->getZExtValue() != 0xFF00) 3393 return SDValue(); 3394 N0 = N0.getOperand(0); 3395 LookPassAnd0 = true; 3396 } 3397 3398 if (N1.getOpcode() == ISD::AND) { 3399 if (!N1.getNode()->hasOneUse()) 3400 return SDValue(); 3401 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3402 if (!N11C || N11C->getZExtValue() != 0xFF) 3403 return SDValue(); 3404 N1 = N1.getOperand(0); 3405 LookPassAnd1 = true; 3406 } 3407 3408 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3409 std::swap(N0, N1); 3410 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3411 return SDValue(); 3412 if (!N0.getNode()->hasOneUse() || 3413 !N1.getNode()->hasOneUse()) 3414 return SDValue(); 3415 3416 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3417 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3418 if (!N01C || !N11C) 3419 return SDValue(); 3420 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3421 return SDValue(); 3422 3423 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3424 SDValue N00 = N0->getOperand(0); 3425 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3426 if (!N00.getNode()->hasOneUse()) 3427 return SDValue(); 3428 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3429 if (!N001C || N001C->getZExtValue() != 0xFF) 3430 return SDValue(); 3431 N00 = N00.getOperand(0); 3432 LookPassAnd0 = true; 3433 } 3434 3435 SDValue N10 = N1->getOperand(0); 3436 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3437 if (!N10.getNode()->hasOneUse()) 3438 return SDValue(); 3439 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3440 if (!N101C || N101C->getZExtValue() != 0xFF00) 3441 return SDValue(); 3442 N10 = N10.getOperand(0); 3443 LookPassAnd1 = true; 3444 } 3445 3446 if (N00 != N10) 3447 return SDValue(); 3448 3449 // Make sure everything beyond the low halfword gets set to zero since the SRL 3450 // 16 will clear the top bits. 3451 unsigned OpSizeInBits = VT.getSizeInBits(); 3452 if (DemandHighBits && OpSizeInBits > 16) { 3453 // If the left-shift isn't masked out then the only way this is a bswap is 3454 // if all bits beyond the low 8 are 0. In that case the entire pattern 3455 // reduces to a left shift anyway: leave it for other parts of the combiner. 3456 if (!LookPassAnd0) 3457 return SDValue(); 3458 3459 // However, if the right shift isn't masked out then it might be because 3460 // it's not needed. See if we can spot that too. 3461 if (!LookPassAnd1 && 3462 !DAG.MaskedValueIsZero( 3463 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3464 return SDValue(); 3465 } 3466 3467 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3468 if (OpSizeInBits > 16) { 3469 SDLoc DL(N); 3470 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3471 DAG.getConstant(OpSizeInBits - 16, DL, 3472 getShiftAmountTy(VT))); 3473 } 3474 return Res; 3475 } 3476 3477 /// Return true if the specified node is an element that makes up a 32-bit 3478 /// packed halfword byteswap. 3479 /// ((x & 0x000000ff) << 8) | 3480 /// ((x & 0x0000ff00) >> 8) | 3481 /// ((x & 0x00ff0000) << 8) | 3482 /// ((x & 0xff000000) >> 8) 3483 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3484 if (!N.getNode()->hasOneUse()) 3485 return false; 3486 3487 unsigned Opc = N.getOpcode(); 3488 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3489 return false; 3490 3491 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3492 if (!N1C) 3493 return false; 3494 3495 unsigned Num; 3496 switch (N1C->getZExtValue()) { 3497 default: 3498 return false; 3499 case 0xFF: Num = 0; break; 3500 case 0xFF00: Num = 1; break; 3501 case 0xFF0000: Num = 2; break; 3502 case 0xFF000000: Num = 3; break; 3503 } 3504 3505 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3506 SDValue N0 = N.getOperand(0); 3507 if (Opc == ISD::AND) { 3508 if (Num == 0 || Num == 2) { 3509 // (x >> 8) & 0xff 3510 // (x >> 8) & 0xff0000 3511 if (N0.getOpcode() != ISD::SRL) 3512 return false; 3513 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3514 if (!C || C->getZExtValue() != 8) 3515 return false; 3516 } else { 3517 // (x << 8) & 0xff00 3518 // (x << 8) & 0xff000000 3519 if (N0.getOpcode() != ISD::SHL) 3520 return false; 3521 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3522 if (!C || C->getZExtValue() != 8) 3523 return false; 3524 } 3525 } else if (Opc == ISD::SHL) { 3526 // (x & 0xff) << 8 3527 // (x & 0xff0000) << 8 3528 if (Num != 0 && Num != 2) 3529 return false; 3530 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3531 if (!C || C->getZExtValue() != 8) 3532 return false; 3533 } else { // Opc == ISD::SRL 3534 // (x & 0xff00) >> 8 3535 // (x & 0xff000000) >> 8 3536 if (Num != 1 && Num != 3) 3537 return false; 3538 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3539 if (!C || C->getZExtValue() != 8) 3540 return false; 3541 } 3542 3543 if (Parts[Num]) 3544 return false; 3545 3546 Parts[Num] = N0.getOperand(0).getNode(); 3547 return true; 3548 } 3549 3550 /// Match a 32-bit packed halfword bswap. That is 3551 /// ((x & 0x000000ff) << 8) | 3552 /// ((x & 0x0000ff00) >> 8) | 3553 /// ((x & 0x00ff0000) << 8) | 3554 /// ((x & 0xff000000) >> 8) 3555 /// => (rotl (bswap x), 16) 3556 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3557 if (!LegalOperations) 3558 return SDValue(); 3559 3560 EVT VT = N->getValueType(0); 3561 if (VT != MVT::i32) 3562 return SDValue(); 3563 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3564 return SDValue(); 3565 3566 // Look for either 3567 // (or (or (and), (and)), (or (and), (and))) 3568 // (or (or (or (and), (and)), (and)), (and)) 3569 if (N0.getOpcode() != ISD::OR) 3570 return SDValue(); 3571 SDValue N00 = N0.getOperand(0); 3572 SDValue N01 = N0.getOperand(1); 3573 SDNode *Parts[4] = {}; 3574 3575 if (N1.getOpcode() == ISD::OR && 3576 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3577 // (or (or (and), (and)), (or (and), (and))) 3578 SDValue N000 = N00.getOperand(0); 3579 if (!isBSwapHWordElement(N000, Parts)) 3580 return SDValue(); 3581 3582 SDValue N001 = N00.getOperand(1); 3583 if (!isBSwapHWordElement(N001, Parts)) 3584 return SDValue(); 3585 SDValue N010 = N01.getOperand(0); 3586 if (!isBSwapHWordElement(N010, Parts)) 3587 return SDValue(); 3588 SDValue N011 = N01.getOperand(1); 3589 if (!isBSwapHWordElement(N011, Parts)) 3590 return SDValue(); 3591 } else { 3592 // (or (or (or (and), (and)), (and)), (and)) 3593 if (!isBSwapHWordElement(N1, Parts)) 3594 return SDValue(); 3595 if (!isBSwapHWordElement(N01, Parts)) 3596 return SDValue(); 3597 if (N00.getOpcode() != ISD::OR) 3598 return SDValue(); 3599 SDValue N000 = N00.getOperand(0); 3600 if (!isBSwapHWordElement(N000, Parts)) 3601 return SDValue(); 3602 SDValue N001 = N00.getOperand(1); 3603 if (!isBSwapHWordElement(N001, Parts)) 3604 return SDValue(); 3605 } 3606 3607 // Make sure the parts are all coming from the same node. 3608 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3609 return SDValue(); 3610 3611 SDLoc DL(N); 3612 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3613 SDValue(Parts[0], 0)); 3614 3615 // Result of the bswap should be rotated by 16. If it's not legal, then 3616 // do (x << 16) | (x >> 16). 3617 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3618 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3619 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3620 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3621 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3622 return DAG.getNode(ISD::OR, DL, VT, 3623 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3624 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3625 } 3626 3627 /// This contains all DAGCombine rules which reduce two values combined by 3628 /// an Or operation to a single value \see visitANDLike(). 3629 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3630 EVT VT = N1.getValueType(); 3631 // fold (or x, undef) -> -1 3632 if (!LegalOperations && 3633 (N0.isUndef() || N1.isUndef())) { 3634 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3635 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3636 SDLoc(LocReference), VT); 3637 } 3638 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3639 SDValue LL, LR, RL, RR, CC0, CC1; 3640 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3641 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3642 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3643 3644 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3645 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3646 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3647 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3648 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3649 LR.getValueType(), LL, RL); 3650 AddToWorklist(ORNode.getNode()); 3651 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3652 } 3653 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3654 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3655 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3656 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3657 LR.getValueType(), LL, RL); 3658 AddToWorklist(ANDNode.getNode()); 3659 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3660 } 3661 } 3662 // canonicalize equivalent to ll == rl 3663 if (LL == RR && LR == RL) { 3664 Op1 = ISD::getSetCCSwappedOperands(Op1); 3665 std::swap(RL, RR); 3666 } 3667 if (LL == RL && LR == RR) { 3668 bool isInteger = LL.getValueType().isInteger(); 3669 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3670 if (Result != ISD::SETCC_INVALID && 3671 (!LegalOperations || 3672 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3673 TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) { 3674 EVT CCVT = getSetCCResultType(LL.getValueType()); 3675 if (N0.getValueType() == CCVT || 3676 (!LegalOperations && N0.getValueType() == MVT::i1)) 3677 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3678 LL, LR, Result); 3679 } 3680 } 3681 } 3682 3683 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3684 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 3685 // Don't increase # computations. 3686 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3687 // We can only do this xform if we know that bits from X that are set in C2 3688 // but not in C1 are already zero. Likewise for Y. 3689 if (const ConstantSDNode *N0O1C = 3690 getAsNonOpaqueConstant(N0.getOperand(1))) { 3691 if (const ConstantSDNode *N1O1C = 3692 getAsNonOpaqueConstant(N1.getOperand(1))) { 3693 // We can only do this xform if we know that bits from X that are set in 3694 // C2 but not in C1 are already zero. Likewise for Y. 3695 const APInt &LHSMask = N0O1C->getAPIntValue(); 3696 const APInt &RHSMask = N1O1C->getAPIntValue(); 3697 3698 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3699 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3700 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3701 N0.getOperand(0), N1.getOperand(0)); 3702 SDLoc DL(LocReference); 3703 return DAG.getNode(ISD::AND, DL, VT, X, 3704 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3705 } 3706 } 3707 } 3708 } 3709 3710 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3711 if (N0.getOpcode() == ISD::AND && 3712 N1.getOpcode() == ISD::AND && 3713 N0.getOperand(0) == N1.getOperand(0) && 3714 // Don't increase # computations. 3715 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3716 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3717 N0.getOperand(1), N1.getOperand(1)); 3718 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3719 } 3720 3721 return SDValue(); 3722 } 3723 3724 SDValue DAGCombiner::visitOR(SDNode *N) { 3725 SDValue N0 = N->getOperand(0); 3726 SDValue N1 = N->getOperand(1); 3727 EVT VT = N1.getValueType(); 3728 3729 // fold vector ops 3730 if (VT.isVector()) { 3731 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3732 return FoldedVOp; 3733 3734 // fold (or x, 0) -> x, vector edition 3735 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3736 return N1; 3737 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3738 return N0; 3739 3740 // fold (or x, -1) -> -1, vector edition 3741 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3742 // do not return N0, because undef node may exist in N0 3743 return DAG.getConstant( 3744 APInt::getAllOnesValue( 3745 N0.getValueType().getScalarType().getSizeInBits()), 3746 SDLoc(N), N0.getValueType()); 3747 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3748 // do not return N1, because undef node may exist in N1 3749 return DAG.getConstant( 3750 APInt::getAllOnesValue( 3751 N1.getValueType().getScalarType().getSizeInBits()), 3752 SDLoc(N), N1.getValueType()); 3753 3754 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3755 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3756 // Do this only if the resulting shuffle is legal. 3757 if (isa<ShuffleVectorSDNode>(N0) && 3758 isa<ShuffleVectorSDNode>(N1) && 3759 // Avoid folding a node with illegal type. 3760 TLI.isTypeLegal(VT) && 3761 N0->getOperand(1) == N1->getOperand(1) && 3762 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3763 bool CanFold = true; 3764 unsigned NumElts = VT.getVectorNumElements(); 3765 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3766 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3767 // We construct two shuffle masks: 3768 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3769 // and N1 as the second operand. 3770 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3771 // and N0 as the second operand. 3772 // We do this because OR is commutable and therefore there might be 3773 // two ways to fold this node into a shuffle. 3774 SmallVector<int,4> Mask1; 3775 SmallVector<int,4> Mask2; 3776 3777 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3778 int M0 = SV0->getMaskElt(i); 3779 int M1 = SV1->getMaskElt(i); 3780 3781 // Both shuffle indexes are undef. Propagate Undef. 3782 if (M0 < 0 && M1 < 0) { 3783 Mask1.push_back(M0); 3784 Mask2.push_back(M0); 3785 continue; 3786 } 3787 3788 if (M0 < 0 || M1 < 0 || 3789 (M0 < (int)NumElts && M1 < (int)NumElts) || 3790 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3791 CanFold = false; 3792 break; 3793 } 3794 3795 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3796 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3797 } 3798 3799 if (CanFold) { 3800 // Fold this sequence only if the resulting shuffle is 'legal'. 3801 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3802 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3803 N1->getOperand(0), &Mask1[0]); 3804 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3805 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3806 N0->getOperand(0), &Mask2[0]); 3807 } 3808 } 3809 } 3810 3811 // fold (or c1, c2) -> c1|c2 3812 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3813 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3814 if (N0C && N1C && !N1C->isOpaque()) 3815 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3816 // canonicalize constant to RHS 3817 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3818 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3819 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3820 // fold (or x, 0) -> x 3821 if (isNullConstant(N1)) 3822 return N0; 3823 // fold (or x, -1) -> -1 3824 if (isAllOnesConstant(N1)) 3825 return N1; 3826 // fold (or x, c) -> c iff (x & ~c) == 0 3827 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3828 return N1; 3829 3830 if (SDValue Combined = visitORLike(N0, N1, N)) 3831 return Combined; 3832 3833 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3834 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 3835 return BSwap; 3836 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 3837 return BSwap; 3838 3839 // reassociate or 3840 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3841 return ROR; 3842 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3843 // iff (c1 & c2) == 0. 3844 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3845 isa<ConstantSDNode>(N0.getOperand(1))) { 3846 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3847 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3848 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3849 N1C, C1)) 3850 return DAG.getNode( 3851 ISD::AND, SDLoc(N), VT, 3852 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3853 return SDValue(); 3854 } 3855 } 3856 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3857 if (N0.getOpcode() == N1.getOpcode()) 3858 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 3859 return Tmp; 3860 3861 // See if this is some rotate idiom. 3862 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3863 return SDValue(Rot, 0); 3864 3865 // Simplify the operands using demanded-bits information. 3866 if (!VT.isVector() && 3867 SimplifyDemandedBits(SDValue(N, 0))) 3868 return SDValue(N, 0); 3869 3870 return SDValue(); 3871 } 3872 3873 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3874 bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3875 if (Op.getOpcode() == ISD::AND) { 3876 if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 3877 Mask = Op.getOperand(1); 3878 Op = Op.getOperand(0); 3879 } else { 3880 return false; 3881 } 3882 } 3883 3884 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3885 Shift = Op; 3886 return true; 3887 } 3888 3889 return false; 3890 } 3891 3892 // Return true if we can prove that, whenever Neg and Pos are both in the 3893 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 3894 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3895 // 3896 // (or (shift1 X, Neg), (shift2 X, Pos)) 3897 // 3898 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3899 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 3900 // to consider shift amounts with defined behavior. 3901 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) { 3902 // If EltSize is a power of 2 then: 3903 // 3904 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 3905 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 3906 // 3907 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 3908 // for the stronger condition: 3909 // 3910 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 3911 // 3912 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 3913 // we can just replace Neg with Neg' for the rest of the function. 3914 // 3915 // In other cases we check for the even stronger condition: 3916 // 3917 // Neg == EltSize - Pos [B] 3918 // 3919 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3920 // behavior if Pos == 0 (and consequently Neg == EltSize). 3921 // 3922 // We could actually use [A] whenever EltSize is a power of 2, but the 3923 // only extra cases that it would match are those uninteresting ones 3924 // where Neg and Pos are never in range at the same time. E.g. for 3925 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3926 // as well as (sub 32, Pos), but: 3927 // 3928 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3929 // 3930 // always invokes undefined behavior for 32-bit X. 3931 // 3932 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 3933 unsigned MaskLoBits = 0; 3934 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 3935 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 3936 if (NegC->getAPIntValue() == EltSize - 1) { 3937 Neg = Neg.getOperand(0); 3938 MaskLoBits = Log2_64(EltSize); 3939 } 3940 } 3941 } 3942 3943 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3944 if (Neg.getOpcode() != ISD::SUB) 3945 return false; 3946 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 3947 if (!NegC) 3948 return false; 3949 SDValue NegOp1 = Neg.getOperand(1); 3950 3951 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 3952 // Pos'. The truncation is redundant for the purpose of the equality. 3953 if (MaskLoBits && Pos.getOpcode() == ISD::AND) 3954 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3955 if (PosC->getAPIntValue() == EltSize - 1) 3956 Pos = Pos.getOperand(0); 3957 3958 // The condition we need is now: 3959 // 3960 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 3961 // 3962 // If NegOp1 == Pos then we need: 3963 // 3964 // EltSize & Mask == NegC & Mask 3965 // 3966 // (because "x & Mask" is a truncation and distributes through subtraction). 3967 APInt Width; 3968 if (Pos == NegOp1) 3969 Width = NegC->getAPIntValue(); 3970 3971 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3972 // Then the condition we want to prove becomes: 3973 // 3974 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 3975 // 3976 // which, again because "x & Mask" is a truncation, becomes: 3977 // 3978 // NegC & Mask == (EltSize - PosC) & Mask 3979 // EltSize & Mask == (NegC + PosC) & Mask 3980 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 3981 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 3982 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 3983 else 3984 return false; 3985 } else 3986 return false; 3987 3988 // Now we just need to check that EltSize & Mask == Width & Mask. 3989 if (MaskLoBits) 3990 // EltSize & Mask is 0 since Mask is EltSize - 1. 3991 return Width.getLoBits(MaskLoBits) == 0; 3992 return Width == EltSize; 3993 } 3994 3995 // A subroutine of MatchRotate used once we have found an OR of two opposite 3996 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3997 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3998 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3999 // Neg with outer conversions stripped away. 4000 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 4001 SDValue Neg, SDValue InnerPos, 4002 SDValue InnerNeg, unsigned PosOpcode, 4003 unsigned NegOpcode, SDLoc DL) { 4004 // fold (or (shl x, (*ext y)), 4005 // (srl x, (*ext (sub 32, y)))) -> 4006 // (rotl x, y) or (rotr x, (sub 32, y)) 4007 // 4008 // fold (or (shl x, (*ext (sub 32, y))), 4009 // (srl x, (*ext y))) -> 4010 // (rotr x, y) or (rotl x, (sub 32, y)) 4011 EVT VT = Shifted.getValueType(); 4012 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) { 4013 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 4014 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 4015 HasPos ? Pos : Neg).getNode(); 4016 } 4017 4018 return nullptr; 4019 } 4020 4021 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 4022 // idioms for rotate, and if the target supports rotation instructions, generate 4023 // a rot[lr]. 4024 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 4025 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 4026 EVT VT = LHS.getValueType(); 4027 if (!TLI.isTypeLegal(VT)) return nullptr; 4028 4029 // The target must have at least one rotate flavor. 4030 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 4031 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 4032 if (!HasROTL && !HasROTR) return nullptr; 4033 4034 // Match "(X shl/srl V1) & V2" where V2 may not be present. 4035 SDValue LHSShift; // The shift. 4036 SDValue LHSMask; // AND value if any. 4037 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 4038 return nullptr; // Not part of a rotate. 4039 4040 SDValue RHSShift; // The shift. 4041 SDValue RHSMask; // AND value if any. 4042 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 4043 return nullptr; // Not part of a rotate. 4044 4045 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 4046 return nullptr; // Not shifting the same value. 4047 4048 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 4049 return nullptr; // Shifts must disagree. 4050 4051 // Canonicalize shl to left side in a shl/srl pair. 4052 if (RHSShift.getOpcode() == ISD::SHL) { 4053 std::swap(LHS, RHS); 4054 std::swap(LHSShift, RHSShift); 4055 std::swap(LHSMask, RHSMask); 4056 } 4057 4058 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4059 SDValue LHSShiftArg = LHSShift.getOperand(0); 4060 SDValue LHSShiftAmt = LHSShift.getOperand(1); 4061 SDValue RHSShiftArg = RHSShift.getOperand(0); 4062 SDValue RHSShiftAmt = RHSShift.getOperand(1); 4063 4064 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 4065 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 4066 if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) { 4067 uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue(); 4068 uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue(); 4069 if ((LShVal + RShVal) != EltSizeInBits) 4070 return nullptr; 4071 4072 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 4073 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 4074 4075 // If there is an AND of either shifted operand, apply it to the result. 4076 if (LHSMask.getNode() || RHSMask.getNode()) { 4077 APInt AllBits = APInt::getAllOnesValue(EltSizeInBits); 4078 SDValue Mask = DAG.getConstant(AllBits, DL, VT); 4079 4080 if (LHSMask.getNode()) { 4081 APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal); 4082 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4083 DAG.getNode(ISD::OR, DL, VT, LHSMask, 4084 DAG.getConstant(RHSBits, DL, VT))); 4085 } 4086 if (RHSMask.getNode()) { 4087 APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal); 4088 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 4089 DAG.getNode(ISD::OR, DL, VT, RHSMask, 4090 DAG.getConstant(LHSBits, DL, VT))); 4091 } 4092 4093 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 4094 } 4095 4096 return Rot.getNode(); 4097 } 4098 4099 // If there is a mask here, and we have a variable shift, we can't be sure 4100 // that we're masking out the right stuff. 4101 if (LHSMask.getNode() || RHSMask.getNode()) 4102 return nullptr; 4103 4104 // If the shift amount is sign/zext/any-extended just peel it off. 4105 SDValue LExtOp0 = LHSShiftAmt; 4106 SDValue RExtOp0 = RHSShiftAmt; 4107 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4108 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4109 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4110 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 4111 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 4112 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 4113 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 4114 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 4115 LExtOp0 = LHSShiftAmt.getOperand(0); 4116 RExtOp0 = RHSShiftAmt.getOperand(0); 4117 } 4118 4119 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 4120 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 4121 if (TryL) 4122 return TryL; 4123 4124 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 4125 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 4126 if (TryR) 4127 return TryR; 4128 4129 return nullptr; 4130 } 4131 4132 SDValue DAGCombiner::visitXOR(SDNode *N) { 4133 SDValue N0 = N->getOperand(0); 4134 SDValue N1 = N->getOperand(1); 4135 EVT VT = N0.getValueType(); 4136 4137 // fold vector ops 4138 if (VT.isVector()) { 4139 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4140 return FoldedVOp; 4141 4142 // fold (xor x, 0) -> x, vector edition 4143 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4144 return N1; 4145 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4146 return N0; 4147 } 4148 4149 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 4150 if (N0.isUndef() && N1.isUndef()) 4151 return DAG.getConstant(0, SDLoc(N), VT); 4152 // fold (xor x, undef) -> undef 4153 if (N0.isUndef()) 4154 return N0; 4155 if (N1.isUndef()) 4156 return N1; 4157 // fold (xor c1, c2) -> c1^c2 4158 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4159 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 4160 if (N0C && N1C) 4161 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 4162 // canonicalize constant to RHS 4163 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4164 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4165 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 4166 // fold (xor x, 0) -> x 4167 if (isNullConstant(N1)) 4168 return N0; 4169 // reassociate xor 4170 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 4171 return RXOR; 4172 4173 // fold !(x cc y) -> (x !cc y) 4174 SDValue LHS, RHS, CC; 4175 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 4176 bool isInt = LHS.getValueType().isInteger(); 4177 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 4178 isInt); 4179 4180 if (!LegalOperations || 4181 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 4182 switch (N0.getOpcode()) { 4183 default: 4184 llvm_unreachable("Unhandled SetCC Equivalent!"); 4185 case ISD::SETCC: 4186 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 4187 case ISD::SELECT_CC: 4188 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 4189 N0.getOperand(3), NotCC); 4190 } 4191 } 4192 } 4193 4194 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 4195 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 4196 N0.getNode()->hasOneUse() && 4197 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 4198 SDValue V = N0.getOperand(0); 4199 SDLoc DL(N0); 4200 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 4201 DAG.getConstant(1, DL, V.getValueType())); 4202 AddToWorklist(V.getNode()); 4203 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 4204 } 4205 4206 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 4207 if (isOneConstant(N1) && VT == MVT::i1 && 4208 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4209 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4210 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 4211 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4212 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4213 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4214 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4215 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4216 } 4217 } 4218 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4219 if (isAllOnesConstant(N1) && 4220 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4221 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4222 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4223 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4224 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4225 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4226 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4227 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4228 } 4229 } 4230 // fold (xor (and x, y), y) -> (and (not x), y) 4231 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4232 N0->getOperand(1) == N1) { 4233 SDValue X = N0->getOperand(0); 4234 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4235 AddToWorklist(NotX.getNode()); 4236 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4237 } 4238 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4239 if (N1C && N0.getOpcode() == ISD::XOR) { 4240 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) { 4241 SDLoc DL(N); 4242 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4243 DAG.getConstant(N1C->getAPIntValue() ^ 4244 N00C->getAPIntValue(), DL, VT)); 4245 } 4246 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) { 4247 SDLoc DL(N); 4248 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4249 DAG.getConstant(N1C->getAPIntValue() ^ 4250 N01C->getAPIntValue(), DL, VT)); 4251 } 4252 } 4253 // fold (xor x, x) -> 0 4254 if (N0 == N1) 4255 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4256 4257 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4258 // Here is a concrete example of this equivalence: 4259 // i16 x == 14 4260 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4261 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4262 // 4263 // => 4264 // 4265 // i16 ~1 == 0b1111111111111110 4266 // i16 rol(~1, 14) == 0b1011111111111111 4267 // 4268 // Some additional tips to help conceptualize this transform: 4269 // - Try to see the operation as placing a single zero in a value of all ones. 4270 // - There exists no value for x which would allow the result to contain zero. 4271 // - Values of x larger than the bitwidth are undefined and do not require a 4272 // consistent result. 4273 // - Pushing the zero left requires shifting one bits in from the right. 4274 // A rotate left of ~1 is a nice way of achieving the desired result. 4275 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4276 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4277 SDLoc DL(N); 4278 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4279 N0.getOperand(1)); 4280 } 4281 4282 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4283 if (N0.getOpcode() == N1.getOpcode()) 4284 if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N)) 4285 return Tmp; 4286 4287 // Simplify the expression using non-local knowledge. 4288 if (!VT.isVector() && 4289 SimplifyDemandedBits(SDValue(N, 0))) 4290 return SDValue(N, 0); 4291 4292 return SDValue(); 4293 } 4294 4295 /// Handle transforms common to the three shifts, when the shift amount is a 4296 /// constant. 4297 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4298 SDNode *LHS = N->getOperand(0).getNode(); 4299 if (!LHS->hasOneUse()) return SDValue(); 4300 4301 // We want to pull some binops through shifts, so that we have (and (shift)) 4302 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4303 // thing happens with address calculations, so it's important to canonicalize 4304 // it. 4305 bool HighBitSet = false; // Can we transform this if the high bit is set? 4306 4307 switch (LHS->getOpcode()) { 4308 default: return SDValue(); 4309 case ISD::OR: 4310 case ISD::XOR: 4311 HighBitSet = false; // We can only transform sra if the high bit is clear. 4312 break; 4313 case ISD::AND: 4314 HighBitSet = true; // We can only transform sra if the high bit is set. 4315 break; 4316 case ISD::ADD: 4317 if (N->getOpcode() != ISD::SHL) 4318 return SDValue(); // only shl(add) not sr[al](add). 4319 HighBitSet = false; // We can only transform sra if the high bit is clear. 4320 break; 4321 } 4322 4323 // We require the RHS of the binop to be a constant and not opaque as well. 4324 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 4325 if (!BinOpCst) return SDValue(); 4326 4327 // FIXME: disable this unless the input to the binop is a shift by a constant. 4328 // If it is not a shift, it pessimizes some common cases like: 4329 // 4330 // void foo(int *X, int i) { X[i & 1235] = 1; } 4331 // int bar(int *X, int i) { return X[i & 255]; } 4332 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4333 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4334 BinOpLHSVal->getOpcode() != ISD::SRA && 4335 BinOpLHSVal->getOpcode() != ISD::SRL) || 4336 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4337 return SDValue(); 4338 4339 EVT VT = N->getValueType(0); 4340 4341 // If this is a signed shift right, and the high bit is modified by the 4342 // logical operation, do not perform the transformation. The highBitSet 4343 // boolean indicates the value of the high bit of the constant which would 4344 // cause it to be modified for this operation. 4345 if (N->getOpcode() == ISD::SRA) { 4346 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4347 if (BinOpRHSSignSet != HighBitSet) 4348 return SDValue(); 4349 } 4350 4351 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4352 return SDValue(); 4353 4354 // Fold the constants, shifting the binop RHS by the shift amount. 4355 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4356 N->getValueType(0), 4357 LHS->getOperand(1), N->getOperand(1)); 4358 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4359 4360 // Create the new shift. 4361 SDValue NewShift = DAG.getNode(N->getOpcode(), 4362 SDLoc(LHS->getOperand(0)), 4363 VT, LHS->getOperand(0), N->getOperand(1)); 4364 4365 // Create the new binop. 4366 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4367 } 4368 4369 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4370 assert(N->getOpcode() == ISD::TRUNCATE); 4371 assert(N->getOperand(0).getOpcode() == ISD::AND); 4372 4373 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4374 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4375 SDValue N01 = N->getOperand(0).getOperand(1); 4376 4377 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4378 if (!N01C->isOpaque()) { 4379 EVT TruncVT = N->getValueType(0); 4380 SDValue N00 = N->getOperand(0).getOperand(0); 4381 APInt TruncC = N01C->getAPIntValue(); 4382 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4383 SDLoc DL(N); 4384 4385 return DAG.getNode(ISD::AND, DL, TruncVT, 4386 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4387 DAG.getConstant(TruncC, DL, TruncVT)); 4388 } 4389 } 4390 } 4391 4392 return SDValue(); 4393 } 4394 4395 SDValue DAGCombiner::visitRotate(SDNode *N) { 4396 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4397 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4398 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4399 if (SDValue NewOp1 = 4400 distributeTruncateThroughAnd(N->getOperand(1).getNode())) 4401 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4402 N->getOperand(0), NewOp1); 4403 } 4404 return SDValue(); 4405 } 4406 4407 SDValue DAGCombiner::visitSHL(SDNode *N) { 4408 SDValue N0 = N->getOperand(0); 4409 SDValue N1 = N->getOperand(1); 4410 EVT VT = N0.getValueType(); 4411 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4412 4413 // fold vector ops 4414 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4415 if (VT.isVector()) { 4416 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4417 return FoldedVOp; 4418 4419 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4420 // If setcc produces all-one true value then: 4421 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4422 if (N1CV && N1CV->isConstant()) { 4423 if (N0.getOpcode() == ISD::AND) { 4424 SDValue N00 = N0->getOperand(0); 4425 SDValue N01 = N0->getOperand(1); 4426 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4427 4428 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4429 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4430 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4431 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4432 N01CV, N1CV)) 4433 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4434 } 4435 } else { 4436 N1C = isConstOrConstSplat(N1); 4437 } 4438 } 4439 } 4440 4441 // fold (shl c1, c2) -> c1<<c2 4442 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4443 if (N0C && N1C && !N1C->isOpaque()) 4444 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4445 // fold (shl 0, x) -> 0 4446 if (isNullConstant(N0)) 4447 return N0; 4448 // fold (shl x, c >= size(x)) -> undef 4449 if (N1C && N1C->getAPIntValue().uge(OpSizeInBits)) 4450 return DAG.getUNDEF(VT); 4451 // fold (shl x, 0) -> x 4452 if (N1C && N1C->isNullValue()) 4453 return N0; 4454 // fold (shl undef, x) -> 0 4455 if (N0.isUndef()) 4456 return DAG.getConstant(0, SDLoc(N), VT); 4457 // if (shl x, c) is known to be zero, return 0 4458 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4459 APInt::getAllOnesValue(OpSizeInBits))) 4460 return DAG.getConstant(0, SDLoc(N), VT); 4461 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4462 if (N1.getOpcode() == ISD::TRUNCATE && 4463 N1.getOperand(0).getOpcode() == ISD::AND) { 4464 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4465 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4466 } 4467 4468 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4469 return SDValue(N, 0); 4470 4471 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4472 if (N1C && N0.getOpcode() == ISD::SHL) { 4473 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4474 uint64_t c1 = N0C1->getZExtValue(); 4475 uint64_t c2 = N1C->getZExtValue(); 4476 SDLoc DL(N); 4477 if (c1 + c2 >= OpSizeInBits) 4478 return DAG.getConstant(0, DL, VT); 4479 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4480 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4481 } 4482 } 4483 4484 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4485 // For this to be valid, the second form must not preserve any of the bits 4486 // that are shifted out by the inner shift in the first form. This means 4487 // the outer shift size must be >= the number of bits added by the ext. 4488 // As a corollary, we don't care what kind of ext it is. 4489 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4490 N0.getOpcode() == ISD::ANY_EXTEND || 4491 N0.getOpcode() == ISD::SIGN_EXTEND) && 4492 N0.getOperand(0).getOpcode() == ISD::SHL) { 4493 SDValue N0Op0 = N0.getOperand(0); 4494 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4495 uint64_t c1 = N0Op0C1->getZExtValue(); 4496 uint64_t c2 = N1C->getZExtValue(); 4497 EVT InnerShiftVT = N0Op0.getValueType(); 4498 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4499 if (c2 >= OpSizeInBits - InnerShiftSize) { 4500 SDLoc DL(N0); 4501 if (c1 + c2 >= OpSizeInBits) 4502 return DAG.getConstant(0, DL, VT); 4503 return DAG.getNode(ISD::SHL, DL, VT, 4504 DAG.getNode(N0.getOpcode(), DL, VT, 4505 N0Op0->getOperand(0)), 4506 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4507 } 4508 } 4509 } 4510 4511 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4512 // Only fold this if the inner zext has no other uses to avoid increasing 4513 // the total number of instructions. 4514 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4515 N0.getOperand(0).getOpcode() == ISD::SRL) { 4516 SDValue N0Op0 = N0.getOperand(0); 4517 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4518 uint64_t c1 = N0Op0C1->getZExtValue(); 4519 if (c1 < VT.getScalarSizeInBits()) { 4520 uint64_t c2 = N1C->getZExtValue(); 4521 if (c1 == c2) { 4522 SDValue NewOp0 = N0.getOperand(0); 4523 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4524 SDLoc DL(N); 4525 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4526 NewOp0, 4527 DAG.getConstant(c2, DL, CountVT)); 4528 AddToWorklist(NewSHL.getNode()); 4529 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4530 } 4531 } 4532 } 4533 } 4534 4535 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 4536 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 4537 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 4538 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) { 4539 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4540 uint64_t C1 = N0C1->getZExtValue(); 4541 uint64_t C2 = N1C->getZExtValue(); 4542 SDLoc DL(N); 4543 if (C1 <= C2) 4544 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4545 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 4546 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 4547 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 4548 } 4549 } 4550 4551 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4552 // (and (srl x, (sub c1, c2), MASK) 4553 // Only fold this if the inner shift has no other uses -- if it does, folding 4554 // this will increase the total number of instructions. 4555 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4556 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4557 uint64_t c1 = N0C1->getZExtValue(); 4558 if (c1 < OpSizeInBits) { 4559 uint64_t c2 = N1C->getZExtValue(); 4560 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4561 SDValue Shift; 4562 if (c2 > c1) { 4563 Mask = Mask.shl(c2 - c1); 4564 SDLoc DL(N); 4565 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4566 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4567 } else { 4568 Mask = Mask.lshr(c1 - c2); 4569 SDLoc DL(N); 4570 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4571 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4572 } 4573 SDLoc DL(N0); 4574 return DAG.getNode(ISD::AND, DL, VT, Shift, 4575 DAG.getConstant(Mask, DL, VT)); 4576 } 4577 } 4578 } 4579 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4580 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4581 unsigned BitSize = VT.getScalarSizeInBits(); 4582 SDLoc DL(N); 4583 SDValue HiBitsMask = 4584 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4585 BitSize - N1C->getZExtValue()), 4586 DL, VT); 4587 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4588 HiBitsMask); 4589 } 4590 4591 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4592 // Variant of version done on multiply, except mul by a power of 2 is turned 4593 // into a shift. 4594 APInt Val; 4595 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4596 (isa<ConstantSDNode>(N0.getOperand(1)) || 4597 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4598 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4599 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4600 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4601 } 4602 4603 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 4604 if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) { 4605 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4606 if (SDValue Folded = 4607 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C)) 4608 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded); 4609 } 4610 } 4611 4612 if (N1C && !N1C->isOpaque()) 4613 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 4614 return NewSHL; 4615 4616 return SDValue(); 4617 } 4618 4619 SDValue DAGCombiner::visitSRA(SDNode *N) { 4620 SDValue N0 = N->getOperand(0); 4621 SDValue N1 = N->getOperand(1); 4622 EVT VT = N0.getValueType(); 4623 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4624 4625 // fold vector ops 4626 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4627 if (VT.isVector()) { 4628 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4629 return FoldedVOp; 4630 4631 N1C = isConstOrConstSplat(N1); 4632 } 4633 4634 // fold (sra c1, c2) -> (sra c1, c2) 4635 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4636 if (N0C && N1C && !N1C->isOpaque()) 4637 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4638 // fold (sra 0, x) -> 0 4639 if (isNullConstant(N0)) 4640 return N0; 4641 // fold (sra -1, x) -> -1 4642 if (isAllOnesConstant(N0)) 4643 return N0; 4644 // fold (sra x, (setge c, size(x))) -> undef 4645 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4646 return DAG.getUNDEF(VT); 4647 // fold (sra x, 0) -> x 4648 if (N1C && N1C->isNullValue()) 4649 return N0; 4650 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4651 // sext_inreg. 4652 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4653 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4654 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4655 if (VT.isVector()) 4656 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4657 ExtVT, VT.getVectorNumElements()); 4658 if ((!LegalOperations || 4659 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4660 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4661 N0.getOperand(0), DAG.getValueType(ExtVT)); 4662 } 4663 4664 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4665 if (N1C && N0.getOpcode() == ISD::SRA) { 4666 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4667 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4668 if (Sum >= OpSizeInBits) 4669 Sum = OpSizeInBits - 1; 4670 SDLoc DL(N); 4671 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4672 DAG.getConstant(Sum, DL, N1.getValueType())); 4673 } 4674 } 4675 4676 // fold (sra (shl X, m), (sub result_size, n)) 4677 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4678 // result_size - n != m. 4679 // If truncate is free for the target sext(shl) is likely to result in better 4680 // code. 4681 if (N0.getOpcode() == ISD::SHL && N1C) { 4682 // Get the two constanst of the shifts, CN0 = m, CN = n. 4683 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4684 if (N01C) { 4685 LLVMContext &Ctx = *DAG.getContext(); 4686 // Determine what the truncate's result bitsize and type would be. 4687 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4688 4689 if (VT.isVector()) 4690 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4691 4692 // Determine the residual right-shift amount. 4693 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4694 4695 // If the shift is not a no-op (in which case this should be just a sign 4696 // extend already), the truncated to type is legal, sign_extend is legal 4697 // on that type, and the truncate to that type is both legal and free, 4698 // perform the transform. 4699 if ((ShiftAmt > 0) && 4700 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4701 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4702 TLI.isTruncateFree(VT, TruncVT)) { 4703 4704 SDLoc DL(N); 4705 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4706 getShiftAmountTy(N0.getOperand(0).getValueType())); 4707 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4708 N0.getOperand(0), Amt); 4709 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4710 Shift); 4711 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4712 N->getValueType(0), Trunc); 4713 } 4714 } 4715 } 4716 4717 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4718 if (N1.getOpcode() == ISD::TRUNCATE && 4719 N1.getOperand(0).getOpcode() == ISD::AND) { 4720 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4721 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4722 } 4723 4724 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4725 // if c1 is equal to the number of bits the trunc removes 4726 if (N0.getOpcode() == ISD::TRUNCATE && 4727 (N0.getOperand(0).getOpcode() == ISD::SRL || 4728 N0.getOperand(0).getOpcode() == ISD::SRA) && 4729 N0.getOperand(0).hasOneUse() && 4730 N0.getOperand(0).getOperand(1).hasOneUse() && 4731 N1C) { 4732 SDValue N0Op0 = N0.getOperand(0); 4733 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4734 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4735 EVT LargeVT = N0Op0.getValueType(); 4736 4737 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4738 SDLoc DL(N); 4739 SDValue Amt = 4740 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4741 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4742 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4743 N0Op0.getOperand(0), Amt); 4744 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4745 } 4746 } 4747 } 4748 4749 // Simplify, based on bits shifted out of the LHS. 4750 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4751 return SDValue(N, 0); 4752 4753 4754 // If the sign bit is known to be zero, switch this to a SRL. 4755 if (DAG.SignBitIsZero(N0)) 4756 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4757 4758 if (N1C && !N1C->isOpaque()) 4759 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 4760 return NewSRA; 4761 4762 return SDValue(); 4763 } 4764 4765 SDValue DAGCombiner::visitSRL(SDNode *N) { 4766 SDValue N0 = N->getOperand(0); 4767 SDValue N1 = N->getOperand(1); 4768 EVT VT = N0.getValueType(); 4769 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4770 4771 // fold vector ops 4772 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4773 if (VT.isVector()) { 4774 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4775 return FoldedVOp; 4776 4777 N1C = isConstOrConstSplat(N1); 4778 } 4779 4780 // fold (srl c1, c2) -> c1 >>u c2 4781 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4782 if (N0C && N1C && !N1C->isOpaque()) 4783 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4784 // fold (srl 0, x) -> 0 4785 if (isNullConstant(N0)) 4786 return N0; 4787 // fold (srl x, c >= size(x)) -> undef 4788 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4789 return DAG.getUNDEF(VT); 4790 // fold (srl x, 0) -> x 4791 if (N1C && N1C->isNullValue()) 4792 return N0; 4793 // if (srl x, c) is known to be zero, return 0 4794 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4795 APInt::getAllOnesValue(OpSizeInBits))) 4796 return DAG.getConstant(0, SDLoc(N), VT); 4797 4798 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4799 if (N1C && N0.getOpcode() == ISD::SRL) { 4800 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4801 uint64_t c1 = N01C->getZExtValue(); 4802 uint64_t c2 = N1C->getZExtValue(); 4803 SDLoc DL(N); 4804 if (c1 + c2 >= OpSizeInBits) 4805 return DAG.getConstant(0, DL, VT); 4806 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4807 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4808 } 4809 } 4810 4811 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4812 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4813 N0.getOperand(0).getOpcode() == ISD::SRL && 4814 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4815 uint64_t c1 = 4816 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4817 uint64_t c2 = N1C->getZExtValue(); 4818 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4819 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4820 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4821 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4822 if (c1 + OpSizeInBits == InnerShiftSize) { 4823 SDLoc DL(N0); 4824 if (c1 + c2 >= InnerShiftSize) 4825 return DAG.getConstant(0, DL, VT); 4826 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4827 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4828 N0.getOperand(0)->getOperand(0), 4829 DAG.getConstant(c1 + c2, DL, 4830 ShiftCountVT))); 4831 } 4832 } 4833 4834 // fold (srl (shl x, c), c) -> (and x, cst2) 4835 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4836 unsigned BitSize = N0.getScalarValueSizeInBits(); 4837 if (BitSize <= 64) { 4838 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4839 SDLoc DL(N); 4840 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4841 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4842 } 4843 } 4844 4845 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4846 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4847 // Shifting in all undef bits? 4848 EVT SmallVT = N0.getOperand(0).getValueType(); 4849 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4850 if (N1C->getZExtValue() >= BitSize) 4851 return DAG.getUNDEF(VT); 4852 4853 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4854 uint64_t ShiftAmt = N1C->getZExtValue(); 4855 SDLoc DL0(N0); 4856 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4857 N0.getOperand(0), 4858 DAG.getConstant(ShiftAmt, DL0, 4859 getShiftAmountTy(SmallVT))); 4860 AddToWorklist(SmallShift.getNode()); 4861 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4862 SDLoc DL(N); 4863 return DAG.getNode(ISD::AND, DL, VT, 4864 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4865 DAG.getConstant(Mask, DL, VT)); 4866 } 4867 } 4868 4869 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4870 // bit, which is unmodified by sra. 4871 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4872 if (N0.getOpcode() == ISD::SRA) 4873 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4874 } 4875 4876 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4877 if (N1C && N0.getOpcode() == ISD::CTLZ && 4878 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4879 APInt KnownZero, KnownOne; 4880 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4881 4882 // If any of the input bits are KnownOne, then the input couldn't be all 4883 // zeros, thus the result of the srl will always be zero. 4884 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4885 4886 // If all of the bits input the to ctlz node are known to be zero, then 4887 // the result of the ctlz is "32" and the result of the shift is one. 4888 APInt UnknownBits = ~KnownZero; 4889 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4890 4891 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4892 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4893 // Okay, we know that only that the single bit specified by UnknownBits 4894 // could be set on input to the CTLZ node. If this bit is set, the SRL 4895 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4896 // to an SRL/XOR pair, which is likely to simplify more. 4897 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4898 SDValue Op = N0.getOperand(0); 4899 4900 if (ShAmt) { 4901 SDLoc DL(N0); 4902 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4903 DAG.getConstant(ShAmt, DL, 4904 getShiftAmountTy(Op.getValueType()))); 4905 AddToWorklist(Op.getNode()); 4906 } 4907 4908 SDLoc DL(N); 4909 return DAG.getNode(ISD::XOR, DL, VT, 4910 Op, DAG.getConstant(1, DL, VT)); 4911 } 4912 } 4913 4914 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4915 if (N1.getOpcode() == ISD::TRUNCATE && 4916 N1.getOperand(0).getOpcode() == ISD::AND) { 4917 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 4918 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4919 } 4920 4921 // fold operands of srl based on knowledge that the low bits are not 4922 // demanded. 4923 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4924 return SDValue(N, 0); 4925 4926 if (N1C && !N1C->isOpaque()) 4927 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 4928 return NewSRL; 4929 4930 // Attempt to convert a srl of a load into a narrower zero-extending load. 4931 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 4932 return NarrowLoad; 4933 4934 // Here is a common situation. We want to optimize: 4935 // 4936 // %a = ... 4937 // %b = and i32 %a, 2 4938 // %c = srl i32 %b, 1 4939 // brcond i32 %c ... 4940 // 4941 // into 4942 // 4943 // %a = ... 4944 // %b = and %a, 2 4945 // %c = setcc eq %b, 0 4946 // brcond %c ... 4947 // 4948 // However when after the source operand of SRL is optimized into AND, the SRL 4949 // itself may not be optimized further. Look for it and add the BRCOND into 4950 // the worklist. 4951 if (N->hasOneUse()) { 4952 SDNode *Use = *N->use_begin(); 4953 if (Use->getOpcode() == ISD::BRCOND) 4954 AddToWorklist(Use); 4955 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4956 // Also look pass the truncate. 4957 Use = *Use->use_begin(); 4958 if (Use->getOpcode() == ISD::BRCOND) 4959 AddToWorklist(Use); 4960 } 4961 } 4962 4963 return SDValue(); 4964 } 4965 4966 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 4967 SDValue N0 = N->getOperand(0); 4968 EVT VT = N->getValueType(0); 4969 4970 // fold (bswap c1) -> c2 4971 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4972 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 4973 // fold (bswap (bswap x)) -> x 4974 if (N0.getOpcode() == ISD::BSWAP) 4975 return N0->getOperand(0); 4976 return SDValue(); 4977 } 4978 4979 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4980 SDValue N0 = N->getOperand(0); 4981 EVT VT = N->getValueType(0); 4982 4983 // fold (ctlz c1) -> c2 4984 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4985 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4986 return SDValue(); 4987 } 4988 4989 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4990 SDValue N0 = N->getOperand(0); 4991 EVT VT = N->getValueType(0); 4992 4993 // fold (ctlz_zero_undef c1) -> c2 4994 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 4995 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4996 return SDValue(); 4997 } 4998 4999 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 5000 SDValue N0 = N->getOperand(0); 5001 EVT VT = N->getValueType(0); 5002 5003 // fold (cttz c1) -> c2 5004 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5005 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 5006 return SDValue(); 5007 } 5008 5009 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 5010 SDValue N0 = N->getOperand(0); 5011 EVT VT = N->getValueType(0); 5012 5013 // fold (cttz_zero_undef c1) -> c2 5014 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5015 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 5016 return SDValue(); 5017 } 5018 5019 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 5020 SDValue N0 = N->getOperand(0); 5021 EVT VT = N->getValueType(0); 5022 5023 // fold (ctpop c1) -> c2 5024 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 5025 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 5026 return SDValue(); 5027 } 5028 5029 5030 /// \brief Generate Min/Max node 5031 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 5032 SDValue True, SDValue False, 5033 ISD::CondCode CC, const TargetLowering &TLI, 5034 SelectionDAG &DAG) { 5035 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 5036 return SDValue(); 5037 5038 switch (CC) { 5039 case ISD::SETOLT: 5040 case ISD::SETOLE: 5041 case ISD::SETLT: 5042 case ISD::SETLE: 5043 case ISD::SETULT: 5044 case ISD::SETULE: { 5045 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 5046 if (TLI.isOperationLegal(Opcode, VT)) 5047 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5048 return SDValue(); 5049 } 5050 case ISD::SETOGT: 5051 case ISD::SETOGE: 5052 case ISD::SETGT: 5053 case ISD::SETGE: 5054 case ISD::SETUGT: 5055 case ISD::SETUGE: { 5056 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 5057 if (TLI.isOperationLegal(Opcode, VT)) 5058 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 5059 return SDValue(); 5060 } 5061 default: 5062 return SDValue(); 5063 } 5064 } 5065 5066 SDValue DAGCombiner::visitSELECT(SDNode *N) { 5067 SDValue N0 = N->getOperand(0); 5068 SDValue N1 = N->getOperand(1); 5069 SDValue N2 = N->getOperand(2); 5070 EVT VT = N->getValueType(0); 5071 EVT VT0 = N0.getValueType(); 5072 5073 // fold (select C, X, X) -> X 5074 if (N1 == N2) 5075 return N1; 5076 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 5077 // fold (select true, X, Y) -> X 5078 // fold (select false, X, Y) -> Y 5079 return !N0C->isNullValue() ? N1 : N2; 5080 } 5081 // fold (select C, 1, X) -> (or C, X) 5082 if (VT == MVT::i1 && isOneConstant(N1)) 5083 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5084 // fold (select C, 0, 1) -> (xor C, 1) 5085 // We can't do this reliably if integer based booleans have different contents 5086 // to floating point based booleans. This is because we can't tell whether we 5087 // have an integer-based boolean or a floating-point-based boolean unless we 5088 // can find the SETCC that produced it and inspect its operands. This is 5089 // fairly easy if C is the SETCC node, but it can potentially be 5090 // undiscoverable (or not reasonably discoverable). For example, it could be 5091 // in another basic block or it could require searching a complicated 5092 // expression. 5093 if (VT.isInteger() && 5094 (VT0 == MVT::i1 || (VT0.isInteger() && 5095 TLI.getBooleanContents(false, false) == 5096 TLI.getBooleanContents(false, true) && 5097 TLI.getBooleanContents(false, false) == 5098 TargetLowering::ZeroOrOneBooleanContent)) && 5099 isNullConstant(N1) && isOneConstant(N2)) { 5100 SDValue XORNode; 5101 if (VT == VT0) { 5102 SDLoc DL(N); 5103 return DAG.getNode(ISD::XOR, DL, VT0, 5104 N0, DAG.getConstant(1, DL, VT0)); 5105 } 5106 SDLoc DL0(N0); 5107 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 5108 N0, DAG.getConstant(1, DL0, VT0)); 5109 AddToWorklist(XORNode.getNode()); 5110 if (VT.bitsGT(VT0)) 5111 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 5112 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 5113 } 5114 // fold (select C, 0, X) -> (and (not C), X) 5115 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 5116 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5117 AddToWorklist(NOTNode.getNode()); 5118 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 5119 } 5120 // fold (select C, X, 1) -> (or (not C), X) 5121 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 5122 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 5123 AddToWorklist(NOTNode.getNode()); 5124 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 5125 } 5126 // fold (select C, X, 0) -> (and C, X) 5127 if (VT == MVT::i1 && isNullConstant(N2)) 5128 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5129 // fold (select X, X, Y) -> (or X, Y) 5130 // fold (select X, 1, Y) -> (or X, Y) 5131 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 5132 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 5133 // fold (select X, Y, X) -> (and X, Y) 5134 // fold (select X, Y, 0) -> (and X, Y) 5135 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 5136 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 5137 5138 // If we can fold this based on the true/false value, do so. 5139 if (SimplifySelectOps(N, N1, N2)) 5140 return SDValue(N, 0); // Don't revisit N. 5141 5142 if (VT0 == MVT::i1) { 5143 // The code in this block deals with the following 2 equivalences: 5144 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 5145 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 5146 // The target can specify its prefered form with the 5147 // shouldNormalizeToSelectSequence() callback. However we always transform 5148 // to the right anyway if we find the inner select exists in the DAG anyway 5149 // and we always transform to the left side if we know that we can further 5150 // optimize the combination of the conditions. 5151 bool normalizeToSequence 5152 = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 5153 // select (and Cond0, Cond1), X, Y 5154 // -> select Cond0, (select Cond1, X, Y), Y 5155 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 5156 SDValue Cond0 = N0->getOperand(0); 5157 SDValue Cond1 = N0->getOperand(1); 5158 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5159 N1.getValueType(), Cond1, N1, N2); 5160 if (normalizeToSequence || !InnerSelect.use_empty()) 5161 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 5162 InnerSelect, N2); 5163 } 5164 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 5165 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 5166 SDValue Cond0 = N0->getOperand(0); 5167 SDValue Cond1 = N0->getOperand(1); 5168 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 5169 N1.getValueType(), Cond1, N1, N2); 5170 if (normalizeToSequence || !InnerSelect.use_empty()) 5171 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 5172 InnerSelect); 5173 } 5174 5175 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 5176 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 5177 SDValue N1_0 = N1->getOperand(0); 5178 SDValue N1_1 = N1->getOperand(1); 5179 SDValue N1_2 = N1->getOperand(2); 5180 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 5181 // Create the actual and node if we can generate good code for it. 5182 if (!normalizeToSequence) { 5183 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 5184 N0, N1_0); 5185 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 5186 N1_1, N2); 5187 } 5188 // Otherwise see if we can optimize the "and" to a better pattern. 5189 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 5190 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5191 N1_1, N2); 5192 } 5193 } 5194 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 5195 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 5196 SDValue N2_0 = N2->getOperand(0); 5197 SDValue N2_1 = N2->getOperand(1); 5198 SDValue N2_2 = N2->getOperand(2); 5199 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 5200 // Create the actual or node if we can generate good code for it. 5201 if (!normalizeToSequence) { 5202 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 5203 N0, N2_0); 5204 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 5205 N1, N2_2); 5206 } 5207 // Otherwise see if we can optimize to a better pattern. 5208 if (SDValue Combined = visitORLike(N0, N2_0, N)) 5209 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 5210 N1, N2_2); 5211 } 5212 } 5213 } 5214 5215 // fold selects based on a setcc into other things, such as min/max/abs 5216 if (N0.getOpcode() == ISD::SETCC) { 5217 // select x, y (fcmp lt x, y) -> fminnum x, y 5218 // select x, y (fcmp gt x, y) -> fmaxnum x, y 5219 // 5220 // This is OK if we don't care about what happens if either operand is a 5221 // NaN. 5222 // 5223 5224 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 5225 // no signed zeros as well as no nans. 5226 const TargetOptions &Options = DAG.getTarget().Options; 5227 if (Options.UnsafeFPMath && 5228 VT.isFloatingPoint() && N0.hasOneUse() && 5229 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 5230 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5231 5232 if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), 5233 N0.getOperand(1), N1, N2, CC, 5234 TLI, DAG)) 5235 return FMinMax; 5236 } 5237 5238 if ((!LegalOperations && 5239 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 5240 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 5241 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 5242 N0.getOperand(0), N0.getOperand(1), 5243 N1, N2, N0.getOperand(2)); 5244 return SimplifySelect(SDLoc(N), N0, N1, N2); 5245 } 5246 5247 return SDValue(); 5248 } 5249 5250 static 5251 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5252 SDLoc DL(N); 5253 EVT LoVT, HiVT; 5254 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5255 5256 // Split the inputs. 5257 SDValue Lo, Hi, LL, LH, RL, RH; 5258 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5259 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5260 5261 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5262 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5263 5264 return std::make_pair(Lo, Hi); 5265 } 5266 5267 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5268 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5269 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5270 SDLoc dl(N); 5271 SDValue Cond = N->getOperand(0); 5272 SDValue LHS = N->getOperand(1); 5273 SDValue RHS = N->getOperand(2); 5274 EVT VT = N->getValueType(0); 5275 int NumElems = VT.getVectorNumElements(); 5276 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5277 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5278 Cond.getOpcode() == ISD::BUILD_VECTOR); 5279 5280 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5281 // binary ones here. 5282 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5283 return SDValue(); 5284 5285 // We're sure we have an even number of elements due to the 5286 // concat_vectors we have as arguments to vselect. 5287 // Skip BV elements until we find one that's not an UNDEF 5288 // After we find an UNDEF element, keep looping until we get to half the 5289 // length of the BV and see if all the non-undef nodes are the same. 5290 ConstantSDNode *BottomHalf = nullptr; 5291 for (int i = 0; i < NumElems / 2; ++i) { 5292 if (Cond->getOperand(i)->isUndef()) 5293 continue; 5294 5295 if (BottomHalf == nullptr) 5296 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5297 else if (Cond->getOperand(i).getNode() != BottomHalf) 5298 return SDValue(); 5299 } 5300 5301 // Do the same for the second half of the BuildVector 5302 ConstantSDNode *TopHalf = nullptr; 5303 for (int i = NumElems / 2; i < NumElems; ++i) { 5304 if (Cond->getOperand(i)->isUndef()) 5305 continue; 5306 5307 if (TopHalf == nullptr) 5308 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5309 else if (Cond->getOperand(i).getNode() != TopHalf) 5310 return SDValue(); 5311 } 5312 5313 assert(TopHalf && BottomHalf && 5314 "One half of the selector was all UNDEFs and the other was all the " 5315 "same value. This should have been addressed before this function."); 5316 return DAG.getNode( 5317 ISD::CONCAT_VECTORS, dl, VT, 5318 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5319 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5320 } 5321 5322 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5323 5324 if (Level >= AfterLegalizeTypes) 5325 return SDValue(); 5326 5327 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5328 SDValue Mask = MSC->getMask(); 5329 SDValue Data = MSC->getValue(); 5330 SDLoc DL(N); 5331 5332 // If the MSCATTER data type requires splitting and the mask is provided by a 5333 // SETCC, then split both nodes and its operands before legalization. This 5334 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5335 // and enables future optimizations (e.g. min/max pattern matching on X86). 5336 if (Mask.getOpcode() != ISD::SETCC) 5337 return SDValue(); 5338 5339 // Check if any splitting is required. 5340 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5341 TargetLowering::TypeSplitVector) 5342 return SDValue(); 5343 SDValue MaskLo, MaskHi, Lo, Hi; 5344 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5345 5346 EVT LoVT, HiVT; 5347 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5348 5349 SDValue Chain = MSC->getChain(); 5350 5351 EVT MemoryVT = MSC->getMemoryVT(); 5352 unsigned Alignment = MSC->getOriginalAlignment(); 5353 5354 EVT LoMemVT, HiMemVT; 5355 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5356 5357 SDValue DataLo, DataHi; 5358 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5359 5360 SDValue BasePtr = MSC->getBasePtr(); 5361 SDValue IndexLo, IndexHi; 5362 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5363 5364 MachineMemOperand *MMO = DAG.getMachineFunction(). 5365 getMachineMemOperand(MSC->getPointerInfo(), 5366 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5367 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5368 5369 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5370 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5371 DL, OpsLo, MMO); 5372 5373 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5374 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5375 DL, OpsHi, MMO); 5376 5377 AddToWorklist(Lo.getNode()); 5378 AddToWorklist(Hi.getNode()); 5379 5380 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5381 } 5382 5383 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5384 5385 if (Level >= AfterLegalizeTypes) 5386 return SDValue(); 5387 5388 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5389 SDValue Mask = MST->getMask(); 5390 SDValue Data = MST->getValue(); 5391 SDLoc DL(N); 5392 5393 // If the MSTORE data type requires splitting and the mask is provided by a 5394 // SETCC, then split both nodes and its operands before legalization. This 5395 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5396 // and enables future optimizations (e.g. min/max pattern matching on X86). 5397 if (Mask.getOpcode() == ISD::SETCC) { 5398 5399 // Check if any splitting is required. 5400 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5401 TargetLowering::TypeSplitVector) 5402 return SDValue(); 5403 5404 SDValue MaskLo, MaskHi, Lo, Hi; 5405 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5406 5407 EVT LoVT, HiVT; 5408 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5409 5410 SDValue Chain = MST->getChain(); 5411 SDValue Ptr = MST->getBasePtr(); 5412 5413 EVT MemoryVT = MST->getMemoryVT(); 5414 unsigned Alignment = MST->getOriginalAlignment(); 5415 5416 // if Alignment is equal to the vector size, 5417 // take the half of it for the second part 5418 unsigned SecondHalfAlignment = 5419 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5420 Alignment/2 : Alignment; 5421 5422 EVT LoMemVT, HiMemVT; 5423 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5424 5425 SDValue DataLo, DataHi; 5426 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5427 5428 MachineMemOperand *MMO = DAG.getMachineFunction(). 5429 getMachineMemOperand(MST->getPointerInfo(), 5430 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5431 Alignment, MST->getAAInfo(), MST->getRanges()); 5432 5433 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5434 MST->isTruncatingStore()); 5435 5436 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5437 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5438 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5439 5440 MMO = DAG.getMachineFunction(). 5441 getMachineMemOperand(MST->getPointerInfo(), 5442 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5443 SecondHalfAlignment, MST->getAAInfo(), 5444 MST->getRanges()); 5445 5446 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5447 MST->isTruncatingStore()); 5448 5449 AddToWorklist(Lo.getNode()); 5450 AddToWorklist(Hi.getNode()); 5451 5452 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5453 } 5454 return SDValue(); 5455 } 5456 5457 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5458 5459 if (Level >= AfterLegalizeTypes) 5460 return SDValue(); 5461 5462 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5463 SDValue Mask = MGT->getMask(); 5464 SDLoc DL(N); 5465 5466 // If the MGATHER result requires splitting and the mask is provided by a 5467 // SETCC, then split both nodes and its operands before legalization. This 5468 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5469 // and enables future optimizations (e.g. min/max pattern matching on X86). 5470 5471 if (Mask.getOpcode() != ISD::SETCC) 5472 return SDValue(); 5473 5474 EVT VT = N->getValueType(0); 5475 5476 // Check if any splitting is required. 5477 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5478 TargetLowering::TypeSplitVector) 5479 return SDValue(); 5480 5481 SDValue MaskLo, MaskHi, Lo, Hi; 5482 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5483 5484 SDValue Src0 = MGT->getValue(); 5485 SDValue Src0Lo, Src0Hi; 5486 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5487 5488 EVT LoVT, HiVT; 5489 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5490 5491 SDValue Chain = MGT->getChain(); 5492 EVT MemoryVT = MGT->getMemoryVT(); 5493 unsigned Alignment = MGT->getOriginalAlignment(); 5494 5495 EVT LoMemVT, HiMemVT; 5496 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5497 5498 SDValue BasePtr = MGT->getBasePtr(); 5499 SDValue Index = MGT->getIndex(); 5500 SDValue IndexLo, IndexHi; 5501 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5502 5503 MachineMemOperand *MMO = DAG.getMachineFunction(). 5504 getMachineMemOperand(MGT->getPointerInfo(), 5505 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5506 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5507 5508 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5509 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5510 MMO); 5511 5512 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5513 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5514 MMO); 5515 5516 AddToWorklist(Lo.getNode()); 5517 AddToWorklist(Hi.getNode()); 5518 5519 // Build a factor node to remember that this load is independent of the 5520 // other one. 5521 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5522 Hi.getValue(1)); 5523 5524 // Legalized the chain result - switch anything that used the old chain to 5525 // use the new one. 5526 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5527 5528 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5529 5530 SDValue RetOps[] = { GatherRes, Chain }; 5531 return DAG.getMergeValues(RetOps, DL); 5532 } 5533 5534 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5535 5536 if (Level >= AfterLegalizeTypes) 5537 return SDValue(); 5538 5539 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5540 SDValue Mask = MLD->getMask(); 5541 SDLoc DL(N); 5542 5543 // If the MLOAD result requires splitting and the mask is provided by a 5544 // SETCC, then split both nodes and its operands before legalization. This 5545 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5546 // and enables future optimizations (e.g. min/max pattern matching on X86). 5547 5548 if (Mask.getOpcode() == ISD::SETCC) { 5549 EVT VT = N->getValueType(0); 5550 5551 // Check if any splitting is required. 5552 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5553 TargetLowering::TypeSplitVector) 5554 return SDValue(); 5555 5556 SDValue MaskLo, MaskHi, Lo, Hi; 5557 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5558 5559 SDValue Src0 = MLD->getSrc0(); 5560 SDValue Src0Lo, Src0Hi; 5561 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5562 5563 EVT LoVT, HiVT; 5564 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5565 5566 SDValue Chain = MLD->getChain(); 5567 SDValue Ptr = MLD->getBasePtr(); 5568 EVT MemoryVT = MLD->getMemoryVT(); 5569 unsigned Alignment = MLD->getOriginalAlignment(); 5570 5571 // if Alignment is equal to the vector size, 5572 // take the half of it for the second part 5573 unsigned SecondHalfAlignment = 5574 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5575 Alignment/2 : Alignment; 5576 5577 EVT LoMemVT, HiMemVT; 5578 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5579 5580 MachineMemOperand *MMO = DAG.getMachineFunction(). 5581 getMachineMemOperand(MLD->getPointerInfo(), 5582 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5583 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5584 5585 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5586 ISD::NON_EXTLOAD); 5587 5588 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5589 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5590 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5591 5592 MMO = DAG.getMachineFunction(). 5593 getMachineMemOperand(MLD->getPointerInfo(), 5594 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5595 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5596 5597 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5598 ISD::NON_EXTLOAD); 5599 5600 AddToWorklist(Lo.getNode()); 5601 AddToWorklist(Hi.getNode()); 5602 5603 // Build a factor node to remember that this load is independent of the 5604 // other one. 5605 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5606 Hi.getValue(1)); 5607 5608 // Legalized the chain result - switch anything that used the old chain to 5609 // use the new one. 5610 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5611 5612 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5613 5614 SDValue RetOps[] = { LoadRes, Chain }; 5615 return DAG.getMergeValues(RetOps, DL); 5616 } 5617 return SDValue(); 5618 } 5619 5620 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5621 SDValue N0 = N->getOperand(0); 5622 SDValue N1 = N->getOperand(1); 5623 SDValue N2 = N->getOperand(2); 5624 SDLoc DL(N); 5625 5626 // Canonicalize integer abs. 5627 // vselect (setg[te] X, 0), X, -X -> 5628 // vselect (setgt X, -1), X, -X -> 5629 // vselect (setl[te] X, 0), -X, X -> 5630 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5631 if (N0.getOpcode() == ISD::SETCC) { 5632 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5633 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5634 bool isAbs = false; 5635 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5636 5637 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5638 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5639 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5640 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5641 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5642 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5643 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5644 5645 if (isAbs) { 5646 EVT VT = LHS.getValueType(); 5647 SDValue Shift = DAG.getNode( 5648 ISD::SRA, DL, VT, LHS, 5649 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5650 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5651 AddToWorklist(Shift.getNode()); 5652 AddToWorklist(Add.getNode()); 5653 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5654 } 5655 } 5656 5657 if (SimplifySelectOps(N, N1, N2)) 5658 return SDValue(N, 0); // Don't revisit N. 5659 5660 // If the VSELECT result requires splitting and the mask is provided by a 5661 // SETCC, then split both nodes and its operands before legalization. This 5662 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5663 // and enables future optimizations (e.g. min/max pattern matching on X86). 5664 if (N0.getOpcode() == ISD::SETCC) { 5665 EVT VT = N->getValueType(0); 5666 5667 // Check if any splitting is required. 5668 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5669 TargetLowering::TypeSplitVector) 5670 return SDValue(); 5671 5672 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5673 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5674 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5675 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5676 5677 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5678 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5679 5680 // Add the new VSELECT nodes to the work list in case they need to be split 5681 // again. 5682 AddToWorklist(Lo.getNode()); 5683 AddToWorklist(Hi.getNode()); 5684 5685 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5686 } 5687 5688 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5689 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5690 return N1; 5691 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5692 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5693 return N2; 5694 5695 // The ConvertSelectToConcatVector function is assuming both the above 5696 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5697 // and addressed. 5698 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5699 N2.getOpcode() == ISD::CONCAT_VECTORS && 5700 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5701 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 5702 return CV; 5703 } 5704 5705 return SDValue(); 5706 } 5707 5708 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5709 SDValue N0 = N->getOperand(0); 5710 SDValue N1 = N->getOperand(1); 5711 SDValue N2 = N->getOperand(2); 5712 SDValue N3 = N->getOperand(3); 5713 SDValue N4 = N->getOperand(4); 5714 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5715 5716 // fold select_cc lhs, rhs, x, x, cc -> x 5717 if (N2 == N3) 5718 return N2; 5719 5720 // Determine if the condition we're dealing with is constant 5721 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 5722 CC, SDLoc(N), false)) { 5723 AddToWorklist(SCC.getNode()); 5724 5725 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5726 if (!SCCC->isNullValue()) 5727 return N2; // cond always true -> true val 5728 else 5729 return N3; // cond always false -> false val 5730 } else if (SCC->isUndef()) { 5731 // When the condition is UNDEF, just return the first operand. This is 5732 // coherent the DAG creation, no setcc node is created in this case 5733 return N2; 5734 } else if (SCC.getOpcode() == ISD::SETCC) { 5735 // Fold to a simpler select_cc 5736 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5737 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5738 SCC.getOperand(2)); 5739 } 5740 } 5741 5742 // If we can fold this based on the true/false value, do so. 5743 if (SimplifySelectOps(N, N2, N3)) 5744 return SDValue(N, 0); // Don't revisit N. 5745 5746 // fold select_cc into other things, such as min/max/abs 5747 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5748 } 5749 5750 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5751 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5752 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5753 SDLoc(N)); 5754 } 5755 5756 SDValue DAGCombiner::visitSETCCE(SDNode *N) { 5757 SDValue LHS = N->getOperand(0); 5758 SDValue RHS = N->getOperand(1); 5759 SDValue Carry = N->getOperand(2); 5760 SDValue Cond = N->getOperand(3); 5761 5762 // If Carry is false, fold to a regular SETCC. 5763 if (Carry.getOpcode() == ISD::CARRY_FALSE) 5764 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 5765 5766 return SDValue(); 5767 } 5768 5769 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 5770 /// a build_vector of constants. 5771 /// This function is called by the DAGCombiner when visiting sext/zext/aext 5772 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5773 /// Vector extends are not folded if operations are legal; this is to 5774 /// avoid introducing illegal build_vector dag nodes. 5775 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5776 SelectionDAG &DAG, bool LegalTypes, 5777 bool LegalOperations) { 5778 unsigned Opcode = N->getOpcode(); 5779 SDValue N0 = N->getOperand(0); 5780 EVT VT = N->getValueType(0); 5781 5782 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5783 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 5784 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 5785 && "Expected EXTEND dag node in input!"); 5786 5787 // fold (sext c1) -> c1 5788 // fold (zext c1) -> c1 5789 // fold (aext c1) -> c1 5790 if (isa<ConstantSDNode>(N0)) 5791 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5792 5793 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5794 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5795 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5796 EVT SVT = VT.getScalarType(); 5797 if (!(VT.isVector() && 5798 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5799 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5800 return nullptr; 5801 5802 // We can fold this node into a build_vector. 5803 unsigned VTBits = SVT.getSizeInBits(); 5804 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5805 SmallVector<SDValue, 8> Elts; 5806 unsigned NumElts = VT.getVectorNumElements(); 5807 SDLoc DL(N); 5808 5809 for (unsigned i=0; i != NumElts; ++i) { 5810 SDValue Op = N0->getOperand(i); 5811 if (Op->isUndef()) { 5812 Elts.push_back(DAG.getUNDEF(SVT)); 5813 continue; 5814 } 5815 5816 SDLoc DL(Op); 5817 // Get the constant value and if needed trunc it to the size of the type. 5818 // Nodes like build_vector might have constants wider than the scalar type. 5819 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 5820 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 5821 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 5822 else 5823 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 5824 } 5825 5826 return DAG.getBuildVector(VT, DL, Elts).getNode(); 5827 } 5828 5829 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5830 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5831 // transformation. Returns true if extension are possible and the above 5832 // mentioned transformation is profitable. 5833 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5834 unsigned ExtOpc, 5835 SmallVectorImpl<SDNode *> &ExtendNodes, 5836 const TargetLowering &TLI) { 5837 bool HasCopyToRegUses = false; 5838 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5839 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5840 UE = N0.getNode()->use_end(); 5841 UI != UE; ++UI) { 5842 SDNode *User = *UI; 5843 if (User == N) 5844 continue; 5845 if (UI.getUse().getResNo() != N0.getResNo()) 5846 continue; 5847 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5848 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5849 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5850 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5851 // Sign bits will be lost after a zext. 5852 return false; 5853 bool Add = false; 5854 for (unsigned i = 0; i != 2; ++i) { 5855 SDValue UseOp = User->getOperand(i); 5856 if (UseOp == N0) 5857 continue; 5858 if (!isa<ConstantSDNode>(UseOp)) 5859 return false; 5860 Add = true; 5861 } 5862 if (Add) 5863 ExtendNodes.push_back(User); 5864 continue; 5865 } 5866 // If truncates aren't free and there are users we can't 5867 // extend, it isn't worthwhile. 5868 if (!isTruncFree) 5869 return false; 5870 // Remember if this value is live-out. 5871 if (User->getOpcode() == ISD::CopyToReg) 5872 HasCopyToRegUses = true; 5873 } 5874 5875 if (HasCopyToRegUses) { 5876 bool BothLiveOut = false; 5877 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5878 UI != UE; ++UI) { 5879 SDUse &Use = UI.getUse(); 5880 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5881 BothLiveOut = true; 5882 break; 5883 } 5884 } 5885 if (BothLiveOut) 5886 // Both unextended and extended values are live out. There had better be 5887 // a good reason for the transformation. 5888 return ExtendNodes.size(); 5889 } 5890 return true; 5891 } 5892 5893 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5894 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5895 ISD::NodeType ExtType) { 5896 // Extend SetCC uses if necessary. 5897 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5898 SDNode *SetCC = SetCCs[i]; 5899 SmallVector<SDValue, 4> Ops; 5900 5901 for (unsigned j = 0; j != 2; ++j) { 5902 SDValue SOp = SetCC->getOperand(j); 5903 if (SOp == Trunc) 5904 Ops.push_back(ExtLoad); 5905 else 5906 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5907 } 5908 5909 Ops.push_back(SetCC->getOperand(2)); 5910 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5911 } 5912 } 5913 5914 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5915 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5916 SDValue N0 = N->getOperand(0); 5917 EVT DstVT = N->getValueType(0); 5918 EVT SrcVT = N0.getValueType(); 5919 5920 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5921 N->getOpcode() == ISD::ZERO_EXTEND) && 5922 "Unexpected node type (not an extend)!"); 5923 5924 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5925 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5926 // (v8i32 (sext (v8i16 (load x)))) 5927 // into: 5928 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5929 // (v4i32 (sextload (x + 16))))) 5930 // Where uses of the original load, i.e.: 5931 // (v8i16 (load x)) 5932 // are replaced with: 5933 // (v8i16 (truncate 5934 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5935 // (v4i32 (sextload (x + 16))))))) 5936 // 5937 // This combine is only applicable to illegal, but splittable, vectors. 5938 // All legal types, and illegal non-vector types, are handled elsewhere. 5939 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5940 // 5941 if (N0->getOpcode() != ISD::LOAD) 5942 return SDValue(); 5943 5944 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5945 5946 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5947 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5948 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5949 return SDValue(); 5950 5951 SmallVector<SDNode *, 4> SetCCs; 5952 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5953 return SDValue(); 5954 5955 ISD::LoadExtType ExtType = 5956 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5957 5958 // Try to split the vector types to get down to legal types. 5959 EVT SplitSrcVT = SrcVT; 5960 EVT SplitDstVT = DstVT; 5961 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5962 SplitSrcVT.getVectorNumElements() > 1) { 5963 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5964 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5965 } 5966 5967 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5968 return SDValue(); 5969 5970 SDLoc DL(N); 5971 const unsigned NumSplits = 5972 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5973 const unsigned Stride = SplitSrcVT.getStoreSize(); 5974 SmallVector<SDValue, 4> Loads; 5975 SmallVector<SDValue, 4> Chains; 5976 5977 SDValue BasePtr = LN0->getBasePtr(); 5978 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5979 const unsigned Offset = Idx * Stride; 5980 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5981 5982 SDValue SplitLoad = DAG.getExtLoad( 5983 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5984 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5985 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5986 Align, LN0->getAAInfo()); 5987 5988 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5989 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5990 5991 Loads.push_back(SplitLoad.getValue(0)); 5992 Chains.push_back(SplitLoad.getValue(1)); 5993 } 5994 5995 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5996 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5997 5998 CombineTo(N, NewValue); 5999 6000 // Replace uses of the original load (before extension) 6001 // with a truncate of the concatenated sextloaded vectors. 6002 SDValue Trunc = 6003 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 6004 CombineTo(N0.getNode(), Trunc, NewChain); 6005 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 6006 (ISD::NodeType)N->getOpcode()); 6007 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6008 } 6009 6010 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 6011 SDValue N0 = N->getOperand(0); 6012 EVT VT = N->getValueType(0); 6013 6014 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6015 LegalOperations)) 6016 return SDValue(Res, 0); 6017 6018 // fold (sext (sext x)) -> (sext x) 6019 // fold (sext (aext x)) -> (sext x) 6020 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6021 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 6022 N0.getOperand(0)); 6023 6024 if (N0.getOpcode() == ISD::TRUNCATE) { 6025 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 6026 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 6027 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6028 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6029 if (NarrowLoad.getNode() != N0.getNode()) { 6030 CombineTo(N0.getNode(), NarrowLoad); 6031 // CombineTo deleted the truncate, if needed, but not what's under it. 6032 AddToWorklist(oye); 6033 } 6034 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6035 } 6036 6037 // See if the value being truncated is already sign extended. If so, just 6038 // eliminate the trunc/sext pair. 6039 SDValue Op = N0.getOperand(0); 6040 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 6041 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 6042 unsigned DestBits = VT.getScalarType().getSizeInBits(); 6043 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 6044 6045 if (OpBits == DestBits) { 6046 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 6047 // bits, it is already ready. 6048 if (NumSignBits > DestBits-MidBits) 6049 return Op; 6050 } else if (OpBits < DestBits) { 6051 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 6052 // bits, just sext from i32. 6053 if (NumSignBits > OpBits-MidBits) 6054 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 6055 } else { 6056 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 6057 // bits, just truncate to i32. 6058 if (NumSignBits > OpBits-MidBits) 6059 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6060 } 6061 6062 // fold (sext (truncate x)) -> (sextinreg x). 6063 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 6064 N0.getValueType())) { 6065 if (OpBits < DestBits) 6066 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 6067 else if (OpBits > DestBits) 6068 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 6069 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 6070 DAG.getValueType(N0.getValueType())); 6071 } 6072 } 6073 6074 // fold (sext (load x)) -> (sext (truncate (sextload x))) 6075 // Only generate vector extloads when 1) they're legal, and 2) they are 6076 // deemed desirable by the target. 6077 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6078 ((!LegalOperations && !VT.isVector() && 6079 !cast<LoadSDNode>(N0)->isVolatile()) || 6080 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 6081 bool DoXform = true; 6082 SmallVector<SDNode*, 4> SetCCs; 6083 if (!N0.hasOneUse()) 6084 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 6085 if (VT.isVector()) 6086 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6087 if (DoXform) { 6088 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6089 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6090 LN0->getChain(), 6091 LN0->getBasePtr(), N0.getValueType(), 6092 LN0->getMemOperand()); 6093 CombineTo(N, ExtLoad); 6094 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6095 N0.getValueType(), ExtLoad); 6096 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6097 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6098 ISD::SIGN_EXTEND); 6099 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6100 } 6101 } 6102 6103 // fold (sext (load x)) to multiple smaller sextloads. 6104 // Only on illegal but splittable vectors. 6105 if (SDValue ExtLoad = CombineExtLoad(N)) 6106 return ExtLoad; 6107 6108 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 6109 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 6110 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6111 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6112 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6113 EVT MemVT = LN0->getMemoryVT(); 6114 if ((!LegalOperations && !LN0->isVolatile()) || 6115 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 6116 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6117 LN0->getChain(), 6118 LN0->getBasePtr(), MemVT, 6119 LN0->getMemOperand()); 6120 CombineTo(N, ExtLoad); 6121 CombineTo(N0.getNode(), 6122 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6123 N0.getValueType(), ExtLoad), 6124 ExtLoad.getValue(1)); 6125 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6126 } 6127 } 6128 6129 // fold (sext (and/or/xor (load x), cst)) -> 6130 // (and/or/xor (sextload x), (sext cst)) 6131 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6132 N0.getOpcode() == ISD::XOR) && 6133 isa<LoadSDNode>(N0.getOperand(0)) && 6134 N0.getOperand(1).getOpcode() == ISD::Constant && 6135 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 6136 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6137 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6138 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 6139 bool DoXform = true; 6140 SmallVector<SDNode*, 4> SetCCs; 6141 if (!N0.hasOneUse()) 6142 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 6143 SetCCs, TLI); 6144 if (DoXform) { 6145 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 6146 LN0->getChain(), LN0->getBasePtr(), 6147 LN0->getMemoryVT(), 6148 LN0->getMemOperand()); 6149 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6150 Mask = Mask.sext(VT.getSizeInBits()); 6151 SDLoc DL(N); 6152 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6153 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6154 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6155 SDLoc(N0.getOperand(0)), 6156 N0.getOperand(0).getValueType(), ExtLoad); 6157 CombineTo(N, And); 6158 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6159 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6160 ISD::SIGN_EXTEND); 6161 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6162 } 6163 } 6164 } 6165 6166 if (N0.getOpcode() == ISD::SETCC) { 6167 EVT N0VT = N0.getOperand(0).getValueType(); 6168 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 6169 // Only do this before legalize for now. 6170 if (VT.isVector() && !LegalOperations && 6171 TLI.getBooleanContents(N0VT) == 6172 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6173 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 6174 // of the same size as the compared operands. Only optimize sext(setcc()) 6175 // if this is the case. 6176 EVT SVT = getSetCCResultType(N0VT); 6177 6178 // We know that the # elements of the results is the same as the 6179 // # elements of the compare (and the # elements of the compare result 6180 // for that matter). Check to see that they are the same size. If so, 6181 // we know that the element size of the sext'd result matches the 6182 // element size of the compare operands. 6183 if (VT.getSizeInBits() == SVT.getSizeInBits()) 6184 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6185 N0.getOperand(1), 6186 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6187 6188 // If the desired elements are smaller or larger than the source 6189 // elements we can use a matching integer vector type and then 6190 // truncate/sign extend 6191 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6192 if (SVT == MatchingVectorType) { 6193 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 6194 N0.getOperand(0), N0.getOperand(1), 6195 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6196 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 6197 } 6198 } 6199 6200 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 6201 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 6202 SDLoc DL(N); 6203 SDValue NegOne = 6204 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 6205 if (SDValue SCC = SimplifySelectCC( 6206 DL, N0.getOperand(0), N0.getOperand(1), NegOne, 6207 DAG.getConstant(0, DL, VT), 6208 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6209 return SCC; 6210 6211 if (!VT.isVector()) { 6212 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 6213 if (!LegalOperations || 6214 TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) { 6215 SDLoc DL(N); 6216 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 6217 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 6218 N0.getOperand(0), N0.getOperand(1), CC); 6219 return DAG.getSelect(DL, VT, SetCC, 6220 NegOne, DAG.getConstant(0, DL, VT)); 6221 } 6222 } 6223 } 6224 6225 // fold (sext x) -> (zext x) if the sign bit is known zero. 6226 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 6227 DAG.SignBitIsZero(N0)) 6228 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 6229 6230 return SDValue(); 6231 } 6232 6233 // isTruncateOf - If N is a truncate of some other value, return true, record 6234 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 6235 // This function computes KnownZero to avoid a duplicated call to 6236 // computeKnownBits in the caller. 6237 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 6238 APInt &KnownZero) { 6239 APInt KnownOne; 6240 if (N->getOpcode() == ISD::TRUNCATE) { 6241 Op = N->getOperand(0); 6242 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6243 return true; 6244 } 6245 6246 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 6247 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 6248 return false; 6249 6250 SDValue Op0 = N->getOperand(0); 6251 SDValue Op1 = N->getOperand(1); 6252 assert(Op0.getValueType() == Op1.getValueType()); 6253 6254 if (isNullConstant(Op0)) 6255 Op = Op1; 6256 else if (isNullConstant(Op1)) 6257 Op = Op0; 6258 else 6259 return false; 6260 6261 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6262 6263 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6264 return false; 6265 6266 return true; 6267 } 6268 6269 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6270 SDValue N0 = N->getOperand(0); 6271 EVT VT = N->getValueType(0); 6272 6273 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6274 LegalOperations)) 6275 return SDValue(Res, 0); 6276 6277 // fold (zext (zext x)) -> (zext x) 6278 // fold (zext (aext x)) -> (zext x) 6279 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6280 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6281 N0.getOperand(0)); 6282 6283 // fold (zext (truncate x)) -> (zext x) or 6284 // (zext (truncate x)) -> (truncate x) 6285 // This is valid when the truncated bits of x are already zero. 6286 // FIXME: We should extend this to work for vectors too. 6287 SDValue Op; 6288 APInt KnownZero; 6289 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6290 APInt TruncatedBits = 6291 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6292 APInt(Op.getValueSizeInBits(), 0) : 6293 APInt::getBitsSet(Op.getValueSizeInBits(), 6294 N0.getValueSizeInBits(), 6295 std::min(Op.getValueSizeInBits(), 6296 VT.getSizeInBits())); 6297 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6298 if (VT.bitsGT(Op.getValueType())) 6299 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6300 if (VT.bitsLT(Op.getValueType())) 6301 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6302 6303 return Op; 6304 } 6305 } 6306 6307 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6308 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6309 if (N0.getOpcode() == ISD::TRUNCATE) { 6310 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6311 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6312 if (NarrowLoad.getNode() != N0.getNode()) { 6313 CombineTo(N0.getNode(), NarrowLoad); 6314 // CombineTo deleted the truncate, if needed, but not what's under it. 6315 AddToWorklist(oye); 6316 } 6317 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6318 } 6319 } 6320 6321 // fold (zext (truncate x)) -> (and x, mask) 6322 if (N0.getOpcode() == ISD::TRUNCATE) { 6323 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6324 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 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 EVT SrcVT = N0.getOperand(0).getValueType(); 6336 EVT MinVT = N0.getValueType(); 6337 6338 // Try to mask before the extension to avoid having to generate a larger mask, 6339 // possibly over several sub-vectors. 6340 if (SrcVT.bitsLT(VT)) { 6341 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 6342 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 6343 SDValue Op = N0.getOperand(0); 6344 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6345 AddToWorklist(Op.getNode()); 6346 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 6347 } 6348 } 6349 6350 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 6351 SDValue Op = N0.getOperand(0); 6352 if (SrcVT.bitsLT(VT)) { 6353 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6354 AddToWorklist(Op.getNode()); 6355 } else if (SrcVT.bitsGT(VT)) { 6356 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6357 AddToWorklist(Op.getNode()); 6358 } 6359 return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 6360 } 6361 } 6362 6363 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6364 // if either of the casts is not free. 6365 if (N0.getOpcode() == ISD::AND && 6366 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6367 N0.getOperand(1).getOpcode() == ISD::Constant && 6368 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6369 N0.getValueType()) || 6370 !TLI.isZExtFree(N0.getValueType(), VT))) { 6371 SDValue X = N0.getOperand(0).getOperand(0); 6372 if (X.getValueType().bitsLT(VT)) { 6373 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6374 } else if (X.getValueType().bitsGT(VT)) { 6375 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6376 } 6377 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6378 Mask = Mask.zext(VT.getSizeInBits()); 6379 SDLoc DL(N); 6380 return DAG.getNode(ISD::AND, DL, VT, 6381 X, DAG.getConstant(Mask, DL, VT)); 6382 } 6383 6384 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6385 // Only generate vector extloads when 1) they're legal, and 2) they are 6386 // deemed desirable by the target. 6387 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6388 ((!LegalOperations && !VT.isVector() && 6389 !cast<LoadSDNode>(N0)->isVolatile()) || 6390 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6391 bool DoXform = true; 6392 SmallVector<SDNode*, 4> SetCCs; 6393 if (!N0.hasOneUse()) 6394 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6395 if (VT.isVector()) 6396 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6397 if (DoXform) { 6398 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6399 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6400 LN0->getChain(), 6401 LN0->getBasePtr(), N0.getValueType(), 6402 LN0->getMemOperand()); 6403 CombineTo(N, ExtLoad); 6404 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6405 N0.getValueType(), ExtLoad); 6406 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6407 6408 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6409 ISD::ZERO_EXTEND); 6410 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6411 } 6412 } 6413 6414 // fold (zext (load x)) to multiple smaller zextloads. 6415 // Only on illegal but splittable vectors. 6416 if (SDValue ExtLoad = CombineExtLoad(N)) 6417 return ExtLoad; 6418 6419 // fold (zext (and/or/xor (load x), cst)) -> 6420 // (and/or/xor (zextload x), (zext cst)) 6421 // Unless (and (load x) cst) will match as a zextload already and has 6422 // additional users. 6423 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6424 N0.getOpcode() == ISD::XOR) && 6425 isa<LoadSDNode>(N0.getOperand(0)) && 6426 N0.getOperand(1).getOpcode() == ISD::Constant && 6427 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6428 (!LegalOperations && TLI.isOperationLegalOrCustom(N0.getOpcode(), VT))) { 6429 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6430 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6431 bool DoXform = true; 6432 SmallVector<SDNode*, 4> SetCCs; 6433 if (!N0.hasOneUse()) { 6434 if (N0.getOpcode() == ISD::AND) { 6435 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 6436 auto NarrowLoad = false; 6437 EVT LoadResultTy = AndC->getValueType(0); 6438 EVT ExtVT, LoadedVT; 6439 if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT, 6440 NarrowLoad)) 6441 DoXform = false; 6442 } 6443 if (DoXform) 6444 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), 6445 ISD::ZERO_EXTEND, SetCCs, TLI); 6446 } 6447 if (DoXform) { 6448 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6449 LN0->getChain(), LN0->getBasePtr(), 6450 LN0->getMemoryVT(), 6451 LN0->getMemOperand()); 6452 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6453 Mask = Mask.zext(VT.getSizeInBits()); 6454 SDLoc DL(N); 6455 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6456 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6457 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6458 SDLoc(N0.getOperand(0)), 6459 N0.getOperand(0).getValueType(), ExtLoad); 6460 CombineTo(N, And); 6461 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6462 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6463 ISD::ZERO_EXTEND); 6464 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6465 } 6466 } 6467 } 6468 6469 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6470 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6471 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6472 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6473 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6474 EVT MemVT = LN0->getMemoryVT(); 6475 if ((!LegalOperations && !LN0->isVolatile()) || 6476 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6477 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6478 LN0->getChain(), 6479 LN0->getBasePtr(), MemVT, 6480 LN0->getMemOperand()); 6481 CombineTo(N, ExtLoad); 6482 CombineTo(N0.getNode(), 6483 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6484 ExtLoad), 6485 ExtLoad.getValue(1)); 6486 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6487 } 6488 } 6489 6490 if (N0.getOpcode() == ISD::SETCC) { 6491 if (!LegalOperations && VT.isVector() && 6492 N0.getValueType().getVectorElementType() == MVT::i1) { 6493 EVT N0VT = N0.getOperand(0).getValueType(); 6494 if (getSetCCResultType(N0VT) == N0.getValueType()) 6495 return SDValue(); 6496 6497 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6498 // Only do this before legalize for now. 6499 SDLoc DL(N); 6500 SDValue VecOnes = DAG.getConstant(1, DL, VT); 6501 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6502 // We know that the # elements of the results is the same as the 6503 // # elements of the compare (and the # elements of the compare result 6504 // for that matter). Check to see that they are the same size. If so, 6505 // we know that the element size of the sext'd result matches the 6506 // element size of the compare operands. 6507 return DAG.getNode(ISD::AND, DL, VT, 6508 DAG.getSetCC(DL, VT, N0.getOperand(0), 6509 N0.getOperand(1), 6510 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6511 VecOnes); 6512 6513 // If the desired elements are smaller or larger than the source 6514 // elements we can use a matching integer vector type and then 6515 // truncate/sign extend 6516 EVT MatchingElementType = 6517 EVT::getIntegerVT(*DAG.getContext(), 6518 N0VT.getScalarType().getSizeInBits()); 6519 EVT MatchingVectorType = 6520 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6521 N0VT.getVectorNumElements()); 6522 SDValue VsetCC = 6523 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6524 N0.getOperand(1), 6525 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6526 return DAG.getNode(ISD::AND, DL, VT, 6527 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6528 VecOnes); 6529 } 6530 6531 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6532 SDLoc DL(N); 6533 if (SDValue SCC = SimplifySelectCC( 6534 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6535 DAG.getConstant(0, DL, VT), 6536 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6537 return SCC; 6538 } 6539 6540 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6541 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6542 isa<ConstantSDNode>(N0.getOperand(1)) && 6543 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6544 N0.hasOneUse()) { 6545 SDValue ShAmt = N0.getOperand(1); 6546 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6547 if (N0.getOpcode() == ISD::SHL) { 6548 SDValue InnerZExt = N0.getOperand(0); 6549 // If the original shl may be shifting out bits, do not perform this 6550 // transformation. 6551 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6552 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6553 if (ShAmtVal > KnownZeroBits) 6554 return SDValue(); 6555 } 6556 6557 SDLoc DL(N); 6558 6559 // Ensure that the shift amount is wide enough for the shifted value. 6560 if (VT.getSizeInBits() >= 256) 6561 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6562 6563 return DAG.getNode(N0.getOpcode(), DL, VT, 6564 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6565 ShAmt); 6566 } 6567 6568 return SDValue(); 6569 } 6570 6571 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6572 SDValue N0 = N->getOperand(0); 6573 EVT VT = N->getValueType(0); 6574 6575 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6576 LegalOperations)) 6577 return SDValue(Res, 0); 6578 6579 // fold (aext (aext x)) -> (aext x) 6580 // fold (aext (zext x)) -> (zext x) 6581 // fold (aext (sext x)) -> (sext x) 6582 if (N0.getOpcode() == ISD::ANY_EXTEND || 6583 N0.getOpcode() == ISD::ZERO_EXTEND || 6584 N0.getOpcode() == ISD::SIGN_EXTEND) 6585 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6586 6587 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6588 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6589 if (N0.getOpcode() == ISD::TRUNCATE) { 6590 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 6591 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6592 if (NarrowLoad.getNode() != N0.getNode()) { 6593 CombineTo(N0.getNode(), NarrowLoad); 6594 // CombineTo deleted the truncate, if needed, but not what's under it. 6595 AddToWorklist(oye); 6596 } 6597 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6598 } 6599 } 6600 6601 // fold (aext (truncate x)) 6602 if (N0.getOpcode() == ISD::TRUNCATE) { 6603 SDValue TruncOp = N0.getOperand(0); 6604 if (TruncOp.getValueType() == VT) 6605 return TruncOp; // x iff x size == zext size. 6606 if (TruncOp.getValueType().bitsGT(VT)) 6607 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6608 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6609 } 6610 6611 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6612 // if the trunc is not free. 6613 if (N0.getOpcode() == ISD::AND && 6614 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6615 N0.getOperand(1).getOpcode() == ISD::Constant && 6616 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6617 N0.getValueType())) { 6618 SDValue X = N0.getOperand(0).getOperand(0); 6619 if (X.getValueType().bitsLT(VT)) { 6620 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6621 } else if (X.getValueType().bitsGT(VT)) { 6622 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6623 } 6624 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6625 Mask = Mask.zext(VT.getSizeInBits()); 6626 SDLoc DL(N); 6627 return DAG.getNode(ISD::AND, DL, VT, 6628 X, DAG.getConstant(Mask, DL, VT)); 6629 } 6630 6631 // fold (aext (load x)) -> (aext (truncate (extload x))) 6632 // None of the supported targets knows how to perform load and any_ext 6633 // on vectors in one instruction. We only perform this transformation on 6634 // scalars. 6635 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6636 ISD::isUNINDEXEDLoad(N0.getNode()) && 6637 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6638 bool DoXform = true; 6639 SmallVector<SDNode*, 4> SetCCs; 6640 if (!N0.hasOneUse()) 6641 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6642 if (DoXform) { 6643 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6644 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6645 LN0->getChain(), 6646 LN0->getBasePtr(), N0.getValueType(), 6647 LN0->getMemOperand()); 6648 CombineTo(N, ExtLoad); 6649 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6650 N0.getValueType(), ExtLoad); 6651 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6652 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6653 ISD::ANY_EXTEND); 6654 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6655 } 6656 } 6657 6658 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6659 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6660 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6661 if (N0.getOpcode() == ISD::LOAD && 6662 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6663 N0.hasOneUse()) { 6664 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6665 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6666 EVT MemVT = LN0->getMemoryVT(); 6667 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6668 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6669 VT, LN0->getChain(), LN0->getBasePtr(), 6670 MemVT, LN0->getMemOperand()); 6671 CombineTo(N, ExtLoad); 6672 CombineTo(N0.getNode(), 6673 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6674 N0.getValueType(), ExtLoad), 6675 ExtLoad.getValue(1)); 6676 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6677 } 6678 } 6679 6680 if (N0.getOpcode() == ISD::SETCC) { 6681 // For vectors: 6682 // aext(setcc) -> vsetcc 6683 // aext(setcc) -> truncate(vsetcc) 6684 // aext(setcc) -> aext(vsetcc) 6685 // Only do this before legalize for now. 6686 if (VT.isVector() && !LegalOperations) { 6687 EVT N0VT = N0.getOperand(0).getValueType(); 6688 // We know that the # elements of the results is the same as the 6689 // # elements of the compare (and the # elements of the compare result 6690 // for that matter). Check to see that they are the same size. If so, 6691 // we know that the element size of the sext'd result matches the 6692 // element size of the compare operands. 6693 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6694 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6695 N0.getOperand(1), 6696 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6697 // If the desired elements are smaller or larger than the source 6698 // elements we can use a matching integer vector type and then 6699 // truncate/any extend 6700 else { 6701 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6702 SDValue VsetCC = 6703 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6704 N0.getOperand(1), 6705 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6706 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6707 } 6708 } 6709 6710 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6711 SDLoc DL(N); 6712 if (SDValue SCC = SimplifySelectCC( 6713 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 6714 DAG.getConstant(0, DL, VT), 6715 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 6716 return SCC; 6717 } 6718 6719 return SDValue(); 6720 } 6721 6722 /// See if the specified operand can be simplified with the knowledge that only 6723 /// the bits specified by Mask are used. If so, return the simpler operand, 6724 /// otherwise return a null SDValue. 6725 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6726 switch (V.getOpcode()) { 6727 default: break; 6728 case ISD::Constant: { 6729 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6730 assert(CV && "Const value should be ConstSDNode."); 6731 const APInt &CVal = CV->getAPIntValue(); 6732 APInt NewVal = CVal & Mask; 6733 if (NewVal != CVal) 6734 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6735 break; 6736 } 6737 case ISD::OR: 6738 case ISD::XOR: 6739 // If the LHS or RHS don't contribute bits to the or, drop them. 6740 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6741 return V.getOperand(1); 6742 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6743 return V.getOperand(0); 6744 break; 6745 case ISD::SRL: 6746 // Only look at single-use SRLs. 6747 if (!V.getNode()->hasOneUse()) 6748 break; 6749 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) { 6750 // See if we can recursively simplify the LHS. 6751 unsigned Amt = RHSC->getZExtValue(); 6752 6753 // Watch out for shift count overflow though. 6754 if (Amt >= Mask.getBitWidth()) break; 6755 APInt NewMask = Mask << Amt; 6756 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask)) 6757 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6758 SimplifyLHS, V.getOperand(1)); 6759 } 6760 } 6761 return SDValue(); 6762 } 6763 6764 /// If the result of a wider load is shifted to right of N bits and then 6765 /// truncated to a narrower type and where N is a multiple of number of bits of 6766 /// the narrower type, transform it to a narrower load from address + N / num of 6767 /// bits of new type. If the result is to be extended, also fold the extension 6768 /// to form a extending load. 6769 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6770 unsigned Opc = N->getOpcode(); 6771 6772 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6773 SDValue N0 = N->getOperand(0); 6774 EVT VT = N->getValueType(0); 6775 EVT ExtVT = VT; 6776 6777 // This transformation isn't valid for vector loads. 6778 if (VT.isVector()) 6779 return SDValue(); 6780 6781 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6782 // extended to VT. 6783 if (Opc == ISD::SIGN_EXTEND_INREG) { 6784 ExtType = ISD::SEXTLOAD; 6785 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6786 } else if (Opc == ISD::SRL) { 6787 // Another special-case: SRL is basically zero-extending a narrower value. 6788 ExtType = ISD::ZEXTLOAD; 6789 N0 = SDValue(N, 0); 6790 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6791 if (!N01) return SDValue(); 6792 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6793 VT.getSizeInBits() - N01->getZExtValue()); 6794 } 6795 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6796 return SDValue(); 6797 6798 unsigned EVTBits = ExtVT.getSizeInBits(); 6799 6800 // Do not generate loads of non-round integer types since these can 6801 // be expensive (and would be wrong if the type is not byte sized). 6802 if (!ExtVT.isRound()) 6803 return SDValue(); 6804 6805 unsigned ShAmt = 0; 6806 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6807 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6808 ShAmt = N01->getZExtValue(); 6809 // Is the shift amount a multiple of size of VT? 6810 if ((ShAmt & (EVTBits-1)) == 0) { 6811 N0 = N0.getOperand(0); 6812 // Is the load width a multiple of size of VT? 6813 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6814 return SDValue(); 6815 } 6816 6817 // At this point, we must have a load or else we can't do the transform. 6818 if (!isa<LoadSDNode>(N0)) return SDValue(); 6819 6820 // Because a SRL must be assumed to *need* to zero-extend the high bits 6821 // (as opposed to anyext the high bits), we can't combine the zextload 6822 // lowering of SRL and an sextload. 6823 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6824 return SDValue(); 6825 6826 // If the shift amount is larger than the input type then we're not 6827 // accessing any of the loaded bytes. If the load was a zextload/extload 6828 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6829 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6830 return SDValue(); 6831 } 6832 } 6833 6834 // If the load is shifted left (and the result isn't shifted back right), 6835 // we can fold the truncate through the shift. 6836 unsigned ShLeftAmt = 0; 6837 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6838 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6839 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6840 ShLeftAmt = N01->getZExtValue(); 6841 N0 = N0.getOperand(0); 6842 } 6843 } 6844 6845 // If we haven't found a load, we can't narrow it. Don't transform one with 6846 // multiple uses, this would require adding a new load. 6847 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6848 return SDValue(); 6849 6850 // Don't change the width of a volatile load. 6851 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6852 if (LN0->isVolatile()) 6853 return SDValue(); 6854 6855 // Verify that we are actually reducing a load width here. 6856 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6857 return SDValue(); 6858 6859 // For the transform to be legal, the load must produce only two values 6860 // (the value loaded and the chain). Don't transform a pre-increment 6861 // load, for example, which produces an extra value. Otherwise the 6862 // transformation is not equivalent, and the downstream logic to replace 6863 // uses gets things wrong. 6864 if (LN0->getNumValues() > 2) 6865 return SDValue(); 6866 6867 // If the load that we're shrinking is an extload and we're not just 6868 // discarding the extension we can't simply shrink the load. Bail. 6869 // TODO: It would be possible to merge the extensions in some cases. 6870 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6871 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6872 return SDValue(); 6873 6874 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6875 return SDValue(); 6876 6877 EVT PtrType = N0.getOperand(1).getValueType(); 6878 6879 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6880 // It's not possible to generate a constant of extended or untyped type. 6881 return SDValue(); 6882 6883 // For big endian targets, we need to adjust the offset to the pointer to 6884 // load the correct bytes. 6885 if (DAG.getDataLayout().isBigEndian()) { 6886 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6887 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6888 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6889 } 6890 6891 uint64_t PtrOff = ShAmt / 8; 6892 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6893 SDLoc DL(LN0); 6894 // The original load itself didn't wrap, so an offset within it doesn't. 6895 SDNodeFlags Flags; 6896 Flags.setNoUnsignedWrap(true); 6897 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6898 PtrType, LN0->getBasePtr(), 6899 DAG.getConstant(PtrOff, DL, PtrType), 6900 &Flags); 6901 AddToWorklist(NewPtr.getNode()); 6902 6903 SDValue Load; 6904 if (ExtType == ISD::NON_EXTLOAD) 6905 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6906 LN0->getPointerInfo().getWithOffset(PtrOff), 6907 LN0->isVolatile(), LN0->isNonTemporal(), 6908 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6909 else 6910 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6911 LN0->getPointerInfo().getWithOffset(PtrOff), 6912 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6913 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6914 6915 // Replace the old load's chain with the new load's chain. 6916 WorklistRemover DeadNodes(*this); 6917 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6918 6919 // Shift the result left, if we've swallowed a left shift. 6920 SDValue Result = Load; 6921 if (ShLeftAmt != 0) { 6922 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6923 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6924 ShImmTy = VT; 6925 // If the shift amount is as large as the result size (but, presumably, 6926 // no larger than the source) then the useful bits of the result are 6927 // zero; we can't simply return the shortened shift, because the result 6928 // of that operation is undefined. 6929 SDLoc DL(N0); 6930 if (ShLeftAmt >= VT.getSizeInBits()) 6931 Result = DAG.getConstant(0, DL, VT); 6932 else 6933 Result = DAG.getNode(ISD::SHL, DL, VT, 6934 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6935 } 6936 6937 // Return the new loaded value. 6938 return Result; 6939 } 6940 6941 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6942 SDValue N0 = N->getOperand(0); 6943 SDValue N1 = N->getOperand(1); 6944 EVT VT = N->getValueType(0); 6945 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6946 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6947 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6948 6949 if (N0.isUndef()) 6950 return DAG.getUNDEF(VT); 6951 6952 // fold (sext_in_reg c1) -> c1 6953 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 6954 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6955 6956 // If the input is already sign extended, just drop the extension. 6957 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6958 return N0; 6959 6960 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6961 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6962 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6963 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6964 N0.getOperand(0), N1); 6965 6966 // fold (sext_in_reg (sext x)) -> (sext x) 6967 // fold (sext_in_reg (aext x)) -> (sext x) 6968 // if x is small enough. 6969 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6970 SDValue N00 = N0.getOperand(0); 6971 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6972 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6973 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6974 } 6975 6976 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6977 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6978 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6979 6980 // fold operands of sext_in_reg based on knowledge that the top bits are not 6981 // demanded. 6982 if (SimplifyDemandedBits(SDValue(N, 0))) 6983 return SDValue(N, 0); 6984 6985 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6986 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6987 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 6988 return NarrowLoad; 6989 6990 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6991 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6992 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6993 if (N0.getOpcode() == ISD::SRL) { 6994 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6995 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6996 // We can turn this into an SRA iff the input to the SRL is already sign 6997 // extended enough. 6998 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6999 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 7000 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 7001 N0.getOperand(0), N0.getOperand(1)); 7002 } 7003 } 7004 7005 // fold (sext_inreg (extload x)) -> (sextload x) 7006 if (ISD::isEXTLoad(N0.getNode()) && 7007 ISD::isUNINDEXEDLoad(N0.getNode()) && 7008 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7009 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7010 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7011 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7012 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7013 LN0->getChain(), 7014 LN0->getBasePtr(), EVT, 7015 LN0->getMemOperand()); 7016 CombineTo(N, ExtLoad); 7017 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7018 AddToWorklist(ExtLoad.getNode()); 7019 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7020 } 7021 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 7022 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 7023 N0.hasOneUse() && 7024 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 7025 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 7026 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 7027 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7028 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 7029 LN0->getChain(), 7030 LN0->getBasePtr(), EVT, 7031 LN0->getMemOperand()); 7032 CombineTo(N, ExtLoad); 7033 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 7034 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7035 } 7036 7037 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 7038 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 7039 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 7040 N0.getOperand(1), false)) 7041 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 7042 BSwap, N1); 7043 } 7044 7045 return SDValue(); 7046 } 7047 7048 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 7049 SDValue N0 = N->getOperand(0); 7050 EVT VT = N->getValueType(0); 7051 7052 if (N0.isUndef()) 7053 return DAG.getUNDEF(VT); 7054 7055 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7056 LegalOperations)) 7057 return SDValue(Res, 0); 7058 7059 return SDValue(); 7060 } 7061 7062 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 7063 SDValue N0 = N->getOperand(0); 7064 EVT VT = N->getValueType(0); 7065 7066 if (N0.isUndef()) 7067 return DAG.getUNDEF(VT); 7068 7069 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 7070 LegalOperations)) 7071 return SDValue(Res, 0); 7072 7073 return SDValue(); 7074 } 7075 7076 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 7077 SDValue N0 = N->getOperand(0); 7078 EVT VT = N->getValueType(0); 7079 bool isLE = DAG.getDataLayout().isLittleEndian(); 7080 7081 // noop truncate 7082 if (N0.getValueType() == N->getValueType(0)) 7083 return N0; 7084 // fold (truncate c1) -> c1 7085 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7086 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 7087 // fold (truncate (truncate x)) -> (truncate x) 7088 if (N0.getOpcode() == ISD::TRUNCATE) 7089 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7090 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 7091 if (N0.getOpcode() == ISD::ZERO_EXTEND || 7092 N0.getOpcode() == ISD::SIGN_EXTEND || 7093 N0.getOpcode() == ISD::ANY_EXTEND) { 7094 // if the source is smaller than the dest, we still need an extend. 7095 if (N0.getOperand(0).getValueType().bitsLT(VT)) 7096 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 7097 // if the source is larger than the dest, than we just need the truncate. 7098 if (N0.getOperand(0).getValueType().bitsGT(VT)) 7099 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 7100 // if the source and dest are the same type, we can drop both the extend 7101 // and the truncate. 7102 return N0.getOperand(0); 7103 } 7104 7105 // Fold extract-and-trunc into a narrow extract. For example: 7106 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 7107 // i32 y = TRUNCATE(i64 x) 7108 // -- becomes -- 7109 // v16i8 b = BITCAST (v2i64 val) 7110 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 7111 // 7112 // Note: We only run this optimization after type legalization (which often 7113 // creates this pattern) and before operation legalization after which 7114 // we need to be more careful about the vector instructions that we generate. 7115 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7116 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 7117 7118 EVT VecTy = N0.getOperand(0).getValueType(); 7119 EVT ExTy = N0.getValueType(); 7120 EVT TrTy = N->getValueType(0); 7121 7122 unsigned NumElem = VecTy.getVectorNumElements(); 7123 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 7124 7125 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 7126 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 7127 7128 SDValue EltNo = N0->getOperand(1); 7129 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 7130 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 7131 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 7132 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 7133 7134 SDLoc DL(N); 7135 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 7136 DAG.getBitcast(NVT, N0.getOperand(0)), 7137 DAG.getConstant(Index, DL, IndexTy)); 7138 } 7139 } 7140 7141 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 7142 if (N0.getOpcode() == ISD::SELECT) { 7143 EVT SrcVT = N0.getValueType(); 7144 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 7145 TLI.isTruncateFree(SrcVT, VT)) { 7146 SDLoc SL(N0); 7147 SDValue Cond = N0.getOperand(0); 7148 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 7149 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 7150 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 7151 } 7152 } 7153 7154 // Fold a series of buildvector, bitcast, and truncate if possible. 7155 // For example fold 7156 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 7157 // (2xi32 (buildvector x, y)). 7158 if (Level == AfterLegalizeVectorOps && VT.isVector() && 7159 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 7160 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 7161 N0.getOperand(0).hasOneUse()) { 7162 7163 SDValue BuildVect = N0.getOperand(0); 7164 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 7165 EVT TruncVecEltTy = VT.getVectorElementType(); 7166 7167 // Check that the element types match. 7168 if (BuildVectEltTy == TruncVecEltTy) { 7169 // Now we only need to compute the offset of the truncated elements. 7170 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 7171 unsigned TruncVecNumElts = VT.getVectorNumElements(); 7172 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 7173 7174 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 7175 "Invalid number of elements"); 7176 7177 SmallVector<SDValue, 8> Opnds; 7178 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 7179 Opnds.push_back(BuildVect.getOperand(i)); 7180 7181 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 7182 } 7183 } 7184 7185 // See if we can simplify the input to this truncate through knowledge that 7186 // only the low bits are being used. 7187 // For example "trunc (or (shl x, 8), y)" // -> trunc y 7188 // Currently we only perform this optimization on scalars because vectors 7189 // may have different active low bits. 7190 if (!VT.isVector()) { 7191 if (SDValue Shorter = 7192 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 7193 VT.getSizeInBits()))) 7194 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 7195 } 7196 // fold (truncate (load x)) -> (smaller load x) 7197 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 7198 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 7199 if (SDValue Reduced = ReduceLoadWidth(N)) 7200 return Reduced; 7201 7202 // Handle the case where the load remains an extending load even 7203 // after truncation. 7204 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 7205 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7206 if (!LN0->isVolatile() && 7207 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 7208 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 7209 VT, LN0->getChain(), LN0->getBasePtr(), 7210 LN0->getMemoryVT(), 7211 LN0->getMemOperand()); 7212 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 7213 return NewLoad; 7214 } 7215 } 7216 } 7217 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 7218 // where ... are all 'undef'. 7219 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 7220 SmallVector<EVT, 8> VTs; 7221 SDValue V; 7222 unsigned Idx = 0; 7223 unsigned NumDefs = 0; 7224 7225 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 7226 SDValue X = N0.getOperand(i); 7227 if (!X.isUndef()) { 7228 V = X; 7229 Idx = i; 7230 NumDefs++; 7231 } 7232 // Stop if more than one members are non-undef. 7233 if (NumDefs > 1) 7234 break; 7235 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 7236 VT.getVectorElementType(), 7237 X.getValueType().getVectorNumElements())); 7238 } 7239 7240 if (NumDefs == 0) 7241 return DAG.getUNDEF(VT); 7242 7243 if (NumDefs == 1) { 7244 assert(V.getNode() && "The single defined operand is empty!"); 7245 SmallVector<SDValue, 8> Opnds; 7246 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 7247 if (i != Idx) { 7248 Opnds.push_back(DAG.getUNDEF(VTs[i])); 7249 continue; 7250 } 7251 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 7252 AddToWorklist(NV.getNode()); 7253 Opnds.push_back(NV); 7254 } 7255 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 7256 } 7257 } 7258 7259 // Fold truncate of a bitcast of a vector to an extract of the low vector 7260 // element. 7261 // 7262 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0 7263 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 7264 SDValue VecSrc = N0.getOperand(0); 7265 EVT SrcVT = VecSrc.getValueType(); 7266 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 7267 (!LegalOperations || 7268 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 7269 SDLoc SL(N); 7270 7271 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 7272 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 7273 VecSrc, DAG.getConstant(0, SL, IdxVT)); 7274 } 7275 } 7276 7277 // Simplify the operands using demanded-bits information. 7278 if (!VT.isVector() && 7279 SimplifyDemandedBits(SDValue(N, 0))) 7280 return SDValue(N, 0); 7281 7282 return SDValue(); 7283 } 7284 7285 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 7286 SDValue Elt = N->getOperand(i); 7287 if (Elt.getOpcode() != ISD::MERGE_VALUES) 7288 return Elt.getNode(); 7289 return Elt.getOperand(Elt.getResNo()).getNode(); 7290 } 7291 7292 /// build_pair (load, load) -> load 7293 /// if load locations are consecutive. 7294 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 7295 assert(N->getOpcode() == ISD::BUILD_PAIR); 7296 7297 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 7298 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 7299 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 7300 LD1->getAddressSpace() != LD2->getAddressSpace()) 7301 return SDValue(); 7302 EVT LD1VT = LD1->getValueType(0); 7303 unsigned LD1Bytes = LD1VT.getSizeInBits() / 8; 7304 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 7305 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 7306 unsigned Align = LD1->getAlignment(); 7307 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 7308 VT.getTypeForEVT(*DAG.getContext())); 7309 7310 if (NewAlign <= Align && 7311 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7312 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7313 LD1->getBasePtr(), LD1->getPointerInfo(), 7314 false, false, false, Align); 7315 } 7316 7317 return SDValue(); 7318 } 7319 7320 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 7321 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 7322 // and Lo parts; on big-endian machines it doesn't. 7323 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 7324 } 7325 7326 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7327 SDValue N0 = N->getOperand(0); 7328 EVT VT = N->getValueType(0); 7329 7330 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7331 // Only do this before legalize, since afterward the target may be depending 7332 // on the bitconvert. 7333 // First check to see if this is all constant. 7334 if (!LegalTypes && 7335 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7336 VT.isVector()) { 7337 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7338 7339 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7340 assert(!DestEltVT.isVector() && 7341 "Element type of vector ValueType must not be vector!"); 7342 if (isSimple) 7343 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7344 } 7345 7346 // If the input is a constant, let getNode fold it. 7347 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7348 // If we can't allow illegal operations, we need to check that this is just 7349 // a fp -> int or int -> conversion and that the resulting operation will 7350 // be legal. 7351 if (!LegalOperations || 7352 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7353 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7354 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7355 TLI.isOperationLegal(ISD::Constant, VT))) 7356 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7357 } 7358 7359 // (conv (conv x, t1), t2) -> (conv x, t2) 7360 if (N0.getOpcode() == ISD::BITCAST) 7361 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7362 N0.getOperand(0)); 7363 7364 // fold (conv (load x)) -> (load (conv*)x) 7365 // If the resultant load doesn't need a higher alignment than the original! 7366 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7367 // Do not change the width of a volatile load. 7368 !cast<LoadSDNode>(N0)->isVolatile() && 7369 // Do not remove the cast if the types differ in endian layout. 7370 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 7371 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 7372 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7373 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7374 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7375 unsigned OrigAlign = LN0->getAlignment(); 7376 7377 bool Fast = false; 7378 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7379 LN0->getAddressSpace(), OrigAlign, &Fast) && 7380 Fast) { 7381 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7382 LN0->getBasePtr(), LN0->getPointerInfo(), 7383 LN0->isVolatile(), LN0->isNonTemporal(), 7384 LN0->isInvariant(), OrigAlign, 7385 LN0->getAAInfo()); 7386 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7387 return Load; 7388 } 7389 } 7390 7391 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7392 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7393 // 7394 // For ppc_fp128: 7395 // fold (bitcast (fneg x)) -> 7396 // flipbit = signbit 7397 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7398 // 7399 // fold (bitcast (fabs x)) -> 7400 // flipbit = (and (extract_element (bitcast x), 0), signbit) 7401 // (xor (bitcast x) (build_pair flipbit, flipbit)) 7402 // This often reduces constant pool loads. 7403 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7404 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7405 N0.getNode()->hasOneUse() && VT.isInteger() && 7406 !VT.isVector() && !N0.getValueType().isVector()) { 7407 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7408 N0.getOperand(0)); 7409 AddToWorklist(NewConv.getNode()); 7410 7411 SDLoc DL(N); 7412 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7413 assert(VT.getSizeInBits() == 128); 7414 SDValue SignBit = DAG.getConstant( 7415 APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 7416 SDValue FlipBit; 7417 if (N0.getOpcode() == ISD::FNEG) { 7418 FlipBit = SignBit; 7419 AddToWorklist(FlipBit.getNode()); 7420 } else { 7421 assert(N0.getOpcode() == ISD::FABS); 7422 SDValue Hi = 7423 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 7424 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7425 SDLoc(NewConv))); 7426 AddToWorklist(Hi.getNode()); 7427 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 7428 AddToWorklist(FlipBit.getNode()); 7429 } 7430 SDValue FlipBits = 7431 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7432 AddToWorklist(FlipBits.getNode()); 7433 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 7434 } 7435 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7436 if (N0.getOpcode() == ISD::FNEG) 7437 return DAG.getNode(ISD::XOR, DL, VT, 7438 NewConv, DAG.getConstant(SignBit, DL, VT)); 7439 assert(N0.getOpcode() == ISD::FABS); 7440 return DAG.getNode(ISD::AND, DL, VT, 7441 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7442 } 7443 7444 // fold (bitconvert (fcopysign cst, x)) -> 7445 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7446 // Note that we don't handle (copysign x, cst) because this can always be 7447 // folded to an fneg or fabs. 7448 // 7449 // For ppc_fp128: 7450 // fold (bitcast (fcopysign cst, x)) -> 7451 // flipbit = (and (extract_element 7452 // (xor (bitcast cst), (bitcast x)), 0), 7453 // signbit) 7454 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 7455 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7456 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7457 VT.isInteger() && !VT.isVector()) { 7458 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7459 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7460 if (isTypeLegal(IntXVT)) { 7461 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7462 IntXVT, N0.getOperand(1)); 7463 AddToWorklist(X.getNode()); 7464 7465 // If X has a different width than the result/lhs, sext it or truncate it. 7466 unsigned VTWidth = VT.getSizeInBits(); 7467 if (OrigXWidth < VTWidth) { 7468 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7469 AddToWorklist(X.getNode()); 7470 } else if (OrigXWidth > VTWidth) { 7471 // To get the sign bit in the right place, we have to shift it right 7472 // before truncating. 7473 SDLoc DL(X); 7474 X = DAG.getNode(ISD::SRL, DL, 7475 X.getValueType(), X, 7476 DAG.getConstant(OrigXWidth-VTWidth, DL, 7477 X.getValueType())); 7478 AddToWorklist(X.getNode()); 7479 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7480 AddToWorklist(X.getNode()); 7481 } 7482 7483 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 7484 APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2); 7485 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 7486 AddToWorklist(Cst.getNode()); 7487 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 7488 AddToWorklist(X.getNode()); 7489 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 7490 AddToWorklist(XorResult.getNode()); 7491 SDValue XorResult64 = DAG.getNode( 7492 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 7493 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 7494 SDLoc(XorResult))); 7495 AddToWorklist(XorResult64.getNode()); 7496 SDValue FlipBit = 7497 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 7498 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 7499 AddToWorklist(FlipBit.getNode()); 7500 SDValue FlipBits = 7501 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 7502 AddToWorklist(FlipBits.getNode()); 7503 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 7504 } 7505 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7506 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7507 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7508 AddToWorklist(X.getNode()); 7509 7510 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7511 VT, N0.getOperand(0)); 7512 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7513 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7514 AddToWorklist(Cst.getNode()); 7515 7516 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7517 } 7518 } 7519 7520 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7521 if (N0.getOpcode() == ISD::BUILD_PAIR) 7522 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 7523 return CombineLD; 7524 7525 // Remove double bitcasts from shuffles - this is often a legacy of 7526 // XformToShuffleWithZero being used to combine bitmaskings (of 7527 // float vectors bitcast to integer vectors) into shuffles. 7528 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7529 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7530 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7531 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7532 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7533 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7534 7535 // If operands are a bitcast, peek through if it casts the original VT. 7536 // If operands are a constant, just bitcast back to original VT. 7537 auto PeekThroughBitcast = [&](SDValue Op) { 7538 if (Op.getOpcode() == ISD::BITCAST && 7539 Op.getOperand(0).getValueType() == VT) 7540 return SDValue(Op.getOperand(0)); 7541 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7542 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7543 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7544 return SDValue(); 7545 }; 7546 7547 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7548 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7549 if (!(SV0 && SV1)) 7550 return SDValue(); 7551 7552 int MaskScale = 7553 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7554 SmallVector<int, 8> NewMask; 7555 for (int M : SVN->getMask()) 7556 for (int i = 0; i != MaskScale; ++i) 7557 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7558 7559 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7560 if (!LegalMask) { 7561 std::swap(SV0, SV1); 7562 ShuffleVectorSDNode::commuteMask(NewMask); 7563 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7564 } 7565 7566 if (LegalMask) 7567 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7568 } 7569 7570 return SDValue(); 7571 } 7572 7573 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7574 EVT VT = N->getValueType(0); 7575 return CombineConsecutiveLoads(N, VT); 7576 } 7577 7578 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7579 /// operands. DstEltVT indicates the destination element value type. 7580 SDValue DAGCombiner:: 7581 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7582 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7583 7584 // If this is already the right type, we're done. 7585 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7586 7587 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7588 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7589 7590 // If this is a conversion of N elements of one type to N elements of another 7591 // type, convert each element. This handles FP<->INT cases. 7592 if (SrcBitSize == DstBitSize) { 7593 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7594 BV->getValueType(0).getVectorNumElements()); 7595 7596 // Due to the FP element handling below calling this routine recursively, 7597 // we can end up with a scalar-to-vector node here. 7598 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7599 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7600 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7601 DstEltVT, BV->getOperand(0))); 7602 7603 SmallVector<SDValue, 8> Ops; 7604 for (SDValue Op : BV->op_values()) { 7605 // If the vector element type is not legal, the BUILD_VECTOR operands 7606 // are promoted and implicitly truncated. Make that explicit here. 7607 if (Op.getValueType() != SrcEltVT) 7608 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7609 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7610 DstEltVT, Op)); 7611 AddToWorklist(Ops.back().getNode()); 7612 } 7613 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 7614 } 7615 7616 // Otherwise, we're growing or shrinking the elements. To avoid having to 7617 // handle annoying details of growing/shrinking FP values, we convert them to 7618 // int first. 7619 if (SrcEltVT.isFloatingPoint()) { 7620 // Convert the input float vector to a int vector where the elements are the 7621 // same sizes. 7622 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7623 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7624 SrcEltVT = IntVT; 7625 } 7626 7627 // Now we know the input is an integer vector. If the output is a FP type, 7628 // convert to integer first, then to FP of the right size. 7629 if (DstEltVT.isFloatingPoint()) { 7630 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7631 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7632 7633 // Next, convert to FP elements of the same size. 7634 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7635 } 7636 7637 SDLoc DL(BV); 7638 7639 // Okay, we know the src/dst types are both integers of differing types. 7640 // Handling growing first. 7641 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7642 if (SrcBitSize < DstBitSize) { 7643 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7644 7645 SmallVector<SDValue, 8> Ops; 7646 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7647 i += NumInputsPerOutput) { 7648 bool isLE = DAG.getDataLayout().isLittleEndian(); 7649 APInt NewBits = APInt(DstBitSize, 0); 7650 bool EltIsUndef = true; 7651 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7652 // Shift the previously computed bits over. 7653 NewBits <<= SrcBitSize; 7654 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7655 if (Op.isUndef()) continue; 7656 EltIsUndef = false; 7657 7658 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7659 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7660 } 7661 7662 if (EltIsUndef) 7663 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7664 else 7665 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7666 } 7667 7668 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7669 return DAG.getBuildVector(VT, DL, Ops); 7670 } 7671 7672 // Finally, this must be the case where we are shrinking elements: each input 7673 // turns into multiple outputs. 7674 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7675 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7676 NumOutputsPerInput*BV->getNumOperands()); 7677 SmallVector<SDValue, 8> Ops; 7678 7679 for (const SDValue &Op : BV->op_values()) { 7680 if (Op.isUndef()) { 7681 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7682 continue; 7683 } 7684 7685 APInt OpVal = cast<ConstantSDNode>(Op)-> 7686 getAPIntValue().zextOrTrunc(SrcBitSize); 7687 7688 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7689 APInt ThisVal = OpVal.trunc(DstBitSize); 7690 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7691 OpVal = OpVal.lshr(DstBitSize); 7692 } 7693 7694 // For big endian targets, swap the order of the pieces of each element. 7695 if (DAG.getDataLayout().isBigEndian()) 7696 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7697 } 7698 7699 return DAG.getBuildVector(VT, DL, Ops); 7700 } 7701 7702 /// Try to perform FMA combining on a given FADD node. 7703 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7704 SDValue N0 = N->getOperand(0); 7705 SDValue N1 = N->getOperand(1); 7706 EVT VT = N->getValueType(0); 7707 SDLoc SL(N); 7708 7709 const TargetOptions &Options = DAG.getTarget().Options; 7710 bool AllowFusion = 7711 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7712 7713 // Floating-point multiply-add with intermediate rounding. 7714 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7715 7716 // Floating-point multiply-add without intermediate rounding. 7717 bool HasFMA = 7718 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7719 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7720 7721 // No valid opcode, do not combine. 7722 if (!HasFMAD && !HasFMA) 7723 return SDValue(); 7724 7725 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7726 ; 7727 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7728 return SDValue(); 7729 7730 // Always prefer FMAD to FMA for precision. 7731 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7732 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7733 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7734 7735 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 7736 // prefer to fold the multiply with fewer uses. 7737 if (Aggressive && N0.getOpcode() == ISD::FMUL && 7738 N1.getOpcode() == ISD::FMUL) { 7739 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 7740 std::swap(N0, N1); 7741 } 7742 7743 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7744 if (N0.getOpcode() == ISD::FMUL && 7745 (Aggressive || N0->hasOneUse())) { 7746 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7747 N0.getOperand(0), N0.getOperand(1), N1); 7748 } 7749 7750 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7751 // Note: Commutes FADD operands. 7752 if (N1.getOpcode() == ISD::FMUL && 7753 (Aggressive || N1->hasOneUse())) { 7754 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7755 N1.getOperand(0), N1.getOperand(1), N0); 7756 } 7757 7758 // Look through FP_EXTEND nodes to do more combining. 7759 if (AllowFusion && LookThroughFPExt) { 7760 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7761 if (N0.getOpcode() == ISD::FP_EXTEND) { 7762 SDValue N00 = N0.getOperand(0); 7763 if (N00.getOpcode() == ISD::FMUL) 7764 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7765 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7766 N00.getOperand(0)), 7767 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7768 N00.getOperand(1)), N1); 7769 } 7770 7771 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7772 // Note: Commutes FADD operands. 7773 if (N1.getOpcode() == ISD::FP_EXTEND) { 7774 SDValue N10 = N1.getOperand(0); 7775 if (N10.getOpcode() == ISD::FMUL) 7776 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7777 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7778 N10.getOperand(0)), 7779 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7780 N10.getOperand(1)), N0); 7781 } 7782 } 7783 7784 // More folding opportunities when target permits. 7785 if ((AllowFusion || HasFMAD) && Aggressive) { 7786 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7787 if (N0.getOpcode() == PreferredFusedOpcode && 7788 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7789 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7790 N0.getOperand(0), N0.getOperand(1), 7791 DAG.getNode(PreferredFusedOpcode, SL, VT, 7792 N0.getOperand(2).getOperand(0), 7793 N0.getOperand(2).getOperand(1), 7794 N1)); 7795 } 7796 7797 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7798 if (N1->getOpcode() == PreferredFusedOpcode && 7799 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7800 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7801 N1.getOperand(0), N1.getOperand(1), 7802 DAG.getNode(PreferredFusedOpcode, SL, VT, 7803 N1.getOperand(2).getOperand(0), 7804 N1.getOperand(2).getOperand(1), 7805 N0)); 7806 } 7807 7808 if (AllowFusion && LookThroughFPExt) { 7809 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7810 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7811 auto FoldFAddFMAFPExtFMul = [&] ( 7812 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7813 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7814 DAG.getNode(PreferredFusedOpcode, SL, VT, 7815 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7816 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7817 Z)); 7818 }; 7819 if (N0.getOpcode() == PreferredFusedOpcode) { 7820 SDValue N02 = N0.getOperand(2); 7821 if (N02.getOpcode() == ISD::FP_EXTEND) { 7822 SDValue N020 = N02.getOperand(0); 7823 if (N020.getOpcode() == ISD::FMUL) 7824 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7825 N020.getOperand(0), N020.getOperand(1), 7826 N1); 7827 } 7828 } 7829 7830 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7831 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7832 // FIXME: This turns two single-precision and one double-precision 7833 // operation into two double-precision operations, which might not be 7834 // interesting for all targets, especially GPUs. 7835 auto FoldFAddFPExtFMAFMul = [&] ( 7836 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7837 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7838 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7839 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7840 DAG.getNode(PreferredFusedOpcode, SL, VT, 7841 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7842 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7843 Z)); 7844 }; 7845 if (N0.getOpcode() == ISD::FP_EXTEND) { 7846 SDValue N00 = N0.getOperand(0); 7847 if (N00.getOpcode() == PreferredFusedOpcode) { 7848 SDValue N002 = N00.getOperand(2); 7849 if (N002.getOpcode() == ISD::FMUL) 7850 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7851 N002.getOperand(0), N002.getOperand(1), 7852 N1); 7853 } 7854 } 7855 7856 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7857 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7858 if (N1.getOpcode() == PreferredFusedOpcode) { 7859 SDValue N12 = N1.getOperand(2); 7860 if (N12.getOpcode() == ISD::FP_EXTEND) { 7861 SDValue N120 = N12.getOperand(0); 7862 if (N120.getOpcode() == ISD::FMUL) 7863 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7864 N120.getOperand(0), N120.getOperand(1), 7865 N0); 7866 } 7867 } 7868 7869 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7870 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7871 // FIXME: This turns two single-precision and one double-precision 7872 // operation into two double-precision operations, which might not be 7873 // interesting for all targets, especially GPUs. 7874 if (N1.getOpcode() == ISD::FP_EXTEND) { 7875 SDValue N10 = N1.getOperand(0); 7876 if (N10.getOpcode() == PreferredFusedOpcode) { 7877 SDValue N102 = N10.getOperand(2); 7878 if (N102.getOpcode() == ISD::FMUL) 7879 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7880 N102.getOperand(0), N102.getOperand(1), 7881 N0); 7882 } 7883 } 7884 } 7885 } 7886 7887 return SDValue(); 7888 } 7889 7890 /// Try to perform FMA combining on a given FSUB node. 7891 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7892 SDValue N0 = N->getOperand(0); 7893 SDValue N1 = N->getOperand(1); 7894 EVT VT = N->getValueType(0); 7895 SDLoc SL(N); 7896 7897 const TargetOptions &Options = DAG.getTarget().Options; 7898 bool AllowFusion = 7899 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 7900 7901 // Floating-point multiply-add with intermediate rounding. 7902 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 7903 7904 // Floating-point multiply-add without intermediate rounding. 7905 bool HasFMA = 7906 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 7907 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 7908 7909 // No valid opcode, do not combine. 7910 if (!HasFMAD && !HasFMA) 7911 return SDValue(); 7912 7913 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 7914 if (AllowFusion && STI && STI->generateFMAsInMachineCombiner(OptLevel)) 7915 return SDValue(); 7916 7917 // Always prefer FMAD to FMA for precision. 7918 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7919 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7920 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7921 7922 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7923 if (N0.getOpcode() == ISD::FMUL && 7924 (Aggressive || N0->hasOneUse())) { 7925 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7926 N0.getOperand(0), N0.getOperand(1), 7927 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7928 } 7929 7930 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7931 // Note: Commutes FSUB operands. 7932 if (N1.getOpcode() == ISD::FMUL && 7933 (Aggressive || N1->hasOneUse())) 7934 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7935 DAG.getNode(ISD::FNEG, SL, VT, 7936 N1.getOperand(0)), 7937 N1.getOperand(1), N0); 7938 7939 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7940 if (N0.getOpcode() == ISD::FNEG && 7941 N0.getOperand(0).getOpcode() == ISD::FMUL && 7942 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7943 SDValue N00 = N0.getOperand(0).getOperand(0); 7944 SDValue N01 = N0.getOperand(0).getOperand(1); 7945 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7946 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7947 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7948 } 7949 7950 // Look through FP_EXTEND nodes to do more combining. 7951 if (AllowFusion && LookThroughFPExt) { 7952 // fold (fsub (fpext (fmul x, y)), z) 7953 // -> (fma (fpext x), (fpext y), (fneg z)) 7954 if (N0.getOpcode() == ISD::FP_EXTEND) { 7955 SDValue N00 = N0.getOperand(0); 7956 if (N00.getOpcode() == ISD::FMUL) 7957 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7958 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7959 N00.getOperand(0)), 7960 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7961 N00.getOperand(1)), 7962 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7963 } 7964 7965 // fold (fsub x, (fpext (fmul y, z))) 7966 // -> (fma (fneg (fpext y)), (fpext z), x) 7967 // Note: Commutes FSUB operands. 7968 if (N1.getOpcode() == ISD::FP_EXTEND) { 7969 SDValue N10 = N1.getOperand(0); 7970 if (N10.getOpcode() == ISD::FMUL) 7971 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7972 DAG.getNode(ISD::FNEG, SL, VT, 7973 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7974 N10.getOperand(0))), 7975 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7976 N10.getOperand(1)), 7977 N0); 7978 } 7979 7980 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7981 // -> (fneg (fma (fpext x), (fpext y), z)) 7982 // Note: This could be removed with appropriate canonicalization of the 7983 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7984 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7985 // from implementing the canonicalization in visitFSUB. 7986 if (N0.getOpcode() == ISD::FP_EXTEND) { 7987 SDValue N00 = N0.getOperand(0); 7988 if (N00.getOpcode() == ISD::FNEG) { 7989 SDValue N000 = N00.getOperand(0); 7990 if (N000.getOpcode() == ISD::FMUL) { 7991 return DAG.getNode(ISD::FNEG, SL, VT, 7992 DAG.getNode(PreferredFusedOpcode, SL, VT, 7993 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7994 N000.getOperand(0)), 7995 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7996 N000.getOperand(1)), 7997 N1)); 7998 } 7999 } 8000 } 8001 8002 // fold (fsub (fneg (fpext (fmul, x, y))), z) 8003 // -> (fneg (fma (fpext x)), (fpext y), z) 8004 // Note: This could be removed with appropriate canonicalization of the 8005 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 8006 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 8007 // from implementing the canonicalization in visitFSUB. 8008 if (N0.getOpcode() == ISD::FNEG) { 8009 SDValue N00 = N0.getOperand(0); 8010 if (N00.getOpcode() == ISD::FP_EXTEND) { 8011 SDValue N000 = N00.getOperand(0); 8012 if (N000.getOpcode() == ISD::FMUL) { 8013 return DAG.getNode(ISD::FNEG, SL, VT, 8014 DAG.getNode(PreferredFusedOpcode, SL, VT, 8015 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8016 N000.getOperand(0)), 8017 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8018 N000.getOperand(1)), 8019 N1)); 8020 } 8021 } 8022 } 8023 8024 } 8025 8026 // More folding opportunities when target permits. 8027 if ((AllowFusion || HasFMAD) && Aggressive) { 8028 // fold (fsub (fma x, y, (fmul u, v)), z) 8029 // -> (fma x, y (fma u, v, (fneg z))) 8030 if (N0.getOpcode() == PreferredFusedOpcode && 8031 N0.getOperand(2).getOpcode() == ISD::FMUL) { 8032 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8033 N0.getOperand(0), N0.getOperand(1), 8034 DAG.getNode(PreferredFusedOpcode, SL, VT, 8035 N0.getOperand(2).getOperand(0), 8036 N0.getOperand(2).getOperand(1), 8037 DAG.getNode(ISD::FNEG, SL, VT, 8038 N1))); 8039 } 8040 8041 // fold (fsub x, (fma y, z, (fmul u, v))) 8042 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 8043 if (N1.getOpcode() == PreferredFusedOpcode && 8044 N1.getOperand(2).getOpcode() == ISD::FMUL) { 8045 SDValue N20 = N1.getOperand(2).getOperand(0); 8046 SDValue N21 = N1.getOperand(2).getOperand(1); 8047 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8048 DAG.getNode(ISD::FNEG, SL, VT, 8049 N1.getOperand(0)), 8050 N1.getOperand(1), 8051 DAG.getNode(PreferredFusedOpcode, SL, VT, 8052 DAG.getNode(ISD::FNEG, SL, VT, N20), 8053 8054 N21, N0)); 8055 } 8056 8057 if (AllowFusion && LookThroughFPExt) { 8058 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 8059 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 8060 if (N0.getOpcode() == PreferredFusedOpcode) { 8061 SDValue N02 = N0.getOperand(2); 8062 if (N02.getOpcode() == ISD::FP_EXTEND) { 8063 SDValue N020 = N02.getOperand(0); 8064 if (N020.getOpcode() == ISD::FMUL) 8065 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8066 N0.getOperand(0), N0.getOperand(1), 8067 DAG.getNode(PreferredFusedOpcode, SL, VT, 8068 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8069 N020.getOperand(0)), 8070 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8071 N020.getOperand(1)), 8072 DAG.getNode(ISD::FNEG, SL, VT, 8073 N1))); 8074 } 8075 } 8076 8077 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 8078 // -> (fma (fpext x), (fpext y), 8079 // (fma (fpext u), (fpext v), (fneg z))) 8080 // FIXME: This turns two single-precision and one double-precision 8081 // operation into two double-precision operations, which might not be 8082 // interesting for all targets, especially GPUs. 8083 if (N0.getOpcode() == ISD::FP_EXTEND) { 8084 SDValue N00 = N0.getOperand(0); 8085 if (N00.getOpcode() == PreferredFusedOpcode) { 8086 SDValue N002 = N00.getOperand(2); 8087 if (N002.getOpcode() == ISD::FMUL) 8088 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8089 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8090 N00.getOperand(0)), 8091 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8092 N00.getOperand(1)), 8093 DAG.getNode(PreferredFusedOpcode, SL, VT, 8094 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8095 N002.getOperand(0)), 8096 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8097 N002.getOperand(1)), 8098 DAG.getNode(ISD::FNEG, SL, VT, 8099 N1))); 8100 } 8101 } 8102 8103 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 8104 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 8105 if (N1.getOpcode() == PreferredFusedOpcode && 8106 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 8107 SDValue N120 = N1.getOperand(2).getOperand(0); 8108 if (N120.getOpcode() == ISD::FMUL) { 8109 SDValue N1200 = N120.getOperand(0); 8110 SDValue N1201 = N120.getOperand(1); 8111 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8112 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 8113 N1.getOperand(1), 8114 DAG.getNode(PreferredFusedOpcode, SL, VT, 8115 DAG.getNode(ISD::FNEG, SL, VT, 8116 DAG.getNode(ISD::FP_EXTEND, SL, 8117 VT, N1200)), 8118 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8119 N1201), 8120 N0)); 8121 } 8122 } 8123 8124 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 8125 // -> (fma (fneg (fpext y)), (fpext z), 8126 // (fma (fneg (fpext u)), (fpext v), x)) 8127 // FIXME: This turns two single-precision and one double-precision 8128 // operation into two double-precision operations, which might not be 8129 // interesting for all targets, especially GPUs. 8130 if (N1.getOpcode() == ISD::FP_EXTEND && 8131 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 8132 SDValue N100 = N1.getOperand(0).getOperand(0); 8133 SDValue N101 = N1.getOperand(0).getOperand(1); 8134 SDValue N102 = N1.getOperand(0).getOperand(2); 8135 if (N102.getOpcode() == ISD::FMUL) { 8136 SDValue N1020 = N102.getOperand(0); 8137 SDValue N1021 = N102.getOperand(1); 8138 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8139 DAG.getNode(ISD::FNEG, SL, VT, 8140 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8141 N100)), 8142 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 8143 DAG.getNode(PreferredFusedOpcode, SL, VT, 8144 DAG.getNode(ISD::FNEG, SL, VT, 8145 DAG.getNode(ISD::FP_EXTEND, SL, 8146 VT, N1020)), 8147 DAG.getNode(ISD::FP_EXTEND, SL, VT, 8148 N1021), 8149 N0)); 8150 } 8151 } 8152 } 8153 } 8154 8155 return SDValue(); 8156 } 8157 8158 /// Try to perform FMA combining on a given FMUL node. 8159 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) { 8160 SDValue N0 = N->getOperand(0); 8161 SDValue N1 = N->getOperand(1); 8162 EVT VT = N->getValueType(0); 8163 SDLoc SL(N); 8164 8165 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 8166 8167 const TargetOptions &Options = DAG.getTarget().Options; 8168 bool AllowFusion = 8169 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath); 8170 8171 // Floating-point multiply-add with intermediate rounding. 8172 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 8173 8174 // Floating-point multiply-add without intermediate rounding. 8175 bool HasFMA = 8176 AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) && 8177 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 8178 8179 // No valid opcode, do not combine. 8180 if (!HasFMAD && !HasFMA) 8181 return SDValue(); 8182 8183 // Always prefer FMAD to FMA for precision. 8184 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 8185 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 8186 8187 // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y) 8188 // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y)) 8189 auto FuseFADD = [&](SDValue X, SDValue Y) { 8190 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 8191 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8192 if (XC1 && XC1->isExactlyValue(+1.0)) 8193 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8194 if (XC1 && XC1->isExactlyValue(-1.0)) 8195 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8196 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8197 } 8198 return SDValue(); 8199 }; 8200 8201 if (SDValue FMA = FuseFADD(N0, N1)) 8202 return FMA; 8203 if (SDValue FMA = FuseFADD(N1, N0)) 8204 return FMA; 8205 8206 // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y) 8207 // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y)) 8208 // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y)) 8209 // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y) 8210 auto FuseFSUB = [&](SDValue X, SDValue Y) { 8211 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 8212 auto XC0 = isConstOrConstSplatFP(X.getOperand(0)); 8213 if (XC0 && XC0->isExactlyValue(+1.0)) 8214 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8215 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8216 Y); 8217 if (XC0 && XC0->isExactlyValue(-1.0)) 8218 return DAG.getNode(PreferredFusedOpcode, SL, VT, 8219 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 8220 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8221 8222 auto XC1 = isConstOrConstSplatFP(X.getOperand(1)); 8223 if (XC1 && XC1->isExactlyValue(+1.0)) 8224 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 8225 DAG.getNode(ISD::FNEG, SL, VT, Y)); 8226 if (XC1 && XC1->isExactlyValue(-1.0)) 8227 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y); 8228 } 8229 return SDValue(); 8230 }; 8231 8232 if (SDValue FMA = FuseFSUB(N0, N1)) 8233 return FMA; 8234 if (SDValue FMA = FuseFSUB(N1, N0)) 8235 return FMA; 8236 8237 return SDValue(); 8238 } 8239 8240 SDValue DAGCombiner::visitFADD(SDNode *N) { 8241 SDValue N0 = N->getOperand(0); 8242 SDValue N1 = N->getOperand(1); 8243 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 8244 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 8245 EVT VT = N->getValueType(0); 8246 SDLoc DL(N); 8247 const TargetOptions &Options = DAG.getTarget().Options; 8248 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8249 8250 // fold vector ops 8251 if (VT.isVector()) 8252 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8253 return FoldedVOp; 8254 8255 // fold (fadd c1, c2) -> c1 + c2 8256 if (N0CFP && N1CFP) 8257 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 8258 8259 // canonicalize constant to RHS 8260 if (N0CFP && !N1CFP) 8261 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 8262 8263 // fold (fadd A, (fneg B)) -> (fsub A, B) 8264 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8265 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 8266 return DAG.getNode(ISD::FSUB, DL, VT, N0, 8267 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8268 8269 // fold (fadd (fneg A), B) -> (fsub B, A) 8270 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 8271 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 8272 return DAG.getNode(ISD::FSUB, DL, VT, N1, 8273 GetNegatedExpression(N0, DAG, LegalOperations), Flags); 8274 8275 // If 'unsafe math' is enabled, fold lots of things. 8276 if (Options.UnsafeFPMath) { 8277 // No FP constant should be created after legalization as Instruction 8278 // Selection pass has a hard time dealing with FP constants. 8279 bool AllowNewConst = (Level < AfterLegalizeDAG); 8280 8281 // fold (fadd A, 0) -> A 8282 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1)) 8283 if (N1C->isZero()) 8284 return N0; 8285 8286 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 8287 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 8288 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) 8289 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 8290 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, 8291 Flags), 8292 Flags); 8293 8294 // If allowed, fold (fadd (fneg x), x) -> 0.0 8295 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 8296 return DAG.getConstantFP(0.0, DL, VT); 8297 8298 // If allowed, fold (fadd x, (fneg x)) -> 0.0 8299 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 8300 return DAG.getConstantFP(0.0, DL, VT); 8301 8302 // We can fold chains of FADD's of the same value into multiplications. 8303 // This transform is not safe in general because we are reducing the number 8304 // of rounding steps. 8305 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 8306 if (N0.getOpcode() == ISD::FMUL) { 8307 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8308 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 8309 8310 // (fadd (fmul x, c), x) -> (fmul x, c+1) 8311 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 8312 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8313 DAG.getConstantFP(1.0, DL, VT), Flags); 8314 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 8315 } 8316 8317 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 8318 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 8319 N1.getOperand(0) == N1.getOperand(1) && 8320 N0.getOperand(0) == N1.getOperand(0)) { 8321 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 8322 DAG.getConstantFP(2.0, DL, VT), Flags); 8323 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 8324 } 8325 } 8326 8327 if (N1.getOpcode() == ISD::FMUL) { 8328 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8329 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 8330 8331 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 8332 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 8333 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8334 DAG.getConstantFP(1.0, DL, VT), Flags); 8335 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 8336 } 8337 8338 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 8339 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 8340 N0.getOperand(0) == N0.getOperand(1) && 8341 N1.getOperand(0) == N0.getOperand(0)) { 8342 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 8343 DAG.getConstantFP(2.0, DL, VT), Flags); 8344 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 8345 } 8346 } 8347 8348 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 8349 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 8350 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 8351 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 8352 (N0.getOperand(0) == N1)) { 8353 return DAG.getNode(ISD::FMUL, DL, VT, 8354 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 8355 } 8356 } 8357 8358 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 8359 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 8360 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 8361 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 8362 N1.getOperand(0) == N0) { 8363 return DAG.getNode(ISD::FMUL, DL, VT, 8364 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 8365 } 8366 } 8367 8368 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 8369 if (AllowNewConst && 8370 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 8371 N0.getOperand(0) == N0.getOperand(1) && 8372 N1.getOperand(0) == N1.getOperand(1) && 8373 N0.getOperand(0) == N1.getOperand(0)) { 8374 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 8375 DAG.getConstantFP(4.0, DL, VT), Flags); 8376 } 8377 } 8378 } // enable-unsafe-fp-math 8379 8380 // FADD -> FMA combines: 8381 if (SDValue Fused = visitFADDForFMACombine(N)) { 8382 AddToWorklist(Fused.getNode()); 8383 return Fused; 8384 } 8385 return SDValue(); 8386 } 8387 8388 SDValue DAGCombiner::visitFSUB(SDNode *N) { 8389 SDValue N0 = N->getOperand(0); 8390 SDValue N1 = N->getOperand(1); 8391 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8392 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8393 EVT VT = N->getValueType(0); 8394 SDLoc dl(N); 8395 const TargetOptions &Options = DAG.getTarget().Options; 8396 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8397 8398 // fold vector ops 8399 if (VT.isVector()) 8400 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8401 return FoldedVOp; 8402 8403 // fold (fsub c1, c2) -> c1-c2 8404 if (N0CFP && N1CFP) 8405 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags); 8406 8407 // fold (fsub A, (fneg B)) -> (fadd A, B) 8408 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8409 return DAG.getNode(ISD::FADD, dl, VT, N0, 8410 GetNegatedExpression(N1, DAG, LegalOperations), Flags); 8411 8412 // If 'unsafe math' is enabled, fold lots of things. 8413 if (Options.UnsafeFPMath) { 8414 // (fsub A, 0) -> A 8415 if (N1CFP && N1CFP->isZero()) 8416 return N0; 8417 8418 // (fsub 0, B) -> -B 8419 if (N0CFP && N0CFP->isZero()) { 8420 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 8421 return GetNegatedExpression(N1, DAG, LegalOperations); 8422 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8423 return DAG.getNode(ISD::FNEG, dl, VT, N1); 8424 } 8425 8426 // (fsub x, x) -> 0.0 8427 if (N0 == N1) 8428 return DAG.getConstantFP(0.0f, dl, VT); 8429 8430 // (fsub x, (fadd x, y)) -> (fneg y) 8431 // (fsub x, (fadd y, x)) -> (fneg y) 8432 if (N1.getOpcode() == ISD::FADD) { 8433 SDValue N10 = N1->getOperand(0); 8434 SDValue N11 = N1->getOperand(1); 8435 8436 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 8437 return GetNegatedExpression(N11, DAG, LegalOperations); 8438 8439 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 8440 return GetNegatedExpression(N10, DAG, LegalOperations); 8441 } 8442 } 8443 8444 // FSUB -> FMA combines: 8445 if (SDValue Fused = visitFSUBForFMACombine(N)) { 8446 AddToWorklist(Fused.getNode()); 8447 return Fused; 8448 } 8449 8450 return SDValue(); 8451 } 8452 8453 SDValue DAGCombiner::visitFMUL(SDNode *N) { 8454 SDValue N0 = N->getOperand(0); 8455 SDValue N1 = N->getOperand(1); 8456 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 8457 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 8458 EVT VT = N->getValueType(0); 8459 SDLoc DL(N); 8460 const TargetOptions &Options = DAG.getTarget().Options; 8461 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8462 8463 // fold vector ops 8464 if (VT.isVector()) { 8465 // This just handles C1 * C2 for vectors. Other vector folds are below. 8466 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8467 return FoldedVOp; 8468 } 8469 8470 // fold (fmul c1, c2) -> c1*c2 8471 if (N0CFP && N1CFP) 8472 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 8473 8474 // canonicalize constant to RHS 8475 if (isConstantFPBuildVectorOrConstantFP(N0) && 8476 !isConstantFPBuildVectorOrConstantFP(N1)) 8477 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 8478 8479 // fold (fmul A, 1.0) -> A 8480 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8481 return N0; 8482 8483 if (Options.UnsafeFPMath) { 8484 // fold (fmul A, 0) -> 0 8485 if (N1CFP && N1CFP->isZero()) 8486 return N1; 8487 8488 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8489 if (N0.getOpcode() == ISD::FMUL) { 8490 // Fold scalars or any vector constants (not just splats). 8491 // This fold is done in general by InstCombine, but extra fmul insts 8492 // may have been generated during lowering. 8493 SDValue N00 = N0.getOperand(0); 8494 SDValue N01 = N0.getOperand(1); 8495 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8496 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8497 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8498 8499 // Check 1: Make sure that the first operand of the inner multiply is NOT 8500 // a constant. Otherwise, we may induce infinite looping. 8501 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8502 // Check 2: Make sure that the second operand of the inner multiply and 8503 // the second operand of the outer multiply are constants. 8504 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8505 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8506 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 8507 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 8508 } 8509 } 8510 } 8511 8512 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8513 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8514 // during an early run of DAGCombiner can prevent folding with fmuls 8515 // inserted during lowering. 8516 if (N0.getOpcode() == ISD::FADD && 8517 (N0.getOperand(0) == N0.getOperand(1)) && 8518 N0.hasOneUse()) { 8519 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8520 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 8521 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 8522 } 8523 } 8524 8525 // fold (fmul X, 2.0) -> (fadd X, X) 8526 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8527 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 8528 8529 // fold (fmul X, -1.0) -> (fneg X) 8530 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8531 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8532 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8533 8534 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8535 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8536 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8537 // Both can be negated for free, check to see if at least one is cheaper 8538 // negated. 8539 if (LHSNeg == 2 || RHSNeg == 2) 8540 return DAG.getNode(ISD::FMUL, DL, VT, 8541 GetNegatedExpression(N0, DAG, LegalOperations), 8542 GetNegatedExpression(N1, DAG, LegalOperations), 8543 Flags); 8544 } 8545 } 8546 8547 // FMUL -> FMA combines: 8548 if (SDValue Fused = visitFMULForFMACombine(N)) { 8549 AddToWorklist(Fused.getNode()); 8550 return Fused; 8551 } 8552 8553 return SDValue(); 8554 } 8555 8556 SDValue DAGCombiner::visitFMA(SDNode *N) { 8557 SDValue N0 = N->getOperand(0); 8558 SDValue N1 = N->getOperand(1); 8559 SDValue N2 = N->getOperand(2); 8560 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8561 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8562 EVT VT = N->getValueType(0); 8563 SDLoc dl(N); 8564 const TargetOptions &Options = DAG.getTarget().Options; 8565 8566 // Constant fold FMA. 8567 if (isa<ConstantFPSDNode>(N0) && 8568 isa<ConstantFPSDNode>(N1) && 8569 isa<ConstantFPSDNode>(N2)) { 8570 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8571 } 8572 8573 if (Options.UnsafeFPMath) { 8574 if (N0CFP && N0CFP->isZero()) 8575 return N2; 8576 if (N1CFP && N1CFP->isZero()) 8577 return N2; 8578 } 8579 // TODO: The FMA node should have flags that propagate to these nodes. 8580 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8581 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8582 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8583 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8584 8585 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8586 if (isConstantFPBuildVectorOrConstantFP(N0) && 8587 !isConstantFPBuildVectorOrConstantFP(N1)) 8588 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8589 8590 // TODO: FMA nodes should have flags that propagate to the created nodes. 8591 // For now, create a Flags object for use with all unsafe math transforms. 8592 SDNodeFlags Flags; 8593 Flags.setUnsafeAlgebra(true); 8594 8595 if (Options.UnsafeFPMath) { 8596 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8597 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 8598 isConstantFPBuildVectorOrConstantFP(N1) && 8599 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 8600 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8601 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1), 8602 &Flags), &Flags); 8603 } 8604 8605 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8606 if (N0.getOpcode() == ISD::FMUL && 8607 isConstantFPBuildVectorOrConstantFP(N1) && 8608 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 8609 return DAG.getNode(ISD::FMA, dl, VT, 8610 N0.getOperand(0), 8611 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1), 8612 &Flags), 8613 N2); 8614 } 8615 } 8616 8617 // (fma x, 1, y) -> (fadd x, y) 8618 // (fma x, -1, y) -> (fadd (fneg x), y) 8619 if (N1CFP) { 8620 if (N1CFP->isExactlyValue(1.0)) 8621 // TODO: The FMA node should have flags that propagate to this node. 8622 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8623 8624 if (N1CFP->isExactlyValue(-1.0) && 8625 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8626 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8627 AddToWorklist(RHSNeg.getNode()); 8628 // TODO: The FMA node should have flags that propagate to this node. 8629 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8630 } 8631 } 8632 8633 if (Options.UnsafeFPMath) { 8634 // (fma x, c, x) -> (fmul x, (c+1)) 8635 if (N1CFP && N0 == N2) { 8636 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8637 DAG.getNode(ISD::FADD, dl, VT, 8638 N1, DAG.getConstantFP(1.0, dl, VT), 8639 &Flags), &Flags); 8640 } 8641 8642 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8643 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 8644 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8645 DAG.getNode(ISD::FADD, dl, VT, 8646 N1, DAG.getConstantFP(-1.0, dl, VT), 8647 &Flags), &Flags); 8648 } 8649 } 8650 8651 return SDValue(); 8652 } 8653 8654 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8655 // reciprocal. 8656 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8657 // Notice that this is not always beneficial. One reason is different target 8658 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8659 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8660 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8661 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 8662 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 8663 const SDNodeFlags *Flags = N->getFlags(); 8664 if (!UnsafeMath && !Flags->hasAllowReciprocal()) 8665 return SDValue(); 8666 8667 // Skip if current node is a reciprocal. 8668 SDValue N0 = N->getOperand(0); 8669 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8670 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8671 return SDValue(); 8672 8673 // Exit early if the target does not want this transform or if there can't 8674 // possibly be enough uses of the divisor to make the transform worthwhile. 8675 SDValue N1 = N->getOperand(1); 8676 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 8677 if (!MinUses || N1->use_size() < MinUses) 8678 return SDValue(); 8679 8680 // Find all FDIV users of the same divisor. 8681 // Use a set because duplicates may be present in the user list. 8682 SetVector<SDNode *> Users; 8683 for (auto *U : N1->uses()) { 8684 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 8685 // This division is eligible for optimization only if global unsafe math 8686 // is enabled or if this division allows reciprocal formation. 8687 if (UnsafeMath || U->getFlags()->hasAllowReciprocal()) 8688 Users.insert(U); 8689 } 8690 } 8691 8692 // Now that we have the actual number of divisor uses, make sure it meets 8693 // the minimum threshold specified by the target. 8694 if (Users.size() < MinUses) 8695 return SDValue(); 8696 8697 EVT VT = N->getValueType(0); 8698 SDLoc DL(N); 8699 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8700 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 8701 8702 // Dividend / Divisor -> Dividend * Reciprocal 8703 for (auto *U : Users) { 8704 SDValue Dividend = U->getOperand(0); 8705 if (Dividend != FPOne) { 8706 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8707 Reciprocal, Flags); 8708 CombineTo(U, NewNode); 8709 } else if (U != Reciprocal.getNode()) { 8710 // In the absence of fast-math-flags, this user node is always the 8711 // same node as Reciprocal, but with FMF they may be different nodes. 8712 CombineTo(U, Reciprocal); 8713 } 8714 } 8715 return SDValue(N, 0); // N was replaced. 8716 } 8717 8718 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8719 SDValue N0 = N->getOperand(0); 8720 SDValue N1 = N->getOperand(1); 8721 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8722 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8723 EVT VT = N->getValueType(0); 8724 SDLoc DL(N); 8725 const TargetOptions &Options = DAG.getTarget().Options; 8726 SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags; 8727 8728 // fold vector ops 8729 if (VT.isVector()) 8730 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8731 return FoldedVOp; 8732 8733 // fold (fdiv c1, c2) -> c1/c2 8734 if (N0CFP && N1CFP) 8735 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 8736 8737 if (Options.UnsafeFPMath) { 8738 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8739 if (N1CFP) { 8740 // Compute the reciprocal 1.0 / c2. 8741 APFloat N1APF = N1CFP->getValueAPF(); 8742 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8743 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8744 // Only do the transform if the reciprocal is a legal fp immediate that 8745 // isn't too nasty (eg NaN, denormal, ...). 8746 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8747 (!LegalOperations || 8748 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8749 // backend)... we should handle this gracefully after Legalize. 8750 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8751 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8752 TLI.isFPImmLegal(Recip, VT))) 8753 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8754 DAG.getConstantFP(Recip, DL, VT), Flags); 8755 } 8756 8757 // If this FDIV is part of a reciprocal square root, it may be folded 8758 // into a target-specific square root estimate instruction. 8759 if (N1.getOpcode() == ISD::FSQRT) { 8760 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) { 8761 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8762 } 8763 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8764 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8765 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8766 Flags)) { 8767 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8768 AddToWorklist(RV.getNode()); 8769 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8770 } 8771 } else if (N1.getOpcode() == ISD::FP_ROUND && 8772 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8773 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0), 8774 Flags)) { 8775 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8776 AddToWorklist(RV.getNode()); 8777 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8778 } 8779 } else if (N1.getOpcode() == ISD::FMUL) { 8780 // Look through an FMUL. Even though this won't remove the FDIV directly, 8781 // it's still worthwhile to get rid of the FSQRT if possible. 8782 SDValue SqrtOp; 8783 SDValue OtherOp; 8784 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8785 SqrtOp = N1.getOperand(0); 8786 OtherOp = N1.getOperand(1); 8787 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8788 SqrtOp = N1.getOperand(1); 8789 OtherOp = N1.getOperand(0); 8790 } 8791 if (SqrtOp.getNode()) { 8792 // We found a FSQRT, so try to make this fold: 8793 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8794 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 8795 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 8796 AddToWorklist(RV.getNode()); 8797 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8798 } 8799 } 8800 } 8801 8802 // Fold into a reciprocal estimate and multiply instead of a real divide. 8803 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 8804 AddToWorklist(RV.getNode()); 8805 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 8806 } 8807 } 8808 8809 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8810 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8811 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8812 // Both can be negated for free, check to see if at least one is cheaper 8813 // negated. 8814 if (LHSNeg == 2 || RHSNeg == 2) 8815 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8816 GetNegatedExpression(N0, DAG, LegalOperations), 8817 GetNegatedExpression(N1, DAG, LegalOperations), 8818 Flags); 8819 } 8820 } 8821 8822 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 8823 return CombineRepeatedDivisors; 8824 8825 return SDValue(); 8826 } 8827 8828 SDValue DAGCombiner::visitFREM(SDNode *N) { 8829 SDValue N0 = N->getOperand(0); 8830 SDValue N1 = N->getOperand(1); 8831 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8832 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8833 EVT VT = N->getValueType(0); 8834 8835 // fold (frem c1, c2) -> fmod(c1,c2) 8836 if (N0CFP && N1CFP) 8837 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, 8838 &cast<BinaryWithFlagsSDNode>(N)->Flags); 8839 8840 return SDValue(); 8841 } 8842 8843 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8844 if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap()) 8845 return SDValue(); 8846 8847 // TODO: FSQRT nodes should have flags that propagate to the created nodes. 8848 // For now, create a Flags object for use with all unsafe math transforms. 8849 SDNodeFlags Flags; 8850 Flags.setUnsafeAlgebra(true); 8851 8852 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8853 SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags); 8854 if (!RV) 8855 return SDValue(); 8856 8857 EVT VT = RV.getValueType(); 8858 SDLoc DL(N); 8859 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags); 8860 AddToWorklist(RV.getNode()); 8861 8862 // Unfortunately, RV is now NaN if the input was exactly 0. 8863 // Select out this case and force the answer to 0. 8864 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8865 EVT CCVT = getSetCCResultType(VT); 8866 SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ); 8867 AddToWorklist(ZeroCmp.getNode()); 8868 AddToWorklist(RV.getNode()); 8869 8870 return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 8871 ZeroCmp, Zero, RV); 8872 } 8873 8874 /// copysign(x, fp_extend(y)) -> copysign(x, y) 8875 /// copysign(x, fp_round(y)) -> copysign(x, y) 8876 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 8877 SDValue N1 = N->getOperand(1); 8878 if ((N1.getOpcode() == ISD::FP_EXTEND || 8879 N1.getOpcode() == ISD::FP_ROUND)) { 8880 // Do not optimize out type conversion of f128 type yet. 8881 // For some targets like x86_64, configuration is changed to keep one f128 8882 // value in one SSE register, but instruction selection cannot handle 8883 // FCOPYSIGN on SSE registers yet. 8884 EVT N1VT = N1->getValueType(0); 8885 EVT N1Op0VT = N1->getOperand(0)->getValueType(0); 8886 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 8887 } 8888 return false; 8889 } 8890 8891 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8892 SDValue N0 = N->getOperand(0); 8893 SDValue N1 = N->getOperand(1); 8894 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8895 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8896 EVT VT = N->getValueType(0); 8897 8898 if (N0CFP && N1CFP) // Constant fold 8899 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8900 8901 if (N1CFP) { 8902 const APFloat& V = N1CFP->getValueAPF(); 8903 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8904 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8905 if (!V.isNegative()) { 8906 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8907 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8908 } else { 8909 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8910 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8911 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8912 } 8913 } 8914 8915 // copysign(fabs(x), y) -> copysign(x, y) 8916 // copysign(fneg(x), y) -> copysign(x, y) 8917 // copysign(copysign(x,z), y) -> copysign(x, y) 8918 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8919 N0.getOpcode() == ISD::FCOPYSIGN) 8920 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8921 N0.getOperand(0), N1); 8922 8923 // copysign(x, abs(y)) -> abs(x) 8924 if (N1.getOpcode() == ISD::FABS) 8925 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8926 8927 // copysign(x, copysign(y,z)) -> copysign(x, z) 8928 if (N1.getOpcode() == ISD::FCOPYSIGN) 8929 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8930 N0, N1.getOperand(1)); 8931 8932 // copysign(x, fp_extend(y)) -> copysign(x, y) 8933 // copysign(x, fp_round(y)) -> copysign(x, y) 8934 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 8935 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8936 N0, N1.getOperand(0)); 8937 8938 return SDValue(); 8939 } 8940 8941 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8942 SDValue N0 = N->getOperand(0); 8943 EVT VT = N->getValueType(0); 8944 EVT OpVT = N0.getValueType(); 8945 8946 // fold (sint_to_fp c1) -> c1fp 8947 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 8948 // ...but only if the target supports immediate floating-point values 8949 (!LegalOperations || 8950 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8951 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8952 8953 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8954 // but UINT_TO_FP is legal on this target, try to convert. 8955 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8956 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8957 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8958 if (DAG.SignBitIsZero(N0)) 8959 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8960 } 8961 8962 // The next optimizations are desirable only if SELECT_CC can be lowered. 8963 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8964 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8965 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8966 !VT.isVector() && 8967 (!LegalOperations || 8968 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8969 SDLoc DL(N); 8970 SDValue Ops[] = 8971 { N0.getOperand(0), N0.getOperand(1), 8972 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8973 N0.getOperand(2) }; 8974 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8975 } 8976 8977 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8978 // (select_cc x, y, 1.0, 0.0,, cc) 8979 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8980 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8981 (!LegalOperations || 8982 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8983 SDLoc DL(N); 8984 SDValue Ops[] = 8985 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8986 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8987 N0.getOperand(0).getOperand(2) }; 8988 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8989 } 8990 } 8991 8992 return SDValue(); 8993 } 8994 8995 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8996 SDValue N0 = N->getOperand(0); 8997 EVT VT = N->getValueType(0); 8998 EVT OpVT = N0.getValueType(); 8999 9000 // fold (uint_to_fp c1) -> c1fp 9001 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 9002 // ...but only if the target supports immediate floating-point values 9003 (!LegalOperations || 9004 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 9005 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 9006 9007 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 9008 // but SINT_TO_FP is legal on this target, try to convert. 9009 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 9010 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 9011 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 9012 if (DAG.SignBitIsZero(N0)) 9013 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 9014 } 9015 9016 // The next optimizations are desirable only if SELECT_CC can be lowered. 9017 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 9018 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 9019 9020 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 9021 (!LegalOperations || 9022 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 9023 SDLoc DL(N); 9024 SDValue Ops[] = 9025 { N0.getOperand(0), N0.getOperand(1), 9026 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 9027 N0.getOperand(2) }; 9028 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 9029 } 9030 } 9031 9032 return SDValue(); 9033 } 9034 9035 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 9036 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 9037 SDValue N0 = N->getOperand(0); 9038 EVT VT = N->getValueType(0); 9039 9040 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 9041 return SDValue(); 9042 9043 SDValue Src = N0.getOperand(0); 9044 EVT SrcVT = Src.getValueType(); 9045 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 9046 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 9047 9048 // We can safely assume the conversion won't overflow the output range, 9049 // because (for example) (uint8_t)18293.f is undefined behavior. 9050 9051 // Since we can assume the conversion won't overflow, our decision as to 9052 // whether the input will fit in the float should depend on the minimum 9053 // of the input range and output range. 9054 9055 // This means this is also safe for a signed input and unsigned output, since 9056 // a negative input would lead to undefined behavior. 9057 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 9058 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 9059 unsigned ActualSize = std::min(InputSize, OutputSize); 9060 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 9061 9062 // We can only fold away the float conversion if the input range can be 9063 // represented exactly in the float range. 9064 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 9065 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 9066 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 9067 : ISD::ZERO_EXTEND; 9068 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 9069 } 9070 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 9071 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 9072 return DAG.getBitcast(VT, Src); 9073 } 9074 return SDValue(); 9075 } 9076 9077 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 9078 SDValue N0 = N->getOperand(0); 9079 EVT VT = N->getValueType(0); 9080 9081 // fold (fp_to_sint c1fp) -> c1 9082 if (isConstantFPBuildVectorOrConstantFP(N0)) 9083 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 9084 9085 return FoldIntToFPToInt(N, DAG); 9086 } 9087 9088 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 9089 SDValue N0 = N->getOperand(0); 9090 EVT VT = N->getValueType(0); 9091 9092 // fold (fp_to_uint c1fp) -> c1 9093 if (isConstantFPBuildVectorOrConstantFP(N0)) 9094 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 9095 9096 return FoldIntToFPToInt(N, DAG); 9097 } 9098 9099 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 9100 SDValue N0 = N->getOperand(0); 9101 SDValue N1 = N->getOperand(1); 9102 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9103 EVT VT = N->getValueType(0); 9104 9105 // fold (fp_round c1fp) -> c1fp 9106 if (N0CFP) 9107 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 9108 9109 // fold (fp_round (fp_extend x)) -> x 9110 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 9111 return N0.getOperand(0); 9112 9113 // fold (fp_round (fp_round x)) -> (fp_round x) 9114 if (N0.getOpcode() == ISD::FP_ROUND) { 9115 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 9116 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 9117 9118 // Skip this folding if it results in an fp_round from f80 to f16. 9119 // 9120 // f80 to f16 always generates an expensive (and as yet, unimplemented) 9121 // libcall to __truncxfhf2 instead of selecting native f16 conversion 9122 // instructions from f32 or f64. Moreover, the first (value-preserving) 9123 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 9124 // x86. 9125 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 9126 return SDValue(); 9127 9128 // If the first fp_round isn't a value preserving truncation, it might 9129 // introduce a tie in the second fp_round, that wouldn't occur in the 9130 // single-step fp_round we want to fold to. 9131 // In other words, double rounding isn't the same as rounding. 9132 // Also, this is a value preserving truncation iff both fp_round's are. 9133 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 9134 SDLoc DL(N); 9135 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 9136 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 9137 } 9138 } 9139 9140 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 9141 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 9142 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 9143 N0.getOperand(0), N1); 9144 AddToWorklist(Tmp.getNode()); 9145 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 9146 Tmp, N0.getOperand(1)); 9147 } 9148 9149 return SDValue(); 9150 } 9151 9152 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 9153 SDValue N0 = N->getOperand(0); 9154 EVT VT = N->getValueType(0); 9155 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9156 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 9157 9158 // fold (fp_round_inreg c1fp) -> c1fp 9159 if (N0CFP && isTypeLegal(EVT)) { 9160 SDLoc DL(N); 9161 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 9162 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 9163 } 9164 9165 return SDValue(); 9166 } 9167 9168 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 9169 SDValue N0 = N->getOperand(0); 9170 EVT VT = N->getValueType(0); 9171 9172 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 9173 if (N->hasOneUse() && 9174 N->use_begin()->getOpcode() == ISD::FP_ROUND) 9175 return SDValue(); 9176 9177 // fold (fp_extend c1fp) -> c1fp 9178 if (isConstantFPBuildVectorOrConstantFP(N0)) 9179 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 9180 9181 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 9182 if (N0.getOpcode() == ISD::FP16_TO_FP && 9183 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 9184 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 9185 9186 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 9187 // value of X. 9188 if (N0.getOpcode() == ISD::FP_ROUND 9189 && N0.getNode()->getConstantOperandVal(1) == 1) { 9190 SDValue In = N0.getOperand(0); 9191 if (In.getValueType() == VT) return In; 9192 if (VT.bitsLT(In.getValueType())) 9193 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 9194 In, N0.getOperand(1)); 9195 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 9196 } 9197 9198 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 9199 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9200 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9201 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9202 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9203 LN0->getChain(), 9204 LN0->getBasePtr(), N0.getValueType(), 9205 LN0->getMemOperand()); 9206 CombineTo(N, ExtLoad); 9207 CombineTo(N0.getNode(), 9208 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 9209 N0.getValueType(), ExtLoad, 9210 DAG.getIntPtrConstant(1, SDLoc(N0))), 9211 ExtLoad.getValue(1)); 9212 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9213 } 9214 9215 return SDValue(); 9216 } 9217 9218 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 9219 SDValue N0 = N->getOperand(0); 9220 EVT VT = N->getValueType(0); 9221 9222 // fold (fceil c1) -> fceil(c1) 9223 if (isConstantFPBuildVectorOrConstantFP(N0)) 9224 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 9225 9226 return SDValue(); 9227 } 9228 9229 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 9230 SDValue N0 = N->getOperand(0); 9231 EVT VT = N->getValueType(0); 9232 9233 // fold (ftrunc c1) -> ftrunc(c1) 9234 if (isConstantFPBuildVectorOrConstantFP(N0)) 9235 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 9236 9237 return SDValue(); 9238 } 9239 9240 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 9241 SDValue N0 = N->getOperand(0); 9242 EVT VT = N->getValueType(0); 9243 9244 // fold (ffloor c1) -> ffloor(c1) 9245 if (isConstantFPBuildVectorOrConstantFP(N0)) 9246 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 9247 9248 return SDValue(); 9249 } 9250 9251 // FIXME: FNEG and FABS have a lot in common; refactor. 9252 SDValue DAGCombiner::visitFNEG(SDNode *N) { 9253 SDValue N0 = N->getOperand(0); 9254 EVT VT = N->getValueType(0); 9255 9256 // Constant fold FNEG. 9257 if (isConstantFPBuildVectorOrConstantFP(N0)) 9258 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 9259 9260 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 9261 &DAG.getTarget().Options)) 9262 return GetNegatedExpression(N0, DAG, LegalOperations); 9263 9264 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 9265 // constant pool values. 9266 if (!TLI.isFNegFree(VT) && 9267 N0.getOpcode() == ISD::BITCAST && 9268 N0.getNode()->hasOneUse()) { 9269 SDValue Int = N0.getOperand(0); 9270 EVT IntVT = Int.getValueType(); 9271 if (IntVT.isInteger() && !IntVT.isVector()) { 9272 APInt SignMask; 9273 if (N0.getValueType().isVector()) { 9274 // For a vector, get a mask such as 0x80... per scalar element 9275 // and splat it. 9276 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9277 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9278 } else { 9279 // For a scalar, just generate 0x80... 9280 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 9281 } 9282 SDLoc DL0(N0); 9283 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 9284 DAG.getConstant(SignMask, DL0, IntVT)); 9285 AddToWorklist(Int.getNode()); 9286 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 9287 } 9288 } 9289 9290 // (fneg (fmul c, x)) -> (fmul -c, x) 9291 if (N0.getOpcode() == ISD::FMUL && 9292 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 9293 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9294 if (CFP1) { 9295 APFloat CVal = CFP1->getValueAPF(); 9296 CVal.changeSign(); 9297 if (Level >= AfterLegalizeDAG && 9298 (TLI.isFPImmLegal(CVal, VT) || 9299 TLI.isOperationLegal(ISD::ConstantFP, VT))) 9300 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 9301 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 9302 N0.getOperand(1)), 9303 &cast<BinaryWithFlagsSDNode>(N0)->Flags); 9304 } 9305 } 9306 9307 return SDValue(); 9308 } 9309 9310 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 9311 SDValue N0 = N->getOperand(0); 9312 SDValue N1 = N->getOperand(1); 9313 EVT VT = N->getValueType(0); 9314 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9315 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9316 9317 if (N0CFP && N1CFP) { 9318 const APFloat &C0 = N0CFP->getValueAPF(); 9319 const APFloat &C1 = N1CFP->getValueAPF(); 9320 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT); 9321 } 9322 9323 // Canonicalize to constant on RHS. 9324 if (isConstantFPBuildVectorOrConstantFP(N0) && 9325 !isConstantFPBuildVectorOrConstantFP(N1)) 9326 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 9327 9328 return SDValue(); 9329 } 9330 9331 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 9332 SDValue N0 = N->getOperand(0); 9333 SDValue N1 = N->getOperand(1); 9334 EVT VT = N->getValueType(0); 9335 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 9336 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 9337 9338 if (N0CFP && N1CFP) { 9339 const APFloat &C0 = N0CFP->getValueAPF(); 9340 const APFloat &C1 = N1CFP->getValueAPF(); 9341 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT); 9342 } 9343 9344 // Canonicalize to constant on RHS. 9345 if (isConstantFPBuildVectorOrConstantFP(N0) && 9346 !isConstantFPBuildVectorOrConstantFP(N1)) 9347 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 9348 9349 return SDValue(); 9350 } 9351 9352 SDValue DAGCombiner::visitFABS(SDNode *N) { 9353 SDValue N0 = N->getOperand(0); 9354 EVT VT = N->getValueType(0); 9355 9356 // fold (fabs c1) -> fabs(c1) 9357 if (isConstantFPBuildVectorOrConstantFP(N0)) 9358 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 9359 9360 // fold (fabs (fabs x)) -> (fabs x) 9361 if (N0.getOpcode() == ISD::FABS) 9362 return N->getOperand(0); 9363 9364 // fold (fabs (fneg x)) -> (fabs x) 9365 // fold (fabs (fcopysign x, y)) -> (fabs x) 9366 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 9367 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 9368 9369 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 9370 // constant pool values. 9371 if (!TLI.isFAbsFree(VT) && 9372 N0.getOpcode() == ISD::BITCAST && 9373 N0.getNode()->hasOneUse()) { 9374 SDValue Int = N0.getOperand(0); 9375 EVT IntVT = Int.getValueType(); 9376 if (IntVT.isInteger() && !IntVT.isVector()) { 9377 APInt SignMask; 9378 if (N0.getValueType().isVector()) { 9379 // For a vector, get a mask such as 0x7f... per scalar element 9380 // and splat it. 9381 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 9382 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 9383 } else { 9384 // For a scalar, just generate 0x7f... 9385 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 9386 } 9387 SDLoc DL(N0); 9388 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 9389 DAG.getConstant(SignMask, DL, IntVT)); 9390 AddToWorklist(Int.getNode()); 9391 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 9392 } 9393 } 9394 9395 return SDValue(); 9396 } 9397 9398 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 9399 SDValue Chain = N->getOperand(0); 9400 SDValue N1 = N->getOperand(1); 9401 SDValue N2 = N->getOperand(2); 9402 9403 // If N is a constant we could fold this into a fallthrough or unconditional 9404 // branch. However that doesn't happen very often in normal code, because 9405 // Instcombine/SimplifyCFG should have handled the available opportunities. 9406 // If we did this folding here, it would be necessary to update the 9407 // MachineBasicBlock CFG, which is awkward. 9408 9409 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 9410 // on the target. 9411 if (N1.getOpcode() == ISD::SETCC && 9412 TLI.isOperationLegalOrCustom(ISD::BR_CC, 9413 N1.getOperand(0).getValueType())) { 9414 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9415 Chain, N1.getOperand(2), 9416 N1.getOperand(0), N1.getOperand(1), N2); 9417 } 9418 9419 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 9420 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 9421 (N1.getOperand(0).hasOneUse() && 9422 N1.getOperand(0).getOpcode() == ISD::SRL))) { 9423 SDNode *Trunc = nullptr; 9424 if (N1.getOpcode() == ISD::TRUNCATE) { 9425 // Look pass the truncate. 9426 Trunc = N1.getNode(); 9427 N1 = N1.getOperand(0); 9428 } 9429 9430 // Match this pattern so that we can generate simpler code: 9431 // 9432 // %a = ... 9433 // %b = and i32 %a, 2 9434 // %c = srl i32 %b, 1 9435 // brcond i32 %c ... 9436 // 9437 // into 9438 // 9439 // %a = ... 9440 // %b = and i32 %a, 2 9441 // %c = setcc eq %b, 0 9442 // brcond %c ... 9443 // 9444 // This applies only when the AND constant value has one bit set and the 9445 // SRL constant is equal to the log2 of the AND constant. The back-end is 9446 // smart enough to convert the result into a TEST/JMP sequence. 9447 SDValue Op0 = N1.getOperand(0); 9448 SDValue Op1 = N1.getOperand(1); 9449 9450 if (Op0.getOpcode() == ISD::AND && 9451 Op1.getOpcode() == ISD::Constant) { 9452 SDValue AndOp1 = Op0.getOperand(1); 9453 9454 if (AndOp1.getOpcode() == ISD::Constant) { 9455 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 9456 9457 if (AndConst.isPowerOf2() && 9458 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 9459 SDLoc DL(N); 9460 SDValue SetCC = 9461 DAG.getSetCC(DL, 9462 getSetCCResultType(Op0.getValueType()), 9463 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 9464 ISD::SETNE); 9465 9466 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 9467 MVT::Other, Chain, SetCC, N2); 9468 // Don't add the new BRCond into the worklist or else SimplifySelectCC 9469 // will convert it back to (X & C1) >> C2. 9470 CombineTo(N, NewBRCond, false); 9471 // Truncate is dead. 9472 if (Trunc) 9473 deleteAndRecombine(Trunc); 9474 // Replace the uses of SRL with SETCC 9475 WorklistRemover DeadNodes(*this); 9476 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9477 deleteAndRecombine(N1.getNode()); 9478 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9479 } 9480 } 9481 } 9482 9483 if (Trunc) 9484 // Restore N1 if the above transformation doesn't match. 9485 N1 = N->getOperand(1); 9486 } 9487 9488 // Transform br(xor(x, y)) -> br(x != y) 9489 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 9490 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 9491 SDNode *TheXor = N1.getNode(); 9492 SDValue Op0 = TheXor->getOperand(0); 9493 SDValue Op1 = TheXor->getOperand(1); 9494 if (Op0.getOpcode() == Op1.getOpcode()) { 9495 // Avoid missing important xor optimizations. 9496 if (SDValue Tmp = visitXOR(TheXor)) { 9497 if (Tmp.getNode() != TheXor) { 9498 DEBUG(dbgs() << "\nReplacing.8 "; 9499 TheXor->dump(&DAG); 9500 dbgs() << "\nWith: "; 9501 Tmp.getNode()->dump(&DAG); 9502 dbgs() << '\n'); 9503 WorklistRemover DeadNodes(*this); 9504 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 9505 deleteAndRecombine(TheXor); 9506 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9507 MVT::Other, Chain, Tmp, N2); 9508 } 9509 9510 // visitXOR has changed XOR's operands or replaced the XOR completely, 9511 // bail out. 9512 return SDValue(N, 0); 9513 } 9514 } 9515 9516 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 9517 bool Equal = false; 9518 if (isOneConstant(Op0) && Op0.hasOneUse() && 9519 Op0.getOpcode() == ISD::XOR) { 9520 TheXor = Op0.getNode(); 9521 Equal = true; 9522 } 9523 9524 EVT SetCCVT = N1.getValueType(); 9525 if (LegalTypes) 9526 SetCCVT = getSetCCResultType(SetCCVT); 9527 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 9528 SetCCVT, 9529 Op0, Op1, 9530 Equal ? ISD::SETEQ : ISD::SETNE); 9531 // Replace the uses of XOR with SETCC 9532 WorklistRemover DeadNodes(*this); 9533 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 9534 deleteAndRecombine(N1.getNode()); 9535 return DAG.getNode(ISD::BRCOND, SDLoc(N), 9536 MVT::Other, Chain, SetCC, N2); 9537 } 9538 } 9539 9540 return SDValue(); 9541 } 9542 9543 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 9544 // 9545 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 9546 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 9547 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 9548 9549 // If N is a constant we could fold this into a fallthrough or unconditional 9550 // branch. However that doesn't happen very often in normal code, because 9551 // Instcombine/SimplifyCFG should have handled the available opportunities. 9552 // If we did this folding here, it would be necessary to update the 9553 // MachineBasicBlock CFG, which is awkward. 9554 9555 // Use SimplifySetCC to simplify SETCC's. 9556 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9557 CondLHS, CondRHS, CC->get(), SDLoc(N), 9558 false); 9559 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9560 9561 // fold to a simpler setcc 9562 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9563 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9564 N->getOperand(0), Simp.getOperand(2), 9565 Simp.getOperand(0), Simp.getOperand(1), 9566 N->getOperand(4)); 9567 9568 return SDValue(); 9569 } 9570 9571 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9572 /// and that N may be folded in the load / store addressing mode. 9573 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9574 SelectionDAG &DAG, 9575 const TargetLowering &TLI) { 9576 EVT VT; 9577 unsigned AS; 9578 9579 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9580 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9581 return false; 9582 VT = LD->getMemoryVT(); 9583 AS = LD->getAddressSpace(); 9584 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9585 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9586 return false; 9587 VT = ST->getMemoryVT(); 9588 AS = ST->getAddressSpace(); 9589 } else 9590 return false; 9591 9592 TargetLowering::AddrMode AM; 9593 if (N->getOpcode() == ISD::ADD) { 9594 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9595 if (Offset) 9596 // [reg +/- imm] 9597 AM.BaseOffs = Offset->getSExtValue(); 9598 else 9599 // [reg +/- reg] 9600 AM.Scale = 1; 9601 } else if (N->getOpcode() == ISD::SUB) { 9602 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9603 if (Offset) 9604 // [reg +/- imm] 9605 AM.BaseOffs = -Offset->getSExtValue(); 9606 else 9607 // [reg +/- reg] 9608 AM.Scale = 1; 9609 } else 9610 return false; 9611 9612 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 9613 VT.getTypeForEVT(*DAG.getContext()), AS); 9614 } 9615 9616 /// Try turning a load/store into a pre-indexed load/store when the base 9617 /// pointer is an add or subtract and it has other uses besides the load/store. 9618 /// After the transformation, the new indexed load/store has effectively folded 9619 /// the add/subtract in and all of its other uses are redirected to the 9620 /// new load/store. 9621 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9622 if (Level < AfterLegalizeDAG) 9623 return false; 9624 9625 bool isLoad = true; 9626 SDValue Ptr; 9627 EVT VT; 9628 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9629 if (LD->isIndexed()) 9630 return false; 9631 VT = LD->getMemoryVT(); 9632 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9633 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9634 return false; 9635 Ptr = LD->getBasePtr(); 9636 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9637 if (ST->isIndexed()) 9638 return false; 9639 VT = ST->getMemoryVT(); 9640 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9641 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9642 return false; 9643 Ptr = ST->getBasePtr(); 9644 isLoad = false; 9645 } else { 9646 return false; 9647 } 9648 9649 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9650 // out. There is no reason to make this a preinc/predec. 9651 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9652 Ptr.getNode()->hasOneUse()) 9653 return false; 9654 9655 // Ask the target to do addressing mode selection. 9656 SDValue BasePtr; 9657 SDValue Offset; 9658 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9659 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9660 return false; 9661 9662 // Backends without true r+i pre-indexed forms may need to pass a 9663 // constant base with a variable offset so that constant coercion 9664 // will work with the patterns in canonical form. 9665 bool Swapped = false; 9666 if (isa<ConstantSDNode>(BasePtr)) { 9667 std::swap(BasePtr, Offset); 9668 Swapped = true; 9669 } 9670 9671 // Don't create a indexed load / store with zero offset. 9672 if (isNullConstant(Offset)) 9673 return false; 9674 9675 // Try turning it into a pre-indexed load / store except when: 9676 // 1) The new base ptr is a frame index. 9677 // 2) If N is a store and the new base ptr is either the same as or is a 9678 // predecessor of the value being stored. 9679 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9680 // that would create a cycle. 9681 // 4) All uses are load / store ops that use it as old base ptr. 9682 9683 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9684 // (plus the implicit offset) to a register to preinc anyway. 9685 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9686 return false; 9687 9688 // Check #2. 9689 if (!isLoad) { 9690 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9691 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9692 return false; 9693 } 9694 9695 // Caches for hasPredecessorHelper. 9696 SmallPtrSet<const SDNode *, 32> Visited; 9697 SmallVector<const SDNode *, 16> Worklist; 9698 Worklist.push_back(N); 9699 9700 // If the offset is a constant, there may be other adds of constants that 9701 // can be folded with this one. We should do this to avoid having to keep 9702 // a copy of the original base pointer. 9703 SmallVector<SDNode *, 16> OtherUses; 9704 if (isa<ConstantSDNode>(Offset)) 9705 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9706 UE = BasePtr.getNode()->use_end(); 9707 UI != UE; ++UI) { 9708 SDUse &Use = UI.getUse(); 9709 // Skip the use that is Ptr and uses of other results from BasePtr's 9710 // node (important for nodes that return multiple results). 9711 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9712 continue; 9713 9714 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 9715 continue; 9716 9717 if (Use.getUser()->getOpcode() != ISD::ADD && 9718 Use.getUser()->getOpcode() != ISD::SUB) { 9719 OtherUses.clear(); 9720 break; 9721 } 9722 9723 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9724 if (!isa<ConstantSDNode>(Op1)) { 9725 OtherUses.clear(); 9726 break; 9727 } 9728 9729 // FIXME: In some cases, we can be smarter about this. 9730 if (Op1.getValueType() != Offset.getValueType()) { 9731 OtherUses.clear(); 9732 break; 9733 } 9734 9735 OtherUses.push_back(Use.getUser()); 9736 } 9737 9738 if (Swapped) 9739 std::swap(BasePtr, Offset); 9740 9741 // Now check for #3 and #4. 9742 bool RealUse = false; 9743 9744 for (SDNode *Use : Ptr.getNode()->uses()) { 9745 if (Use == N) 9746 continue; 9747 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 9748 return false; 9749 9750 // If Ptr may be folded in addressing mode of other use, then it's 9751 // not profitable to do this transformation. 9752 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9753 RealUse = true; 9754 } 9755 9756 if (!RealUse) 9757 return false; 9758 9759 SDValue Result; 9760 if (isLoad) 9761 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9762 BasePtr, Offset, AM); 9763 else 9764 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9765 BasePtr, Offset, AM); 9766 ++PreIndexedNodes; 9767 ++NodesCombined; 9768 DEBUG(dbgs() << "\nReplacing.4 "; 9769 N->dump(&DAG); 9770 dbgs() << "\nWith: "; 9771 Result.getNode()->dump(&DAG); 9772 dbgs() << '\n'); 9773 WorklistRemover DeadNodes(*this); 9774 if (isLoad) { 9775 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9776 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9777 } else { 9778 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9779 } 9780 9781 // Finally, since the node is now dead, remove it from the graph. 9782 deleteAndRecombine(N); 9783 9784 if (Swapped) 9785 std::swap(BasePtr, Offset); 9786 9787 // Replace other uses of BasePtr that can be updated to use Ptr 9788 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9789 unsigned OffsetIdx = 1; 9790 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9791 OffsetIdx = 0; 9792 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9793 BasePtr.getNode() && "Expected BasePtr operand"); 9794 9795 // We need to replace ptr0 in the following expression: 9796 // x0 * offset0 + y0 * ptr0 = t0 9797 // knowing that 9798 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9799 // 9800 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9801 // indexed load/store and the expresion that needs to be re-written. 9802 // 9803 // Therefore, we have: 9804 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9805 9806 ConstantSDNode *CN = 9807 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9808 int X0, X1, Y0, Y1; 9809 APInt Offset0 = CN->getAPIntValue(); 9810 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9811 9812 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9813 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9814 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9815 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9816 9817 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9818 9819 APInt CNV = Offset0; 9820 if (X0 < 0) CNV = -CNV; 9821 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9822 else CNV = CNV - Offset1; 9823 9824 SDLoc DL(OtherUses[i]); 9825 9826 // We can now generate the new expression. 9827 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9828 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9829 9830 SDValue NewUse = DAG.getNode(Opcode, 9831 DL, 9832 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9833 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9834 deleteAndRecombine(OtherUses[i]); 9835 } 9836 9837 // Replace the uses of Ptr with uses of the updated base value. 9838 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9839 deleteAndRecombine(Ptr.getNode()); 9840 9841 return true; 9842 } 9843 9844 /// Try to combine a load/store with a add/sub of the base pointer node into a 9845 /// post-indexed load/store. The transformation folded the add/subtract into the 9846 /// new indexed load/store effectively and all of its uses are redirected to the 9847 /// new load/store. 9848 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9849 if (Level < AfterLegalizeDAG) 9850 return false; 9851 9852 bool isLoad = true; 9853 SDValue Ptr; 9854 EVT VT; 9855 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9856 if (LD->isIndexed()) 9857 return false; 9858 VT = LD->getMemoryVT(); 9859 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9860 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9861 return false; 9862 Ptr = LD->getBasePtr(); 9863 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9864 if (ST->isIndexed()) 9865 return false; 9866 VT = ST->getMemoryVT(); 9867 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9868 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9869 return false; 9870 Ptr = ST->getBasePtr(); 9871 isLoad = false; 9872 } else { 9873 return false; 9874 } 9875 9876 if (Ptr.getNode()->hasOneUse()) 9877 return false; 9878 9879 for (SDNode *Op : Ptr.getNode()->uses()) { 9880 if (Op == N || 9881 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9882 continue; 9883 9884 SDValue BasePtr; 9885 SDValue Offset; 9886 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9887 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9888 // Don't create a indexed load / store with zero offset. 9889 if (isNullConstant(Offset)) 9890 continue; 9891 9892 // Try turning it into a post-indexed load / store except when 9893 // 1) All uses are load / store ops that use it as base ptr (and 9894 // it may be folded as addressing mmode). 9895 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9896 // nor a successor of N. Otherwise, if Op is folded that would 9897 // create a cycle. 9898 9899 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9900 continue; 9901 9902 // Check for #1. 9903 bool TryNext = false; 9904 for (SDNode *Use : BasePtr.getNode()->uses()) { 9905 if (Use == Ptr.getNode()) 9906 continue; 9907 9908 // If all the uses are load / store addresses, then don't do the 9909 // transformation. 9910 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9911 bool RealUse = false; 9912 for (SDNode *UseUse : Use->uses()) { 9913 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9914 RealUse = true; 9915 } 9916 9917 if (!RealUse) { 9918 TryNext = true; 9919 break; 9920 } 9921 } 9922 } 9923 9924 if (TryNext) 9925 continue; 9926 9927 // Check for #2 9928 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9929 SDValue Result = isLoad 9930 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9931 BasePtr, Offset, AM) 9932 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9933 BasePtr, Offset, AM); 9934 ++PostIndexedNodes; 9935 ++NodesCombined; 9936 DEBUG(dbgs() << "\nReplacing.5 "; 9937 N->dump(&DAG); 9938 dbgs() << "\nWith: "; 9939 Result.getNode()->dump(&DAG); 9940 dbgs() << '\n'); 9941 WorklistRemover DeadNodes(*this); 9942 if (isLoad) { 9943 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9944 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9945 } else { 9946 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9947 } 9948 9949 // Finally, since the node is now dead, remove it from the graph. 9950 deleteAndRecombine(N); 9951 9952 // Replace the uses of Use with uses of the updated base value. 9953 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9954 Result.getValue(isLoad ? 1 : 0)); 9955 deleteAndRecombine(Op); 9956 return true; 9957 } 9958 } 9959 } 9960 9961 return false; 9962 } 9963 9964 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9965 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9966 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9967 assert(AM != ISD::UNINDEXED); 9968 SDValue BP = LD->getOperand(1); 9969 SDValue Inc = LD->getOperand(2); 9970 9971 // Some backends use TargetConstants for load offsets, but don't expect 9972 // TargetConstants in general ADD nodes. We can convert these constants into 9973 // regular Constants (if the constant is not opaque). 9974 assert((Inc.getOpcode() != ISD::TargetConstant || 9975 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9976 "Cannot split out indexing using opaque target constants"); 9977 if (Inc.getOpcode() == ISD::TargetConstant) { 9978 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9979 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9980 ConstInc->getValueType(0)); 9981 } 9982 9983 unsigned Opc = 9984 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9985 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9986 } 9987 9988 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9989 LoadSDNode *LD = cast<LoadSDNode>(N); 9990 SDValue Chain = LD->getChain(); 9991 SDValue Ptr = LD->getBasePtr(); 9992 9993 // If load is not volatile and there are no uses of the loaded value (and 9994 // the updated indexed value in case of indexed loads), change uses of the 9995 // chain value into uses of the chain input (i.e. delete the dead load). 9996 if (!LD->isVolatile()) { 9997 if (N->getValueType(1) == MVT::Other) { 9998 // Unindexed loads. 9999 if (!N->hasAnyUseOfValue(0)) { 10000 // It's not safe to use the two value CombineTo variant here. e.g. 10001 // v1, chain2 = load chain1, loc 10002 // v2, chain3 = load chain2, loc 10003 // v3 = add v2, c 10004 // Now we replace use of chain2 with chain1. This makes the second load 10005 // isomorphic to the one we are deleting, and thus makes this load live. 10006 DEBUG(dbgs() << "\nReplacing.6 "; 10007 N->dump(&DAG); 10008 dbgs() << "\nWith chain: "; 10009 Chain.getNode()->dump(&DAG); 10010 dbgs() << "\n"); 10011 WorklistRemover DeadNodes(*this); 10012 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10013 10014 if (N->use_empty()) 10015 deleteAndRecombine(N); 10016 10017 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10018 } 10019 } else { 10020 // Indexed loads. 10021 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 10022 10023 // If this load has an opaque TargetConstant offset, then we cannot split 10024 // the indexing into an add/sub directly (that TargetConstant may not be 10025 // valid for a different type of node, and we cannot convert an opaque 10026 // target constant into a regular constant). 10027 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 10028 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 10029 10030 if (!N->hasAnyUseOfValue(0) && 10031 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 10032 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 10033 SDValue Index; 10034 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 10035 Index = SplitIndexingFromLoad(LD); 10036 // Try to fold the base pointer arithmetic into subsequent loads and 10037 // stores. 10038 AddUsersToWorklist(N); 10039 } else 10040 Index = DAG.getUNDEF(N->getValueType(1)); 10041 DEBUG(dbgs() << "\nReplacing.7 "; 10042 N->dump(&DAG); 10043 dbgs() << "\nWith: "; 10044 Undef.getNode()->dump(&DAG); 10045 dbgs() << " and 2 other values\n"); 10046 WorklistRemover DeadNodes(*this); 10047 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 10048 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 10049 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 10050 deleteAndRecombine(N); 10051 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10052 } 10053 } 10054 } 10055 10056 // If this load is directly stored, replace the load value with the stored 10057 // value. 10058 // TODO: Handle store large -> read small portion. 10059 // TODO: Handle TRUNCSTORE/LOADEXT 10060 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 10061 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 10062 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 10063 if (PrevST->getBasePtr() == Ptr && 10064 PrevST->getValue().getValueType() == N->getValueType(0)) 10065 return CombineTo(N, Chain.getOperand(1), Chain); 10066 } 10067 } 10068 10069 // Try to infer better alignment information than the load already has. 10070 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 10071 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10072 if (Align > LD->getMemOperand()->getBaseAlignment()) { 10073 SDValue NewLoad = 10074 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 10075 LD->getValueType(0), 10076 Chain, Ptr, LD->getPointerInfo(), 10077 LD->getMemoryVT(), 10078 LD->isVolatile(), LD->isNonTemporal(), 10079 LD->isInvariant(), Align, LD->getAAInfo()); 10080 if (NewLoad.getNode() != N) 10081 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 10082 } 10083 } 10084 } 10085 10086 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10087 : DAG.getSubtarget().useAA(); 10088 #ifndef NDEBUG 10089 if (CombinerAAOnlyFunc.getNumOccurrences() && 10090 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10091 UseAA = false; 10092 #endif 10093 if (UseAA && LD->isUnindexed()) { 10094 // Walk up chain skipping non-aliasing memory nodes. 10095 SDValue BetterChain = FindBetterChain(N, Chain); 10096 10097 // If there is a better chain. 10098 if (Chain != BetterChain) { 10099 SDValue ReplLoad; 10100 10101 // Replace the chain to void dependency. 10102 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 10103 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 10104 BetterChain, Ptr, LD->getMemOperand()); 10105 } else { 10106 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 10107 LD->getValueType(0), 10108 BetterChain, Ptr, LD->getMemoryVT(), 10109 LD->getMemOperand()); 10110 } 10111 10112 // Create token factor to keep old chain connected. 10113 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10114 MVT::Other, Chain, ReplLoad.getValue(1)); 10115 10116 // Make sure the new and old chains are cleaned up. 10117 AddToWorklist(Token.getNode()); 10118 10119 // Replace uses with load result and token factor. Don't add users 10120 // to work list. 10121 return CombineTo(N, ReplLoad.getValue(0), Token, false); 10122 } 10123 } 10124 10125 // Try transforming N to an indexed load. 10126 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10127 return SDValue(N, 0); 10128 10129 // Try to slice up N to more direct loads if the slices are mapped to 10130 // different register banks or pairing can take place. 10131 if (SliceUpLoad(N)) 10132 return SDValue(N, 0); 10133 10134 return SDValue(); 10135 } 10136 10137 namespace { 10138 /// \brief Helper structure used to slice a load in smaller loads. 10139 /// Basically a slice is obtained from the following sequence: 10140 /// Origin = load Ty1, Base 10141 /// Shift = srl Ty1 Origin, CstTy Amount 10142 /// Inst = trunc Shift to Ty2 10143 /// 10144 /// Then, it will be rewriten into: 10145 /// Slice = load SliceTy, Base + SliceOffset 10146 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 10147 /// 10148 /// SliceTy is deduced from the number of bits that are actually used to 10149 /// build Inst. 10150 struct LoadedSlice { 10151 /// \brief Helper structure used to compute the cost of a slice. 10152 struct Cost { 10153 /// Are we optimizing for code size. 10154 bool ForCodeSize; 10155 /// Various cost. 10156 unsigned Loads; 10157 unsigned Truncates; 10158 unsigned CrossRegisterBanksCopies; 10159 unsigned ZExts; 10160 unsigned Shift; 10161 10162 Cost(bool ForCodeSize = false) 10163 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 10164 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 10165 10166 /// \brief Get the cost of one isolated slice. 10167 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 10168 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 10169 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 10170 EVT TruncType = LS.Inst->getValueType(0); 10171 EVT LoadedType = LS.getLoadedType(); 10172 if (TruncType != LoadedType && 10173 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 10174 ZExts = 1; 10175 } 10176 10177 /// \brief Account for slicing gain in the current cost. 10178 /// Slicing provide a few gains like removing a shift or a 10179 /// truncate. This method allows to grow the cost of the original 10180 /// load with the gain from this slice. 10181 void addSliceGain(const LoadedSlice &LS) { 10182 // Each slice saves a truncate. 10183 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 10184 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 10185 LS.Inst->getValueType(0))) 10186 ++Truncates; 10187 // If there is a shift amount, this slice gets rid of it. 10188 if (LS.Shift) 10189 ++Shift; 10190 // If this slice can merge a cross register bank copy, account for it. 10191 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 10192 ++CrossRegisterBanksCopies; 10193 } 10194 10195 Cost &operator+=(const Cost &RHS) { 10196 Loads += RHS.Loads; 10197 Truncates += RHS.Truncates; 10198 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 10199 ZExts += RHS.ZExts; 10200 Shift += RHS.Shift; 10201 return *this; 10202 } 10203 10204 bool operator==(const Cost &RHS) const { 10205 return Loads == RHS.Loads && Truncates == RHS.Truncates && 10206 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 10207 ZExts == RHS.ZExts && Shift == RHS.Shift; 10208 } 10209 10210 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 10211 10212 bool operator<(const Cost &RHS) const { 10213 // Assume cross register banks copies are as expensive as loads. 10214 // FIXME: Do we want some more target hooks? 10215 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 10216 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 10217 // Unless we are optimizing for code size, consider the 10218 // expensive operation first. 10219 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 10220 return ExpensiveOpsLHS < ExpensiveOpsRHS; 10221 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 10222 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 10223 } 10224 10225 bool operator>(const Cost &RHS) const { return RHS < *this; } 10226 10227 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 10228 10229 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 10230 }; 10231 // The last instruction that represent the slice. This should be a 10232 // truncate instruction. 10233 SDNode *Inst; 10234 // The original load instruction. 10235 LoadSDNode *Origin; 10236 // The right shift amount in bits from the original load. 10237 unsigned Shift; 10238 // The DAG from which Origin came from. 10239 // This is used to get some contextual information about legal types, etc. 10240 SelectionDAG *DAG; 10241 10242 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 10243 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 10244 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 10245 10246 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 10247 /// \return Result is \p BitWidth and has used bits set to 1 and 10248 /// not used bits set to 0. 10249 APInt getUsedBits() const { 10250 // Reproduce the trunc(lshr) sequence: 10251 // - Start from the truncated value. 10252 // - Zero extend to the desired bit width. 10253 // - Shift left. 10254 assert(Origin && "No original load to compare against."); 10255 unsigned BitWidth = Origin->getValueSizeInBits(0); 10256 assert(Inst && "This slice is not bound to an instruction"); 10257 assert(Inst->getValueSizeInBits(0) <= BitWidth && 10258 "Extracted slice is bigger than the whole type!"); 10259 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 10260 UsedBits.setAllBits(); 10261 UsedBits = UsedBits.zext(BitWidth); 10262 UsedBits <<= Shift; 10263 return UsedBits; 10264 } 10265 10266 /// \brief Get the size of the slice to be loaded in bytes. 10267 unsigned getLoadedSize() const { 10268 unsigned SliceSize = getUsedBits().countPopulation(); 10269 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 10270 return SliceSize / 8; 10271 } 10272 10273 /// \brief Get the type that will be loaded for this slice. 10274 /// Note: This may not be the final type for the slice. 10275 EVT getLoadedType() const { 10276 assert(DAG && "Missing context"); 10277 LLVMContext &Ctxt = *DAG->getContext(); 10278 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 10279 } 10280 10281 /// \brief Get the alignment of the load used for this slice. 10282 unsigned getAlignment() const { 10283 unsigned Alignment = Origin->getAlignment(); 10284 unsigned Offset = getOffsetFromBase(); 10285 if (Offset != 0) 10286 Alignment = MinAlign(Alignment, Alignment + Offset); 10287 return Alignment; 10288 } 10289 10290 /// \brief Check if this slice can be rewritten with legal operations. 10291 bool isLegal() const { 10292 // An invalid slice is not legal. 10293 if (!Origin || !Inst || !DAG) 10294 return false; 10295 10296 // Offsets are for indexed load only, we do not handle that. 10297 if (!Origin->getOffset().isUndef()) 10298 return false; 10299 10300 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10301 10302 // Check that the type is legal. 10303 EVT SliceType = getLoadedType(); 10304 if (!TLI.isTypeLegal(SliceType)) 10305 return false; 10306 10307 // Check that the load is legal for this type. 10308 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 10309 return false; 10310 10311 // Check that the offset can be computed. 10312 // 1. Check its type. 10313 EVT PtrType = Origin->getBasePtr().getValueType(); 10314 if (PtrType == MVT::Untyped || PtrType.isExtended()) 10315 return false; 10316 10317 // 2. Check that it fits in the immediate. 10318 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 10319 return false; 10320 10321 // 3. Check that the computation is legal. 10322 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 10323 return false; 10324 10325 // Check that the zext is legal if it needs one. 10326 EVT TruncateType = Inst->getValueType(0); 10327 if (TruncateType != SliceType && 10328 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 10329 return false; 10330 10331 return true; 10332 } 10333 10334 /// \brief Get the offset in bytes of this slice in the original chunk of 10335 /// bits. 10336 /// \pre DAG != nullptr. 10337 uint64_t getOffsetFromBase() const { 10338 assert(DAG && "Missing context."); 10339 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 10340 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 10341 uint64_t Offset = Shift / 8; 10342 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 10343 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 10344 "The size of the original loaded type is not a multiple of a" 10345 " byte."); 10346 // If Offset is bigger than TySizeInBytes, it means we are loading all 10347 // zeros. This should have been optimized before in the process. 10348 assert(TySizeInBytes > Offset && 10349 "Invalid shift amount for given loaded size"); 10350 if (IsBigEndian) 10351 Offset = TySizeInBytes - Offset - getLoadedSize(); 10352 return Offset; 10353 } 10354 10355 /// \brief Generate the sequence of instructions to load the slice 10356 /// represented by this object and redirect the uses of this slice to 10357 /// this new sequence of instructions. 10358 /// \pre this->Inst && this->Origin are valid Instructions and this 10359 /// object passed the legal check: LoadedSlice::isLegal returned true. 10360 /// \return The last instruction of the sequence used to load the slice. 10361 SDValue loadSlice() const { 10362 assert(Inst && Origin && "Unable to replace a non-existing slice."); 10363 const SDValue &OldBaseAddr = Origin->getBasePtr(); 10364 SDValue BaseAddr = OldBaseAddr; 10365 // Get the offset in that chunk of bytes w.r.t. the endianess. 10366 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 10367 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 10368 if (Offset) { 10369 // BaseAddr = BaseAddr + Offset. 10370 EVT ArithType = BaseAddr.getValueType(); 10371 SDLoc DL(Origin); 10372 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 10373 DAG->getConstant(Offset, DL, ArithType)); 10374 } 10375 10376 // Create the type of the loaded slice according to its size. 10377 EVT SliceType = getLoadedType(); 10378 10379 // Create the load for the slice. 10380 SDValue LastInst = DAG->getLoad( 10381 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 10382 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 10383 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 10384 // If the final type is not the same as the loaded type, this means that 10385 // we have to pad with zero. Create a zero extend for that. 10386 EVT FinalType = Inst->getValueType(0); 10387 if (SliceType != FinalType) 10388 LastInst = 10389 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 10390 return LastInst; 10391 } 10392 10393 /// \brief Check if this slice can be merged with an expensive cross register 10394 /// bank copy. E.g., 10395 /// i = load i32 10396 /// f = bitcast i32 i to float 10397 bool canMergeExpensiveCrossRegisterBankCopy() const { 10398 if (!Inst || !Inst->hasOneUse()) 10399 return false; 10400 SDNode *Use = *Inst->use_begin(); 10401 if (Use->getOpcode() != ISD::BITCAST) 10402 return false; 10403 assert(DAG && "Missing context"); 10404 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 10405 EVT ResVT = Use->getValueType(0); 10406 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 10407 const TargetRegisterClass *ArgRC = 10408 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 10409 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 10410 return false; 10411 10412 // At this point, we know that we perform a cross-register-bank copy. 10413 // Check if it is expensive. 10414 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 10415 // Assume bitcasts are cheap, unless both register classes do not 10416 // explicitly share a common sub class. 10417 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 10418 return false; 10419 10420 // Check if it will be merged with the load. 10421 // 1. Check the alignment constraint. 10422 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 10423 ResVT.getTypeForEVT(*DAG->getContext())); 10424 10425 if (RequiredAlignment > getAlignment()) 10426 return false; 10427 10428 // 2. Check that the load is a legal operation for that type. 10429 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 10430 return false; 10431 10432 // 3. Check that we do not have a zext in the way. 10433 if (Inst->getValueType(0) != getLoadedType()) 10434 return false; 10435 10436 return true; 10437 } 10438 }; 10439 } 10440 10441 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 10442 /// \p UsedBits looks like 0..0 1..1 0..0. 10443 static bool areUsedBitsDense(const APInt &UsedBits) { 10444 // If all the bits are one, this is dense! 10445 if (UsedBits.isAllOnesValue()) 10446 return true; 10447 10448 // Get rid of the unused bits on the right. 10449 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 10450 // Get rid of the unused bits on the left. 10451 if (NarrowedUsedBits.countLeadingZeros()) 10452 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 10453 // Check that the chunk of bits is completely used. 10454 return NarrowedUsedBits.isAllOnesValue(); 10455 } 10456 10457 /// \brief Check whether or not \p First and \p Second are next to each other 10458 /// in memory. This means that there is no hole between the bits loaded 10459 /// by \p First and the bits loaded by \p Second. 10460 static bool areSlicesNextToEachOther(const LoadedSlice &First, 10461 const LoadedSlice &Second) { 10462 assert(First.Origin == Second.Origin && First.Origin && 10463 "Unable to match different memory origins."); 10464 APInt UsedBits = First.getUsedBits(); 10465 assert((UsedBits & Second.getUsedBits()) == 0 && 10466 "Slices are not supposed to overlap."); 10467 UsedBits |= Second.getUsedBits(); 10468 return areUsedBitsDense(UsedBits); 10469 } 10470 10471 /// \brief Adjust the \p GlobalLSCost according to the target 10472 /// paring capabilities and the layout of the slices. 10473 /// \pre \p GlobalLSCost should account for at least as many loads as 10474 /// there is in the slices in \p LoadedSlices. 10475 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10476 LoadedSlice::Cost &GlobalLSCost) { 10477 unsigned NumberOfSlices = LoadedSlices.size(); 10478 // If there is less than 2 elements, no pairing is possible. 10479 if (NumberOfSlices < 2) 10480 return; 10481 10482 // Sort the slices so that elements that are likely to be next to each 10483 // other in memory are next to each other in the list. 10484 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 10485 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 10486 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 10487 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 10488 }); 10489 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 10490 // First (resp. Second) is the first (resp. Second) potentially candidate 10491 // to be placed in a paired load. 10492 const LoadedSlice *First = nullptr; 10493 const LoadedSlice *Second = nullptr; 10494 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 10495 // Set the beginning of the pair. 10496 First = Second) { 10497 10498 Second = &LoadedSlices[CurrSlice]; 10499 10500 // If First is NULL, it means we start a new pair. 10501 // Get to the next slice. 10502 if (!First) 10503 continue; 10504 10505 EVT LoadedType = First->getLoadedType(); 10506 10507 // If the types of the slices are different, we cannot pair them. 10508 if (LoadedType != Second->getLoadedType()) 10509 continue; 10510 10511 // Check if the target supplies paired loads for this type. 10512 unsigned RequiredAlignment = 0; 10513 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 10514 // move to the next pair, this type is hopeless. 10515 Second = nullptr; 10516 continue; 10517 } 10518 // Check if we meet the alignment requirement. 10519 if (RequiredAlignment > First->getAlignment()) 10520 continue; 10521 10522 // Check that both loads are next to each other in memory. 10523 if (!areSlicesNextToEachOther(*First, *Second)) 10524 continue; 10525 10526 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 10527 --GlobalLSCost.Loads; 10528 // Move to the next pair. 10529 Second = nullptr; 10530 } 10531 } 10532 10533 /// \brief Check the profitability of all involved LoadedSlice. 10534 /// Currently, it is considered profitable if there is exactly two 10535 /// involved slices (1) which are (2) next to each other in memory, and 10536 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 10537 /// 10538 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 10539 /// the elements themselves. 10540 /// 10541 /// FIXME: When the cost model will be mature enough, we can relax 10542 /// constraints (1) and (2). 10543 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 10544 const APInt &UsedBits, bool ForCodeSize) { 10545 unsigned NumberOfSlices = LoadedSlices.size(); 10546 if (StressLoadSlicing) 10547 return NumberOfSlices > 1; 10548 10549 // Check (1). 10550 if (NumberOfSlices != 2) 10551 return false; 10552 10553 // Check (2). 10554 if (!areUsedBitsDense(UsedBits)) 10555 return false; 10556 10557 // Check (3). 10558 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10559 // The original code has one big load. 10560 OrigCost.Loads = 1; 10561 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10562 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10563 // Accumulate the cost of all the slices. 10564 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10565 GlobalSlicingCost += SliceCost; 10566 10567 // Account as cost in the original configuration the gain obtained 10568 // with the current slices. 10569 OrigCost.addSliceGain(LS); 10570 } 10571 10572 // If the target supports paired load, adjust the cost accordingly. 10573 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10574 return OrigCost > GlobalSlicingCost; 10575 } 10576 10577 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10578 /// operations, split it in the various pieces being extracted. 10579 /// 10580 /// This sort of thing is introduced by SROA. 10581 /// This slicing takes care not to insert overlapping loads. 10582 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10583 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10584 if (Level < AfterLegalizeDAG) 10585 return false; 10586 10587 LoadSDNode *LD = cast<LoadSDNode>(N); 10588 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10589 !LD->getValueType(0).isInteger()) 10590 return false; 10591 10592 // Keep track of already used bits to detect overlapping values. 10593 // In that case, we will just abort the transformation. 10594 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10595 10596 SmallVector<LoadedSlice, 4> LoadedSlices; 10597 10598 // Check if this load is used as several smaller chunks of bits. 10599 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10600 // of computation for each trunc. 10601 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10602 UI != UIEnd; ++UI) { 10603 // Skip the uses of the chain. 10604 if (UI.getUse().getResNo() != 0) 10605 continue; 10606 10607 SDNode *User = *UI; 10608 unsigned Shift = 0; 10609 10610 // Check if this is a trunc(lshr). 10611 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10612 isa<ConstantSDNode>(User->getOperand(1))) { 10613 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10614 User = *User->use_begin(); 10615 } 10616 10617 // At this point, User is a Truncate, iff we encountered, trunc or 10618 // trunc(lshr). 10619 if (User->getOpcode() != ISD::TRUNCATE) 10620 return false; 10621 10622 // The width of the type must be a power of 2 and greater than 8-bits. 10623 // Otherwise the load cannot be represented in LLVM IR. 10624 // Moreover, if we shifted with a non-8-bits multiple, the slice 10625 // will be across several bytes. We do not support that. 10626 unsigned Width = User->getValueSizeInBits(0); 10627 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10628 return 0; 10629 10630 // Build the slice for this chain of computations. 10631 LoadedSlice LS(User, LD, Shift, &DAG); 10632 APInt CurrentUsedBits = LS.getUsedBits(); 10633 10634 // Check if this slice overlaps with another. 10635 if ((CurrentUsedBits & UsedBits) != 0) 10636 return false; 10637 // Update the bits used globally. 10638 UsedBits |= CurrentUsedBits; 10639 10640 // Check if the new slice would be legal. 10641 if (!LS.isLegal()) 10642 return false; 10643 10644 // Record the slice. 10645 LoadedSlices.push_back(LS); 10646 } 10647 10648 // Abort slicing if it does not seem to be profitable. 10649 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10650 return false; 10651 10652 ++SlicedLoads; 10653 10654 // Rewrite each chain to use an independent load. 10655 // By construction, each chain can be represented by a unique load. 10656 10657 // Prepare the argument for the new token factor for all the slices. 10658 SmallVector<SDValue, 8> ArgChains; 10659 for (SmallVectorImpl<LoadedSlice>::const_iterator 10660 LSIt = LoadedSlices.begin(), 10661 LSItEnd = LoadedSlices.end(); 10662 LSIt != LSItEnd; ++LSIt) { 10663 SDValue SliceInst = LSIt->loadSlice(); 10664 CombineTo(LSIt->Inst, SliceInst, true); 10665 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10666 SliceInst = SliceInst.getOperand(0); 10667 assert(SliceInst->getOpcode() == ISD::LOAD && 10668 "It takes more than a zext to get to the loaded slice!!"); 10669 ArgChains.push_back(SliceInst.getValue(1)); 10670 } 10671 10672 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10673 ArgChains); 10674 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10675 return true; 10676 } 10677 10678 /// Check to see if V is (and load (ptr), imm), where the load is having 10679 /// specific bytes cleared out. If so, return the byte size being masked out 10680 /// and the shift amount. 10681 static std::pair<unsigned, unsigned> 10682 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10683 std::pair<unsigned, unsigned> Result(0, 0); 10684 10685 // Check for the structure we're looking for. 10686 if (V->getOpcode() != ISD::AND || 10687 !isa<ConstantSDNode>(V->getOperand(1)) || 10688 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10689 return Result; 10690 10691 // Check the chain and pointer. 10692 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10693 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10694 10695 // The store should be chained directly to the load or be an operand of a 10696 // tokenfactor. 10697 if (LD == Chain.getNode()) 10698 ; // ok. 10699 else if (Chain->getOpcode() != ISD::TokenFactor) 10700 return Result; // Fail. 10701 else { 10702 bool isOk = false; 10703 for (const SDValue &ChainOp : Chain->op_values()) 10704 if (ChainOp.getNode() == LD) { 10705 isOk = true; 10706 break; 10707 } 10708 if (!isOk) return Result; 10709 } 10710 10711 // This only handles simple types. 10712 if (V.getValueType() != MVT::i16 && 10713 V.getValueType() != MVT::i32 && 10714 V.getValueType() != MVT::i64) 10715 return Result; 10716 10717 // Check the constant mask. Invert it so that the bits being masked out are 10718 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10719 // follow the sign bit for uniformity. 10720 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10721 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10722 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10723 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10724 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10725 if (NotMaskLZ == 64) return Result; // All zero mask. 10726 10727 // See if we have a continuous run of bits. If so, we have 0*1+0* 10728 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10729 return Result; 10730 10731 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10732 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10733 NotMaskLZ -= 64-V.getValueSizeInBits(); 10734 10735 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10736 switch (MaskedBytes) { 10737 case 1: 10738 case 2: 10739 case 4: break; 10740 default: return Result; // All one mask, or 5-byte mask. 10741 } 10742 10743 // Verify that the first bit starts at a multiple of mask so that the access 10744 // is aligned the same as the access width. 10745 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10746 10747 Result.first = MaskedBytes; 10748 Result.second = NotMaskTZ/8; 10749 return Result; 10750 } 10751 10752 10753 /// Check to see if IVal is something that provides a value as specified by 10754 /// MaskInfo. If so, replace the specified store with a narrower store of 10755 /// truncated IVal. 10756 static SDNode * 10757 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10758 SDValue IVal, StoreSDNode *St, 10759 DAGCombiner *DC) { 10760 unsigned NumBytes = MaskInfo.first; 10761 unsigned ByteShift = MaskInfo.second; 10762 SelectionDAG &DAG = DC->getDAG(); 10763 10764 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10765 // that uses this. If not, this is not a replacement. 10766 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10767 ByteShift*8, (ByteShift+NumBytes)*8); 10768 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10769 10770 // Check that it is legal on the target to do this. It is legal if the new 10771 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10772 // legalization. 10773 MVT VT = MVT::getIntegerVT(NumBytes*8); 10774 if (!DC->isTypeLegal(VT)) 10775 return nullptr; 10776 10777 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10778 // shifted by ByteShift and truncated down to NumBytes. 10779 if (ByteShift) { 10780 SDLoc DL(IVal); 10781 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10782 DAG.getConstant(ByteShift*8, DL, 10783 DC->getShiftAmountTy(IVal.getValueType()))); 10784 } 10785 10786 // Figure out the offset for the store and the alignment of the access. 10787 unsigned StOffset; 10788 unsigned NewAlign = St->getAlignment(); 10789 10790 if (DAG.getDataLayout().isLittleEndian()) 10791 StOffset = ByteShift; 10792 else 10793 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10794 10795 SDValue Ptr = St->getBasePtr(); 10796 if (StOffset) { 10797 SDLoc DL(IVal); 10798 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10799 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10800 NewAlign = MinAlign(NewAlign, StOffset); 10801 } 10802 10803 // Truncate down to the new size. 10804 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10805 10806 ++OpsNarrowed; 10807 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10808 St->getPointerInfo().getWithOffset(StOffset), 10809 false, false, NewAlign).getNode(); 10810 } 10811 10812 10813 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10814 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10815 /// narrowing the load and store if it would end up being a win for performance 10816 /// or code size. 10817 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10818 StoreSDNode *ST = cast<StoreSDNode>(N); 10819 if (ST->isVolatile()) 10820 return SDValue(); 10821 10822 SDValue Chain = ST->getChain(); 10823 SDValue Value = ST->getValue(); 10824 SDValue Ptr = ST->getBasePtr(); 10825 EVT VT = Value.getValueType(); 10826 10827 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10828 return SDValue(); 10829 10830 unsigned Opc = Value.getOpcode(); 10831 10832 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10833 // is a byte mask indicating a consecutive number of bytes, check to see if 10834 // Y is known to provide just those bytes. If so, we try to replace the 10835 // load + replace + store sequence with a single (narrower) store, which makes 10836 // the load dead. 10837 if (Opc == ISD::OR) { 10838 std::pair<unsigned, unsigned> MaskedLoad; 10839 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10840 if (MaskedLoad.first) 10841 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10842 Value.getOperand(1), ST,this)) 10843 return SDValue(NewST, 0); 10844 10845 // Or is commutative, so try swapping X and Y. 10846 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10847 if (MaskedLoad.first) 10848 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10849 Value.getOperand(0), ST,this)) 10850 return SDValue(NewST, 0); 10851 } 10852 10853 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10854 Value.getOperand(1).getOpcode() != ISD::Constant) 10855 return SDValue(); 10856 10857 SDValue N0 = Value.getOperand(0); 10858 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10859 Chain == SDValue(N0.getNode(), 1)) { 10860 LoadSDNode *LD = cast<LoadSDNode>(N0); 10861 if (LD->getBasePtr() != Ptr || 10862 LD->getPointerInfo().getAddrSpace() != 10863 ST->getPointerInfo().getAddrSpace()) 10864 return SDValue(); 10865 10866 // Find the type to narrow it the load / op / store to. 10867 SDValue N1 = Value.getOperand(1); 10868 unsigned BitWidth = N1.getValueSizeInBits(); 10869 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10870 if (Opc == ISD::AND) 10871 Imm ^= APInt::getAllOnesValue(BitWidth); 10872 if (Imm == 0 || Imm.isAllOnesValue()) 10873 return SDValue(); 10874 unsigned ShAmt = Imm.countTrailingZeros(); 10875 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10876 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10877 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10878 // The narrowing should be profitable, the load/store operation should be 10879 // legal (or custom) and the store size should be equal to the NewVT width. 10880 while (NewBW < BitWidth && 10881 (NewVT.getStoreSizeInBits() != NewBW || 10882 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10883 !TLI.isNarrowingProfitable(VT, NewVT))) { 10884 NewBW = NextPowerOf2(NewBW); 10885 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10886 } 10887 if (NewBW >= BitWidth) 10888 return SDValue(); 10889 10890 // If the lsb changed does not start at the type bitwidth boundary, 10891 // start at the previous one. 10892 if (ShAmt % NewBW) 10893 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10894 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10895 std::min(BitWidth, ShAmt + NewBW)); 10896 if ((Imm & Mask) == Imm) { 10897 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10898 if (Opc == ISD::AND) 10899 NewImm ^= APInt::getAllOnesValue(NewBW); 10900 uint64_t PtrOff = ShAmt / 8; 10901 // For big endian targets, we need to adjust the offset to the pointer to 10902 // load the correct bytes. 10903 if (DAG.getDataLayout().isBigEndian()) 10904 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10905 10906 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10907 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10908 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 10909 return SDValue(); 10910 10911 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10912 Ptr.getValueType(), Ptr, 10913 DAG.getConstant(PtrOff, SDLoc(LD), 10914 Ptr.getValueType())); 10915 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10916 LD->getChain(), NewPtr, 10917 LD->getPointerInfo().getWithOffset(PtrOff), 10918 LD->isVolatile(), LD->isNonTemporal(), 10919 LD->isInvariant(), NewAlign, 10920 LD->getAAInfo()); 10921 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10922 DAG.getConstant(NewImm, SDLoc(Value), 10923 NewVT)); 10924 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10925 NewVal, NewPtr, 10926 ST->getPointerInfo().getWithOffset(PtrOff), 10927 false, false, NewAlign); 10928 10929 AddToWorklist(NewPtr.getNode()); 10930 AddToWorklist(NewLD.getNode()); 10931 AddToWorklist(NewVal.getNode()); 10932 WorklistRemover DeadNodes(*this); 10933 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10934 ++OpsNarrowed; 10935 return NewST; 10936 } 10937 } 10938 10939 return SDValue(); 10940 } 10941 10942 /// For a given floating point load / store pair, if the load value isn't used 10943 /// by any other operations, then consider transforming the pair to integer 10944 /// load / store operations if the target deems the transformation profitable. 10945 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10946 StoreSDNode *ST = cast<StoreSDNode>(N); 10947 SDValue Chain = ST->getChain(); 10948 SDValue Value = ST->getValue(); 10949 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10950 Value.hasOneUse() && 10951 Chain == SDValue(Value.getNode(), 1)) { 10952 LoadSDNode *LD = cast<LoadSDNode>(Value); 10953 EVT VT = LD->getMemoryVT(); 10954 if (!VT.isFloatingPoint() || 10955 VT != ST->getMemoryVT() || 10956 LD->isNonTemporal() || 10957 ST->isNonTemporal() || 10958 LD->getPointerInfo().getAddrSpace() != 0 || 10959 ST->getPointerInfo().getAddrSpace() != 0) 10960 return SDValue(); 10961 10962 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10963 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10964 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10965 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10966 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10967 return SDValue(); 10968 10969 unsigned LDAlign = LD->getAlignment(); 10970 unsigned STAlign = ST->getAlignment(); 10971 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10972 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 10973 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10974 return SDValue(); 10975 10976 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10977 LD->getChain(), LD->getBasePtr(), 10978 LD->getPointerInfo(), 10979 false, false, false, LDAlign); 10980 10981 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10982 NewLD, ST->getBasePtr(), 10983 ST->getPointerInfo(), 10984 false, false, STAlign); 10985 10986 AddToWorklist(NewLD.getNode()); 10987 AddToWorklist(NewST.getNode()); 10988 WorklistRemover DeadNodes(*this); 10989 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10990 ++LdStFP2Int; 10991 return NewST; 10992 } 10993 10994 return SDValue(); 10995 } 10996 10997 namespace { 10998 /// Helper struct to parse and store a memory address as base + index + offset. 10999 /// We ignore sign extensions when it is safe to do so. 11000 /// The following two expressions are not equivalent. To differentiate we need 11001 /// to store whether there was a sign extension involved in the index 11002 /// computation. 11003 /// (load (i64 add (i64 copyfromreg %c) 11004 /// (i64 signextend (add (i8 load %index) 11005 /// (i8 1)))) 11006 /// vs 11007 /// 11008 /// (load (i64 add (i64 copyfromreg %c) 11009 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 11010 /// (i32 1))))) 11011 struct BaseIndexOffset { 11012 SDValue Base; 11013 SDValue Index; 11014 int64_t Offset; 11015 bool IsIndexSignExt; 11016 11017 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 11018 11019 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 11020 bool IsIndexSignExt) : 11021 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 11022 11023 bool equalBaseIndex(const BaseIndexOffset &Other) { 11024 return Other.Base == Base && Other.Index == Index && 11025 Other.IsIndexSignExt == IsIndexSignExt; 11026 } 11027 11028 /// Parses tree in Ptr for base, index, offset addresses. 11029 static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG) { 11030 bool IsIndexSignExt = false; 11031 11032 // Split up a folded GlobalAddress+Offset into its component parts. 11033 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr)) 11034 if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) { 11035 return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(), 11036 SDLoc(GA), 11037 GA->getValueType(0), 11038 /*Offset=*/0, 11039 /*isTargetGA=*/false, 11040 GA->getTargetFlags()), 11041 SDValue(), 11042 GA->getOffset(), 11043 IsIndexSignExt); 11044 } 11045 11046 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 11047 // instruction, then it could be just the BASE or everything else we don't 11048 // know how to handle. Just use Ptr as BASE and give up. 11049 if (Ptr->getOpcode() != ISD::ADD) 11050 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11051 11052 // We know that we have at least an ADD instruction. Try to pattern match 11053 // the simple case of BASE + OFFSET. 11054 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 11055 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 11056 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 11057 IsIndexSignExt); 11058 } 11059 11060 // Inside a loop the current BASE pointer is calculated using an ADD and a 11061 // MUL instruction. In this case Ptr is the actual BASE pointer. 11062 // (i64 add (i64 %array_ptr) 11063 // (i64 mul (i64 %induction_var) 11064 // (i64 %element_size))) 11065 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 11066 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11067 11068 // Look at Base + Index + Offset cases. 11069 SDValue Base = Ptr->getOperand(0); 11070 SDValue IndexOffset = Ptr->getOperand(1); 11071 11072 // Skip signextends. 11073 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 11074 IndexOffset = IndexOffset->getOperand(0); 11075 IsIndexSignExt = true; 11076 } 11077 11078 // Either the case of Base + Index (no offset) or something else. 11079 if (IndexOffset->getOpcode() != ISD::ADD) 11080 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 11081 11082 // Now we have the case of Base + Index + offset. 11083 SDValue Index = IndexOffset->getOperand(0); 11084 SDValue Offset = IndexOffset->getOperand(1); 11085 11086 if (!isa<ConstantSDNode>(Offset)) 11087 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 11088 11089 // Ignore signextends. 11090 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 11091 Index = Index->getOperand(0); 11092 IsIndexSignExt = true; 11093 } else IsIndexSignExt = false; 11094 11095 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 11096 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 11097 } 11098 }; 11099 } // namespace 11100 11101 // This is a helper function for visitMUL to check the profitability 11102 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 11103 // MulNode is the original multiply, AddNode is (add x, c1), 11104 // and ConstNode is c2. 11105 // 11106 // If the (add x, c1) has multiple uses, we could increase 11107 // the number of adds if we make this transformation. 11108 // It would only be worth doing this if we can remove a 11109 // multiply in the process. Check for that here. 11110 // To illustrate: 11111 // (A + c1) * c3 11112 // (A + c2) * c3 11113 // We're checking for cases where we have common "c3 * A" expressions. 11114 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 11115 SDValue &AddNode, 11116 SDValue &ConstNode) { 11117 APInt Val; 11118 11119 // If the add only has one use, this would be OK to do. 11120 if (AddNode.getNode()->hasOneUse()) 11121 return true; 11122 11123 // Walk all the users of the constant with which we're multiplying. 11124 for (SDNode *Use : ConstNode->uses()) { 11125 11126 if (Use == MulNode) // This use is the one we're on right now. Skip it. 11127 continue; 11128 11129 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 11130 SDNode *OtherOp; 11131 SDNode *MulVar = AddNode.getOperand(0).getNode(); 11132 11133 // OtherOp is what we're multiplying against the constant. 11134 if (Use->getOperand(0) == ConstNode) 11135 OtherOp = Use->getOperand(1).getNode(); 11136 else 11137 OtherOp = Use->getOperand(0).getNode(); 11138 11139 // Check to see if multiply is with the same operand of our "add". 11140 // 11141 // ConstNode = CONST 11142 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 11143 // ... 11144 // AddNode = (A + c1) <-- MulVar is A. 11145 // = AddNode * ConstNode <-- current visiting instruction. 11146 // 11147 // If we make this transformation, we will have a common 11148 // multiply (ConstNode * A) that we can save. 11149 if (OtherOp == MulVar) 11150 return true; 11151 11152 // Now check to see if a future expansion will give us a common 11153 // multiply. 11154 // 11155 // ConstNode = CONST 11156 // AddNode = (A + c1) 11157 // ... = AddNode * ConstNode <-- current visiting instruction. 11158 // ... 11159 // OtherOp = (A + c2) 11160 // Use = OtherOp * ConstNode <-- visiting Use. 11161 // 11162 // If we make this transformation, we will have a common 11163 // multiply (CONST * A) after we also do the same transformation 11164 // to the "t2" instruction. 11165 if (OtherOp->getOpcode() == ISD::ADD && 11166 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 11167 OtherOp->getOperand(0).getNode() == MulVar) 11168 return true; 11169 } 11170 } 11171 11172 // Didn't find a case where this would be profitable. 11173 return false; 11174 } 11175 11176 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG, 11177 SDLoc SL, 11178 ArrayRef<MemOpLink> Stores, 11179 SmallVectorImpl<SDValue> &Chains, 11180 EVT Ty) const { 11181 SmallVector<SDValue, 8> BuildVector; 11182 11183 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) { 11184 StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode); 11185 Chains.push_back(St->getChain()); 11186 BuildVector.push_back(St->getValue()); 11187 } 11188 11189 return DAG.getBuildVector(Ty, SL, BuildVector); 11190 } 11191 11192 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 11193 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 11194 unsigned NumStores, bool IsConstantSrc, bool UseVector) { 11195 // Make sure we have something to merge. 11196 if (NumStores < 2) 11197 return false; 11198 11199 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11200 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11201 unsigned LatestNodeUsed = 0; 11202 11203 for (unsigned i=0; i < NumStores; ++i) { 11204 // Find a chain for the new wide-store operand. Notice that some 11205 // of the store nodes that we found may not be selected for inclusion 11206 // in the wide store. The chain we use needs to be the chain of the 11207 // latest store node which is *used* and replaced by the wide store. 11208 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11209 LatestNodeUsed = i; 11210 } 11211 11212 SmallVector<SDValue, 8> Chains; 11213 11214 // The latest Node in the DAG. 11215 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11216 SDLoc DL(StoreNodes[0].MemNode); 11217 11218 SDValue StoredVal; 11219 if (UseVector) { 11220 bool IsVec = MemVT.isVector(); 11221 unsigned Elts = NumStores; 11222 if (IsVec) { 11223 // When merging vector stores, get the total number of elements. 11224 Elts *= MemVT.getVectorNumElements(); 11225 } 11226 // Get the type for the merged vector store. 11227 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11228 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 11229 11230 if (IsConstantSrc) { 11231 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty); 11232 } else { 11233 SmallVector<SDValue, 8> Ops; 11234 for (unsigned i = 0; i < NumStores; ++i) { 11235 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11236 SDValue Val = St->getValue(); 11237 // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type. 11238 if (Val.getValueType() != MemVT) 11239 return false; 11240 Ops.push_back(Val); 11241 Chains.push_back(St->getChain()); 11242 } 11243 11244 // Build the extracted vector elements back into a vector. 11245 StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, 11246 DL, Ty, Ops); } 11247 } else { 11248 // We should always use a vector store when merging extracted vector 11249 // elements, so this path implies a store of constants. 11250 assert(IsConstantSrc && "Merged vector elements should use vector store"); 11251 11252 unsigned SizeInBits = NumStores * ElementSizeBytes * 8; 11253 APInt StoreInt(SizeInBits, 0); 11254 11255 // Construct a single integer constant which is made of the smaller 11256 // constant inputs. 11257 bool IsLE = DAG.getDataLayout().isLittleEndian(); 11258 for (unsigned i = 0; i < NumStores; ++i) { 11259 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 11260 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 11261 Chains.push_back(St->getChain()); 11262 11263 SDValue Val = St->getValue(); 11264 StoreInt <<= ElementSizeBytes * 8; 11265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 11266 StoreInt |= C->getAPIntValue().zext(SizeInBits); 11267 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 11268 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits); 11269 } else { 11270 llvm_unreachable("Invalid constant element type"); 11271 } 11272 } 11273 11274 // Create the new Load and Store operations. 11275 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 11276 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 11277 } 11278 11279 assert(!Chains.empty()); 11280 11281 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 11282 SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal, 11283 FirstInChain->getBasePtr(), 11284 FirstInChain->getPointerInfo(), 11285 false, false, 11286 FirstInChain->getAlignment()); 11287 11288 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11289 : DAG.getSubtarget().useAA(); 11290 if (UseAA) { 11291 // Replace all merged stores with the new store. 11292 for (unsigned i = 0; i < NumStores; ++i) 11293 CombineTo(StoreNodes[i].MemNode, NewStore); 11294 } else { 11295 // Replace the last store with the new store. 11296 CombineTo(LatestOp, NewStore); 11297 // Erase all other stores. 11298 for (unsigned i = 0; i < NumStores; ++i) { 11299 if (StoreNodes[i].MemNode == LatestOp) 11300 continue; 11301 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11302 // ReplaceAllUsesWith will replace all uses that existed when it was 11303 // called, but graph optimizations may cause new ones to appear. For 11304 // example, the case in pr14333 looks like 11305 // 11306 // St's chain -> St -> another store -> X 11307 // 11308 // And the only difference from St to the other store is the chain. 11309 // When we change it's chain to be St's chain they become identical, 11310 // get CSEed and the net result is that X is now a use of St. 11311 // Since we know that St is redundant, just iterate. 11312 while (!St->use_empty()) 11313 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 11314 deleteAndRecombine(St); 11315 } 11316 } 11317 11318 return true; 11319 } 11320 11321 void DAGCombiner::getStoreMergeAndAliasCandidates( 11322 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes, 11323 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) { 11324 // This holds the base pointer, index, and the offset in bytes from the base 11325 // pointer. 11326 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 11327 11328 // We must have a base and an offset. 11329 if (!BasePtr.Base.getNode()) 11330 return; 11331 11332 // Do not handle stores to undef base pointers. 11333 if (BasePtr.Base.isUndef()) 11334 return; 11335 11336 // Walk up the chain and look for nodes with offsets from the same 11337 // base pointer. Stop when reaching an instruction with a different kind 11338 // or instruction which has a different base pointer. 11339 EVT MemVT = St->getMemoryVT(); 11340 unsigned Seq = 0; 11341 StoreSDNode *Index = St; 11342 11343 11344 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11345 : DAG.getSubtarget().useAA(); 11346 11347 if (UseAA) { 11348 // Look at other users of the same chain. Stores on the same chain do not 11349 // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized 11350 // to be on the same chain, so don't bother looking at adjacent chains. 11351 11352 SDValue Chain = St->getChain(); 11353 for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) { 11354 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 11355 if (I.getOperandNo() != 0) 11356 continue; 11357 11358 if (OtherST->isVolatile() || OtherST->isIndexed()) 11359 continue; 11360 11361 if (OtherST->getMemoryVT() != MemVT) 11362 continue; 11363 11364 BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr(), DAG); 11365 11366 if (Ptr.equalBaseIndex(BasePtr)) 11367 StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++)); 11368 } 11369 } 11370 11371 return; 11372 } 11373 11374 while (Index) { 11375 // If the chain has more than one use, then we can't reorder the mem ops. 11376 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 11377 break; 11378 11379 // Find the base pointer and offset for this memory node. 11380 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 11381 11382 // Check that the base pointer is the same as the original one. 11383 if (!Ptr.equalBaseIndex(BasePtr)) 11384 break; 11385 11386 // The memory operands must not be volatile. 11387 if (Index->isVolatile() || Index->isIndexed()) 11388 break; 11389 11390 // No truncation. 11391 if (Index->isTruncatingStore()) 11392 break; 11393 11394 // The stored memory type must be the same. 11395 if (Index->getMemoryVT() != MemVT) 11396 break; 11397 11398 // We do not allow under-aligned stores in order to prevent 11399 // overriding stores. NOTE: this is a bad hack. Alignment SHOULD 11400 // be irrelevant here; what MATTERS is that we not move memory 11401 // operations that potentially overlap past each-other. 11402 if (Index->getAlignment() < MemVT.getStoreSize()) 11403 break; 11404 11405 // We found a potential memory operand to merge. 11406 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 11407 11408 // Find the next memory operand in the chain. If the next operand in the 11409 // chain is a store then move up and continue the scan with the next 11410 // memory operand. If the next operand is a load save it and use alias 11411 // information to check if it interferes with anything. 11412 SDNode *NextInChain = Index->getChain().getNode(); 11413 while (1) { 11414 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 11415 // We found a store node. Use it for the next iteration. 11416 Index = STn; 11417 break; 11418 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 11419 if (Ldn->isVolatile()) { 11420 Index = nullptr; 11421 break; 11422 } 11423 11424 // Save the load node for later. Continue the scan. 11425 AliasLoadNodes.push_back(Ldn); 11426 NextInChain = Ldn->getChain().getNode(); 11427 continue; 11428 } else { 11429 Index = nullptr; 11430 break; 11431 } 11432 } 11433 } 11434 } 11435 11436 // We need to check that merging these stores does not cause a loop 11437 // in the DAG. Any store candidate may depend on another candidate 11438 // indirectly through its operand (we already consider dependencies 11439 // through the chain). Check in parallel by searching up from 11440 // non-chain operands of candidates. 11441 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 11442 SmallVectorImpl<MemOpLink> &StoreNodes) { 11443 SmallPtrSet<const SDNode *, 16> Visited; 11444 SmallVector<const SDNode *, 8> Worklist; 11445 // search ops of store candidates 11446 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11447 SDNode *n = StoreNodes[i].MemNode; 11448 // Potential loops may happen only through non-chain operands 11449 for (unsigned j = 1; j < n->getNumOperands(); ++j) 11450 Worklist.push_back(n->getOperand(j).getNode()); 11451 } 11452 // search through DAG. We can stop early if we find a storenode 11453 for (unsigned i = 0; i < StoreNodes.size(); ++i) { 11454 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist)) 11455 return false; 11456 } 11457 return true; 11458 } 11459 11460 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 11461 if (OptLevel == CodeGenOpt::None) 11462 return false; 11463 11464 EVT MemVT = St->getMemoryVT(); 11465 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 11466 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 11467 Attribute::NoImplicitFloat); 11468 11469 // This function cannot currently deal with non-byte-sized memory sizes. 11470 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 11471 return false; 11472 11473 if (!MemVT.isSimple()) 11474 return false; 11475 11476 // Perform an early exit check. Do not bother looking at stored values that 11477 // are not constants, loads, or extracted vector elements. 11478 SDValue StoredVal = St->getValue(); 11479 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 11480 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 11481 isa<ConstantFPSDNode>(StoredVal); 11482 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 11483 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 11484 11485 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 11486 return false; 11487 11488 // Don't merge vectors into wider vectors if the source data comes from loads. 11489 // TODO: This restriction can be lifted by using logic similar to the 11490 // ExtractVecSrc case. 11491 if (MemVT.isVector() && IsLoadSrc) 11492 return false; 11493 11494 // Only look at ends of store sequences. 11495 SDValue Chain = SDValue(St, 0); 11496 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 11497 return false; 11498 11499 // Save the LoadSDNodes that we find in the chain. 11500 // We need to make sure that these nodes do not interfere with 11501 // any of the store nodes. 11502 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 11503 11504 // Save the StoreSDNodes that we find in the chain. 11505 SmallVector<MemOpLink, 8> StoreNodes; 11506 11507 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes); 11508 11509 // Check if there is anything to merge. 11510 if (StoreNodes.size() < 2) 11511 return false; 11512 11513 // only do dep endence check in AA case 11514 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11515 : DAG.getSubtarget().useAA(); 11516 if (UseAA && !checkMergeStoreCandidatesForDependencies(StoreNodes)) 11517 return false; 11518 11519 // Sort the memory operands according to their distance from the 11520 // base pointer. As a secondary criteria: make sure stores coming 11521 // later in the code come first in the list. This is important for 11522 // the non-UseAA case, because we're merging stores into the FINAL 11523 // store along a chain which potentially contains aliasing stores. 11524 // Thus, if there are multiple stores to the same address, the last 11525 // one can be considered for merging but not the others. 11526 std::sort(StoreNodes.begin(), StoreNodes.end(), 11527 [](MemOpLink LHS, MemOpLink RHS) { 11528 return LHS.OffsetFromBase < RHS.OffsetFromBase || 11529 (LHS.OffsetFromBase == RHS.OffsetFromBase && 11530 LHS.SequenceNum < RHS.SequenceNum); 11531 }); 11532 11533 // Scan the memory operations on the chain and find the first non-consecutive 11534 // store memory address. 11535 unsigned LastConsecutiveStore = 0; 11536 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 11537 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 11538 11539 // Check that the addresses are consecutive starting from the second 11540 // element in the list of stores. 11541 if (i > 0) { 11542 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 11543 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11544 break; 11545 } 11546 11547 // Check if this store interferes with any of the loads that we found. 11548 // If we find a load that alias with this store. Stop the sequence. 11549 if (std::any_of(AliasLoadNodes.begin(), AliasLoadNodes.end(), 11550 [&](LSBaseSDNode* Ldn) { 11551 return isAlias(Ldn, StoreNodes[i].MemNode); 11552 })) 11553 break; 11554 11555 // Mark this node as useful. 11556 LastConsecutiveStore = i; 11557 } 11558 11559 // The node with the lowest store address. 11560 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 11561 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 11562 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 11563 LLVMContext &Context = *DAG.getContext(); 11564 const DataLayout &DL = DAG.getDataLayout(); 11565 11566 // Store the constants into memory as one consecutive store. 11567 if (IsConstantSrc) { 11568 unsigned LastLegalType = 0; 11569 unsigned LastLegalVectorType = 0; 11570 bool NonZero = false; 11571 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11572 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11573 SDValue StoredVal = St->getValue(); 11574 11575 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 11576 NonZero |= !C->isNullValue(); 11577 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 11578 NonZero |= !C->getConstantFPValue()->isNullValue(); 11579 } else { 11580 // Non-constant. 11581 break; 11582 } 11583 11584 // Find a legal type for the constant store. 11585 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11586 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11587 bool IsFast; 11588 if (TLI.isTypeLegal(StoreTy) && 11589 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11590 FirstStoreAlign, &IsFast) && IsFast) { 11591 LastLegalType = i+1; 11592 // Or check whether a truncstore is legal. 11593 } else if (TLI.getTypeAction(Context, StoreTy) == 11594 TargetLowering::TypePromoteInteger) { 11595 EVT LegalizedStoredValueTy = 11596 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 11597 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11598 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11599 FirstStoreAS, FirstStoreAlign, &IsFast) && 11600 IsFast) { 11601 LastLegalType = i + 1; 11602 } 11603 } 11604 11605 // We only use vectors if the constant is known to be zero or the target 11606 // allows it and the function is not marked with the noimplicitfloat 11607 // attribute. 11608 if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1, 11609 FirstStoreAS)) && 11610 !NoVectors) { 11611 // Find a legal type for the vector store. 11612 EVT Ty = EVT::getVectorVT(Context, MemVT, i+1); 11613 if (TLI.isTypeLegal(Ty) && 11614 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11615 FirstStoreAlign, &IsFast) && IsFast) 11616 LastLegalVectorType = i + 1; 11617 } 11618 } 11619 11620 // Check if we found a legal integer type to store. 11621 if (LastLegalType == 0 && LastLegalVectorType == 0) 11622 return false; 11623 11624 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 11625 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 11626 11627 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 11628 true, UseVector); 11629 } 11630 11631 // When extracting multiple vector elements, try to store them 11632 // in one vector store rather than a sequence of scalar stores. 11633 if (IsExtractVecSrc) { 11634 unsigned NumStoresToMerge = 0; 11635 bool IsVec = MemVT.isVector(); 11636 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 11637 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11638 unsigned StoreValOpcode = St->getValue().getOpcode(); 11639 // This restriction could be loosened. 11640 // Bail out if any stored values are not elements extracted from a vector. 11641 // It should be possible to handle mixed sources, but load sources need 11642 // more careful handling (see the block of code below that handles 11643 // consecutive loads). 11644 if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT && 11645 StoreValOpcode != ISD::EXTRACT_SUBVECTOR) 11646 return false; 11647 11648 // Find a legal type for the vector store. 11649 unsigned Elts = i + 1; 11650 if (IsVec) { 11651 // When merging vector stores, get the total number of elements. 11652 Elts *= MemVT.getVectorNumElements(); 11653 } 11654 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 11655 bool IsFast; 11656 if (TLI.isTypeLegal(Ty) && 11657 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 11658 FirstStoreAlign, &IsFast) && IsFast) 11659 NumStoresToMerge = i + 1; 11660 } 11661 11662 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge, 11663 false, true); 11664 } 11665 11666 // Below we handle the case of multiple consecutive stores that 11667 // come from multiple consecutive loads. We merge them into a single 11668 // wide load and a single wide store. 11669 11670 // Look for load nodes which are used by the stored values. 11671 SmallVector<MemOpLink, 8> LoadNodes; 11672 11673 // Find acceptable loads. Loads need to have the same chain (token factor), 11674 // must not be zext, volatile, indexed, and they must be consecutive. 11675 BaseIndexOffset LdBasePtr; 11676 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 11677 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11678 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 11679 if (!Ld) break; 11680 11681 // Loads must only have one use. 11682 if (!Ld->hasNUsesOfValue(1, 0)) 11683 break; 11684 11685 // The memory operands must not be volatile. 11686 if (Ld->isVolatile() || Ld->isIndexed()) 11687 break; 11688 11689 // We do not accept ext loads. 11690 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 11691 break; 11692 11693 // The stored memory type must be the same. 11694 if (Ld->getMemoryVT() != MemVT) 11695 break; 11696 11697 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG); 11698 // If this is not the first ptr that we check. 11699 if (LdBasePtr.Base.getNode()) { 11700 // The base ptr must be the same. 11701 if (!LdPtr.equalBaseIndex(LdBasePtr)) 11702 break; 11703 } else { 11704 // Check that all other base pointers are the same as this one. 11705 LdBasePtr = LdPtr; 11706 } 11707 11708 // We found a potential memory operand to merge. 11709 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 11710 } 11711 11712 if (LoadNodes.size() < 2) 11713 return false; 11714 11715 // If we have load/store pair instructions and we only have two values, 11716 // don't bother. 11717 unsigned RequiredAlignment; 11718 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 11719 St->getAlignment() >= RequiredAlignment) 11720 return false; 11721 11722 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 11723 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 11724 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 11725 11726 // Scan the memory operations on the chain and find the first non-consecutive 11727 // load memory address. These variables hold the index in the store node 11728 // array. 11729 unsigned LastConsecutiveLoad = 0; 11730 // This variable refers to the size and not index in the array. 11731 unsigned LastLegalVectorType = 0; 11732 unsigned LastLegalIntegerType = 0; 11733 StartAddress = LoadNodes[0].OffsetFromBase; 11734 SDValue FirstChain = FirstLoad->getChain(); 11735 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 11736 // All loads must share the same chain. 11737 if (LoadNodes[i].MemNode->getChain() != FirstChain) 11738 break; 11739 11740 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 11741 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 11742 break; 11743 LastConsecutiveLoad = i; 11744 // Find a legal type for the vector store. 11745 EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1); 11746 bool IsFastSt, IsFastLd; 11747 if (TLI.isTypeLegal(StoreTy) && 11748 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11749 FirstStoreAlign, &IsFastSt) && IsFastSt && 11750 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11751 FirstLoadAlign, &IsFastLd) && IsFastLd) { 11752 LastLegalVectorType = i + 1; 11753 } 11754 11755 // Find a legal type for the integer store. 11756 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8; 11757 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 11758 if (TLI.isTypeLegal(StoreTy) && 11759 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 11760 FirstStoreAlign, &IsFastSt) && IsFastSt && 11761 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 11762 FirstLoadAlign, &IsFastLd) && IsFastLd) 11763 LastLegalIntegerType = i + 1; 11764 // Or check whether a truncstore and extload is legal. 11765 else if (TLI.getTypeAction(Context, StoreTy) == 11766 TargetLowering::TypePromoteInteger) { 11767 EVT LegalizedStoredValueTy = 11768 TLI.getTypeToTransformTo(Context, StoreTy); 11769 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 11770 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11771 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11772 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11773 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11774 FirstStoreAS, FirstStoreAlign, &IsFastSt) && 11775 IsFastSt && 11776 TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy, 11777 FirstLoadAS, FirstLoadAlign, &IsFastLd) && 11778 IsFastLd) 11779 LastLegalIntegerType = i+1; 11780 } 11781 } 11782 11783 // Only use vector types if the vector type is larger than the integer type. 11784 // If they are the same, use integers. 11785 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11786 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11787 11788 // We add +1 here because the LastXXX variables refer to location while 11789 // the NumElem refers to array/index size. 11790 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11791 NumElem = std::min(LastLegalType, NumElem); 11792 11793 if (NumElem < 2) 11794 return false; 11795 11796 // Collect the chains from all merged stores. 11797 SmallVector<SDValue, 8> MergeStoreChains; 11798 MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain()); 11799 11800 // The latest Node in the DAG. 11801 unsigned LatestNodeUsed = 0; 11802 for (unsigned i=1; i<NumElem; ++i) { 11803 // Find a chain for the new wide-store operand. Notice that some 11804 // of the store nodes that we found may not be selected for inclusion 11805 // in the wide store. The chain we use needs to be the chain of the 11806 // latest store node which is *used* and replaced by the wide store. 11807 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11808 LatestNodeUsed = i; 11809 11810 MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain()); 11811 } 11812 11813 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11814 11815 // Find if it is better to use vectors or integers to load and store 11816 // to memory. 11817 EVT JointMemOpVT; 11818 if (UseVectorTy) { 11819 JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem); 11820 } else { 11821 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 11822 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 11823 } 11824 11825 SDLoc LoadDL(LoadNodes[0].MemNode); 11826 SDLoc StoreDL(StoreNodes[0].MemNode); 11827 11828 // The merged loads are required to have the same incoming chain, so 11829 // using the first's chain is acceptable. 11830 SDValue NewLoad = DAG.getLoad( 11831 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11832 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11833 11834 SDValue NewStoreChain = 11835 DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains); 11836 11837 SDValue NewStore = DAG.getStore( 11838 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 11839 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11840 11841 // Transfer chain users from old loads to the new load. 11842 for (unsigned i = 0; i < NumElem; ++i) { 11843 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11844 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11845 SDValue(NewLoad.getNode(), 1)); 11846 } 11847 11848 if (UseAA) { 11849 // Replace the all stores with the new store. 11850 for (unsigned i = 0; i < NumElem; ++i) 11851 CombineTo(StoreNodes[i].MemNode, NewStore); 11852 } else { 11853 // Replace the last store with the new store. 11854 CombineTo(LatestOp, NewStore); 11855 // Erase all other stores. 11856 for (unsigned i = 0; i < NumElem; ++i) { 11857 // Remove all Store nodes. 11858 if (StoreNodes[i].MemNode == LatestOp) 11859 continue; 11860 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11861 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11862 deleteAndRecombine(St); 11863 } 11864 } 11865 11866 return true; 11867 } 11868 11869 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 11870 SDLoc SL(ST); 11871 SDValue ReplStore; 11872 11873 // Replace the chain to avoid dependency. 11874 if (ST->isTruncatingStore()) { 11875 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 11876 ST->getBasePtr(), ST->getMemoryVT(), 11877 ST->getMemOperand()); 11878 } else { 11879 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 11880 ST->getMemOperand()); 11881 } 11882 11883 // Create token to keep both nodes around. 11884 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 11885 MVT::Other, ST->getChain(), ReplStore); 11886 11887 // Make sure the new and old chains are cleaned up. 11888 AddToWorklist(Token.getNode()); 11889 11890 // Don't add users to work list. 11891 return CombineTo(ST, Token, false); 11892 } 11893 11894 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 11895 SDValue Value = ST->getValue(); 11896 if (Value.getOpcode() == ISD::TargetConstantFP) 11897 return SDValue(); 11898 11899 SDLoc DL(ST); 11900 11901 SDValue Chain = ST->getChain(); 11902 SDValue Ptr = ST->getBasePtr(); 11903 11904 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 11905 11906 // NOTE: If the original store is volatile, this transform must not increase 11907 // the number of stores. For example, on x86-32 an f64 can be stored in one 11908 // processor operation but an i64 (which is not legal) requires two. So the 11909 // transform should not be done in this case. 11910 11911 SDValue Tmp; 11912 switch (CFP->getSimpleValueType(0).SimpleTy) { 11913 default: 11914 llvm_unreachable("Unknown FP type"); 11915 case MVT::f16: // We don't do this for these yet. 11916 case MVT::f80: 11917 case MVT::f128: 11918 case MVT::ppcf128: 11919 return SDValue(); 11920 case MVT::f32: 11921 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11922 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11923 ; 11924 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11925 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11926 MVT::i32); 11927 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 11928 } 11929 11930 return SDValue(); 11931 case MVT::f64: 11932 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11933 !ST->isVolatile()) || 11934 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11935 ; 11936 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11937 getZExtValue(), SDLoc(CFP), MVT::i64); 11938 return DAG.getStore(Chain, DL, Tmp, 11939 Ptr, ST->getMemOperand()); 11940 } 11941 11942 if (!ST->isVolatile() && 11943 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11944 // Many FP stores are not made apparent until after legalize, e.g. for 11945 // argument passing. Since this is so common, custom legalize the 11946 // 64-bit integer store into two 32-bit stores. 11947 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11948 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11949 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11950 if (DAG.getDataLayout().isBigEndian()) 11951 std::swap(Lo, Hi); 11952 11953 unsigned Alignment = ST->getAlignment(); 11954 bool isVolatile = ST->isVolatile(); 11955 bool isNonTemporal = ST->isNonTemporal(); 11956 AAMDNodes AAInfo = ST->getAAInfo(); 11957 11958 SDValue St0 = DAG.getStore(Chain, DL, Lo, 11959 Ptr, ST->getPointerInfo(), 11960 isVolatile, isNonTemporal, 11961 ST->getAlignment(), AAInfo); 11962 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11963 DAG.getConstant(4, DL, Ptr.getValueType())); 11964 Alignment = MinAlign(Alignment, 4U); 11965 SDValue St1 = DAG.getStore(Chain, DL, Hi, 11966 Ptr, ST->getPointerInfo().getWithOffset(4), 11967 isVolatile, isNonTemporal, 11968 Alignment, AAInfo); 11969 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11970 St0, St1); 11971 } 11972 11973 return SDValue(); 11974 } 11975 } 11976 11977 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11978 StoreSDNode *ST = cast<StoreSDNode>(N); 11979 SDValue Chain = ST->getChain(); 11980 SDValue Value = ST->getValue(); 11981 SDValue Ptr = ST->getBasePtr(); 11982 11983 // If this is a store of a bit convert, store the input value if the 11984 // resultant store does not need a higher alignment than the original. 11985 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11986 ST->isUnindexed()) { 11987 EVT SVT = Value.getOperand(0).getValueType(); 11988 if (((!LegalOperations && !ST->isVolatile()) || 11989 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) && 11990 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 11991 unsigned OrigAlign = ST->getAlignment(); 11992 bool Fast = false; 11993 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 11994 ST->getAddressSpace(), OrigAlign, &Fast) && 11995 Fast) { 11996 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11997 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11998 ST->isNonTemporal(), OrigAlign, 11999 ST->getAAInfo()); 12000 } 12001 } 12002 } 12003 12004 // Turn 'store undef, Ptr' -> nothing. 12005 if (Value.isUndef() && ST->isUnindexed()) 12006 return Chain; 12007 12008 // Try to infer better alignment information than the store already has. 12009 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 12010 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 12011 if (Align > ST->getAlignment()) { 12012 SDValue NewStore = 12013 DAG.getTruncStore(Chain, SDLoc(N), Value, 12014 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 12015 ST->isVolatile(), ST->isNonTemporal(), Align, 12016 ST->getAAInfo()); 12017 if (NewStore.getNode() != N) 12018 return CombineTo(ST, NewStore, true); 12019 } 12020 } 12021 } 12022 12023 // Try transforming a pair floating point load / store ops to integer 12024 // load / store ops. 12025 if (SDValue NewST = TransformFPLoadStorePair(N)) 12026 return NewST; 12027 12028 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 12029 : DAG.getSubtarget().useAA(); 12030 #ifndef NDEBUG 12031 if (CombinerAAOnlyFunc.getNumOccurrences() && 12032 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12033 UseAA = false; 12034 #endif 12035 if (UseAA && ST->isUnindexed()) { 12036 // FIXME: We should do this even without AA enabled. AA will just allow 12037 // FindBetterChain to work in more situations. The problem with this is that 12038 // any combine that expects memory operations to be on consecutive chains 12039 // first needs to be updated to look for users of the same chain. 12040 12041 // Walk up chain skipping non-aliasing memory nodes, on this store and any 12042 // adjacent stores. 12043 if (findBetterNeighborChains(ST)) { 12044 // replaceStoreChain uses CombineTo, which handled all of the worklist 12045 // manipulation. Return the original node to not do anything else. 12046 return SDValue(ST, 0); 12047 } 12048 } 12049 12050 // Try transforming N to an indexed store. 12051 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 12052 return SDValue(N, 0); 12053 12054 // FIXME: is there such a thing as a truncating indexed store? 12055 if (ST->isTruncatingStore() && ST->isUnindexed() && 12056 Value.getValueType().isInteger()) { 12057 // See if we can simplify the input to this truncstore with knowledge that 12058 // only the low bits are being used. For example: 12059 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 12060 SDValue Shorter = 12061 GetDemandedBits(Value, 12062 APInt::getLowBitsSet( 12063 Value.getValueType().getScalarType().getSizeInBits(), 12064 ST->getMemoryVT().getScalarType().getSizeInBits())); 12065 AddToWorklist(Value.getNode()); 12066 if (Shorter.getNode()) 12067 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 12068 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12069 12070 // Otherwise, see if we can simplify the operation with 12071 // SimplifyDemandedBits, which only works if the value has a single use. 12072 if (SimplifyDemandedBits(Value, 12073 APInt::getLowBitsSet( 12074 Value.getValueType().getScalarType().getSizeInBits(), 12075 ST->getMemoryVT().getScalarType().getSizeInBits()))) 12076 return SDValue(N, 0); 12077 } 12078 12079 // If this is a load followed by a store to the same location, then the store 12080 // is dead/noop. 12081 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 12082 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 12083 ST->isUnindexed() && !ST->isVolatile() && 12084 // There can't be any side effects between the load and store, such as 12085 // a call or store. 12086 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 12087 // The store is dead, remove it. 12088 return Chain; 12089 } 12090 } 12091 12092 // If this is a store followed by a store with the same value to the same 12093 // location, then the store is dead/noop. 12094 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 12095 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 12096 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 12097 ST1->isUnindexed() && !ST1->isVolatile()) { 12098 // The store is dead, remove it. 12099 return Chain; 12100 } 12101 } 12102 12103 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 12104 // truncating store. We can do this even if this is already a truncstore. 12105 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 12106 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 12107 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 12108 ST->getMemoryVT())) { 12109 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 12110 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 12111 } 12112 12113 // Only perform this optimization before the types are legal, because we 12114 // don't want to perform this optimization on every DAGCombine invocation. 12115 if (!LegalTypes) { 12116 bool EverChanged = false; 12117 12118 do { 12119 // There can be multiple store sequences on the same chain. 12120 // Keep trying to merge store sequences until we are unable to do so 12121 // or until we merge the last store on the chain. 12122 bool Changed = MergeConsecutiveStores(ST); 12123 EverChanged |= Changed; 12124 if (!Changed) break; 12125 } while (ST->getOpcode() != ISD::DELETED_NODE); 12126 12127 if (EverChanged) 12128 return SDValue(N, 0); 12129 } 12130 12131 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 12132 // 12133 // Make sure to do this only after attempting to merge stores in order to 12134 // avoid changing the types of some subset of stores due to visit order, 12135 // preventing their merging. 12136 if (isa<ConstantFPSDNode>(Value)) { 12137 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 12138 return NewSt; 12139 } 12140 12141 return ReduceLoadOpStoreWidth(N); 12142 } 12143 12144 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 12145 SDValue InVec = N->getOperand(0); 12146 SDValue InVal = N->getOperand(1); 12147 SDValue EltNo = N->getOperand(2); 12148 SDLoc dl(N); 12149 12150 // If the inserted element is an UNDEF, just use the input vector. 12151 if (InVal.isUndef()) 12152 return InVec; 12153 12154 EVT VT = InVec.getValueType(); 12155 12156 // If we can't generate a legal BUILD_VECTOR, exit 12157 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 12158 return SDValue(); 12159 12160 // Check that we know which element is being inserted 12161 if (!isa<ConstantSDNode>(EltNo)) 12162 return SDValue(); 12163 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12164 12165 // Canonicalize insert_vector_elt dag nodes. 12166 // Example: 12167 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 12168 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 12169 // 12170 // Do this only if the child insert_vector node has one use; also 12171 // do this only if indices are both constants and Idx1 < Idx0. 12172 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 12173 && isa<ConstantSDNode>(InVec.getOperand(2))) { 12174 unsigned OtherElt = 12175 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 12176 if (Elt < OtherElt) { 12177 // Swap nodes. 12178 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 12179 InVec.getOperand(0), InVal, EltNo); 12180 AddToWorklist(NewOp.getNode()); 12181 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 12182 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 12183 } 12184 } 12185 12186 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 12187 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 12188 // vector elements. 12189 SmallVector<SDValue, 8> Ops; 12190 // Do not combine these two vectors if the output vector will not replace 12191 // the input vector. 12192 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 12193 Ops.append(InVec.getNode()->op_begin(), 12194 InVec.getNode()->op_end()); 12195 } else if (InVec.isUndef()) { 12196 unsigned NElts = VT.getVectorNumElements(); 12197 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 12198 } else { 12199 return SDValue(); 12200 } 12201 12202 // Insert the element 12203 if (Elt < Ops.size()) { 12204 // All the operands of BUILD_VECTOR must have the same type; 12205 // we enforce that here. 12206 EVT OpVT = Ops[0].getValueType(); 12207 if (InVal.getValueType() != OpVT) 12208 InVal = OpVT.bitsGT(InVal.getValueType()) ? 12209 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 12210 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 12211 Ops[Elt] = InVal; 12212 } 12213 12214 // Return the new vector 12215 return DAG.getBuildVector(VT, dl, Ops); 12216 } 12217 12218 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 12219 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 12220 EVT ResultVT = EVE->getValueType(0); 12221 EVT VecEltVT = InVecVT.getVectorElementType(); 12222 unsigned Align = OriginalLoad->getAlignment(); 12223 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 12224 VecEltVT.getTypeForEVT(*DAG.getContext())); 12225 12226 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 12227 return SDValue(); 12228 12229 Align = NewAlign; 12230 12231 SDValue NewPtr = OriginalLoad->getBasePtr(); 12232 SDValue Offset; 12233 EVT PtrType = NewPtr.getValueType(); 12234 MachinePointerInfo MPI; 12235 SDLoc DL(EVE); 12236 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 12237 int Elt = ConstEltNo->getZExtValue(); 12238 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 12239 Offset = DAG.getConstant(PtrOff, DL, PtrType); 12240 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 12241 } else { 12242 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 12243 Offset = DAG.getNode( 12244 ISD::MUL, DL, PtrType, Offset, 12245 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 12246 MPI = OriginalLoad->getPointerInfo(); 12247 } 12248 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 12249 12250 // The replacement we need to do here is a little tricky: we need to 12251 // replace an extractelement of a load with a load. 12252 // Use ReplaceAllUsesOfValuesWith to do the replacement. 12253 // Note that this replacement assumes that the extractvalue is the only 12254 // use of the load; that's okay because we don't want to perform this 12255 // transformation in other cases anyway. 12256 SDValue Load; 12257 SDValue Chain; 12258 if (ResultVT.bitsGT(VecEltVT)) { 12259 // If the result type of vextract is wider than the load, then issue an 12260 // extending load instead. 12261 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 12262 VecEltVT) 12263 ? ISD::ZEXTLOAD 12264 : ISD::EXTLOAD; 12265 Load = DAG.getExtLoad( 12266 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 12267 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12268 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12269 Chain = Load.getValue(1); 12270 } else { 12271 Load = DAG.getLoad( 12272 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 12273 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 12274 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 12275 Chain = Load.getValue(1); 12276 if (ResultVT.bitsLT(VecEltVT)) 12277 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 12278 else 12279 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 12280 } 12281 WorklistRemover DeadNodes(*this); 12282 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 12283 SDValue To[] = { Load, Chain }; 12284 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 12285 // Since we're explicitly calling ReplaceAllUses, add the new node to the 12286 // worklist explicitly as well. 12287 AddToWorklist(Load.getNode()); 12288 AddUsersToWorklist(Load.getNode()); // Add users too 12289 // Make sure to revisit this node to clean it up; it will usually be dead. 12290 AddToWorklist(EVE); 12291 ++OpsNarrowed; 12292 return SDValue(EVE, 0); 12293 } 12294 12295 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 12296 // (vextract (scalar_to_vector val, 0) -> val 12297 SDValue InVec = N->getOperand(0); 12298 EVT VT = InVec.getValueType(); 12299 EVT NVT = N->getValueType(0); 12300 12301 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 12302 // Check if the result type doesn't match the inserted element type. A 12303 // SCALAR_TO_VECTOR may truncate the inserted element and the 12304 // EXTRACT_VECTOR_ELT may widen the extracted vector. 12305 SDValue InOp = InVec.getOperand(0); 12306 if (InOp.getValueType() != NVT) { 12307 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12308 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 12309 } 12310 return InOp; 12311 } 12312 12313 SDValue EltNo = N->getOperand(1); 12314 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 12315 12316 // extract_vector_elt (build_vector x, y), 1 -> y 12317 if (ConstEltNo && 12318 InVec.getOpcode() == ISD::BUILD_VECTOR && 12319 TLI.isTypeLegal(VT) && 12320 (InVec.hasOneUse() || 12321 TLI.aggressivelyPreferBuildVectorSources(VT))) { 12322 SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue()); 12323 EVT InEltVT = Elt.getValueType(); 12324 12325 // Sometimes build_vector's scalar input types do not match result type. 12326 if (NVT == InEltVT) 12327 return Elt; 12328 12329 // TODO: It may be useful to truncate if free if the build_vector implicitly 12330 // converts. 12331 } 12332 12333 // extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x) 12334 if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() && 12335 ConstEltNo->isNullValue() && VT.isInteger()) { 12336 SDValue BCSrc = InVec.getOperand(0); 12337 if (BCSrc.getValueType().isScalarInteger()) 12338 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc); 12339 } 12340 12341 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 12342 // We only perform this optimization before the op legalization phase because 12343 // we may introduce new vector instructions which are not backed by TD 12344 // patterns. For example on AVX, extracting elements from a wide vector 12345 // without using extract_subvector. However, if we can find an underlying 12346 // scalar value, then we can always use that. 12347 if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) { 12348 int NumElem = VT.getVectorNumElements(); 12349 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 12350 // Find the new index to extract from. 12351 int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue()); 12352 12353 // Extracting an undef index is undef. 12354 if (OrigElt == -1) 12355 return DAG.getUNDEF(NVT); 12356 12357 // Select the right vector half to extract from. 12358 SDValue SVInVec; 12359 if (OrigElt < NumElem) { 12360 SVInVec = InVec->getOperand(0); 12361 } else { 12362 SVInVec = InVec->getOperand(1); 12363 OrigElt -= NumElem; 12364 } 12365 12366 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 12367 SDValue InOp = SVInVec.getOperand(OrigElt); 12368 if (InOp.getValueType() != NVT) { 12369 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 12370 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 12371 } 12372 12373 return InOp; 12374 } 12375 12376 // FIXME: We should handle recursing on other vector shuffles and 12377 // scalar_to_vector here as well. 12378 12379 if (!LegalOperations) { 12380 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 12381 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 12382 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 12383 } 12384 } 12385 12386 bool BCNumEltsChanged = false; 12387 EVT ExtVT = VT.getVectorElementType(); 12388 EVT LVT = ExtVT; 12389 12390 // If the result of load has to be truncated, then it's not necessarily 12391 // profitable. 12392 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 12393 return SDValue(); 12394 12395 if (InVec.getOpcode() == ISD::BITCAST) { 12396 // Don't duplicate a load with other uses. 12397 if (!InVec.hasOneUse()) 12398 return SDValue(); 12399 12400 EVT BCVT = InVec.getOperand(0).getValueType(); 12401 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 12402 return SDValue(); 12403 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 12404 BCNumEltsChanged = true; 12405 InVec = InVec.getOperand(0); 12406 ExtVT = BCVT.getVectorElementType(); 12407 } 12408 12409 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 12410 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 12411 ISD::isNormalLoad(InVec.getNode()) && 12412 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 12413 SDValue Index = N->getOperand(1); 12414 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 12415 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 12416 OrigLoad); 12417 } 12418 12419 // Perform only after legalization to ensure build_vector / vector_shuffle 12420 // optimizations have already been done. 12421 if (!LegalOperations) return SDValue(); 12422 12423 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 12424 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 12425 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 12426 12427 if (ConstEltNo) { 12428 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12429 12430 LoadSDNode *LN0 = nullptr; 12431 const ShuffleVectorSDNode *SVN = nullptr; 12432 if (ISD::isNormalLoad(InVec.getNode())) { 12433 LN0 = cast<LoadSDNode>(InVec); 12434 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 12435 InVec.getOperand(0).getValueType() == ExtVT && 12436 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 12437 // Don't duplicate a load with other uses. 12438 if (!InVec.hasOneUse()) 12439 return SDValue(); 12440 12441 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 12442 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 12443 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 12444 // => 12445 // (load $addr+1*size) 12446 12447 // Don't duplicate a load with other uses. 12448 if (!InVec.hasOneUse()) 12449 return SDValue(); 12450 12451 // If the bit convert changed the number of elements, it is unsafe 12452 // to examine the mask. 12453 if (BCNumEltsChanged) 12454 return SDValue(); 12455 12456 // Select the input vector, guarding against out of range extract vector. 12457 unsigned NumElems = VT.getVectorNumElements(); 12458 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 12459 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 12460 12461 if (InVec.getOpcode() == ISD::BITCAST) { 12462 // Don't duplicate a load with other uses. 12463 if (!InVec.hasOneUse()) 12464 return SDValue(); 12465 12466 InVec = InVec.getOperand(0); 12467 } 12468 if (ISD::isNormalLoad(InVec.getNode())) { 12469 LN0 = cast<LoadSDNode>(InVec); 12470 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 12471 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 12472 } 12473 } 12474 12475 // Make sure we found a non-volatile load and the extractelement is 12476 // the only use. 12477 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 12478 return SDValue(); 12479 12480 // If Idx was -1 above, Elt is going to be -1, so just return undef. 12481 if (Elt == -1) 12482 return DAG.getUNDEF(LVT); 12483 12484 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 12485 } 12486 12487 return SDValue(); 12488 } 12489 12490 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 12491 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 12492 // We perform this optimization post type-legalization because 12493 // the type-legalizer often scalarizes integer-promoted vectors. 12494 // Performing this optimization before may create bit-casts which 12495 // will be type-legalized to complex code sequences. 12496 // We perform this optimization only before the operation legalizer because we 12497 // may introduce illegal operations. 12498 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 12499 return SDValue(); 12500 12501 unsigned NumInScalars = N->getNumOperands(); 12502 SDLoc dl(N); 12503 EVT VT = N->getValueType(0); 12504 12505 // Check to see if this is a BUILD_VECTOR of a bunch of values 12506 // which come from any_extend or zero_extend nodes. If so, we can create 12507 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 12508 // optimizations. We do not handle sign-extend because we can't fill the sign 12509 // using shuffles. 12510 EVT SourceType = MVT::Other; 12511 bool AllAnyExt = true; 12512 12513 for (unsigned i = 0; i != NumInScalars; ++i) { 12514 SDValue In = N->getOperand(i); 12515 // Ignore undef inputs. 12516 if (In.isUndef()) continue; 12517 12518 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 12519 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 12520 12521 // Abort if the element is not an extension. 12522 if (!ZeroExt && !AnyExt) { 12523 SourceType = MVT::Other; 12524 break; 12525 } 12526 12527 // The input is a ZeroExt or AnyExt. Check the original type. 12528 EVT InTy = In.getOperand(0).getValueType(); 12529 12530 // Check that all of the widened source types are the same. 12531 if (SourceType == MVT::Other) 12532 // First time. 12533 SourceType = InTy; 12534 else if (InTy != SourceType) { 12535 // Multiple income types. Abort. 12536 SourceType = MVT::Other; 12537 break; 12538 } 12539 12540 // Check if all of the extends are ANY_EXTENDs. 12541 AllAnyExt &= AnyExt; 12542 } 12543 12544 // In order to have valid types, all of the inputs must be extended from the 12545 // same source type and all of the inputs must be any or zero extend. 12546 // Scalar sizes must be a power of two. 12547 EVT OutScalarTy = VT.getScalarType(); 12548 bool ValidTypes = SourceType != MVT::Other && 12549 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 12550 isPowerOf2_32(SourceType.getSizeInBits()); 12551 12552 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 12553 // turn into a single shuffle instruction. 12554 if (!ValidTypes) 12555 return SDValue(); 12556 12557 bool isLE = DAG.getDataLayout().isLittleEndian(); 12558 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 12559 assert(ElemRatio > 1 && "Invalid element size ratio"); 12560 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 12561 DAG.getConstant(0, SDLoc(N), SourceType); 12562 12563 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 12564 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 12565 12566 // Populate the new build_vector 12567 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12568 SDValue Cast = N->getOperand(i); 12569 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 12570 Cast.getOpcode() == ISD::ZERO_EXTEND || 12571 Cast.isUndef()) && "Invalid cast opcode"); 12572 SDValue In; 12573 if (Cast.isUndef()) 12574 In = DAG.getUNDEF(SourceType); 12575 else 12576 In = Cast->getOperand(0); 12577 unsigned Index = isLE ? (i * ElemRatio) : 12578 (i * ElemRatio + (ElemRatio - 1)); 12579 12580 assert(Index < Ops.size() && "Invalid index"); 12581 Ops[Index] = In; 12582 } 12583 12584 // The type of the new BUILD_VECTOR node. 12585 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 12586 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 12587 "Invalid vector size"); 12588 // Check if the new vector type is legal. 12589 if (!isTypeLegal(VecVT)) return SDValue(); 12590 12591 // Make the new BUILD_VECTOR. 12592 SDValue BV = DAG.getBuildVector(VecVT, dl, Ops); 12593 12594 // The new BUILD_VECTOR node has the potential to be further optimized. 12595 AddToWorklist(BV.getNode()); 12596 // Bitcast to the desired type. 12597 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 12598 } 12599 12600 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 12601 EVT VT = N->getValueType(0); 12602 12603 unsigned NumInScalars = N->getNumOperands(); 12604 SDLoc dl(N); 12605 12606 EVT SrcVT = MVT::Other; 12607 unsigned Opcode = ISD::DELETED_NODE; 12608 unsigned NumDefs = 0; 12609 12610 for (unsigned i = 0; i != NumInScalars; ++i) { 12611 SDValue In = N->getOperand(i); 12612 unsigned Opc = In.getOpcode(); 12613 12614 if (Opc == ISD::UNDEF) 12615 continue; 12616 12617 // If all scalar values are floats and converted from integers. 12618 if (Opcode == ISD::DELETED_NODE && 12619 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 12620 Opcode = Opc; 12621 } 12622 12623 if (Opc != Opcode) 12624 return SDValue(); 12625 12626 EVT InVT = In.getOperand(0).getValueType(); 12627 12628 // If all scalar values are typed differently, bail out. It's chosen to 12629 // simplify BUILD_VECTOR of integer types. 12630 if (SrcVT == MVT::Other) 12631 SrcVT = InVT; 12632 if (SrcVT != InVT) 12633 return SDValue(); 12634 NumDefs++; 12635 } 12636 12637 // If the vector has just one element defined, it's not worth to fold it into 12638 // a vectorized one. 12639 if (NumDefs < 2) 12640 return SDValue(); 12641 12642 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 12643 && "Should only handle conversion from integer to float."); 12644 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 12645 12646 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 12647 12648 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 12649 return SDValue(); 12650 12651 // Just because the floating-point vector type is legal does not necessarily 12652 // mean that the corresponding integer vector type is. 12653 if (!isTypeLegal(NVT)) 12654 return SDValue(); 12655 12656 SmallVector<SDValue, 8> Opnds; 12657 for (unsigned i = 0; i != NumInScalars; ++i) { 12658 SDValue In = N->getOperand(i); 12659 12660 if (In.isUndef()) 12661 Opnds.push_back(DAG.getUNDEF(SrcVT)); 12662 else 12663 Opnds.push_back(In.getOperand(0)); 12664 } 12665 SDValue BV = DAG.getBuildVector(NVT, dl, Opnds); 12666 AddToWorklist(BV.getNode()); 12667 12668 return DAG.getNode(Opcode, dl, VT, BV); 12669 } 12670 12671 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 12672 unsigned NumInScalars = N->getNumOperands(); 12673 SDLoc dl(N); 12674 EVT VT = N->getValueType(0); 12675 12676 // A vector built entirely of undefs is undef. 12677 if (ISD::allOperandsUndef(N)) 12678 return DAG.getUNDEF(VT); 12679 12680 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 12681 return V; 12682 12683 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 12684 return V; 12685 12686 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 12687 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 12688 // at most two distinct vectors, turn this into a shuffle node. 12689 12690 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 12691 if (!isTypeLegal(VT)) 12692 return SDValue(); 12693 12694 // May only combine to shuffle after legalize if shuffle is legal. 12695 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 12696 return SDValue(); 12697 12698 SDValue VecIn1, VecIn2; 12699 bool UsesZeroVector = false; 12700 for (unsigned i = 0; i != NumInScalars; ++i) { 12701 SDValue Op = N->getOperand(i); 12702 // Ignore undef inputs. 12703 if (Op.isUndef()) continue; 12704 12705 // See if we can combine this build_vector into a blend with a zero vector. 12706 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) { 12707 UsesZeroVector = true; 12708 continue; 12709 } 12710 12711 // If this input is something other than a EXTRACT_VECTOR_ELT with a 12712 // constant index, bail out. 12713 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 12714 !isa<ConstantSDNode>(Op.getOperand(1))) { 12715 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12716 break; 12717 } 12718 12719 // We allow up to two distinct input vectors. 12720 SDValue ExtractedFromVec = Op.getOperand(0); 12721 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 12722 continue; 12723 12724 if (!VecIn1.getNode()) { 12725 VecIn1 = ExtractedFromVec; 12726 } else if (!VecIn2.getNode() && !UsesZeroVector) { 12727 VecIn2 = ExtractedFromVec; 12728 } else { 12729 // Too many inputs. 12730 VecIn1 = VecIn2 = SDValue(nullptr, 0); 12731 break; 12732 } 12733 } 12734 12735 // If everything is good, we can make a shuffle operation. 12736 if (VecIn1.getNode()) { 12737 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 12738 SmallVector<int, 8> Mask; 12739 for (unsigned i = 0; i != NumInScalars; ++i) { 12740 unsigned Opcode = N->getOperand(i).getOpcode(); 12741 if (Opcode == ISD::UNDEF) { 12742 Mask.push_back(-1); 12743 continue; 12744 } 12745 12746 // Operands can also be zero. 12747 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 12748 assert(UsesZeroVector && 12749 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 12750 "Unexpected node found!"); 12751 Mask.push_back(NumInScalars+i); 12752 continue; 12753 } 12754 12755 // If extracting from the first vector, just use the index directly. 12756 SDValue Extract = N->getOperand(i); 12757 SDValue ExtVal = Extract.getOperand(1); 12758 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 12759 if (Extract.getOperand(0) == VecIn1) { 12760 Mask.push_back(ExtIndex); 12761 continue; 12762 } 12763 12764 // Otherwise, use InIdx + InputVecSize 12765 Mask.push_back(InNumElements + ExtIndex); 12766 } 12767 12768 // Avoid introducing illegal shuffles with zero. 12769 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 12770 return SDValue(); 12771 12772 // We can't generate a shuffle node with mismatched input and output types. 12773 // Attempt to transform a single input vector to the correct type. 12774 if ((VT != VecIn1.getValueType())) { 12775 // If the input vector type has a different base type to the output 12776 // vector type, bail out. 12777 EVT VTElemType = VT.getVectorElementType(); 12778 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 12779 (VecIn2.getNode() && 12780 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 12781 return SDValue(); 12782 12783 // If the input vector is too small, widen it. 12784 // We only support widening of vectors which are half the size of the 12785 // output registers. For example XMM->YMM widening on X86 with AVX. 12786 EVT VecInT = VecIn1.getValueType(); 12787 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 12788 // If we only have one small input, widen it by adding undef values. 12789 if (!VecIn2.getNode()) 12790 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 12791 DAG.getUNDEF(VecIn1.getValueType())); 12792 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 12793 // If we have two small inputs of the same type, try to concat them. 12794 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 12795 VecIn2 = SDValue(nullptr, 0); 12796 } else 12797 return SDValue(); 12798 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 12799 // If the input vector is too large, try to split it. 12800 // We don't support having two input vectors that are too large. 12801 // If the zero vector was used, we can not split the vector, 12802 // since we'd need 3 inputs. 12803 if (UsesZeroVector || VecIn2.getNode()) 12804 return SDValue(); 12805 12806 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 12807 return SDValue(); 12808 12809 // Try to replace VecIn1 with two extract_subvectors 12810 // No need to update the masks, they should still be correct. 12811 VecIn2 = DAG.getNode( 12812 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12813 DAG.getConstant(VT.getVectorNumElements(), dl, 12814 TLI.getVectorIdxTy(DAG.getDataLayout()))); 12815 VecIn1 = DAG.getNode( 12816 ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 12817 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 12818 } else 12819 return SDValue(); 12820 } 12821 12822 if (UsesZeroVector) 12823 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 12824 DAG.getConstantFP(0.0, dl, VT); 12825 else 12826 // If VecIn2 is unused then change it to undef. 12827 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 12828 12829 // Check that we were able to transform all incoming values to the same 12830 // type. 12831 if (VecIn2.getValueType() != VecIn1.getValueType() || 12832 VecIn1.getValueType() != VT) 12833 return SDValue(); 12834 12835 // Return the new VECTOR_SHUFFLE node. 12836 SDValue Ops[2]; 12837 Ops[0] = VecIn1; 12838 Ops[1] = VecIn2; 12839 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 12840 } 12841 12842 return SDValue(); 12843 } 12844 12845 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12846 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12847 EVT OpVT = N->getOperand(0).getValueType(); 12848 12849 // If the operands are legal vectors, leave them alone. 12850 if (TLI.isTypeLegal(OpVT)) 12851 return SDValue(); 12852 12853 SDLoc DL(N); 12854 EVT VT = N->getValueType(0); 12855 SmallVector<SDValue, 8> Ops; 12856 12857 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12858 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12859 12860 // Keep track of what we encounter. 12861 bool AnyInteger = false; 12862 bool AnyFP = false; 12863 for (const SDValue &Op : N->ops()) { 12864 if (ISD::BITCAST == Op.getOpcode() && 12865 !Op.getOperand(0).getValueType().isVector()) 12866 Ops.push_back(Op.getOperand(0)); 12867 else if (ISD::UNDEF == Op.getOpcode()) 12868 Ops.push_back(ScalarUndef); 12869 else 12870 return SDValue(); 12871 12872 // Note whether we encounter an integer or floating point scalar. 12873 // If it's neither, bail out, it could be something weird like x86mmx. 12874 EVT LastOpVT = Ops.back().getValueType(); 12875 if (LastOpVT.isFloatingPoint()) 12876 AnyFP = true; 12877 else if (LastOpVT.isInteger()) 12878 AnyInteger = true; 12879 else 12880 return SDValue(); 12881 } 12882 12883 // If any of the operands is a floating point scalar bitcast to a vector, 12884 // use floating point types throughout, and bitcast everything. 12885 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12886 if (AnyFP) { 12887 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12888 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12889 if (AnyInteger) { 12890 for (SDValue &Op : Ops) { 12891 if (Op.getValueType() == SVT) 12892 continue; 12893 if (Op.isUndef()) 12894 Op = ScalarUndef; 12895 else 12896 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12897 } 12898 } 12899 } 12900 12901 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12902 VT.getSizeInBits() / SVT.getSizeInBits()); 12903 return DAG.getNode(ISD::BITCAST, DL, VT, 12904 DAG.getBuildVector(VecVT, DL, Ops)); 12905 } 12906 12907 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 12908 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 12909 // most two distinct vectors the same size as the result, attempt to turn this 12910 // into a legal shuffle. 12911 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 12912 EVT VT = N->getValueType(0); 12913 EVT OpVT = N->getOperand(0).getValueType(); 12914 int NumElts = VT.getVectorNumElements(); 12915 int NumOpElts = OpVT.getVectorNumElements(); 12916 12917 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 12918 SmallVector<int, 8> Mask; 12919 12920 for (SDValue Op : N->ops()) { 12921 // Peek through any bitcast. 12922 while (Op.getOpcode() == ISD::BITCAST) 12923 Op = Op.getOperand(0); 12924 12925 // UNDEF nodes convert to UNDEF shuffle mask values. 12926 if (Op.isUndef()) { 12927 Mask.append((unsigned)NumOpElts, -1); 12928 continue; 12929 } 12930 12931 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12932 return SDValue(); 12933 12934 // What vector are we extracting the subvector from and at what index? 12935 SDValue ExtVec = Op.getOperand(0); 12936 12937 // We want the EVT of the original extraction to correctly scale the 12938 // extraction index. 12939 EVT ExtVT = ExtVec.getValueType(); 12940 12941 // Peek through any bitcast. 12942 while (ExtVec.getOpcode() == ISD::BITCAST) 12943 ExtVec = ExtVec.getOperand(0); 12944 12945 // UNDEF nodes convert to UNDEF shuffle mask values. 12946 if (ExtVec.isUndef()) { 12947 Mask.append((unsigned)NumOpElts, -1); 12948 continue; 12949 } 12950 12951 if (!isa<ConstantSDNode>(Op.getOperand(1))) 12952 return SDValue(); 12953 int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 12954 12955 // Ensure that we are extracting a subvector from a vector the same 12956 // size as the result. 12957 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 12958 return SDValue(); 12959 12960 // Scale the subvector index to account for any bitcast. 12961 int NumExtElts = ExtVT.getVectorNumElements(); 12962 if (0 == (NumExtElts % NumElts)) 12963 ExtIdx /= (NumExtElts / NumElts); 12964 else if (0 == (NumElts % NumExtElts)) 12965 ExtIdx *= (NumElts / NumExtElts); 12966 else 12967 return SDValue(); 12968 12969 // At most we can reference 2 inputs in the final shuffle. 12970 if (SV0.isUndef() || SV0 == ExtVec) { 12971 SV0 = ExtVec; 12972 for (int i = 0; i != NumOpElts; ++i) 12973 Mask.push_back(i + ExtIdx); 12974 } else if (SV1.isUndef() || SV1 == ExtVec) { 12975 SV1 = ExtVec; 12976 for (int i = 0; i != NumOpElts; ++i) 12977 Mask.push_back(i + ExtIdx + NumElts); 12978 } else { 12979 return SDValue(); 12980 } 12981 } 12982 12983 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 12984 return SDValue(); 12985 12986 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 12987 DAG.getBitcast(VT, SV1), Mask); 12988 } 12989 12990 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12991 // If we only have one input vector, we don't need to do any concatenation. 12992 if (N->getNumOperands() == 1) 12993 return N->getOperand(0); 12994 12995 // Check if all of the operands are undefs. 12996 EVT VT = N->getValueType(0); 12997 if (ISD::allOperandsUndef(N)) 12998 return DAG.getUNDEF(VT); 12999 13000 // Optimize concat_vectors where all but the first of the vectors are undef. 13001 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 13002 return Op.isUndef(); 13003 })) { 13004 SDValue In = N->getOperand(0); 13005 assert(In.getValueType().isVector() && "Must concat vectors"); 13006 13007 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 13008 if (In->getOpcode() == ISD::BITCAST && 13009 !In->getOperand(0)->getValueType(0).isVector()) { 13010 SDValue Scalar = In->getOperand(0); 13011 13012 // If the bitcast type isn't legal, it might be a trunc of a legal type; 13013 // look through the trunc so we can still do the transform: 13014 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 13015 if (Scalar->getOpcode() == ISD::TRUNCATE && 13016 !TLI.isTypeLegal(Scalar.getValueType()) && 13017 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 13018 Scalar = Scalar->getOperand(0); 13019 13020 EVT SclTy = Scalar->getValueType(0); 13021 13022 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 13023 return SDValue(); 13024 13025 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 13026 VT.getSizeInBits() / SclTy.getSizeInBits()); 13027 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 13028 return SDValue(); 13029 13030 SDLoc dl = SDLoc(N); 13031 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 13032 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 13033 } 13034 } 13035 13036 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 13037 // We have already tested above for an UNDEF only concatenation. 13038 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 13039 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 13040 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 13041 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 13042 }; 13043 bool AllBuildVectorsOrUndefs = 13044 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 13045 if (AllBuildVectorsOrUndefs) { 13046 SmallVector<SDValue, 8> Opnds; 13047 EVT SVT = VT.getScalarType(); 13048 13049 EVT MinVT = SVT; 13050 if (!SVT.isFloatingPoint()) { 13051 // If BUILD_VECTOR are from built from integer, they may have different 13052 // operand types. Get the smallest type and truncate all operands to it. 13053 bool FoundMinVT = false; 13054 for (const SDValue &Op : N->ops()) 13055 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13056 EVT OpSVT = Op.getOperand(0)->getValueType(0); 13057 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 13058 FoundMinVT = true; 13059 } 13060 assert(FoundMinVT && "Concat vector type mismatch"); 13061 } 13062 13063 for (const SDValue &Op : N->ops()) { 13064 EVT OpVT = Op.getValueType(); 13065 unsigned NumElts = OpVT.getVectorNumElements(); 13066 13067 if (ISD::UNDEF == Op.getOpcode()) 13068 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 13069 13070 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 13071 if (SVT.isFloatingPoint()) { 13072 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 13073 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 13074 } else { 13075 for (unsigned i = 0; i != NumElts; ++i) 13076 Opnds.push_back( 13077 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 13078 } 13079 } 13080 } 13081 13082 assert(VT.getVectorNumElements() == Opnds.size() && 13083 "Concat vector type mismatch"); 13084 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 13085 } 13086 13087 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 13088 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 13089 return V; 13090 13091 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 13092 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 13093 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 13094 return V; 13095 13096 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 13097 // nodes often generate nop CONCAT_VECTOR nodes. 13098 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 13099 // place the incoming vectors at the exact same location. 13100 SDValue SingleSource = SDValue(); 13101 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 13102 13103 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 13104 SDValue Op = N->getOperand(i); 13105 13106 if (Op.isUndef()) 13107 continue; 13108 13109 // Check if this is the identity extract: 13110 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 13111 return SDValue(); 13112 13113 // Find the single incoming vector for the extract_subvector. 13114 if (SingleSource.getNode()) { 13115 if (Op.getOperand(0) != SingleSource) 13116 return SDValue(); 13117 } else { 13118 SingleSource = Op.getOperand(0); 13119 13120 // Check the source type is the same as the type of the result. 13121 // If not, this concat may extend the vector, so we can not 13122 // optimize it away. 13123 if (SingleSource.getValueType() != N->getValueType(0)) 13124 return SDValue(); 13125 } 13126 13127 unsigned IdentityIndex = i * PartNumElem; 13128 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 13129 // The extract index must be constant. 13130 if (!CS) 13131 return SDValue(); 13132 13133 // Check that we are reading from the identity index. 13134 if (CS->getZExtValue() != IdentityIndex) 13135 return SDValue(); 13136 } 13137 13138 if (SingleSource.getNode()) 13139 return SingleSource; 13140 13141 return SDValue(); 13142 } 13143 13144 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 13145 EVT NVT = N->getValueType(0); 13146 SDValue V = N->getOperand(0); 13147 13148 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 13149 // Combine: 13150 // (extract_subvec (concat V1, V2, ...), i) 13151 // Into: 13152 // Vi if possible 13153 // Only operand 0 is checked as 'concat' assumes all inputs of the same 13154 // type. 13155 if (V->getOperand(0).getValueType() != NVT) 13156 return SDValue(); 13157 unsigned Idx = N->getConstantOperandVal(1); 13158 unsigned NumElems = NVT.getVectorNumElements(); 13159 assert((Idx % NumElems) == 0 && 13160 "IDX in concat is not a multiple of the result vector length."); 13161 return V->getOperand(Idx / NumElems); 13162 } 13163 13164 // Skip bitcasting 13165 if (V->getOpcode() == ISD::BITCAST) 13166 V = V.getOperand(0); 13167 13168 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 13169 SDLoc dl(N); 13170 // Handle only simple case where vector being inserted and vector 13171 // being extracted are of same type, and are half size of larger vectors. 13172 EVT BigVT = V->getOperand(0).getValueType(); 13173 EVT SmallVT = V->getOperand(1).getValueType(); 13174 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 13175 return SDValue(); 13176 13177 // Only handle cases where both indexes are constants with the same type. 13178 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 13179 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13180 13181 if (InsIdx && ExtIdx && 13182 InsIdx->getValueType(0).getSizeInBits() <= 64 && 13183 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 13184 // Combine: 13185 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 13186 // Into: 13187 // indices are equal or bit offsets are equal => V1 13188 // otherwise => (extract_subvec V1, ExtIdx) 13189 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 13190 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 13191 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 13192 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 13193 DAG.getNode(ISD::BITCAST, dl, 13194 N->getOperand(0).getValueType(), 13195 V->getOperand(0)), N->getOperand(1)); 13196 } 13197 } 13198 13199 return SDValue(); 13200 } 13201 13202 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 13203 SDValue V, SelectionDAG &DAG) { 13204 SDLoc DL(V); 13205 EVT VT = V.getValueType(); 13206 13207 switch (V.getOpcode()) { 13208 default: 13209 return V; 13210 13211 case ISD::CONCAT_VECTORS: { 13212 EVT OpVT = V->getOperand(0).getValueType(); 13213 int OpSize = OpVT.getVectorNumElements(); 13214 SmallBitVector OpUsedElements(OpSize, false); 13215 bool FoundSimplification = false; 13216 SmallVector<SDValue, 4> NewOps; 13217 NewOps.reserve(V->getNumOperands()); 13218 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 13219 SDValue Op = V->getOperand(i); 13220 bool OpUsed = false; 13221 for (int j = 0; j < OpSize; ++j) 13222 if (UsedElements[i * OpSize + j]) { 13223 OpUsedElements[j] = true; 13224 OpUsed = true; 13225 } 13226 NewOps.push_back( 13227 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 13228 : DAG.getUNDEF(OpVT)); 13229 FoundSimplification |= Op == NewOps.back(); 13230 OpUsedElements.reset(); 13231 } 13232 if (FoundSimplification) 13233 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 13234 return V; 13235 } 13236 13237 case ISD::INSERT_SUBVECTOR: { 13238 SDValue BaseV = V->getOperand(0); 13239 SDValue SubV = V->getOperand(1); 13240 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 13241 if (!IdxN) 13242 return V; 13243 13244 int SubSize = SubV.getValueType().getVectorNumElements(); 13245 int Idx = IdxN->getZExtValue(); 13246 bool SubVectorUsed = false; 13247 SmallBitVector SubUsedElements(SubSize, false); 13248 for (int i = 0; i < SubSize; ++i) 13249 if (UsedElements[i + Idx]) { 13250 SubVectorUsed = true; 13251 SubUsedElements[i] = true; 13252 UsedElements[i + Idx] = false; 13253 } 13254 13255 // Now recurse on both the base and sub vectors. 13256 SDValue SimplifiedSubV = 13257 SubVectorUsed 13258 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 13259 : DAG.getUNDEF(SubV.getValueType()); 13260 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 13261 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 13262 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 13263 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 13264 return V; 13265 } 13266 } 13267 } 13268 13269 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 13270 SDValue N1, SelectionDAG &DAG) { 13271 EVT VT = SVN->getValueType(0); 13272 int NumElts = VT.getVectorNumElements(); 13273 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 13274 for (int M : SVN->getMask()) 13275 if (M >= 0 && M < NumElts) 13276 N0UsedElements[M] = true; 13277 else if (M >= NumElts) 13278 N1UsedElements[M - NumElts] = true; 13279 13280 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 13281 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 13282 if (S0 == N0 && S1 == N1) 13283 return SDValue(); 13284 13285 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 13286 } 13287 13288 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 13289 // or turn a shuffle of a single concat into simpler shuffle then concat. 13290 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 13291 EVT VT = N->getValueType(0); 13292 unsigned NumElts = VT.getVectorNumElements(); 13293 13294 SDValue N0 = N->getOperand(0); 13295 SDValue N1 = N->getOperand(1); 13296 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13297 13298 SmallVector<SDValue, 4> Ops; 13299 EVT ConcatVT = N0.getOperand(0).getValueType(); 13300 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 13301 unsigned NumConcats = NumElts / NumElemsPerConcat; 13302 13303 // Special case: shuffle(concat(A,B)) can be more efficiently represented 13304 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 13305 // half vector elements. 13306 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 13307 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 13308 SVN->getMask().end(), [](int i) { return i == -1; })) { 13309 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 13310 makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat)); 13311 N1 = DAG.getUNDEF(ConcatVT); 13312 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 13313 } 13314 13315 // Look at every vector that's inserted. We're looking for exact 13316 // subvector-sized copies from a concatenated vector 13317 for (unsigned I = 0; I != NumConcats; ++I) { 13318 // Make sure we're dealing with a copy. 13319 unsigned Begin = I * NumElemsPerConcat; 13320 bool AllUndef = true, NoUndef = true; 13321 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 13322 if (SVN->getMaskElt(J) >= 0) 13323 AllUndef = false; 13324 else 13325 NoUndef = false; 13326 } 13327 13328 if (NoUndef) { 13329 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 13330 return SDValue(); 13331 13332 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 13333 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 13334 return SDValue(); 13335 13336 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 13337 if (FirstElt < N0.getNumOperands()) 13338 Ops.push_back(N0.getOperand(FirstElt)); 13339 else 13340 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 13341 13342 } else if (AllUndef) { 13343 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 13344 } else { // Mixed with general masks and undefs, can't do optimization. 13345 return SDValue(); 13346 } 13347 } 13348 13349 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 13350 } 13351 13352 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 13353 EVT VT = N->getValueType(0); 13354 unsigned NumElts = VT.getVectorNumElements(); 13355 13356 SDValue N0 = N->getOperand(0); 13357 SDValue N1 = N->getOperand(1); 13358 13359 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 13360 13361 // Canonicalize shuffle undef, undef -> undef 13362 if (N0.isUndef() && N1.isUndef()) 13363 return DAG.getUNDEF(VT); 13364 13365 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 13366 13367 // Canonicalize shuffle v, v -> v, undef 13368 if (N0 == N1) { 13369 SmallVector<int, 8> NewMask; 13370 for (unsigned i = 0; i != NumElts; ++i) { 13371 int Idx = SVN->getMaskElt(i); 13372 if (Idx >= (int)NumElts) Idx -= NumElts; 13373 NewMask.push_back(Idx); 13374 } 13375 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 13376 &NewMask[0]); 13377 } 13378 13379 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 13380 if (N0.isUndef()) { 13381 SmallVector<int, 8> NewMask; 13382 for (unsigned i = 0; i != NumElts; ++i) { 13383 int Idx = SVN->getMaskElt(i); 13384 if (Idx >= 0) { 13385 if (Idx >= (int)NumElts) 13386 Idx -= NumElts; 13387 else 13388 Idx = -1; // remove reference to lhs 13389 } 13390 NewMask.push_back(Idx); 13391 } 13392 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 13393 &NewMask[0]); 13394 } 13395 13396 // Remove references to rhs if it is undef 13397 if (N1.isUndef()) { 13398 bool Changed = false; 13399 SmallVector<int, 8> NewMask; 13400 for (unsigned i = 0; i != NumElts; ++i) { 13401 int Idx = SVN->getMaskElt(i); 13402 if (Idx >= (int)NumElts) { 13403 Idx = -1; 13404 Changed = true; 13405 } 13406 NewMask.push_back(Idx); 13407 } 13408 if (Changed) 13409 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 13410 } 13411 13412 // If it is a splat, check if the argument vector is another splat or a 13413 // build_vector. 13414 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 13415 SDNode *V = N0.getNode(); 13416 13417 // If this is a bit convert that changes the element type of the vector but 13418 // not the number of vector elements, look through it. Be careful not to 13419 // look though conversions that change things like v4f32 to v2f64. 13420 if (V->getOpcode() == ISD::BITCAST) { 13421 SDValue ConvInput = V->getOperand(0); 13422 if (ConvInput.getValueType().isVector() && 13423 ConvInput.getValueType().getVectorNumElements() == NumElts) 13424 V = ConvInput.getNode(); 13425 } 13426 13427 if (V->getOpcode() == ISD::BUILD_VECTOR) { 13428 assert(V->getNumOperands() == NumElts && 13429 "BUILD_VECTOR has wrong number of operands"); 13430 SDValue Base; 13431 bool AllSame = true; 13432 for (unsigned i = 0; i != NumElts; ++i) { 13433 if (!V->getOperand(i).isUndef()) { 13434 Base = V->getOperand(i); 13435 break; 13436 } 13437 } 13438 // Splat of <u, u, u, u>, return <u, u, u, u> 13439 if (!Base.getNode()) 13440 return N0; 13441 for (unsigned i = 0; i != NumElts; ++i) { 13442 if (V->getOperand(i) != Base) { 13443 AllSame = false; 13444 break; 13445 } 13446 } 13447 // Splat of <x, x, x, x>, return <x, x, x, x> 13448 if (AllSame) 13449 return N0; 13450 13451 // Canonicalize any other splat as a build_vector. 13452 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 13453 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 13454 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 13455 13456 // We may have jumped through bitcasts, so the type of the 13457 // BUILD_VECTOR may not match the type of the shuffle. 13458 if (V->getValueType(0) != VT) 13459 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 13460 return NewBV; 13461 } 13462 } 13463 13464 // There are various patterns used to build up a vector from smaller vectors, 13465 // subvectors, or elements. Scan chains of these and replace unused insertions 13466 // or components with undef. 13467 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 13468 return S; 13469 13470 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13471 Level < AfterLegalizeVectorOps && 13472 (N1.isUndef() || 13473 (N1.getOpcode() == ISD::CONCAT_VECTORS && 13474 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 13475 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 13476 return V; 13477 } 13478 13479 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 13480 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 13481 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 13482 SmallVector<SDValue, 8> Ops; 13483 for (int M : SVN->getMask()) { 13484 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 13485 if (M >= 0) { 13486 int Idx = M % NumElts; 13487 SDValue &S = (M < (int)NumElts ? N0 : N1); 13488 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 13489 Op = S.getOperand(Idx); 13490 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 13491 if (Idx == 0) 13492 Op = S.getOperand(0); 13493 } else { 13494 // Operand can't be combined - bail out. 13495 break; 13496 } 13497 } 13498 Ops.push_back(Op); 13499 } 13500 if (Ops.size() == VT.getVectorNumElements()) { 13501 // BUILD_VECTOR requires all inputs to be of the same type, find the 13502 // maximum type and extend them all. 13503 EVT SVT = VT.getScalarType(); 13504 if (SVT.isInteger()) 13505 for (SDValue &Op : Ops) 13506 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 13507 if (SVT != VT.getScalarType()) 13508 for (SDValue &Op : Ops) 13509 Op = TLI.isZExtFree(Op.getValueType(), SVT) 13510 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 13511 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 13512 return DAG.getBuildVector(VT, SDLoc(N), Ops); 13513 } 13514 } 13515 13516 // If this shuffle only has a single input that is a bitcasted shuffle, 13517 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 13518 // back to their original types. 13519 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 13520 N1.isUndef() && Level < AfterLegalizeVectorOps && 13521 TLI.isTypeLegal(VT)) { 13522 13523 // Peek through the bitcast only if there is one user. 13524 SDValue BC0 = N0; 13525 while (BC0.getOpcode() == ISD::BITCAST) { 13526 if (!BC0.hasOneUse()) 13527 break; 13528 BC0 = BC0.getOperand(0); 13529 } 13530 13531 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 13532 if (Scale == 1) 13533 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 13534 13535 SmallVector<int, 8> NewMask; 13536 for (int M : Mask) 13537 for (int s = 0; s != Scale; ++s) 13538 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 13539 return NewMask; 13540 }; 13541 13542 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 13543 EVT SVT = VT.getScalarType(); 13544 EVT InnerVT = BC0->getValueType(0); 13545 EVT InnerSVT = InnerVT.getScalarType(); 13546 13547 // Determine which shuffle works with the smaller scalar type. 13548 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 13549 EVT ScaleSVT = ScaleVT.getScalarType(); 13550 13551 if (TLI.isTypeLegal(ScaleVT) && 13552 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 13553 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 13554 13555 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13556 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 13557 13558 // Scale the shuffle masks to the smaller scalar type. 13559 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 13560 SmallVector<int, 8> InnerMask = 13561 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 13562 SmallVector<int, 8> OuterMask = 13563 ScaleShuffleMask(SVN->getMask(), OuterScale); 13564 13565 // Merge the shuffle masks. 13566 SmallVector<int, 8> NewMask; 13567 for (int M : OuterMask) 13568 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 13569 13570 // Test for shuffle mask legality over both commutations. 13571 SDValue SV0 = BC0->getOperand(0); 13572 SDValue SV1 = BC0->getOperand(1); 13573 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13574 if (!LegalMask) { 13575 std::swap(SV0, SV1); 13576 ShuffleVectorSDNode::commuteMask(NewMask); 13577 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 13578 } 13579 13580 if (LegalMask) { 13581 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 13582 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 13583 return DAG.getNode( 13584 ISD::BITCAST, SDLoc(N), VT, 13585 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 13586 } 13587 } 13588 } 13589 } 13590 13591 // Canonicalize shuffles according to rules: 13592 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 13593 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 13594 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 13595 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 13596 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 13597 TLI.isTypeLegal(VT)) { 13598 // The incoming shuffle must be of the same type as the result of the 13599 // current shuffle. 13600 assert(N1->getOperand(0).getValueType() == VT && 13601 "Shuffle types don't match"); 13602 13603 SDValue SV0 = N1->getOperand(0); 13604 SDValue SV1 = N1->getOperand(1); 13605 bool HasSameOp0 = N0 == SV0; 13606 bool IsSV1Undef = SV1.isUndef(); 13607 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 13608 // Commute the operands of this shuffle so that next rule 13609 // will trigger. 13610 return DAG.getCommutedVectorShuffle(*SVN); 13611 } 13612 13613 // Try to fold according to rules: 13614 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13615 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13616 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13617 // Don't try to fold shuffles with illegal type. 13618 // Only fold if this shuffle is the only user of the other shuffle. 13619 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 13620 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 13621 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 13622 13623 // The incoming shuffle must be of the same type as the result of the 13624 // current shuffle. 13625 assert(OtherSV->getOperand(0).getValueType() == VT && 13626 "Shuffle types don't match"); 13627 13628 SDValue SV0, SV1; 13629 SmallVector<int, 4> Mask; 13630 // Compute the combined shuffle mask for a shuffle with SV0 as the first 13631 // operand, and SV1 as the second operand. 13632 for (unsigned i = 0; i != NumElts; ++i) { 13633 int Idx = SVN->getMaskElt(i); 13634 if (Idx < 0) { 13635 // Propagate Undef. 13636 Mask.push_back(Idx); 13637 continue; 13638 } 13639 13640 SDValue CurrentVec; 13641 if (Idx < (int)NumElts) { 13642 // This shuffle index refers to the inner shuffle N0. Lookup the inner 13643 // shuffle mask to identify which vector is actually referenced. 13644 Idx = OtherSV->getMaskElt(Idx); 13645 if (Idx < 0) { 13646 // Propagate Undef. 13647 Mask.push_back(Idx); 13648 continue; 13649 } 13650 13651 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 13652 : OtherSV->getOperand(1); 13653 } else { 13654 // This shuffle index references an element within N1. 13655 CurrentVec = N1; 13656 } 13657 13658 // Simple case where 'CurrentVec' is UNDEF. 13659 if (CurrentVec.isUndef()) { 13660 Mask.push_back(-1); 13661 continue; 13662 } 13663 13664 // Canonicalize the shuffle index. We don't know yet if CurrentVec 13665 // will be the first or second operand of the combined shuffle. 13666 Idx = Idx % NumElts; 13667 if (!SV0.getNode() || SV0 == CurrentVec) { 13668 // Ok. CurrentVec is the left hand side. 13669 // Update the mask accordingly. 13670 SV0 = CurrentVec; 13671 Mask.push_back(Idx); 13672 continue; 13673 } 13674 13675 // Bail out if we cannot convert the shuffle pair into a single shuffle. 13676 if (SV1.getNode() && SV1 != CurrentVec) 13677 return SDValue(); 13678 13679 // Ok. CurrentVec is the right hand side. 13680 // Update the mask accordingly. 13681 SV1 = CurrentVec; 13682 Mask.push_back(Idx + NumElts); 13683 } 13684 13685 // Check if all indices in Mask are Undef. In case, propagate Undef. 13686 bool isUndefMask = true; 13687 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 13688 isUndefMask &= Mask[i] < 0; 13689 13690 if (isUndefMask) 13691 return DAG.getUNDEF(VT); 13692 13693 if (!SV0.getNode()) 13694 SV0 = DAG.getUNDEF(VT); 13695 if (!SV1.getNode()) 13696 SV1 = DAG.getUNDEF(VT); 13697 13698 // Avoid introducing shuffles with illegal mask. 13699 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 13700 ShuffleVectorSDNode::commuteMask(Mask); 13701 13702 if (!TLI.isShuffleMaskLegal(Mask, VT)) 13703 return SDValue(); 13704 13705 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 13706 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 13707 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 13708 std::swap(SV0, SV1); 13709 } 13710 13711 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 13712 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 13713 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 13714 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 13715 } 13716 13717 return SDValue(); 13718 } 13719 13720 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 13721 SDValue InVal = N->getOperand(0); 13722 EVT VT = N->getValueType(0); 13723 13724 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 13725 // with a VECTOR_SHUFFLE. 13726 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 13727 SDValue InVec = InVal->getOperand(0); 13728 SDValue EltNo = InVal->getOperand(1); 13729 13730 // FIXME: We could support implicit truncation if the shuffle can be 13731 // scaled to a smaller vector scalar type. 13732 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 13733 if (C0 && VT == InVec.getValueType() && 13734 VT.getScalarType() == InVal.getValueType()) { 13735 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 13736 int Elt = C0->getZExtValue(); 13737 NewMask[0] = Elt; 13738 13739 if (TLI.isShuffleMaskLegal(NewMask, VT)) 13740 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 13741 NewMask); 13742 } 13743 } 13744 13745 return SDValue(); 13746 } 13747 13748 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 13749 SDValue N0 = N->getOperand(0); 13750 SDValue N2 = N->getOperand(2); 13751 13752 // If the input vector is a concatenation, and the insert replaces 13753 // one of the halves, we can optimize into a single concat_vectors. 13754 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 13755 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 13756 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 13757 EVT VT = N->getValueType(0); 13758 13759 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13760 // (concat_vectors Z, Y) 13761 if (InsIdx == 0) 13762 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13763 N->getOperand(1), N0.getOperand(1)); 13764 13765 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 13766 // (concat_vectors X, Z) 13767 if (InsIdx == VT.getVectorNumElements()/2) 13768 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 13769 N0.getOperand(0), N->getOperand(1)); 13770 } 13771 13772 return SDValue(); 13773 } 13774 13775 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 13776 SDValue N0 = N->getOperand(0); 13777 13778 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 13779 if (N0->getOpcode() == ISD::FP16_TO_FP) 13780 return N0->getOperand(0); 13781 13782 return SDValue(); 13783 } 13784 13785 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 13786 SDValue N0 = N->getOperand(0); 13787 13788 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 13789 if (N0->getOpcode() == ISD::AND) { 13790 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 13791 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 13792 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 13793 N0.getOperand(0)); 13794 } 13795 } 13796 13797 return SDValue(); 13798 } 13799 13800 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 13801 /// with the destination vector and a zero vector. 13802 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 13803 /// vector_shuffle V, Zero, <0, 4, 2, 4> 13804 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 13805 EVT VT = N->getValueType(0); 13806 SDValue LHS = N->getOperand(0); 13807 SDValue RHS = N->getOperand(1); 13808 SDLoc dl(N); 13809 13810 // Make sure we're not running after operation legalization where it 13811 // may have custom lowered the vector shuffles. 13812 if (LegalOperations) 13813 return SDValue(); 13814 13815 if (N->getOpcode() != ISD::AND) 13816 return SDValue(); 13817 13818 if (RHS.getOpcode() == ISD::BITCAST) 13819 RHS = RHS.getOperand(0); 13820 13821 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 13822 return SDValue(); 13823 13824 EVT RVT = RHS.getValueType(); 13825 unsigned NumElts = RHS.getNumOperands(); 13826 13827 // Attempt to create a valid clear mask, splitting the mask into 13828 // sub elements and checking to see if each is 13829 // all zeros or all ones - suitable for shuffle masking. 13830 auto BuildClearMask = [&](int Split) { 13831 int NumSubElts = NumElts * Split; 13832 int NumSubBits = RVT.getScalarSizeInBits() / Split; 13833 13834 SmallVector<int, 8> Indices; 13835 for (int i = 0; i != NumSubElts; ++i) { 13836 int EltIdx = i / Split; 13837 int SubIdx = i % Split; 13838 SDValue Elt = RHS.getOperand(EltIdx); 13839 if (Elt.isUndef()) { 13840 Indices.push_back(-1); 13841 continue; 13842 } 13843 13844 APInt Bits; 13845 if (isa<ConstantSDNode>(Elt)) 13846 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 13847 else if (isa<ConstantFPSDNode>(Elt)) 13848 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 13849 else 13850 return SDValue(); 13851 13852 // Extract the sub element from the constant bit mask. 13853 if (DAG.getDataLayout().isBigEndian()) { 13854 Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits); 13855 } else { 13856 Bits = Bits.lshr(SubIdx * NumSubBits); 13857 } 13858 13859 if (Split > 1) 13860 Bits = Bits.trunc(NumSubBits); 13861 13862 if (Bits.isAllOnesValue()) 13863 Indices.push_back(i); 13864 else if (Bits == 0) 13865 Indices.push_back(i + NumSubElts); 13866 else 13867 return SDValue(); 13868 } 13869 13870 // Let's see if the target supports this vector_shuffle. 13871 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 13872 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 13873 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 13874 return SDValue(); 13875 13876 SDValue Zero = DAG.getConstant(0, dl, ClearVT); 13877 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl, 13878 DAG.getBitcast(ClearVT, LHS), 13879 Zero, &Indices[0])); 13880 }; 13881 13882 // Determine maximum split level (byte level masking). 13883 int MaxSplit = 1; 13884 if (RVT.getScalarSizeInBits() % 8 == 0) 13885 MaxSplit = RVT.getScalarSizeInBits() / 8; 13886 13887 for (int Split = 1; Split <= MaxSplit; ++Split) 13888 if (RVT.getScalarSizeInBits() % Split == 0) 13889 if (SDValue S = BuildClearMask(Split)) 13890 return S; 13891 13892 return SDValue(); 13893 } 13894 13895 /// Visit a binary vector operation, like ADD. 13896 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 13897 assert(N->getValueType(0).isVector() && 13898 "SimplifyVBinOp only works on vectors!"); 13899 13900 SDValue LHS = N->getOperand(0); 13901 SDValue RHS = N->getOperand(1); 13902 SDValue Ops[] = {LHS, RHS}; 13903 13904 // See if we can constant fold the vector operation. 13905 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 13906 N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 13907 return Fold; 13908 13909 // Try to convert a constant mask AND into a shuffle clear mask. 13910 if (SDValue Shuffle = XformToShuffleWithZero(N)) 13911 return Shuffle; 13912 13913 // Type legalization might introduce new shuffles in the DAG. 13914 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 13915 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 13916 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 13917 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 13918 LHS.getOperand(1).isUndef() && 13919 RHS.getOperand(1).isUndef()) { 13920 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 13921 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 13922 13923 if (SVN0->getMask().equals(SVN1->getMask())) { 13924 EVT VT = N->getValueType(0); 13925 SDValue UndefVector = LHS.getOperand(1); 13926 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 13927 LHS.getOperand(0), RHS.getOperand(0), 13928 N->getFlags()); 13929 AddUsersToWorklist(N); 13930 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 13931 &SVN0->getMask()[0]); 13932 } 13933 } 13934 13935 return SDValue(); 13936 } 13937 13938 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13939 SDValue N1, SDValue N2){ 13940 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13941 13942 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13943 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13944 13945 // If we got a simplified select_cc node back from SimplifySelectCC, then 13946 // break it down into a new SETCC node, and a new SELECT node, and then return 13947 // the SELECT node, since we were called with a SELECT node. 13948 if (SCC.getNode()) { 13949 // Check to see if we got a select_cc back (to turn into setcc/select). 13950 // Otherwise, just return whatever node we got back, like fabs. 13951 if (SCC.getOpcode() == ISD::SELECT_CC) { 13952 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13953 N0.getValueType(), 13954 SCC.getOperand(0), SCC.getOperand(1), 13955 SCC.getOperand(4)); 13956 AddToWorklist(SETCC.getNode()); 13957 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13958 SCC.getOperand(2), SCC.getOperand(3)); 13959 } 13960 13961 return SCC; 13962 } 13963 return SDValue(); 13964 } 13965 13966 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13967 /// being selected between, see if we can simplify the select. Callers of this 13968 /// should assume that TheSelect is deleted if this returns true. As such, they 13969 /// should return the appropriate thing (e.g. the node) back to the top-level of 13970 /// the DAG combiner loop to avoid it being looked at. 13971 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13972 SDValue RHS) { 13973 13974 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 13975 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 13976 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13977 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13978 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13979 SDValue Sqrt = RHS; 13980 ISD::CondCode CC; 13981 SDValue CmpLHS; 13982 const ConstantFPSDNode *Zero = nullptr; 13983 13984 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13985 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13986 CmpLHS = TheSelect->getOperand(0); 13987 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13988 } else { 13989 // SELECT or VSELECT 13990 SDValue Cmp = TheSelect->getOperand(0); 13991 if (Cmp.getOpcode() == ISD::SETCC) { 13992 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13993 CmpLHS = Cmp.getOperand(0); 13994 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13995 } 13996 } 13997 if (Zero && Zero->isZero() && 13998 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13999 CC == ISD::SETULT || CC == ISD::SETLT)) { 14000 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 14001 CombineTo(TheSelect, Sqrt); 14002 return true; 14003 } 14004 } 14005 } 14006 // Cannot simplify select with vector condition 14007 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 14008 14009 // If this is a select from two identical things, try to pull the operation 14010 // through the select. 14011 if (LHS.getOpcode() != RHS.getOpcode() || 14012 !LHS.hasOneUse() || !RHS.hasOneUse()) 14013 return false; 14014 14015 // If this is a load and the token chain is identical, replace the select 14016 // of two loads with a load through a select of the address to load from. 14017 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 14018 // constants have been dropped into the constant pool. 14019 if (LHS.getOpcode() == ISD::LOAD) { 14020 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 14021 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 14022 14023 // Token chains must be identical. 14024 if (LHS.getOperand(0) != RHS.getOperand(0) || 14025 // Do not let this transformation reduce the number of volatile loads. 14026 LLD->isVolatile() || RLD->isVolatile() || 14027 // FIXME: If either is a pre/post inc/dec load, 14028 // we'd need to split out the address adjustment. 14029 LLD->isIndexed() || RLD->isIndexed() || 14030 // If this is an EXTLOAD, the VT's must match. 14031 LLD->getMemoryVT() != RLD->getMemoryVT() || 14032 // If this is an EXTLOAD, the kind of extension must match. 14033 (LLD->getExtensionType() != RLD->getExtensionType() && 14034 // The only exception is if one of the extensions is anyext. 14035 LLD->getExtensionType() != ISD::EXTLOAD && 14036 RLD->getExtensionType() != ISD::EXTLOAD) || 14037 // FIXME: this discards src value information. This is 14038 // over-conservative. It would be beneficial to be able to remember 14039 // both potential memory locations. Since we are discarding 14040 // src value info, don't do the transformation if the memory 14041 // locations are not in the default address space. 14042 LLD->getPointerInfo().getAddrSpace() != 0 || 14043 RLD->getPointerInfo().getAddrSpace() != 0 || 14044 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 14045 LLD->getBasePtr().getValueType())) 14046 return false; 14047 14048 // Check that the select condition doesn't reach either load. If so, 14049 // folding this will induce a cycle into the DAG. If not, this is safe to 14050 // xform, so create a select of the addresses. 14051 SDValue Addr; 14052 if (TheSelect->getOpcode() == ISD::SELECT) { 14053 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 14054 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 14055 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 14056 return false; 14057 // The loads must not depend on one another. 14058 if (LLD->isPredecessorOf(RLD) || 14059 RLD->isPredecessorOf(LLD)) 14060 return false; 14061 Addr = DAG.getSelect(SDLoc(TheSelect), 14062 LLD->getBasePtr().getValueType(), 14063 TheSelect->getOperand(0), LLD->getBasePtr(), 14064 RLD->getBasePtr()); 14065 } else { // Otherwise SELECT_CC 14066 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 14067 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 14068 14069 if ((LLD->hasAnyUseOfValue(1) && 14070 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 14071 (RLD->hasAnyUseOfValue(1) && 14072 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 14073 return false; 14074 14075 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 14076 LLD->getBasePtr().getValueType(), 14077 TheSelect->getOperand(0), 14078 TheSelect->getOperand(1), 14079 LLD->getBasePtr(), RLD->getBasePtr(), 14080 TheSelect->getOperand(4)); 14081 } 14082 14083 SDValue Load; 14084 // It is safe to replace the two loads if they have different alignments, 14085 // but the new load must be the minimum (most restrictive) alignment of the 14086 // inputs. 14087 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 14088 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 14089 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 14090 Load = DAG.getLoad(TheSelect->getValueType(0), 14091 SDLoc(TheSelect), 14092 // FIXME: Discards pointer and AA info. 14093 LLD->getChain(), Addr, MachinePointerInfo(), 14094 LLD->isVolatile(), LLD->isNonTemporal(), 14095 isInvariant, Alignment); 14096 } else { 14097 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 14098 RLD->getExtensionType() : LLD->getExtensionType(), 14099 SDLoc(TheSelect), 14100 TheSelect->getValueType(0), 14101 // FIXME: Discards pointer and AA info. 14102 LLD->getChain(), Addr, MachinePointerInfo(), 14103 LLD->getMemoryVT(), LLD->isVolatile(), 14104 LLD->isNonTemporal(), isInvariant, Alignment); 14105 } 14106 14107 // Users of the select now use the result of the load. 14108 CombineTo(TheSelect, Load); 14109 14110 // Users of the old loads now use the new load's chain. We know the 14111 // old-load value is dead now. 14112 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 14113 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 14114 return true; 14115 } 14116 14117 return false; 14118 } 14119 14120 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 14121 /// where 'cond' is the comparison specified by CC. 14122 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 14123 SDValue N2, SDValue N3, 14124 ISD::CondCode CC, bool NotExtCompare) { 14125 // (x ? y : y) -> y. 14126 if (N2 == N3) return N2; 14127 14128 EVT VT = N2.getValueType(); 14129 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 14130 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 14131 14132 // Determine if the condition we're dealing with is constant 14133 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 14134 N0, N1, CC, DL, false); 14135 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 14136 14137 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 14138 // fold select_cc true, x, y -> x 14139 // fold select_cc false, x, y -> y 14140 return !SCCC->isNullValue() ? N2 : N3; 14141 } 14142 14143 // Check to see if we can simplify the select into an fabs node 14144 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 14145 // Allow either -0.0 or 0.0 14146 if (CFP->isZero()) { 14147 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 14148 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 14149 N0 == N2 && N3.getOpcode() == ISD::FNEG && 14150 N2 == N3.getOperand(0)) 14151 return DAG.getNode(ISD::FABS, DL, VT, N0); 14152 14153 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 14154 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 14155 N0 == N3 && N2.getOpcode() == ISD::FNEG && 14156 N2.getOperand(0) == N3) 14157 return DAG.getNode(ISD::FABS, DL, VT, N3); 14158 } 14159 } 14160 14161 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 14162 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 14163 // in it. This is a win when the constant is not otherwise available because 14164 // it replaces two constant pool loads with one. We only do this if the FP 14165 // type is known to be legal, because if it isn't, then we are before legalize 14166 // types an we want the other legalization to happen first (e.g. to avoid 14167 // messing with soft float) and if the ConstantFP is not legal, because if 14168 // it is legal, we may not need to store the FP constant in a constant pool. 14169 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 14170 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 14171 if (TLI.isTypeLegal(N2.getValueType()) && 14172 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 14173 TargetLowering::Legal && 14174 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 14175 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 14176 // If both constants have multiple uses, then we won't need to do an 14177 // extra load, they are likely around in registers for other users. 14178 (TV->hasOneUse() || FV->hasOneUse())) { 14179 Constant *Elts[] = { 14180 const_cast<ConstantFP*>(FV->getConstantFPValue()), 14181 const_cast<ConstantFP*>(TV->getConstantFPValue()) 14182 }; 14183 Type *FPTy = Elts[0]->getType(); 14184 const DataLayout &TD = DAG.getDataLayout(); 14185 14186 // Create a ConstantArray of the two constants. 14187 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 14188 SDValue CPIdx = 14189 DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 14190 TD.getPrefTypeAlignment(FPTy)); 14191 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 14192 14193 // Get the offsets to the 0 and 1 element of the array so that we can 14194 // select between them. 14195 SDValue Zero = DAG.getIntPtrConstant(0, DL); 14196 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 14197 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 14198 14199 SDValue Cond = DAG.getSetCC(DL, 14200 getSetCCResultType(N0.getValueType()), 14201 N0, N1, CC); 14202 AddToWorklist(Cond.getNode()); 14203 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 14204 Cond, One, Zero); 14205 AddToWorklist(CstOffset.getNode()); 14206 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 14207 CstOffset); 14208 AddToWorklist(CPIdx.getNode()); 14209 return DAG.getLoad( 14210 TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 14211 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), 14212 false, false, false, Alignment); 14213 } 14214 } 14215 14216 // Check to see if we can perform the "gzip trick", transforming 14217 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 14218 if (isNullConstant(N3) && CC == ISD::SETLT && 14219 (isNullConstant(N1) || // (a < 0) ? b : 0 14220 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 14221 EVT XType = N0.getValueType(); 14222 EVT AType = N2.getValueType(); 14223 if (XType.bitsGE(AType)) { 14224 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 14225 // single-bit constant. 14226 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 14227 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 14228 ShCtV = XType.getSizeInBits() - ShCtV - 1; 14229 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 14230 getShiftAmountTy(N0.getValueType())); 14231 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 14232 XType, N0, ShCt); 14233 AddToWorklist(Shift.getNode()); 14234 14235 if (XType.bitsGT(AType)) { 14236 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14237 AddToWorklist(Shift.getNode()); 14238 } 14239 14240 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14241 } 14242 14243 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 14244 XType, N0, 14245 DAG.getConstant(XType.getSizeInBits() - 1, 14246 SDLoc(N0), 14247 getShiftAmountTy(N0.getValueType()))); 14248 AddToWorklist(Shift.getNode()); 14249 14250 if (XType.bitsGT(AType)) { 14251 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 14252 AddToWorklist(Shift.getNode()); 14253 } 14254 14255 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 14256 } 14257 } 14258 14259 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 14260 // where y is has a single bit set. 14261 // A plaintext description would be, we can turn the SELECT_CC into an AND 14262 // when the condition can be materialized as an all-ones register. Any 14263 // single bit-test can be materialized as an all-ones register with 14264 // shift-left and shift-right-arith. 14265 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 14266 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 14267 SDValue AndLHS = N0->getOperand(0); 14268 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 14269 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 14270 // Shift the tested bit over the sign bit. 14271 APInt AndMask = ConstAndRHS->getAPIntValue(); 14272 SDValue ShlAmt = 14273 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 14274 getShiftAmountTy(AndLHS.getValueType())); 14275 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 14276 14277 // Now arithmetic right shift it all the way over, so the result is either 14278 // all-ones, or zero. 14279 SDValue ShrAmt = 14280 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 14281 getShiftAmountTy(Shl.getValueType())); 14282 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 14283 14284 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 14285 } 14286 } 14287 14288 // fold select C, 16, 0 -> shl C, 4 14289 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 14290 TLI.getBooleanContents(N0.getValueType()) == 14291 TargetLowering::ZeroOrOneBooleanContent) { 14292 14293 // If the caller doesn't want us to simplify this into a zext of a compare, 14294 // don't do it. 14295 if (NotExtCompare && N2C->isOne()) 14296 return SDValue(); 14297 14298 // Get a SetCC of the condition 14299 // NOTE: Don't create a SETCC if it's not legal on this target. 14300 if (!LegalOperations || 14301 TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) { 14302 SDValue Temp, SCC; 14303 // cast from setcc result type to select result type 14304 if (LegalTypes) { 14305 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 14306 N0, N1, CC); 14307 if (N2.getValueType().bitsLT(SCC.getValueType())) 14308 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 14309 N2.getValueType()); 14310 else 14311 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14312 N2.getValueType(), SCC); 14313 } else { 14314 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 14315 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 14316 N2.getValueType(), SCC); 14317 } 14318 14319 AddToWorklist(SCC.getNode()); 14320 AddToWorklist(Temp.getNode()); 14321 14322 if (N2C->isOne()) 14323 return Temp; 14324 14325 // shl setcc result by log2 n2c 14326 return DAG.getNode( 14327 ISD::SHL, DL, N2.getValueType(), Temp, 14328 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 14329 getShiftAmountTy(Temp.getValueType()))); 14330 } 14331 } 14332 14333 // Check to see if this is an integer abs. 14334 // select_cc setg[te] X, 0, X, -X -> 14335 // select_cc setgt X, -1, X, -X -> 14336 // select_cc setl[te] X, 0, -X, X -> 14337 // select_cc setlt X, 1, -X, X -> 14338 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 14339 if (N1C) { 14340 ConstantSDNode *SubC = nullptr; 14341 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 14342 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 14343 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 14344 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 14345 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 14346 (N1C->isOne() && CC == ISD::SETLT)) && 14347 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 14348 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 14349 14350 EVT XType = N0.getValueType(); 14351 if (SubC && SubC->isNullValue() && XType.isInteger()) { 14352 SDLoc DL(N0); 14353 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 14354 N0, 14355 DAG.getConstant(XType.getSizeInBits() - 1, DL, 14356 getShiftAmountTy(N0.getValueType()))); 14357 SDValue Add = DAG.getNode(ISD::ADD, DL, 14358 XType, N0, Shift); 14359 AddToWorklist(Shift.getNode()); 14360 AddToWorklist(Add.getNode()); 14361 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 14362 } 14363 } 14364 14365 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 14366 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 14367 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 14368 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 14369 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 14370 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 14371 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 14372 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 14373 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 14374 SDValue ValueOnZero = N2; 14375 SDValue Count = N3; 14376 // If the condition is NE instead of E, swap the operands. 14377 if (CC == ISD::SETNE) 14378 std::swap(ValueOnZero, Count); 14379 // Check if the value on zero is a constant equal to the bits in the type. 14380 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 14381 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 14382 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 14383 // legal, combine to just cttz. 14384 if ((Count.getOpcode() == ISD::CTTZ || 14385 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 14386 N0 == Count.getOperand(0) && 14387 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 14388 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 14389 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 14390 // legal, combine to just ctlz. 14391 if ((Count.getOpcode() == ISD::CTLZ || 14392 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 14393 N0 == Count.getOperand(0) && 14394 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 14395 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 14396 } 14397 } 14398 } 14399 14400 return SDValue(); 14401 } 14402 14403 /// This is a stub for TargetLowering::SimplifySetCC. 14404 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 14405 SDValue N1, ISD::CondCode Cond, 14406 SDLoc DL, bool foldBooleans) { 14407 TargetLowering::DAGCombinerInfo 14408 DagCombineInfo(DAG, Level, false, this); 14409 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 14410 } 14411 14412 /// Given an ISD::SDIV node expressing a divide by constant, return 14413 /// a DAG expression to select that will generate the same value by multiplying 14414 /// by a magic number. 14415 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14416 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 14417 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14418 if (!C) 14419 return SDValue(); 14420 14421 // Avoid division by zero. 14422 if (C->isNullValue()) 14423 return SDValue(); 14424 14425 std::vector<SDNode*> Built; 14426 SDValue S = 14427 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14428 14429 for (SDNode *N : Built) 14430 AddToWorklist(N); 14431 return S; 14432 } 14433 14434 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 14435 /// DAG expression that will generate the same value by right shifting. 14436 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 14437 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14438 if (!C) 14439 return SDValue(); 14440 14441 // Avoid division by zero. 14442 if (C->isNullValue()) 14443 return SDValue(); 14444 14445 std::vector<SDNode *> Built; 14446 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 14447 14448 for (SDNode *N : Built) 14449 AddToWorklist(N); 14450 return S; 14451 } 14452 14453 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 14454 /// expression that will generate the same value by multiplying by a magic 14455 /// number. 14456 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 14457 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 14458 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 14459 if (!C) 14460 return SDValue(); 14461 14462 // Avoid division by zero. 14463 if (C->isNullValue()) 14464 return SDValue(); 14465 14466 std::vector<SDNode*> Built; 14467 SDValue S = 14468 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 14469 14470 for (SDNode *N : Built) 14471 AddToWorklist(N); 14472 return S; 14473 } 14474 14475 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) { 14476 if (Level >= AfterLegalizeDAG) 14477 return SDValue(); 14478 14479 // Expose the DAG combiner to the target combiner implementations. 14480 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14481 14482 unsigned Iterations = 0; 14483 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 14484 if (Iterations) { 14485 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14486 // For the reciprocal, we need to find the zero of the function: 14487 // F(X) = A X - 1 [which has a zero at X = 1/A] 14488 // => 14489 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 14490 // does not require additional intermediate precision] 14491 EVT VT = Op.getValueType(); 14492 SDLoc DL(Op); 14493 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14494 14495 AddToWorklist(Est.getNode()); 14496 14497 // Newton iterations: Est = Est + Est (1 - Arg * Est) 14498 for (unsigned i = 0; i < Iterations; ++i) { 14499 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 14500 AddToWorklist(NewEst.getNode()); 14501 14502 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 14503 AddToWorklist(NewEst.getNode()); 14504 14505 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14506 AddToWorklist(NewEst.getNode()); 14507 14508 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 14509 AddToWorklist(Est.getNode()); 14510 } 14511 } 14512 return Est; 14513 } 14514 14515 return SDValue(); 14516 } 14517 14518 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14519 /// For the reciprocal sqrt, we need to find the zero of the function: 14520 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14521 /// => 14522 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 14523 /// As a result, we precompute A/2 prior to the iteration loop. 14524 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 14525 unsigned Iterations, 14526 SDNodeFlags *Flags) { 14527 EVT VT = Arg.getValueType(); 14528 SDLoc DL(Arg); 14529 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 14530 14531 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 14532 // this entire sequence requires only one FP constant. 14533 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 14534 AddToWorklist(HalfArg.getNode()); 14535 14536 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 14537 AddToWorklist(HalfArg.getNode()); 14538 14539 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 14540 for (unsigned i = 0; i < Iterations; ++i) { 14541 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14542 AddToWorklist(NewEst.getNode()); 14543 14544 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 14545 AddToWorklist(NewEst.getNode()); 14546 14547 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 14548 AddToWorklist(NewEst.getNode()); 14549 14550 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 14551 AddToWorklist(Est.getNode()); 14552 } 14553 return Est; 14554 } 14555 14556 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 14557 /// For the reciprocal sqrt, we need to find the zero of the function: 14558 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 14559 /// => 14560 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 14561 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 14562 unsigned Iterations, 14563 SDNodeFlags *Flags) { 14564 EVT VT = Arg.getValueType(); 14565 SDLoc DL(Arg); 14566 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 14567 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 14568 14569 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 14570 for (unsigned i = 0; i < Iterations; ++i) { 14571 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 14572 AddToWorklist(HalfEst.getNode()); 14573 14574 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 14575 AddToWorklist(Est.getNode()); 14576 14577 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 14578 AddToWorklist(Est.getNode()); 14579 14580 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags); 14581 AddToWorklist(Est.getNode()); 14582 14583 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags); 14584 AddToWorklist(Est.getNode()); 14585 } 14586 return Est; 14587 } 14588 14589 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) { 14590 if (Level >= AfterLegalizeDAG) 14591 return SDValue(); 14592 14593 // Expose the DAG combiner to the target combiner implementations. 14594 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 14595 unsigned Iterations = 0; 14596 bool UseOneConstNR = false; 14597 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 14598 AddToWorklist(Est.getNode()); 14599 if (Iterations) { 14600 Est = UseOneConstNR ? 14601 BuildRsqrtNROneConst(Op, Est, Iterations, Flags) : 14602 BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags); 14603 } 14604 return Est; 14605 } 14606 14607 return SDValue(); 14608 } 14609 14610 /// Return true if base is a frame index, which is known not to alias with 14611 /// anything but itself. Provides base object and offset as results. 14612 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 14613 const GlobalValue *&GV, const void *&CV) { 14614 // Assume it is a primitive operation. 14615 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 14616 14617 // If it's an adding a simple constant then integrate the offset. 14618 if (Base.getOpcode() == ISD::ADD) { 14619 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 14620 Base = Base.getOperand(0); 14621 Offset += C->getZExtValue(); 14622 } 14623 } 14624 14625 // Return the underlying GlobalValue, and update the Offset. Return false 14626 // for GlobalAddressSDNode since the same GlobalAddress may be represented 14627 // by multiple nodes with different offsets. 14628 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 14629 GV = G->getGlobal(); 14630 Offset += G->getOffset(); 14631 return false; 14632 } 14633 14634 // Return the underlying Constant value, and update the Offset. Return false 14635 // for ConstantSDNodes since the same constant pool entry may be represented 14636 // by multiple nodes with different offsets. 14637 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 14638 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 14639 : (const void *)C->getConstVal(); 14640 Offset += C->getOffset(); 14641 return false; 14642 } 14643 // If it's any of the following then it can't alias with anything but itself. 14644 return isa<FrameIndexSDNode>(Base); 14645 } 14646 14647 /// Return true if there is any possibility that the two addresses overlap. 14648 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 14649 // If they are the same then they must be aliases. 14650 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 14651 14652 // If they are both volatile then they cannot be reordered. 14653 if (Op0->isVolatile() && Op1->isVolatile()) return true; 14654 14655 // If one operation reads from invariant memory, and the other may store, they 14656 // cannot alias. These should really be checking the equivalent of mayWrite, 14657 // but it only matters for memory nodes other than load /store. 14658 if (Op0->isInvariant() && Op1->writeMem()) 14659 return false; 14660 14661 if (Op1->isInvariant() && Op0->writeMem()) 14662 return false; 14663 14664 // Gather base node and offset information. 14665 SDValue Base1, Base2; 14666 int64_t Offset1, Offset2; 14667 const GlobalValue *GV1, *GV2; 14668 const void *CV1, *CV2; 14669 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 14670 Base1, Offset1, GV1, CV1); 14671 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 14672 Base2, Offset2, GV2, CV2); 14673 14674 // If they have a same base address then check to see if they overlap. 14675 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 14676 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14677 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14678 14679 // It is possible for different frame indices to alias each other, mostly 14680 // when tail call optimization reuses return address slots for arguments. 14681 // To catch this case, look up the actual index of frame indices to compute 14682 // the real alias relationship. 14683 if (isFrameIndex1 && isFrameIndex2) { 14684 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 14685 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 14686 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 14687 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 14688 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 14689 } 14690 14691 // Otherwise, if we know what the bases are, and they aren't identical, then 14692 // we know they cannot alias. 14693 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 14694 return false; 14695 14696 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 14697 // compared to the size and offset of the access, we may be able to prove they 14698 // do not alias. This check is conservative for now to catch cases created by 14699 // splitting vector types. 14700 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 14701 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 14702 (Op0->getMemoryVT().getSizeInBits() >> 3 == 14703 Op1->getMemoryVT().getSizeInBits() >> 3) && 14704 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 14705 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 14706 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 14707 14708 // There is no overlap between these relatively aligned accesses of similar 14709 // size, return no alias. 14710 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 14711 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 14712 return false; 14713 } 14714 14715 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 14716 ? CombinerGlobalAA 14717 : DAG.getSubtarget().useAA(); 14718 #ifndef NDEBUG 14719 if (CombinerAAOnlyFunc.getNumOccurrences() && 14720 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 14721 UseAA = false; 14722 #endif 14723 if (UseAA && 14724 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 14725 // Use alias analysis information. 14726 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 14727 Op1->getSrcValueOffset()); 14728 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 14729 Op0->getSrcValueOffset() - MinOffset; 14730 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 14731 Op1->getSrcValueOffset() - MinOffset; 14732 AliasResult AAResult = 14733 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1, 14734 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 14735 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2, 14736 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 14737 if (AAResult == NoAlias) 14738 return false; 14739 } 14740 14741 // Otherwise we have to assume they alias. 14742 return true; 14743 } 14744 14745 /// Walk up chain skipping non-aliasing memory nodes, 14746 /// looking for aliasing nodes and adding them to the Aliases vector. 14747 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 14748 SmallVectorImpl<SDValue> &Aliases) { 14749 SmallVector<SDValue, 8> Chains; // List of chains to visit. 14750 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 14751 14752 // Get alias information for node. 14753 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 14754 14755 // Starting off. 14756 Chains.push_back(OriginalChain); 14757 unsigned Depth = 0; 14758 14759 // Look at each chain and determine if it is an alias. If so, add it to the 14760 // aliases list. If not, then continue up the chain looking for the next 14761 // candidate. 14762 while (!Chains.empty()) { 14763 SDValue Chain = Chains.pop_back_val(); 14764 14765 // For TokenFactor nodes, look at each operand and only continue up the 14766 // chain until we reach the depth limit. 14767 // 14768 // FIXME: The depth check could be made to return the last non-aliasing 14769 // chain we found before we hit a tokenfactor rather than the original 14770 // chain. 14771 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 14772 Aliases.clear(); 14773 Aliases.push_back(OriginalChain); 14774 return; 14775 } 14776 14777 // Don't bother if we've been before. 14778 if (!Visited.insert(Chain.getNode()).second) 14779 continue; 14780 14781 switch (Chain.getOpcode()) { 14782 case ISD::EntryToken: 14783 // Entry token is ideal chain operand, but handled in FindBetterChain. 14784 break; 14785 14786 case ISD::LOAD: 14787 case ISD::STORE: { 14788 // Get alias information for Chain. 14789 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 14790 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 14791 14792 // If chain is alias then stop here. 14793 if (!(IsLoad && IsOpLoad) && 14794 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 14795 Aliases.push_back(Chain); 14796 } else { 14797 // Look further up the chain. 14798 Chains.push_back(Chain.getOperand(0)); 14799 ++Depth; 14800 } 14801 break; 14802 } 14803 14804 case ISD::TokenFactor: 14805 // We have to check each of the operands of the token factor for "small" 14806 // token factors, so we queue them up. Adding the operands to the queue 14807 // (stack) in reverse order maintains the original order and increases the 14808 // likelihood that getNode will find a matching token factor (CSE.) 14809 if (Chain.getNumOperands() > 16) { 14810 Aliases.push_back(Chain); 14811 break; 14812 } 14813 for (unsigned n = Chain.getNumOperands(); n;) 14814 Chains.push_back(Chain.getOperand(--n)); 14815 ++Depth; 14816 break; 14817 14818 default: 14819 // For all other instructions we will just have to take what we can get. 14820 Aliases.push_back(Chain); 14821 break; 14822 } 14823 } 14824 } 14825 14826 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 14827 /// (aliasing node.) 14828 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 14829 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 14830 14831 // Accumulate all the aliases to this node. 14832 GatherAllAliases(N, OldChain, Aliases); 14833 14834 // If no operands then chain to entry token. 14835 if (Aliases.size() == 0) 14836 return DAG.getEntryNode(); 14837 14838 // If a single operand then chain to it. We don't need to revisit it. 14839 if (Aliases.size() == 1) 14840 return Aliases[0]; 14841 14842 // Construct a custom tailored token factor. 14843 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 14844 } 14845 14846 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) { 14847 // This holds the base pointer, index, and the offset in bytes from the base 14848 // pointer. 14849 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG); 14850 14851 // We must have a base and an offset. 14852 if (!BasePtr.Base.getNode()) 14853 return false; 14854 14855 // Do not handle stores to undef base pointers. 14856 if (BasePtr.Base.isUndef()) 14857 return false; 14858 14859 SmallVector<StoreSDNode *, 8> ChainedStores; 14860 ChainedStores.push_back(St); 14861 14862 // Walk up the chain and look for nodes with offsets from the same 14863 // base pointer. Stop when reaching an instruction with a different kind 14864 // or instruction which has a different base pointer. 14865 StoreSDNode *Index = St; 14866 while (Index) { 14867 // If the chain has more than one use, then we can't reorder the mem ops. 14868 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 14869 break; 14870 14871 if (Index->isVolatile() || Index->isIndexed()) 14872 break; 14873 14874 // Find the base pointer and offset for this memory node. 14875 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG); 14876 14877 // Check that the base pointer is the same as the original one. 14878 if (!Ptr.equalBaseIndex(BasePtr)) 14879 break; 14880 14881 // Find the next memory operand in the chain. If the next operand in the 14882 // chain is a store then move up and continue the scan with the next 14883 // memory operand. If the next operand is a load save it and use alias 14884 // information to check if it interferes with anything. 14885 SDNode *NextInChain = Index->getChain().getNode(); 14886 while (true) { 14887 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 14888 // We found a store node. Use it for the next iteration. 14889 if (STn->isVolatile() || STn->isIndexed()) { 14890 Index = nullptr; 14891 break; 14892 } 14893 ChainedStores.push_back(STn); 14894 Index = STn; 14895 break; 14896 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 14897 NextInChain = Ldn->getChain().getNode(); 14898 continue; 14899 } else { 14900 Index = nullptr; 14901 break; 14902 } 14903 } 14904 } 14905 14906 bool MadeChange = false; 14907 SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains; 14908 14909 for (StoreSDNode *ChainedStore : ChainedStores) { 14910 SDValue Chain = ChainedStore->getChain(); 14911 SDValue BetterChain = FindBetterChain(ChainedStore, Chain); 14912 14913 if (Chain != BetterChain) { 14914 MadeChange = true; 14915 BetterChains.push_back(std::make_pair(ChainedStore, BetterChain)); 14916 } 14917 } 14918 14919 // Do all replacements after finding the replacements to make to avoid making 14920 // the chains more complicated by introducing new TokenFactors. 14921 for (auto Replacement : BetterChains) 14922 replaceStoreChain(Replacement.first, Replacement.second); 14923 14924 return MadeChange; 14925 } 14926 14927 /// This is the entry point for the file. 14928 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 14929 CodeGenOpt::Level OptLevel) { 14930 /// This is the main entry point to this class. 14931 DAGCombiner(*this, AA, OptLevel).Run(Level); 14932 } 14933