1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/SelectionDAG.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetLowering.h" 37 #include "llvm/Target/TargetOptions.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 #define DEBUG_TYPE "dagcombine" 44 45 STATISTIC(NodesCombined , "Number of dag nodes combined"); 46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 50 STATISTIC(SlicedLoads, "Number of load sliced"); 51 52 namespace { 53 static cl::opt<bool> 54 CombinerAA("combiner-alias-analysis", cl::Hidden, 55 cl::desc("Enable DAG combiner alias-analysis heuristics")); 56 57 static cl::opt<bool> 58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 59 cl::desc("Enable DAG combiner's use of IR alias analysis")); 60 61 static cl::opt<bool> 62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 63 cl::desc("Enable DAG combiner's use of TBAA")); 64 65 #ifndef NDEBUG 66 static cl::opt<std::string> 67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 68 cl::desc("Only use DAG-combiner alias analysis in this" 69 " function")); 70 #endif 71 72 /// Hidden option to stress test load slicing, i.e., when this option 73 /// is enabled, load slicing bypasses most of its profitability guards. 74 static cl::opt<bool> 75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 76 cl::desc("Bypass the profitability model of load " 77 "slicing"), 78 cl::init(false)); 79 80 static cl::opt<bool> 81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 82 cl::desc("DAG combiner may split indexing from loads")); 83 84 //------------------------------ DAGCombiner ---------------------------------// 85 86 class DAGCombiner { 87 SelectionDAG &DAG; 88 const TargetLowering &TLI; 89 CombineLevel Level; 90 CodeGenOpt::Level OptLevel; 91 bool LegalOperations; 92 bool LegalTypes; 93 bool ForCodeSize; 94 95 /// \brief Worklist of all of the nodes that need to be simplified. 96 /// 97 /// This must behave as a stack -- new nodes to process are pushed onto the 98 /// back and when processing we pop off of the back. 99 /// 100 /// The worklist will not contain duplicates but may contain null entries 101 /// due to nodes being deleted from the underlying DAG. 102 SmallVector<SDNode *, 64> Worklist; 103 104 /// \brief Mapping from an SDNode to its position on the worklist. 105 /// 106 /// This is used to find and remove nodes from the worklist (by nulling 107 /// them) when they are deleted from the underlying DAG. It relies on 108 /// stable indices of nodes within the worklist. 109 DenseMap<SDNode *, unsigned> WorklistMap; 110 111 /// \brief Set of nodes which have been combined (at least once). 112 /// 113 /// This is used to allow us to reliably add any operands of a DAG node 114 /// which have not yet been combined to the worklist. 115 SmallPtrSet<SDNode *, 64> CombinedNodes; 116 117 // AA - Used for DAG load/store alias analysis. 118 AliasAnalysis &AA; 119 120 /// When an instruction is simplified, add all users of the instruction to 121 /// the work lists because they might get more simplified now. 122 void AddUsersToWorklist(SDNode *N) { 123 for (SDNode *Node : N->uses()) 124 AddToWorklist(Node); 125 } 126 127 /// Call the node-specific routine that folds each particular type of node. 128 SDValue visit(SDNode *N); 129 130 public: 131 /// Add to the worklist making sure its instance is at the back (next to be 132 /// processed.) 133 void AddToWorklist(SDNode *N) { 134 // Skip handle nodes as they can't usefully be combined and confuse the 135 // zero-use deletion strategy. 136 if (N->getOpcode() == ISD::HANDLENODE) 137 return; 138 139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 140 Worklist.push_back(N); 141 } 142 143 /// Remove all instances of N from the worklist. 144 void removeFromWorklist(SDNode *N) { 145 CombinedNodes.erase(N); 146 147 auto It = WorklistMap.find(N); 148 if (It == WorklistMap.end()) 149 return; // Not in the worklist. 150 151 // Null out the entry rather than erasing it to avoid a linear operation. 152 Worklist[It->second] = nullptr; 153 WorklistMap.erase(It); 154 } 155 156 void deleteAndRecombine(SDNode *N); 157 bool recursivelyDeleteUnusedNodes(SDNode *N); 158 159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 160 bool AddTo = true); 161 162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 163 return CombineTo(N, &Res, 1, AddTo); 164 } 165 166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 167 bool AddTo = true) { 168 SDValue To[] = { Res0, Res1 }; 169 return CombineTo(N, To, 2, AddTo); 170 } 171 172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 173 174 private: 175 176 /// Check the specified integer node value to see if it can be simplified or 177 /// if things it uses can be simplified by bit propagation. 178 /// If so, return true. 179 bool SimplifyDemandedBits(SDValue Op) { 180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 181 APInt Demanded = APInt::getAllOnesValue(BitWidth); 182 return SimplifyDemandedBits(Op, Demanded); 183 } 184 185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 186 187 bool CombineToPreIndexedLoadStore(SDNode *N); 188 bool CombineToPostIndexedLoadStore(SDNode *N); 189 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 190 bool SliceUpLoad(SDNode *N); 191 192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 193 /// load. 194 /// 195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 197 /// \param EltNo index of the vector element to load. 198 /// \param OriginalLoad load that EVE came from to be replaced. 199 /// \returns EVE on success SDValue() on failure. 200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 206 SDValue PromoteIntBinOp(SDValue Op); 207 SDValue PromoteIntShiftOp(SDValue Op); 208 SDValue PromoteExtend(SDValue Op); 209 bool PromoteLoad(SDValue Op); 210 211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 212 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 213 ISD::NodeType ExtType); 214 215 /// Call the node-specific routine that knows how to fold each 216 /// particular type of node. If that doesn't do anything, try the 217 /// target-specific DAG combines. 218 SDValue combine(SDNode *N); 219 220 // Visitation implementation - Implement dag node combining for different 221 // node types. The semantics are as follows: 222 // Return Value: 223 // SDValue.getNode() == 0 - No change was made 224 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 225 // otherwise - N should be replaced by the returned Operand. 226 // 227 SDValue visitTokenFactor(SDNode *N); 228 SDValue visitMERGE_VALUES(SDNode *N); 229 SDValue visitADD(SDNode *N); 230 SDValue visitSUB(SDNode *N); 231 SDValue visitADDC(SDNode *N); 232 SDValue visitSUBC(SDNode *N); 233 SDValue visitADDE(SDNode *N); 234 SDValue visitSUBE(SDNode *N); 235 SDValue visitMUL(SDNode *N); 236 SDValue visitSDIV(SDNode *N); 237 SDValue visitUDIV(SDNode *N); 238 SDValue visitSREM(SDNode *N); 239 SDValue visitUREM(SDNode *N); 240 SDValue visitMULHU(SDNode *N); 241 SDValue visitMULHS(SDNode *N); 242 SDValue visitSMUL_LOHI(SDNode *N); 243 SDValue visitUMUL_LOHI(SDNode *N); 244 SDValue visitSMULO(SDNode *N); 245 SDValue visitUMULO(SDNode *N); 246 SDValue visitSDIVREM(SDNode *N); 247 SDValue visitUDIVREM(SDNode *N); 248 SDValue visitAND(SDNode *N); 249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 250 SDValue visitOR(SDNode *N); 251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 252 SDValue visitXOR(SDNode *N); 253 SDValue SimplifyVBinOp(SDNode *N); 254 SDValue visitSHL(SDNode *N); 255 SDValue visitSRA(SDNode *N); 256 SDValue visitSRL(SDNode *N); 257 SDValue visitRotate(SDNode *N); 258 SDValue visitCTLZ(SDNode *N); 259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 260 SDValue visitCTTZ(SDNode *N); 261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 262 SDValue visitCTPOP(SDNode *N); 263 SDValue visitSELECT(SDNode *N); 264 SDValue visitVSELECT(SDNode *N); 265 SDValue visitSELECT_CC(SDNode *N); 266 SDValue visitSETCC(SDNode *N); 267 SDValue visitSIGN_EXTEND(SDNode *N); 268 SDValue visitZERO_EXTEND(SDNode *N); 269 SDValue visitANY_EXTEND(SDNode *N); 270 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 271 SDValue visitTRUNCATE(SDNode *N); 272 SDValue visitBITCAST(SDNode *N); 273 SDValue visitBUILD_PAIR(SDNode *N); 274 SDValue visitFADD(SDNode *N); 275 SDValue visitFSUB(SDNode *N); 276 SDValue visitFMUL(SDNode *N); 277 SDValue visitFMA(SDNode *N); 278 SDValue visitFDIV(SDNode *N); 279 SDValue visitFREM(SDNode *N); 280 SDValue visitFSQRT(SDNode *N); 281 SDValue visitFCOPYSIGN(SDNode *N); 282 SDValue visitSINT_TO_FP(SDNode *N); 283 SDValue visitUINT_TO_FP(SDNode *N); 284 SDValue visitFP_TO_SINT(SDNode *N); 285 SDValue visitFP_TO_UINT(SDNode *N); 286 SDValue visitFP_ROUND(SDNode *N); 287 SDValue visitFP_ROUND_INREG(SDNode *N); 288 SDValue visitFP_EXTEND(SDNode *N); 289 SDValue visitFNEG(SDNode *N); 290 SDValue visitFABS(SDNode *N); 291 SDValue visitFCEIL(SDNode *N); 292 SDValue visitFTRUNC(SDNode *N); 293 SDValue visitFFLOOR(SDNode *N); 294 SDValue visitFMINNUM(SDNode *N); 295 SDValue visitFMAXNUM(SDNode *N); 296 SDValue visitBRCOND(SDNode *N); 297 SDValue visitBR_CC(SDNode *N); 298 SDValue visitLOAD(SDNode *N); 299 SDValue visitSTORE(SDNode *N); 300 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 301 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 302 SDValue visitBUILD_VECTOR(SDNode *N); 303 SDValue visitCONCAT_VECTORS(SDNode *N); 304 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 305 SDValue visitVECTOR_SHUFFLE(SDNode *N); 306 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 307 SDValue visitINSERT_SUBVECTOR(SDNode *N); 308 SDValue visitMLOAD(SDNode *N); 309 SDValue visitMSTORE(SDNode *N); 310 SDValue visitFP_TO_FP16(SDNode *N); 311 312 SDValue visitFADDForFMACombine(SDNode *N); 313 SDValue visitFSUBForFMACombine(SDNode *N); 314 315 SDValue XformToShuffleWithZero(SDNode *N); 316 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 317 318 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 319 320 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 321 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 322 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 323 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 324 SDValue N3, ISD::CondCode CC, 325 bool NotExtCompare = false); 326 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 327 SDLoc DL, bool foldBooleans = true); 328 329 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 330 SDValue &CC) const; 331 bool isOneUseSetCC(SDValue N) const; 332 333 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 334 unsigned HiOp); 335 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 336 SDValue CombineExtLoad(SDNode *N); 337 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 338 SDValue BuildSDIV(SDNode *N); 339 SDValue BuildSDIVPow2(SDNode *N); 340 SDValue BuildUDIV(SDNode *N); 341 SDValue BuildReciprocalEstimate(SDValue Op); 342 SDValue BuildRsqrtEstimate(SDValue Op); 343 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations); 344 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations); 345 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 346 bool DemandHighBits = true); 347 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 348 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 349 SDValue InnerPos, SDValue InnerNeg, 350 unsigned PosOpcode, unsigned NegOpcode, 351 SDLoc DL); 352 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 353 SDValue ReduceLoadWidth(SDNode *N); 354 SDValue ReduceLoadOpStoreWidth(SDNode *N); 355 SDValue TransformFPLoadStorePair(SDNode *N); 356 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 357 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 358 359 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 360 361 /// Walk up chain skipping non-aliasing memory nodes, 362 /// looking for aliasing nodes and adding them to the Aliases vector. 363 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 364 SmallVectorImpl<SDValue> &Aliases); 365 366 /// Return true if there is any possibility that the two addresses overlap. 367 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 368 369 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 370 /// chain (aliasing node.) 371 SDValue FindBetterChain(SDNode *N, SDValue Chain); 372 373 /// Holds a pointer to an LSBaseSDNode as well as information on where it 374 /// is located in a sequence of memory operations connected by a chain. 375 struct MemOpLink { 376 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 377 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 378 // Ptr to the mem node. 379 LSBaseSDNode *MemNode; 380 // Offset from the base ptr. 381 int64_t OffsetFromBase; 382 // What is the sequence number of this mem node. 383 // Lowest mem operand in the DAG starts at zero. 384 unsigned SequenceNum; 385 }; 386 387 /// This is a helper function for MergeConsecutiveStores. When the source 388 /// elements of the consecutive stores are all constants or all extracted 389 /// vector elements, try to merge them into one larger store. 390 /// \return True if a merged store was created. 391 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 392 EVT MemVT, unsigned NumElem, 393 bool IsConstantSrc, bool UseVector); 394 395 /// Merge consecutive store operations into a wide store. 396 /// This optimization uses wide integers or vectors when possible. 397 /// \return True if some memory operations were changed. 398 bool MergeConsecutiveStores(StoreSDNode *N); 399 400 /// \brief Try to transform a truncation where C is a constant: 401 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 402 /// 403 /// \p N needs to be a truncation and its first operand an AND. Other 404 /// requirements are checked by the function (e.g. that trunc is 405 /// single-use) and if missed an empty SDValue is returned. 406 SDValue distributeTruncateThroughAnd(SDNode *N); 407 408 public: 409 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 410 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 411 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 412 auto *F = DAG.getMachineFunction().getFunction(); 413 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) || 414 F->hasFnAttribute(Attribute::MinSize); 415 } 416 417 /// Runs the dag combiner on all nodes in the work list 418 void Run(CombineLevel AtLevel); 419 420 SelectionDAG &getDAG() const { return DAG; } 421 422 /// Returns a type large enough to hold any valid shift amount - before type 423 /// legalization these can be huge. 424 EVT getShiftAmountTy(EVT LHSTy) { 425 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 426 if (LHSTy.isVector()) 427 return LHSTy; 428 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 429 : TLI.getPointerTy(); 430 } 431 432 /// This method returns true if we are running before type legalization or 433 /// if the specified VT is legal. 434 bool isTypeLegal(const EVT &VT) { 435 if (!LegalTypes) return true; 436 return TLI.isTypeLegal(VT); 437 } 438 439 /// Convenience wrapper around TargetLowering::getSetCCResultType 440 EVT getSetCCResultType(EVT VT) const { 441 return TLI.getSetCCResultType(*DAG.getContext(), VT); 442 } 443 }; 444 } 445 446 447 namespace { 448 /// This class is a DAGUpdateListener that removes any deleted 449 /// nodes from the worklist. 450 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 451 DAGCombiner &DC; 452 public: 453 explicit WorklistRemover(DAGCombiner &dc) 454 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 455 456 void NodeDeleted(SDNode *N, SDNode *E) override { 457 DC.removeFromWorklist(N); 458 } 459 }; 460 } 461 462 //===----------------------------------------------------------------------===// 463 // TargetLowering::DAGCombinerInfo implementation 464 //===----------------------------------------------------------------------===// 465 466 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 467 ((DAGCombiner*)DC)->AddToWorklist(N); 468 } 469 470 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 471 ((DAGCombiner*)DC)->removeFromWorklist(N); 472 } 473 474 SDValue TargetLowering::DAGCombinerInfo:: 475 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 476 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 477 } 478 479 SDValue TargetLowering::DAGCombinerInfo:: 480 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 481 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 482 } 483 484 485 SDValue TargetLowering::DAGCombinerInfo:: 486 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 487 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 488 } 489 490 void TargetLowering::DAGCombinerInfo:: 491 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 492 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 493 } 494 495 //===----------------------------------------------------------------------===// 496 // Helper Functions 497 //===----------------------------------------------------------------------===// 498 499 void DAGCombiner::deleteAndRecombine(SDNode *N) { 500 removeFromWorklist(N); 501 502 // If the operands of this node are only used by the node, they will now be 503 // dead. Make sure to re-visit them and recursively delete dead nodes. 504 for (const SDValue &Op : N->ops()) 505 // For an operand generating multiple values, one of the values may 506 // become dead allowing further simplification (e.g. split index 507 // arithmetic from an indexed load). 508 if (Op->hasOneUse() || Op->getNumValues() > 1) 509 AddToWorklist(Op.getNode()); 510 511 DAG.DeleteNode(N); 512 } 513 514 /// Return 1 if we can compute the negated form of the specified expression for 515 /// the same cost as the expression itself, or 2 if we can compute the negated 516 /// form more cheaply than the expression itself. 517 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 518 const TargetLowering &TLI, 519 const TargetOptions *Options, 520 unsigned Depth = 0) { 521 // fneg is removable even if it has multiple uses. 522 if (Op.getOpcode() == ISD::FNEG) return 2; 523 524 // Don't allow anything with multiple uses. 525 if (!Op.hasOneUse()) return 0; 526 527 // Don't recurse exponentially. 528 if (Depth > 6) return 0; 529 530 switch (Op.getOpcode()) { 531 default: return false; 532 case ISD::ConstantFP: 533 // Don't invert constant FP values after legalize. The negated constant 534 // isn't necessarily legal. 535 return LegalOperations ? 0 : 1; 536 case ISD::FADD: 537 // FIXME: determine better conditions for this xform. 538 if (!Options->UnsafeFPMath) return 0; 539 540 // After operation legalization, it might not be legal to create new FSUBs. 541 if (LegalOperations && 542 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 543 return 0; 544 545 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 546 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 547 Options, Depth + 1)) 548 return V; 549 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 550 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 551 Depth + 1); 552 case ISD::FSUB: 553 // We can't turn -(A-B) into B-A when we honor signed zeros. 554 if (!Options->UnsafeFPMath) return 0; 555 556 // fold (fneg (fsub A, B)) -> (fsub B, A) 557 return 1; 558 559 case ISD::FMUL: 560 case ISD::FDIV: 561 if (Options->HonorSignDependentRoundingFPMath()) return 0; 562 563 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 564 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 565 Options, Depth + 1)) 566 return V; 567 568 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 569 Depth + 1); 570 571 case ISD::FP_EXTEND: 572 case ISD::FP_ROUND: 573 case ISD::FSIN: 574 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 575 Depth + 1); 576 } 577 } 578 579 /// If isNegatibleForFree returns true, return the newly negated expression. 580 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 581 bool LegalOperations, unsigned Depth = 0) { 582 const TargetOptions &Options = DAG.getTarget().Options; 583 // fneg is removable even if it has multiple uses. 584 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 585 586 // Don't allow anything with multiple uses. 587 assert(Op.hasOneUse() && "Unknown reuse!"); 588 589 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 590 switch (Op.getOpcode()) { 591 default: llvm_unreachable("Unknown code"); 592 case ISD::ConstantFP: { 593 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 594 V.changeSign(); 595 return DAG.getConstantFP(V, Op.getValueType()); 596 } 597 case ISD::FADD: 598 // FIXME: determine better conditions for this xform. 599 assert(Options.UnsafeFPMath); 600 601 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 602 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 603 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 604 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 605 GetNegatedExpression(Op.getOperand(0), DAG, 606 LegalOperations, Depth+1), 607 Op.getOperand(1)); 608 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 609 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 610 GetNegatedExpression(Op.getOperand(1), DAG, 611 LegalOperations, Depth+1), 612 Op.getOperand(0)); 613 case ISD::FSUB: 614 // We can't turn -(A-B) into B-A when we honor signed zeros. 615 assert(Options.UnsafeFPMath); 616 617 // fold (fneg (fsub 0, B)) -> B 618 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 619 if (N0CFP->getValueAPF().isZero()) 620 return Op.getOperand(1); 621 622 // fold (fneg (fsub A, B)) -> (fsub B, A) 623 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 624 Op.getOperand(1), Op.getOperand(0)); 625 626 case ISD::FMUL: 627 case ISD::FDIV: 628 assert(!Options.HonorSignDependentRoundingFPMath()); 629 630 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 631 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 632 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 633 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 634 GetNegatedExpression(Op.getOperand(0), DAG, 635 LegalOperations, Depth+1), 636 Op.getOperand(1)); 637 638 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 639 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 640 Op.getOperand(0), 641 GetNegatedExpression(Op.getOperand(1), DAG, 642 LegalOperations, Depth+1)); 643 644 case ISD::FP_EXTEND: 645 case ISD::FSIN: 646 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 647 GetNegatedExpression(Op.getOperand(0), DAG, 648 LegalOperations, Depth+1)); 649 case ISD::FP_ROUND: 650 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 651 GetNegatedExpression(Op.getOperand(0), DAG, 652 LegalOperations, Depth+1), 653 Op.getOperand(1)); 654 } 655 } 656 657 // Return true if this node is a setcc, or is a select_cc 658 // that selects between the target values used for true and false, making it 659 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 660 // the appropriate nodes based on the type of node we are checking. This 661 // simplifies life a bit for the callers. 662 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 663 SDValue &CC) const { 664 if (N.getOpcode() == ISD::SETCC) { 665 LHS = N.getOperand(0); 666 RHS = N.getOperand(1); 667 CC = N.getOperand(2); 668 return true; 669 } 670 671 if (N.getOpcode() != ISD::SELECT_CC || 672 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 673 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 674 return false; 675 676 if (TLI.getBooleanContents(N.getValueType()) == 677 TargetLowering::UndefinedBooleanContent) 678 return false; 679 680 LHS = N.getOperand(0); 681 RHS = N.getOperand(1); 682 CC = N.getOperand(4); 683 return true; 684 } 685 686 /// Return true if this is a SetCC-equivalent operation with only one use. 687 /// If this is true, it allows the users to invert the operation for free when 688 /// it is profitable to do so. 689 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 690 SDValue N0, N1, N2; 691 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 692 return true; 693 return false; 694 } 695 696 /// Returns true if N is a BUILD_VECTOR node whose 697 /// elements are all the same constant or undefined. 698 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 699 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 700 if (!C) 701 return false; 702 703 APInt SplatUndef; 704 unsigned SplatBitSize; 705 bool HasAnyUndefs; 706 EVT EltVT = N->getValueType(0).getVectorElementType(); 707 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 708 HasAnyUndefs) && 709 EltVT.getSizeInBits() >= SplatBitSize); 710 } 711 712 // \brief Returns the SDNode if it is a constant integer BuildVector 713 // or constant integer. 714 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) { 715 if (isa<ConstantSDNode>(N)) 716 return N.getNode(); 717 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 718 return N.getNode(); 719 return nullptr; 720 } 721 722 // \brief Returns the SDNode if it is a constant float BuildVector 723 // or constant float. 724 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 725 if (isa<ConstantFPSDNode>(N)) 726 return N.getNode(); 727 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 728 return N.getNode(); 729 return nullptr; 730 } 731 732 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 733 // int. 734 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 735 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 736 return CN; 737 738 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 739 BitVector UndefElements; 740 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 741 742 // BuildVectors can truncate their operands. Ignore that case here. 743 // FIXME: We blindly ignore splats which include undef which is overly 744 // pessimistic. 745 if (CN && UndefElements.none() && 746 CN->getValueType(0) == N.getValueType().getScalarType()) 747 return CN; 748 } 749 750 return nullptr; 751 } 752 753 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 754 // float. 755 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 756 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 757 return CN; 758 759 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 760 BitVector UndefElements; 761 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 762 763 if (CN && UndefElements.none()) 764 return CN; 765 } 766 767 return nullptr; 768 } 769 770 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 771 SDValue N0, SDValue N1) { 772 EVT VT = N0.getValueType(); 773 if (N0.getOpcode() == Opc) { 774 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 775 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) { 776 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 777 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R)) 778 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 779 return SDValue(); 780 } 781 if (N0.hasOneUse()) { 782 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 783 // use 784 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 785 if (!OpNode.getNode()) 786 return SDValue(); 787 AddToWorklist(OpNode.getNode()); 788 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 789 } 790 } 791 } 792 793 if (N1.getOpcode() == Opc) { 794 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 795 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) { 796 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 797 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L)) 798 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 799 return SDValue(); 800 } 801 if (N1.hasOneUse()) { 802 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 803 // use 804 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 805 if (!OpNode.getNode()) 806 return SDValue(); 807 AddToWorklist(OpNode.getNode()); 808 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 809 } 810 } 811 } 812 813 return SDValue(); 814 } 815 816 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 817 bool AddTo) { 818 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 819 ++NodesCombined; 820 DEBUG(dbgs() << "\nReplacing.1 "; 821 N->dump(&DAG); 822 dbgs() << "\nWith: "; 823 To[0].getNode()->dump(&DAG); 824 dbgs() << " and " << NumTo-1 << " other values\n"); 825 for (unsigned i = 0, e = NumTo; i != e; ++i) 826 assert((!To[i].getNode() || 827 N->getValueType(i) == To[i].getValueType()) && 828 "Cannot combine value to value of different type!"); 829 830 WorklistRemover DeadNodes(*this); 831 DAG.ReplaceAllUsesWith(N, To); 832 if (AddTo) { 833 // Push the new nodes and any users onto the worklist 834 for (unsigned i = 0, e = NumTo; i != e; ++i) { 835 if (To[i].getNode()) { 836 AddToWorklist(To[i].getNode()); 837 AddUsersToWorklist(To[i].getNode()); 838 } 839 } 840 } 841 842 // Finally, if the node is now dead, remove it from the graph. The node 843 // may not be dead if the replacement process recursively simplified to 844 // something else needing this node. 845 if (N->use_empty()) 846 deleteAndRecombine(N); 847 return SDValue(N, 0); 848 } 849 850 void DAGCombiner:: 851 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 852 // Replace all uses. If any nodes become isomorphic to other nodes and 853 // are deleted, make sure to remove them from our worklist. 854 WorklistRemover DeadNodes(*this); 855 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 856 857 // Push the new node and any (possibly new) users onto the worklist. 858 AddToWorklist(TLO.New.getNode()); 859 AddUsersToWorklist(TLO.New.getNode()); 860 861 // Finally, if the node is now dead, remove it from the graph. The node 862 // may not be dead if the replacement process recursively simplified to 863 // something else needing this node. 864 if (TLO.Old.getNode()->use_empty()) 865 deleteAndRecombine(TLO.Old.getNode()); 866 } 867 868 /// Check the specified integer node value to see if it can be simplified or if 869 /// things it uses can be simplified by bit propagation. If so, return true. 870 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 871 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 872 APInt KnownZero, KnownOne; 873 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 874 return false; 875 876 // Revisit the node. 877 AddToWorklist(Op.getNode()); 878 879 // Replace the old value with the new one. 880 ++NodesCombined; 881 DEBUG(dbgs() << "\nReplacing.2 "; 882 TLO.Old.getNode()->dump(&DAG); 883 dbgs() << "\nWith: "; 884 TLO.New.getNode()->dump(&DAG); 885 dbgs() << '\n'); 886 887 CommitTargetLoweringOpt(TLO); 888 return true; 889 } 890 891 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 892 SDLoc dl(Load); 893 EVT VT = Load->getValueType(0); 894 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 895 896 DEBUG(dbgs() << "\nReplacing.9 "; 897 Load->dump(&DAG); 898 dbgs() << "\nWith: "; 899 Trunc.getNode()->dump(&DAG); 900 dbgs() << '\n'); 901 WorklistRemover DeadNodes(*this); 902 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 903 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 904 deleteAndRecombine(Load); 905 AddToWorklist(Trunc.getNode()); 906 } 907 908 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 909 Replace = false; 910 SDLoc dl(Op); 911 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 912 EVT MemVT = LD->getMemoryVT(); 913 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 914 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 915 : ISD::EXTLOAD) 916 : LD->getExtensionType(); 917 Replace = true; 918 return DAG.getExtLoad(ExtType, dl, PVT, 919 LD->getChain(), LD->getBasePtr(), 920 MemVT, LD->getMemOperand()); 921 } 922 923 unsigned Opc = Op.getOpcode(); 924 switch (Opc) { 925 default: break; 926 case ISD::AssertSext: 927 return DAG.getNode(ISD::AssertSext, dl, PVT, 928 SExtPromoteOperand(Op.getOperand(0), PVT), 929 Op.getOperand(1)); 930 case ISD::AssertZext: 931 return DAG.getNode(ISD::AssertZext, dl, PVT, 932 ZExtPromoteOperand(Op.getOperand(0), PVT), 933 Op.getOperand(1)); 934 case ISD::Constant: { 935 unsigned ExtOpc = 936 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 937 return DAG.getNode(ExtOpc, dl, PVT, Op); 938 } 939 } 940 941 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 942 return SDValue(); 943 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 944 } 945 946 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 947 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 948 return SDValue(); 949 EVT OldVT = Op.getValueType(); 950 SDLoc dl(Op); 951 bool Replace = false; 952 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 953 if (!NewOp.getNode()) 954 return SDValue(); 955 AddToWorklist(NewOp.getNode()); 956 957 if (Replace) 958 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 959 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 960 DAG.getValueType(OldVT)); 961 } 962 963 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 964 EVT OldVT = Op.getValueType(); 965 SDLoc dl(Op); 966 bool Replace = false; 967 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 968 if (!NewOp.getNode()) 969 return SDValue(); 970 AddToWorklist(NewOp.getNode()); 971 972 if (Replace) 973 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 974 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 975 } 976 977 /// Promote the specified integer binary operation if the target indicates it is 978 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 979 /// i32 since i16 instructions are longer. 980 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 981 if (!LegalOperations) 982 return SDValue(); 983 984 EVT VT = Op.getValueType(); 985 if (VT.isVector() || !VT.isInteger()) 986 return SDValue(); 987 988 // If operation type is 'undesirable', e.g. i16 on x86, consider 989 // promoting it. 990 unsigned Opc = Op.getOpcode(); 991 if (TLI.isTypeDesirableForOp(Opc, VT)) 992 return SDValue(); 993 994 EVT PVT = VT; 995 // Consult target whether it is a good idea to promote this operation and 996 // what's the right type to promote it to. 997 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 998 assert(PVT != VT && "Don't know what type to promote to!"); 999 1000 bool Replace0 = false; 1001 SDValue N0 = Op.getOperand(0); 1002 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1003 if (!NN0.getNode()) 1004 return SDValue(); 1005 1006 bool Replace1 = false; 1007 SDValue N1 = Op.getOperand(1); 1008 SDValue NN1; 1009 if (N0 == N1) 1010 NN1 = NN0; 1011 else { 1012 NN1 = PromoteOperand(N1, PVT, Replace1); 1013 if (!NN1.getNode()) 1014 return SDValue(); 1015 } 1016 1017 AddToWorklist(NN0.getNode()); 1018 if (NN1.getNode()) 1019 AddToWorklist(NN1.getNode()); 1020 1021 if (Replace0) 1022 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1023 if (Replace1) 1024 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1025 1026 DEBUG(dbgs() << "\nPromoting "; 1027 Op.getNode()->dump(&DAG)); 1028 SDLoc dl(Op); 1029 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1030 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1031 } 1032 return SDValue(); 1033 } 1034 1035 /// Promote the specified integer shift operation if the target indicates it is 1036 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1037 /// i32 since i16 instructions are longer. 1038 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1039 if (!LegalOperations) 1040 return SDValue(); 1041 1042 EVT VT = Op.getValueType(); 1043 if (VT.isVector() || !VT.isInteger()) 1044 return SDValue(); 1045 1046 // If operation type is 'undesirable', e.g. i16 on x86, consider 1047 // promoting it. 1048 unsigned Opc = Op.getOpcode(); 1049 if (TLI.isTypeDesirableForOp(Opc, VT)) 1050 return SDValue(); 1051 1052 EVT PVT = VT; 1053 // Consult target whether it is a good idea to promote this operation and 1054 // what's the right type to promote it to. 1055 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1056 assert(PVT != VT && "Don't know what type to promote to!"); 1057 1058 bool Replace = false; 1059 SDValue N0 = Op.getOperand(0); 1060 if (Opc == ISD::SRA) 1061 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1062 else if (Opc == ISD::SRL) 1063 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1064 else 1065 N0 = PromoteOperand(N0, PVT, Replace); 1066 if (!N0.getNode()) 1067 return SDValue(); 1068 1069 AddToWorklist(N0.getNode()); 1070 if (Replace) 1071 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1072 1073 DEBUG(dbgs() << "\nPromoting "; 1074 Op.getNode()->dump(&DAG)); 1075 SDLoc dl(Op); 1076 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1077 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1078 } 1079 return SDValue(); 1080 } 1081 1082 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1083 if (!LegalOperations) 1084 return SDValue(); 1085 1086 EVT VT = Op.getValueType(); 1087 if (VT.isVector() || !VT.isInteger()) 1088 return SDValue(); 1089 1090 // If operation type is 'undesirable', e.g. i16 on x86, consider 1091 // promoting it. 1092 unsigned Opc = Op.getOpcode(); 1093 if (TLI.isTypeDesirableForOp(Opc, VT)) 1094 return SDValue(); 1095 1096 EVT PVT = VT; 1097 // Consult target whether it is a good idea to promote this operation and 1098 // what's the right type to promote it to. 1099 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1100 assert(PVT != VT && "Don't know what type to promote to!"); 1101 // fold (aext (aext x)) -> (aext x) 1102 // fold (aext (zext x)) -> (zext x) 1103 // fold (aext (sext x)) -> (sext x) 1104 DEBUG(dbgs() << "\nPromoting "; 1105 Op.getNode()->dump(&DAG)); 1106 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1107 } 1108 return SDValue(); 1109 } 1110 1111 bool DAGCombiner::PromoteLoad(SDValue Op) { 1112 if (!LegalOperations) 1113 return false; 1114 1115 EVT VT = Op.getValueType(); 1116 if (VT.isVector() || !VT.isInteger()) 1117 return false; 1118 1119 // If operation type is 'undesirable', e.g. i16 on x86, consider 1120 // promoting it. 1121 unsigned Opc = Op.getOpcode(); 1122 if (TLI.isTypeDesirableForOp(Opc, VT)) 1123 return false; 1124 1125 EVT PVT = VT; 1126 // Consult target whether it is a good idea to promote this operation and 1127 // what's the right type to promote it to. 1128 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1129 assert(PVT != VT && "Don't know what type to promote to!"); 1130 1131 SDLoc dl(Op); 1132 SDNode *N = Op.getNode(); 1133 LoadSDNode *LD = cast<LoadSDNode>(N); 1134 EVT MemVT = LD->getMemoryVT(); 1135 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1136 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1137 : ISD::EXTLOAD) 1138 : LD->getExtensionType(); 1139 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1140 LD->getChain(), LD->getBasePtr(), 1141 MemVT, LD->getMemOperand()); 1142 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1143 1144 DEBUG(dbgs() << "\nPromoting "; 1145 N->dump(&DAG); 1146 dbgs() << "\nTo: "; 1147 Result.getNode()->dump(&DAG); 1148 dbgs() << '\n'); 1149 WorklistRemover DeadNodes(*this); 1150 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1151 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1152 deleteAndRecombine(N); 1153 AddToWorklist(Result.getNode()); 1154 return true; 1155 } 1156 return false; 1157 } 1158 1159 /// \brief Recursively delete a node which has no uses and any operands for 1160 /// which it is the only use. 1161 /// 1162 /// Note that this both deletes the nodes and removes them from the worklist. 1163 /// It also adds any nodes who have had a user deleted to the worklist as they 1164 /// may now have only one use and subject to other combines. 1165 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1166 if (!N->use_empty()) 1167 return false; 1168 1169 SmallSetVector<SDNode *, 16> Nodes; 1170 Nodes.insert(N); 1171 do { 1172 N = Nodes.pop_back_val(); 1173 if (!N) 1174 continue; 1175 1176 if (N->use_empty()) { 1177 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1178 Nodes.insert(N->getOperand(i).getNode()); 1179 1180 removeFromWorklist(N); 1181 DAG.DeleteNode(N); 1182 } else { 1183 AddToWorklist(N); 1184 } 1185 } while (!Nodes.empty()); 1186 return true; 1187 } 1188 1189 //===----------------------------------------------------------------------===// 1190 // Main DAG Combiner implementation 1191 //===----------------------------------------------------------------------===// 1192 1193 void DAGCombiner::Run(CombineLevel AtLevel) { 1194 // set the instance variables, so that the various visit routines may use it. 1195 Level = AtLevel; 1196 LegalOperations = Level >= AfterLegalizeVectorOps; 1197 LegalTypes = Level >= AfterLegalizeTypes; 1198 1199 // Add all the dag nodes to the worklist. 1200 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1201 E = DAG.allnodes_end(); I != E; ++I) 1202 AddToWorklist(I); 1203 1204 // Create a dummy node (which is not added to allnodes), that adds a reference 1205 // to the root node, preventing it from being deleted, and tracking any 1206 // changes of the root. 1207 HandleSDNode Dummy(DAG.getRoot()); 1208 1209 // while the worklist isn't empty, find a node and 1210 // try and combine it. 1211 while (!WorklistMap.empty()) { 1212 SDNode *N; 1213 // The Worklist holds the SDNodes in order, but it may contain null entries. 1214 do { 1215 N = Worklist.pop_back_val(); 1216 } while (!N); 1217 1218 bool GoodWorklistEntry = WorklistMap.erase(N); 1219 (void)GoodWorklistEntry; 1220 assert(GoodWorklistEntry && 1221 "Found a worklist entry without a corresponding map entry!"); 1222 1223 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1224 // N is deleted from the DAG, since they too may now be dead or may have a 1225 // reduced number of uses, allowing other xforms. 1226 if (recursivelyDeleteUnusedNodes(N)) 1227 continue; 1228 1229 WorklistRemover DeadNodes(*this); 1230 1231 // If this combine is running after legalizing the DAG, re-legalize any 1232 // nodes pulled off the worklist. 1233 if (Level == AfterLegalizeDAG) { 1234 SmallSetVector<SDNode *, 16> UpdatedNodes; 1235 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1236 1237 for (SDNode *LN : UpdatedNodes) { 1238 AddToWorklist(LN); 1239 AddUsersToWorklist(LN); 1240 } 1241 if (!NIsValid) 1242 continue; 1243 } 1244 1245 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1246 1247 // Add any operands of the new node which have not yet been combined to the 1248 // worklist as well. Because the worklist uniques things already, this 1249 // won't repeatedly process the same operand. 1250 CombinedNodes.insert(N); 1251 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1252 if (!CombinedNodes.count(N->getOperand(i).getNode())) 1253 AddToWorklist(N->getOperand(i).getNode()); 1254 1255 SDValue RV = combine(N); 1256 1257 if (!RV.getNode()) 1258 continue; 1259 1260 ++NodesCombined; 1261 1262 // If we get back the same node we passed in, rather than a new node or 1263 // zero, we know that the node must have defined multiple values and 1264 // CombineTo was used. Since CombineTo takes care of the worklist 1265 // mechanics for us, we have no work to do in this case. 1266 if (RV.getNode() == N) 1267 continue; 1268 1269 assert(N->getOpcode() != ISD::DELETED_NODE && 1270 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1271 "Node was deleted but visit returned new node!"); 1272 1273 DEBUG(dbgs() << " ... into: "; 1274 RV.getNode()->dump(&DAG)); 1275 1276 // Transfer debug value. 1277 DAG.TransferDbgValues(SDValue(N, 0), RV); 1278 if (N->getNumValues() == RV.getNode()->getNumValues()) 1279 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1280 else { 1281 assert(N->getValueType(0) == RV.getValueType() && 1282 N->getNumValues() == 1 && "Type mismatch"); 1283 SDValue OpV = RV; 1284 DAG.ReplaceAllUsesWith(N, &OpV); 1285 } 1286 1287 // Push the new node and any users onto the worklist 1288 AddToWorklist(RV.getNode()); 1289 AddUsersToWorklist(RV.getNode()); 1290 1291 // Finally, if the node is now dead, remove it from the graph. The node 1292 // may not be dead if the replacement process recursively simplified to 1293 // something else needing this node. This will also take care of adding any 1294 // operands which have lost a user to the worklist. 1295 recursivelyDeleteUnusedNodes(N); 1296 } 1297 1298 // If the root changed (e.g. it was a dead load, update the root). 1299 DAG.setRoot(Dummy.getValue()); 1300 DAG.RemoveDeadNodes(); 1301 } 1302 1303 SDValue DAGCombiner::visit(SDNode *N) { 1304 switch (N->getOpcode()) { 1305 default: break; 1306 case ISD::TokenFactor: return visitTokenFactor(N); 1307 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1308 case ISD::ADD: return visitADD(N); 1309 case ISD::SUB: return visitSUB(N); 1310 case ISD::ADDC: return visitADDC(N); 1311 case ISD::SUBC: return visitSUBC(N); 1312 case ISD::ADDE: return visitADDE(N); 1313 case ISD::SUBE: return visitSUBE(N); 1314 case ISD::MUL: return visitMUL(N); 1315 case ISD::SDIV: return visitSDIV(N); 1316 case ISD::UDIV: return visitUDIV(N); 1317 case ISD::SREM: return visitSREM(N); 1318 case ISD::UREM: return visitUREM(N); 1319 case ISD::MULHU: return visitMULHU(N); 1320 case ISD::MULHS: return visitMULHS(N); 1321 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1322 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1323 case ISD::SMULO: return visitSMULO(N); 1324 case ISD::UMULO: return visitUMULO(N); 1325 case ISD::SDIVREM: return visitSDIVREM(N); 1326 case ISD::UDIVREM: return visitUDIVREM(N); 1327 case ISD::AND: return visitAND(N); 1328 case ISD::OR: return visitOR(N); 1329 case ISD::XOR: return visitXOR(N); 1330 case ISD::SHL: return visitSHL(N); 1331 case ISD::SRA: return visitSRA(N); 1332 case ISD::SRL: return visitSRL(N); 1333 case ISD::ROTR: 1334 case ISD::ROTL: return visitRotate(N); 1335 case ISD::CTLZ: return visitCTLZ(N); 1336 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1337 case ISD::CTTZ: return visitCTTZ(N); 1338 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1339 case ISD::CTPOP: return visitCTPOP(N); 1340 case ISD::SELECT: return visitSELECT(N); 1341 case ISD::VSELECT: return visitVSELECT(N); 1342 case ISD::SELECT_CC: return visitSELECT_CC(N); 1343 case ISD::SETCC: return visitSETCC(N); 1344 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1345 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1346 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1347 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1348 case ISD::TRUNCATE: return visitTRUNCATE(N); 1349 case ISD::BITCAST: return visitBITCAST(N); 1350 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1351 case ISD::FADD: return visitFADD(N); 1352 case ISD::FSUB: return visitFSUB(N); 1353 case ISD::FMUL: return visitFMUL(N); 1354 case ISD::FMA: return visitFMA(N); 1355 case ISD::FDIV: return visitFDIV(N); 1356 case ISD::FREM: return visitFREM(N); 1357 case ISD::FSQRT: return visitFSQRT(N); 1358 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1359 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1360 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1361 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1362 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1363 case ISD::FP_ROUND: return visitFP_ROUND(N); 1364 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1365 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1366 case ISD::FNEG: return visitFNEG(N); 1367 case ISD::FABS: return visitFABS(N); 1368 case ISD::FFLOOR: return visitFFLOOR(N); 1369 case ISD::FMINNUM: return visitFMINNUM(N); 1370 case ISD::FMAXNUM: return visitFMAXNUM(N); 1371 case ISD::FCEIL: return visitFCEIL(N); 1372 case ISD::FTRUNC: return visitFTRUNC(N); 1373 case ISD::BRCOND: return visitBRCOND(N); 1374 case ISD::BR_CC: return visitBR_CC(N); 1375 case ISD::LOAD: return visitLOAD(N); 1376 case ISD::STORE: return visitSTORE(N); 1377 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1378 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1379 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1380 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1381 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1382 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1383 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1384 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1385 case ISD::MLOAD: return visitMLOAD(N); 1386 case ISD::MSTORE: return visitMSTORE(N); 1387 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1388 } 1389 return SDValue(); 1390 } 1391 1392 SDValue DAGCombiner::combine(SDNode *N) { 1393 SDValue RV = visit(N); 1394 1395 // If nothing happened, try a target-specific DAG combine. 1396 if (!RV.getNode()) { 1397 assert(N->getOpcode() != ISD::DELETED_NODE && 1398 "Node was deleted but visit returned NULL!"); 1399 1400 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1401 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1402 1403 // Expose the DAG combiner to the target combiner impls. 1404 TargetLowering::DAGCombinerInfo 1405 DagCombineInfo(DAG, Level, false, this); 1406 1407 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1408 } 1409 } 1410 1411 // If nothing happened still, try promoting the operation. 1412 if (!RV.getNode()) { 1413 switch (N->getOpcode()) { 1414 default: break; 1415 case ISD::ADD: 1416 case ISD::SUB: 1417 case ISD::MUL: 1418 case ISD::AND: 1419 case ISD::OR: 1420 case ISD::XOR: 1421 RV = PromoteIntBinOp(SDValue(N, 0)); 1422 break; 1423 case ISD::SHL: 1424 case ISD::SRA: 1425 case ISD::SRL: 1426 RV = PromoteIntShiftOp(SDValue(N, 0)); 1427 break; 1428 case ISD::SIGN_EXTEND: 1429 case ISD::ZERO_EXTEND: 1430 case ISD::ANY_EXTEND: 1431 RV = PromoteExtend(SDValue(N, 0)); 1432 break; 1433 case ISD::LOAD: 1434 if (PromoteLoad(SDValue(N, 0))) 1435 RV = SDValue(N, 0); 1436 break; 1437 } 1438 } 1439 1440 // If N is a commutative binary node, try commuting it to enable more 1441 // sdisel CSE. 1442 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1443 N->getNumValues() == 1) { 1444 SDValue N0 = N->getOperand(0); 1445 SDValue N1 = N->getOperand(1); 1446 1447 // Constant operands are canonicalized to RHS. 1448 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1449 SDValue Ops[] = {N1, N0}; 1450 SDNode *CSENode; 1451 if (const BinaryWithFlagsSDNode *BinNode = 1452 dyn_cast<BinaryWithFlagsSDNode>(N)) { 1453 CSENode = DAG.getNodeIfExists( 1454 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(), 1455 BinNode->hasNoSignedWrap(), BinNode->isExact()); 1456 } else { 1457 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops); 1458 } 1459 if (CSENode) 1460 return SDValue(CSENode, 0); 1461 } 1462 } 1463 1464 return RV; 1465 } 1466 1467 /// Given a node, return its input chain if it has one, otherwise return a null 1468 /// sd operand. 1469 static SDValue getInputChainForNode(SDNode *N) { 1470 if (unsigned NumOps = N->getNumOperands()) { 1471 if (N->getOperand(0).getValueType() == MVT::Other) 1472 return N->getOperand(0); 1473 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1474 return N->getOperand(NumOps-1); 1475 for (unsigned i = 1; i < NumOps-1; ++i) 1476 if (N->getOperand(i).getValueType() == MVT::Other) 1477 return N->getOperand(i); 1478 } 1479 return SDValue(); 1480 } 1481 1482 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1483 // If N has two operands, where one has an input chain equal to the other, 1484 // the 'other' chain is redundant. 1485 if (N->getNumOperands() == 2) { 1486 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1487 return N->getOperand(0); 1488 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1489 return N->getOperand(1); 1490 } 1491 1492 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1493 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1494 SmallPtrSet<SDNode*, 16> SeenOps; 1495 bool Changed = false; // If we should replace this token factor. 1496 1497 // Start out with this token factor. 1498 TFs.push_back(N); 1499 1500 // Iterate through token factors. The TFs grows when new token factors are 1501 // encountered. 1502 for (unsigned i = 0; i < TFs.size(); ++i) { 1503 SDNode *TF = TFs[i]; 1504 1505 // Check each of the operands. 1506 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1507 SDValue Op = TF->getOperand(i); 1508 1509 switch (Op.getOpcode()) { 1510 case ISD::EntryToken: 1511 // Entry tokens don't need to be added to the list. They are 1512 // redundant. 1513 Changed = true; 1514 break; 1515 1516 case ISD::TokenFactor: 1517 if (Op.hasOneUse() && 1518 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1519 // Queue up for processing. 1520 TFs.push_back(Op.getNode()); 1521 // Clean up in case the token factor is removed. 1522 AddToWorklist(Op.getNode()); 1523 Changed = true; 1524 break; 1525 } 1526 // Fall thru 1527 1528 default: 1529 // Only add if it isn't already in the list. 1530 if (SeenOps.insert(Op.getNode()).second) 1531 Ops.push_back(Op); 1532 else 1533 Changed = true; 1534 break; 1535 } 1536 } 1537 } 1538 1539 SDValue Result; 1540 1541 // If we've changed things around then replace token factor. 1542 if (Changed) { 1543 if (Ops.empty()) { 1544 // The entry token is the only possible outcome. 1545 Result = DAG.getEntryNode(); 1546 } else { 1547 // New and improved token factor. 1548 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1549 } 1550 1551 // Add users to worklist if AA is enabled, since it may introduce 1552 // a lot of new chained token factors while removing memory deps. 1553 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1554 : DAG.getSubtarget().useAA(); 1555 return CombineTo(N, Result, UseAA /*add to worklist*/); 1556 } 1557 1558 return Result; 1559 } 1560 1561 /// MERGE_VALUES can always be eliminated. 1562 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1563 WorklistRemover DeadNodes(*this); 1564 // Replacing results may cause a different MERGE_VALUES to suddenly 1565 // be CSE'd with N, and carry its uses with it. Iterate until no 1566 // uses remain, to ensure that the node can be safely deleted. 1567 // First add the users of this node to the work list so that they 1568 // can be tried again once they have new operands. 1569 AddUsersToWorklist(N); 1570 do { 1571 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1572 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1573 } while (!N->use_empty()); 1574 deleteAndRecombine(N); 1575 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1576 } 1577 1578 SDValue DAGCombiner::visitADD(SDNode *N) { 1579 SDValue N0 = N->getOperand(0); 1580 SDValue N1 = N->getOperand(1); 1581 EVT VT = N0.getValueType(); 1582 1583 // fold vector ops 1584 if (VT.isVector()) { 1585 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1586 return FoldedVOp; 1587 1588 // fold (add x, 0) -> x, vector edition 1589 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1590 return N0; 1591 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1592 return N1; 1593 } 1594 1595 // fold (add x, undef) -> undef 1596 if (N0.getOpcode() == ISD::UNDEF) 1597 return N0; 1598 if (N1.getOpcode() == ISD::UNDEF) 1599 return N1; 1600 // fold (add c1, c2) -> c1+c2 1601 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1602 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1603 if (N0C && N1C) 1604 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1605 // canonicalize constant to RHS 1606 if (isConstantIntBuildVectorOrConstantInt(N0) && 1607 !isConstantIntBuildVectorOrConstantInt(N1)) 1608 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1609 // fold (add x, 0) -> x 1610 if (N1C && N1C->isNullValue()) 1611 return N0; 1612 // fold (add Sym, c) -> Sym+c 1613 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1614 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1615 GA->getOpcode() == ISD::GlobalAddress) 1616 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1617 GA->getOffset() + 1618 (uint64_t)N1C->getSExtValue()); 1619 // fold ((c1-A)+c2) -> (c1+c2)-A 1620 if (N1C && N0.getOpcode() == ISD::SUB) 1621 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1622 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1623 DAG.getConstant(N1C->getAPIntValue()+ 1624 N0C->getAPIntValue(), VT), 1625 N0.getOperand(1)); 1626 // reassociate add 1627 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1628 return RADD; 1629 // fold ((0-A) + B) -> B-A 1630 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1631 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1632 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1633 // fold (A + (0-B)) -> A-B 1634 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1635 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1636 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1637 // fold (A+(B-A)) -> B 1638 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1639 return N1.getOperand(0); 1640 // fold ((B-A)+A) -> B 1641 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1642 return N0.getOperand(0); 1643 // fold (A+(B-(A+C))) to (B-C) 1644 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1645 N0 == N1.getOperand(1).getOperand(0)) 1646 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1647 N1.getOperand(1).getOperand(1)); 1648 // fold (A+(B-(C+A))) to (B-C) 1649 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1650 N0 == N1.getOperand(1).getOperand(1)) 1651 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1652 N1.getOperand(1).getOperand(0)); 1653 // fold (A+((B-A)+or-C)) to (B+or-C) 1654 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1655 N1.getOperand(0).getOpcode() == ISD::SUB && 1656 N0 == N1.getOperand(0).getOperand(1)) 1657 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1658 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1659 1660 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1661 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1662 SDValue N00 = N0.getOperand(0); 1663 SDValue N01 = N0.getOperand(1); 1664 SDValue N10 = N1.getOperand(0); 1665 SDValue N11 = N1.getOperand(1); 1666 1667 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1668 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1669 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1670 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1671 } 1672 1673 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1674 return SDValue(N, 0); 1675 1676 // fold (a+b) -> (a|b) iff a and b share no bits. 1677 if (VT.isInteger() && !VT.isVector()) { 1678 APInt LHSZero, LHSOne; 1679 APInt RHSZero, RHSOne; 1680 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1681 1682 if (LHSZero.getBoolValue()) { 1683 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1684 1685 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1686 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1687 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1688 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1689 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1690 } 1691 } 1692 } 1693 1694 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1695 if (N1.getOpcode() == ISD::SHL && 1696 N1.getOperand(0).getOpcode() == ISD::SUB) 1697 if (ConstantSDNode *C = 1698 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1699 if (C->getAPIntValue() == 0) 1700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1701 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1702 N1.getOperand(0).getOperand(1), 1703 N1.getOperand(1))); 1704 if (N0.getOpcode() == ISD::SHL && 1705 N0.getOperand(0).getOpcode() == ISD::SUB) 1706 if (ConstantSDNode *C = 1707 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1708 if (C->getAPIntValue() == 0) 1709 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1710 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1711 N0.getOperand(0).getOperand(1), 1712 N0.getOperand(1))); 1713 1714 if (N1.getOpcode() == ISD::AND) { 1715 SDValue AndOp0 = N1.getOperand(0); 1716 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1717 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1718 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1719 1720 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1721 // and similar xforms where the inner op is either ~0 or 0. 1722 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1723 SDLoc DL(N); 1724 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1725 } 1726 } 1727 1728 // add (sext i1), X -> sub X, (zext i1) 1729 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1730 N0.getOperand(0).getValueType() == MVT::i1 && 1731 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1732 SDLoc DL(N); 1733 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1734 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1735 } 1736 1737 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1738 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1739 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1740 if (TN->getVT() == MVT::i1) { 1741 SDLoc DL(N); 1742 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1743 DAG.getConstant(1, VT)); 1744 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1745 } 1746 } 1747 1748 return SDValue(); 1749 } 1750 1751 SDValue DAGCombiner::visitADDC(SDNode *N) { 1752 SDValue N0 = N->getOperand(0); 1753 SDValue N1 = N->getOperand(1); 1754 EVT VT = N0.getValueType(); 1755 1756 // If the flag result is dead, turn this into an ADD. 1757 if (!N->hasAnyUseOfValue(1)) 1758 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1759 DAG.getNode(ISD::CARRY_FALSE, 1760 SDLoc(N), MVT::Glue)); 1761 1762 // canonicalize constant to RHS. 1763 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1765 if (N0C && !N1C) 1766 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1767 1768 // fold (addc x, 0) -> x + no carry out 1769 if (N1C && N1C->isNullValue()) 1770 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1771 SDLoc(N), MVT::Glue)); 1772 1773 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1774 APInt LHSZero, LHSOne; 1775 APInt RHSZero, RHSOne; 1776 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1777 1778 if (LHSZero.getBoolValue()) { 1779 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1780 1781 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1782 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1783 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1784 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1785 DAG.getNode(ISD::CARRY_FALSE, 1786 SDLoc(N), MVT::Glue)); 1787 } 1788 1789 return SDValue(); 1790 } 1791 1792 SDValue DAGCombiner::visitADDE(SDNode *N) { 1793 SDValue N0 = N->getOperand(0); 1794 SDValue N1 = N->getOperand(1); 1795 SDValue CarryIn = N->getOperand(2); 1796 1797 // canonicalize constant to RHS 1798 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1799 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1800 if (N0C && !N1C) 1801 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1802 N1, N0, CarryIn); 1803 1804 // fold (adde x, y, false) -> (addc x, y) 1805 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1806 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1807 1808 return SDValue(); 1809 } 1810 1811 // Since it may not be valid to emit a fold to zero for vector initializers 1812 // check if we can before folding. 1813 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1814 SelectionDAG &DAG, 1815 bool LegalOperations, bool LegalTypes) { 1816 if (!VT.isVector()) 1817 return DAG.getConstant(0, VT); 1818 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1819 return DAG.getConstant(0, VT); 1820 return SDValue(); 1821 } 1822 1823 SDValue DAGCombiner::visitSUB(SDNode *N) { 1824 SDValue N0 = N->getOperand(0); 1825 SDValue N1 = N->getOperand(1); 1826 EVT VT = N0.getValueType(); 1827 1828 // fold vector ops 1829 if (VT.isVector()) { 1830 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1831 return FoldedVOp; 1832 1833 // fold (sub x, 0) -> x, vector edition 1834 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1835 return N0; 1836 } 1837 1838 // fold (sub x, x) -> 0 1839 // FIXME: Refactor this and xor and other similar operations together. 1840 if (N0 == N1) 1841 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1842 // fold (sub c1, c2) -> c1-c2 1843 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1844 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1845 if (N0C && N1C) 1846 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1847 // fold (sub x, c) -> (add x, -c) 1848 if (N1C) 1849 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1850 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1851 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1852 if (N0C && N0C->isAllOnesValue()) 1853 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1854 // fold A-(A-B) -> B 1855 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1856 return N1.getOperand(1); 1857 // fold (A+B)-A -> B 1858 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1859 return N0.getOperand(1); 1860 // fold (A+B)-B -> A 1861 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1862 return N0.getOperand(0); 1863 // fold C2-(A+C1) -> (C2-C1)-A 1864 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1865 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1866 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1867 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1868 VT); 1869 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1870 N1.getOperand(0)); 1871 } 1872 // fold ((A+(B+or-C))-B) -> A+or-C 1873 if (N0.getOpcode() == ISD::ADD && 1874 (N0.getOperand(1).getOpcode() == ISD::SUB || 1875 N0.getOperand(1).getOpcode() == ISD::ADD) && 1876 N0.getOperand(1).getOperand(0) == N1) 1877 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1878 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1879 // fold ((A+(C+B))-B) -> A+C 1880 if (N0.getOpcode() == ISD::ADD && 1881 N0.getOperand(1).getOpcode() == ISD::ADD && 1882 N0.getOperand(1).getOperand(1) == N1) 1883 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1884 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1885 // fold ((A-(B-C))-C) -> A-B 1886 if (N0.getOpcode() == ISD::SUB && 1887 N0.getOperand(1).getOpcode() == ISD::SUB && 1888 N0.getOperand(1).getOperand(1) == N1) 1889 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1890 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1891 1892 // If either operand of a sub is undef, the result is undef 1893 if (N0.getOpcode() == ISD::UNDEF) 1894 return N0; 1895 if (N1.getOpcode() == ISD::UNDEF) 1896 return N1; 1897 1898 // If the relocation model supports it, consider symbol offsets. 1899 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1900 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1901 // fold (sub Sym, c) -> Sym-c 1902 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1903 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1904 GA->getOffset() - 1905 (uint64_t)N1C->getSExtValue()); 1906 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1907 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1908 if (GA->getGlobal() == GB->getGlobal()) 1909 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1910 VT); 1911 } 1912 1913 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1914 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1915 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1916 if (TN->getVT() == MVT::i1) { 1917 SDLoc DL(N); 1918 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1919 DAG.getConstant(1, VT)); 1920 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1921 } 1922 } 1923 1924 return SDValue(); 1925 } 1926 1927 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1928 SDValue N0 = N->getOperand(0); 1929 SDValue N1 = N->getOperand(1); 1930 EVT VT = N0.getValueType(); 1931 1932 // If the flag result is dead, turn this into an SUB. 1933 if (!N->hasAnyUseOfValue(1)) 1934 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1935 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1936 MVT::Glue)); 1937 1938 // fold (subc x, x) -> 0 + no borrow 1939 if (N0 == N1) 1940 return CombineTo(N, DAG.getConstant(0, VT), 1941 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1942 MVT::Glue)); 1943 1944 // fold (subc x, 0) -> x + no borrow 1945 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1946 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1947 if (N1C && N1C->isNullValue()) 1948 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1949 MVT::Glue)); 1950 1951 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1952 if (N0C && N0C->isAllOnesValue()) 1953 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1954 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1955 MVT::Glue)); 1956 1957 return SDValue(); 1958 } 1959 1960 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1961 SDValue N0 = N->getOperand(0); 1962 SDValue N1 = N->getOperand(1); 1963 SDValue CarryIn = N->getOperand(2); 1964 1965 // fold (sube x, y, false) -> (subc x, y) 1966 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1967 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1968 1969 return SDValue(); 1970 } 1971 1972 SDValue DAGCombiner::visitMUL(SDNode *N) { 1973 SDValue N0 = N->getOperand(0); 1974 SDValue N1 = N->getOperand(1); 1975 EVT VT = N0.getValueType(); 1976 1977 // fold (mul x, undef) -> 0 1978 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1979 return DAG.getConstant(0, VT); 1980 1981 bool N0IsConst = false; 1982 bool N1IsConst = false; 1983 APInt ConstValue0, ConstValue1; 1984 // fold vector ops 1985 if (VT.isVector()) { 1986 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1987 return FoldedVOp; 1988 1989 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1990 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1991 } else { 1992 N0IsConst = isa<ConstantSDNode>(N0); 1993 if (N0IsConst) 1994 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 1995 N1IsConst = isa<ConstantSDNode>(N1); 1996 if (N1IsConst) 1997 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 1998 } 1999 2000 // fold (mul c1, c2) -> c1*c2 2001 if (N0IsConst && N1IsConst) 2002 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 2003 2004 // canonicalize constant to RHS (vector doesn't have to splat) 2005 if (isConstantIntBuildVectorOrConstantInt(N0) && 2006 !isConstantIntBuildVectorOrConstantInt(N1)) 2007 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2008 // fold (mul x, 0) -> 0 2009 if (N1IsConst && ConstValue1 == 0) 2010 return N1; 2011 // We require a splat of the entire scalar bit width for non-contiguous 2012 // bit patterns. 2013 bool IsFullSplat = 2014 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2015 // fold (mul x, 1) -> x 2016 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2017 return N0; 2018 // fold (mul x, -1) -> 0-x 2019 if (N1IsConst && ConstValue1.isAllOnesValue()) 2020 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2021 DAG.getConstant(0, VT), N0); 2022 // fold (mul x, (1 << c)) -> x << c 2023 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) 2024 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 2025 DAG.getConstant(ConstValue1.logBase2(), 2026 getShiftAmountTy(N0.getValueType()))); 2027 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2028 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 2029 unsigned Log2Val = (-ConstValue1).logBase2(); 2030 // FIXME: If the input is something that is easily negated (e.g. a 2031 // single-use add), we should put the negate there. 2032 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2033 DAG.getConstant(0, VT), 2034 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 2035 DAG.getConstant(Log2Val, 2036 getShiftAmountTy(N0.getValueType())))); 2037 } 2038 2039 APInt Val; 2040 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2041 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2042 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2043 isa<ConstantSDNode>(N0.getOperand(1)))) { 2044 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2045 N1, N0.getOperand(1)); 2046 AddToWorklist(C3.getNode()); 2047 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2048 N0.getOperand(0), C3); 2049 } 2050 2051 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2052 // use. 2053 { 2054 SDValue Sh(nullptr,0), Y(nullptr,0); 2055 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2056 if (N0.getOpcode() == ISD::SHL && 2057 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2058 isa<ConstantSDNode>(N0.getOperand(1))) && 2059 N0.getNode()->hasOneUse()) { 2060 Sh = N0; Y = N1; 2061 } else if (N1.getOpcode() == ISD::SHL && 2062 isa<ConstantSDNode>(N1.getOperand(1)) && 2063 N1.getNode()->hasOneUse()) { 2064 Sh = N1; Y = N0; 2065 } 2066 2067 if (Sh.getNode()) { 2068 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2069 Sh.getOperand(0), Y); 2070 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2071 Mul, Sh.getOperand(1)); 2072 } 2073 } 2074 2075 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2076 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 2077 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2078 isa<ConstantSDNode>(N0.getOperand(1)))) 2079 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2080 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2081 N0.getOperand(0), N1), 2082 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2083 N0.getOperand(1), N1)); 2084 2085 // reassociate mul 2086 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2087 return RMUL; 2088 2089 return SDValue(); 2090 } 2091 2092 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2093 SDValue N0 = N->getOperand(0); 2094 SDValue N1 = N->getOperand(1); 2095 EVT VT = N->getValueType(0); 2096 2097 // fold vector ops 2098 if (VT.isVector()) 2099 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2100 return FoldedVOp; 2101 2102 // fold (sdiv c1, c2) -> c1/c2 2103 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2104 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2105 if (N0C && N1C && !N1C->isNullValue()) 2106 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 2107 // fold (sdiv X, 1) -> X 2108 if (N1C && N1C->getAPIntValue() == 1LL) 2109 return N0; 2110 // fold (sdiv X, -1) -> 0-X 2111 if (N1C && N1C->isAllOnesValue()) 2112 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2113 DAG.getConstant(0, VT), N0); 2114 // If we know the sign bits of both operands are zero, strength reduce to a 2115 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2116 if (!VT.isVector()) { 2117 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2118 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2119 N0, N1); 2120 } 2121 2122 // fold (sdiv X, pow2) -> simple ops after legalize 2123 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() || 2124 (-N1C->getAPIntValue()).isPowerOf2())) { 2125 // If dividing by powers of two is cheap, then don't perform the following 2126 // fold. 2127 if (TLI.isPow2SDivCheap()) 2128 return SDValue(); 2129 2130 // Target-specific implementation of sdiv x, pow2. 2131 SDValue Res = BuildSDIVPow2(N); 2132 if (Res.getNode()) 2133 return Res; 2134 2135 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2136 2137 // Splat the sign bit into the register 2138 SDValue SGN = 2139 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 2140 DAG.getConstant(VT.getScalarSizeInBits() - 1, 2141 getShiftAmountTy(N0.getValueType()))); 2142 AddToWorklist(SGN.getNode()); 2143 2144 // Add (N0 < 0) ? abs2 - 1 : 0; 2145 SDValue SRL = 2146 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 2147 DAG.getConstant(VT.getScalarSizeInBits() - lg2, 2148 getShiftAmountTy(SGN.getValueType()))); 2149 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 2150 AddToWorklist(SRL.getNode()); 2151 AddToWorklist(ADD.getNode()); // Divide by pow2 2152 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 2153 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 2154 2155 // If we're dividing by a positive value, we're done. Otherwise, we must 2156 // negate the result. 2157 if (N1C->getAPIntValue().isNonNegative()) 2158 return SRA; 2159 2160 AddToWorklist(SRA.getNode()); 2161 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA); 2162 } 2163 2164 // If integer divide is expensive and we satisfy the requirements, emit an 2165 // alternate sequence. 2166 if (N1C && !TLI.isIntDivCheap()) { 2167 SDValue Op = BuildSDIV(N); 2168 if (Op.getNode()) return Op; 2169 } 2170 2171 // undef / X -> 0 2172 if (N0.getOpcode() == ISD::UNDEF) 2173 return DAG.getConstant(0, VT); 2174 // X / undef -> undef 2175 if (N1.getOpcode() == ISD::UNDEF) 2176 return N1; 2177 2178 return SDValue(); 2179 } 2180 2181 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2182 SDValue N0 = N->getOperand(0); 2183 SDValue N1 = N->getOperand(1); 2184 EVT VT = N->getValueType(0); 2185 2186 // fold vector ops 2187 if (VT.isVector()) 2188 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2189 return FoldedVOp; 2190 2191 // fold (udiv c1, c2) -> c1/c2 2192 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2193 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2194 if (N0C && N1C && !N1C->isNullValue()) 2195 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2196 // fold (udiv x, (1 << c)) -> x >>u c 2197 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2198 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2199 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2200 getShiftAmountTy(N0.getValueType()))); 2201 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2202 if (N1.getOpcode() == ISD::SHL) { 2203 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2204 if (SHC->getAPIntValue().isPowerOf2()) { 2205 EVT ADDVT = N1.getOperand(1).getValueType(); 2206 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2207 N1.getOperand(1), 2208 DAG.getConstant(SHC->getAPIntValue() 2209 .logBase2(), 2210 ADDVT)); 2211 AddToWorklist(Add.getNode()); 2212 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2213 } 2214 } 2215 } 2216 // fold (udiv x, c) -> alternate 2217 if (N1C && !TLI.isIntDivCheap()) { 2218 SDValue Op = BuildUDIV(N); 2219 if (Op.getNode()) return Op; 2220 } 2221 2222 // undef / X -> 0 2223 if (N0.getOpcode() == ISD::UNDEF) 2224 return DAG.getConstant(0, VT); 2225 // X / undef -> undef 2226 if (N1.getOpcode() == ISD::UNDEF) 2227 return N1; 2228 2229 return SDValue(); 2230 } 2231 2232 SDValue DAGCombiner::visitSREM(SDNode *N) { 2233 SDValue N0 = N->getOperand(0); 2234 SDValue N1 = N->getOperand(1); 2235 EVT VT = N->getValueType(0); 2236 2237 // fold (srem c1, c2) -> c1%c2 2238 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2239 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2240 if (N0C && N1C && !N1C->isNullValue()) 2241 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2242 // If we know the sign bits of both operands are zero, strength reduce to a 2243 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2244 if (!VT.isVector()) { 2245 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2246 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2247 } 2248 2249 // If X/C can be simplified by the division-by-constant logic, lower 2250 // X%C to the equivalent of X-X/C*C. 2251 if (N1C && !N1C->isNullValue()) { 2252 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2253 AddToWorklist(Div.getNode()); 2254 SDValue OptimizedDiv = combine(Div.getNode()); 2255 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2256 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2257 OptimizedDiv, N1); 2258 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2259 AddToWorklist(Mul.getNode()); 2260 return Sub; 2261 } 2262 } 2263 2264 // undef % X -> 0 2265 if (N0.getOpcode() == ISD::UNDEF) 2266 return DAG.getConstant(0, VT); 2267 // X % undef -> undef 2268 if (N1.getOpcode() == ISD::UNDEF) 2269 return N1; 2270 2271 return SDValue(); 2272 } 2273 2274 SDValue DAGCombiner::visitUREM(SDNode *N) { 2275 SDValue N0 = N->getOperand(0); 2276 SDValue N1 = N->getOperand(1); 2277 EVT VT = N->getValueType(0); 2278 2279 // fold (urem c1, c2) -> c1%c2 2280 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2281 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2282 if (N0C && N1C && !N1C->isNullValue()) 2283 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2284 // fold (urem x, pow2) -> (and x, pow2-1) 2285 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2286 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2287 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2288 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2289 if (N1.getOpcode() == ISD::SHL) { 2290 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2291 if (SHC->getAPIntValue().isPowerOf2()) { 2292 SDValue Add = 2293 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2294 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2295 VT)); 2296 AddToWorklist(Add.getNode()); 2297 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2298 } 2299 } 2300 } 2301 2302 // If X/C can be simplified by the division-by-constant logic, lower 2303 // X%C to the equivalent of X-X/C*C. 2304 if (N1C && !N1C->isNullValue()) { 2305 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2306 AddToWorklist(Div.getNode()); 2307 SDValue OptimizedDiv = combine(Div.getNode()); 2308 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2309 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2310 OptimizedDiv, N1); 2311 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2312 AddToWorklist(Mul.getNode()); 2313 return Sub; 2314 } 2315 } 2316 2317 // undef % X -> 0 2318 if (N0.getOpcode() == ISD::UNDEF) 2319 return DAG.getConstant(0, VT); 2320 // X % undef -> undef 2321 if (N1.getOpcode() == ISD::UNDEF) 2322 return N1; 2323 2324 return SDValue(); 2325 } 2326 2327 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2328 SDValue N0 = N->getOperand(0); 2329 SDValue N1 = N->getOperand(1); 2330 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2331 EVT VT = N->getValueType(0); 2332 SDLoc DL(N); 2333 2334 // fold (mulhs x, 0) -> 0 2335 if (N1C && N1C->isNullValue()) 2336 return N1; 2337 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2338 if (N1C && N1C->getAPIntValue() == 1) 2339 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2340 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2341 getShiftAmountTy(N0.getValueType()))); 2342 // fold (mulhs x, undef) -> 0 2343 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2344 return DAG.getConstant(0, VT); 2345 2346 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2347 // plus a shift. 2348 if (VT.isSimple() && !VT.isVector()) { 2349 MVT Simple = VT.getSimpleVT(); 2350 unsigned SimpleSize = Simple.getSizeInBits(); 2351 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2352 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2353 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2354 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2355 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2356 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2357 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2358 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2359 } 2360 } 2361 2362 return SDValue(); 2363 } 2364 2365 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2366 SDValue N0 = N->getOperand(0); 2367 SDValue N1 = N->getOperand(1); 2368 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2369 EVT VT = N->getValueType(0); 2370 SDLoc DL(N); 2371 2372 // fold (mulhu x, 0) -> 0 2373 if (N1C && N1C->isNullValue()) 2374 return N1; 2375 // fold (mulhu x, 1) -> 0 2376 if (N1C && N1C->getAPIntValue() == 1) 2377 return DAG.getConstant(0, N0.getValueType()); 2378 // fold (mulhu x, undef) -> 0 2379 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2380 return DAG.getConstant(0, VT); 2381 2382 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2383 // plus a shift. 2384 if (VT.isSimple() && !VT.isVector()) { 2385 MVT Simple = VT.getSimpleVT(); 2386 unsigned SimpleSize = Simple.getSizeInBits(); 2387 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2388 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2389 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2390 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2391 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2392 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2393 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2394 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2395 } 2396 } 2397 2398 return SDValue(); 2399 } 2400 2401 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2402 /// give the opcodes for the two computations that are being performed. Return 2403 /// true if a simplification was made. 2404 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2405 unsigned HiOp) { 2406 // If the high half is not needed, just compute the low half. 2407 bool HiExists = N->hasAnyUseOfValue(1); 2408 if (!HiExists && 2409 (!LegalOperations || 2410 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2411 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2412 return CombineTo(N, Res, Res); 2413 } 2414 2415 // If the low half is not needed, just compute the high half. 2416 bool LoExists = N->hasAnyUseOfValue(0); 2417 if (!LoExists && 2418 (!LegalOperations || 2419 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2420 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2421 return CombineTo(N, Res, Res); 2422 } 2423 2424 // If both halves are used, return as it is. 2425 if (LoExists && HiExists) 2426 return SDValue(); 2427 2428 // If the two computed results can be simplified separately, separate them. 2429 if (LoExists) { 2430 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2431 AddToWorklist(Lo.getNode()); 2432 SDValue LoOpt = combine(Lo.getNode()); 2433 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2434 (!LegalOperations || 2435 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2436 return CombineTo(N, LoOpt, LoOpt); 2437 } 2438 2439 if (HiExists) { 2440 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2441 AddToWorklist(Hi.getNode()); 2442 SDValue HiOpt = combine(Hi.getNode()); 2443 if (HiOpt.getNode() && HiOpt != Hi && 2444 (!LegalOperations || 2445 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2446 return CombineTo(N, HiOpt, HiOpt); 2447 } 2448 2449 return SDValue(); 2450 } 2451 2452 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2453 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2454 if (Res.getNode()) return Res; 2455 2456 EVT VT = N->getValueType(0); 2457 SDLoc DL(N); 2458 2459 // If the type is twice as wide is legal, transform the mulhu to a wider 2460 // multiply plus a shift. 2461 if (VT.isSimple() && !VT.isVector()) { 2462 MVT Simple = VT.getSimpleVT(); 2463 unsigned SimpleSize = Simple.getSizeInBits(); 2464 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2465 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2466 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2467 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2468 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2469 // Compute the high part as N1. 2470 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2471 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2472 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2473 // Compute the low part as N0. 2474 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2475 return CombineTo(N, Lo, Hi); 2476 } 2477 } 2478 2479 return SDValue(); 2480 } 2481 2482 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2483 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2484 if (Res.getNode()) return Res; 2485 2486 EVT VT = N->getValueType(0); 2487 SDLoc DL(N); 2488 2489 // If the type is twice as wide is legal, transform the mulhu to a wider 2490 // multiply plus a shift. 2491 if (VT.isSimple() && !VT.isVector()) { 2492 MVT Simple = VT.getSimpleVT(); 2493 unsigned SimpleSize = Simple.getSizeInBits(); 2494 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2495 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2496 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2497 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2498 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2499 // Compute the high part as N1. 2500 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2501 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2502 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2503 // Compute the low part as N0. 2504 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2505 return CombineTo(N, Lo, Hi); 2506 } 2507 } 2508 2509 return SDValue(); 2510 } 2511 2512 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2513 // (smulo x, 2) -> (saddo x, x) 2514 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2515 if (C2->getAPIntValue() == 2) 2516 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2517 N->getOperand(0), N->getOperand(0)); 2518 2519 return SDValue(); 2520 } 2521 2522 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2523 // (umulo x, 2) -> (uaddo x, x) 2524 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2525 if (C2->getAPIntValue() == 2) 2526 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2527 N->getOperand(0), N->getOperand(0)); 2528 2529 return SDValue(); 2530 } 2531 2532 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2533 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2534 if (Res.getNode()) return Res; 2535 2536 return SDValue(); 2537 } 2538 2539 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2540 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2541 if (Res.getNode()) return Res; 2542 2543 return SDValue(); 2544 } 2545 2546 /// If this is a binary operator with two operands of the same opcode, try to 2547 /// simplify it. 2548 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2549 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2550 EVT VT = N0.getValueType(); 2551 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2552 2553 // Bail early if none of these transforms apply. 2554 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2555 2556 // For each of OP in AND/OR/XOR: 2557 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2558 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2559 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2560 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2561 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2562 // 2563 // do not sink logical op inside of a vector extend, since it may combine 2564 // into a vsetcc. 2565 EVT Op0VT = N0.getOperand(0).getValueType(); 2566 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2567 N0.getOpcode() == ISD::SIGN_EXTEND || 2568 N0.getOpcode() == ISD::BSWAP || 2569 // Avoid infinite looping with PromoteIntBinOp. 2570 (N0.getOpcode() == ISD::ANY_EXTEND && 2571 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2572 (N0.getOpcode() == ISD::TRUNCATE && 2573 (!TLI.isZExtFree(VT, Op0VT) || 2574 !TLI.isTruncateFree(Op0VT, VT)) && 2575 TLI.isTypeLegal(Op0VT))) && 2576 !VT.isVector() && 2577 Op0VT == N1.getOperand(0).getValueType() && 2578 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2579 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2580 N0.getOperand(0).getValueType(), 2581 N0.getOperand(0), N1.getOperand(0)); 2582 AddToWorklist(ORNode.getNode()); 2583 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2584 } 2585 2586 // For each of OP in SHL/SRL/SRA/AND... 2587 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2588 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2589 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2590 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2591 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2592 N0.getOperand(1) == N1.getOperand(1)) { 2593 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2594 N0.getOperand(0).getValueType(), 2595 N0.getOperand(0), N1.getOperand(0)); 2596 AddToWorklist(ORNode.getNode()); 2597 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2598 ORNode, N0.getOperand(1)); 2599 } 2600 2601 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2602 // Only perform this optimization after type legalization and before 2603 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2604 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2605 // we don't want to undo this promotion. 2606 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2607 // on scalars. 2608 if ((N0.getOpcode() == ISD::BITCAST || 2609 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2610 Level == AfterLegalizeTypes) { 2611 SDValue In0 = N0.getOperand(0); 2612 SDValue In1 = N1.getOperand(0); 2613 EVT In0Ty = In0.getValueType(); 2614 EVT In1Ty = In1.getValueType(); 2615 SDLoc DL(N); 2616 // If both incoming values are integers, and the original types are the 2617 // same. 2618 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2619 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2620 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2621 AddToWorklist(Op.getNode()); 2622 return BC; 2623 } 2624 } 2625 2626 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2627 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2628 // If both shuffles use the same mask, and both shuffle within a single 2629 // vector, then it is worthwhile to move the swizzle after the operation. 2630 // The type-legalizer generates this pattern when loading illegal 2631 // vector types from memory. In many cases this allows additional shuffle 2632 // optimizations. 2633 // There are other cases where moving the shuffle after the xor/and/or 2634 // is profitable even if shuffles don't perform a swizzle. 2635 // If both shuffles use the same mask, and both shuffles have the same first 2636 // or second operand, then it might still be profitable to move the shuffle 2637 // after the xor/and/or operation. 2638 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2639 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2640 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2641 2642 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2643 "Inputs to shuffles are not the same type"); 2644 2645 // Check that both shuffles use the same mask. The masks are known to be of 2646 // the same length because the result vector type is the same. 2647 // Check also that shuffles have only one use to avoid introducing extra 2648 // instructions. 2649 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2650 SVN0->getMask().equals(SVN1->getMask())) { 2651 SDValue ShOp = N0->getOperand(1); 2652 2653 // Don't try to fold this node if it requires introducing a 2654 // build vector of all zeros that might be illegal at this stage. 2655 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2656 if (!LegalTypes) 2657 ShOp = DAG.getConstant(0, VT); 2658 else 2659 ShOp = SDValue(); 2660 } 2661 2662 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2663 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2664 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2665 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2666 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2667 N0->getOperand(0), N1->getOperand(0)); 2668 AddToWorklist(NewNode.getNode()); 2669 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2670 &SVN0->getMask()[0]); 2671 } 2672 2673 // Don't try to fold this node if it requires introducing a 2674 // build vector of all zeros that might be illegal at this stage. 2675 ShOp = N0->getOperand(0); 2676 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2677 if (!LegalTypes) 2678 ShOp = DAG.getConstant(0, VT); 2679 else 2680 ShOp = SDValue(); 2681 } 2682 2683 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2684 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2685 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2686 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2687 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2688 N0->getOperand(1), N1->getOperand(1)); 2689 AddToWorklist(NewNode.getNode()); 2690 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2691 &SVN0->getMask()[0]); 2692 } 2693 } 2694 } 2695 2696 return SDValue(); 2697 } 2698 2699 /// This contains all DAGCombine rules which reduce two values combined by 2700 /// an And operation to a single value. This makes them reusable in the context 2701 /// of visitSELECT(). Rules involving constants are not included as 2702 /// visitSELECT() already handles those cases. 2703 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2704 SDNode *LocReference) { 2705 EVT VT = N1.getValueType(); 2706 2707 // fold (and x, undef) -> 0 2708 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2709 return DAG.getConstant(0, VT); 2710 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2711 SDValue LL, LR, RL, RR, CC0, CC1; 2712 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2713 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2714 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2715 2716 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2717 LL.getValueType().isInteger()) { 2718 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2719 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2720 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2721 LR.getValueType(), LL, RL); 2722 AddToWorklist(ORNode.getNode()); 2723 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2724 } 2725 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2726 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2727 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2728 LR.getValueType(), LL, RL); 2729 AddToWorklist(ANDNode.getNode()); 2730 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2731 } 2732 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2733 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2734 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2735 LR.getValueType(), LL, RL); 2736 AddToWorklist(ORNode.getNode()); 2737 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2738 } 2739 } 2740 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2741 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2742 Op0 == Op1 && LL.getValueType().isInteger() && 2743 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2744 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2745 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2746 cast<ConstantSDNode>(RR)->isNullValue()))) { 2747 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2748 LL, DAG.getConstant(1, LL.getValueType())); 2749 AddToWorklist(ADDNode.getNode()); 2750 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2751 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2752 } 2753 // canonicalize equivalent to ll == rl 2754 if (LL == RR && LR == RL) { 2755 Op1 = ISD::getSetCCSwappedOperands(Op1); 2756 std::swap(RL, RR); 2757 } 2758 if (LL == RL && LR == RR) { 2759 bool isInteger = LL.getValueType().isInteger(); 2760 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2761 if (Result != ISD::SETCC_INVALID && 2762 (!LegalOperations || 2763 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2764 TLI.isOperationLegal(ISD::SETCC, 2765 getSetCCResultType(N0.getSimpleValueType()))))) 2766 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2767 LL, LR, Result); 2768 } 2769 } 2770 2771 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2772 VT.getSizeInBits() <= 64) { 2773 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2774 APInt ADDC = ADDI->getAPIntValue(); 2775 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2776 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2777 // immediate for an add, but it is legal if its top c2 bits are set, 2778 // transform the ADD so the immediate doesn't need to be materialized 2779 // in a register. 2780 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2781 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2782 SRLI->getZExtValue()); 2783 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2784 ADDC |= Mask; 2785 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2786 SDValue NewAdd = 2787 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 2788 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2789 CombineTo(N0.getNode(), NewAdd); 2790 // Return N so it doesn't get rechecked! 2791 return SDValue(LocReference, 0); 2792 } 2793 } 2794 } 2795 } 2796 } 2797 } 2798 2799 return SDValue(); 2800 } 2801 2802 SDValue DAGCombiner::visitAND(SDNode *N) { 2803 SDValue N0 = N->getOperand(0); 2804 SDValue N1 = N->getOperand(1); 2805 EVT VT = N1.getValueType(); 2806 2807 // fold vector ops 2808 if (VT.isVector()) { 2809 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2810 return FoldedVOp; 2811 2812 // fold (and x, 0) -> 0, vector edition 2813 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2814 // do not return N0, because undef node may exist in N0 2815 return DAG.getConstant( 2816 APInt::getNullValue( 2817 N0.getValueType().getScalarType().getSizeInBits()), 2818 N0.getValueType()); 2819 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2820 // do not return N1, because undef node may exist in N1 2821 return DAG.getConstant( 2822 APInt::getNullValue( 2823 N1.getValueType().getScalarType().getSizeInBits()), 2824 N1.getValueType()); 2825 2826 // fold (and x, -1) -> x, vector edition 2827 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2828 return N1; 2829 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2830 return N0; 2831 } 2832 2833 // fold (and c1, c2) -> c1&c2 2834 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2835 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2836 if (N0C && N1C) 2837 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2838 // canonicalize constant to RHS 2839 if (isConstantIntBuildVectorOrConstantInt(N0) && 2840 !isConstantIntBuildVectorOrConstantInt(N1)) 2841 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2842 // fold (and x, -1) -> x 2843 if (N1C && N1C->isAllOnesValue()) 2844 return N0; 2845 // if (and x, c) is known to be zero, return 0 2846 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2847 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2848 APInt::getAllOnesValue(BitWidth))) 2849 return DAG.getConstant(0, VT); 2850 // reassociate and 2851 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 2852 return RAND; 2853 // fold (and (or x, C), D) -> D if (C & D) == D 2854 if (N1C && N0.getOpcode() == ISD::OR) 2855 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2856 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2857 return N1; 2858 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2859 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2860 SDValue N0Op0 = N0.getOperand(0); 2861 APInt Mask = ~N1C->getAPIntValue(); 2862 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2863 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2864 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2865 N0.getValueType(), N0Op0); 2866 2867 // Replace uses of the AND with uses of the Zero extend node. 2868 CombineTo(N, Zext); 2869 2870 // We actually want to replace all uses of the any_extend with the 2871 // zero_extend, to avoid duplicating things. This will later cause this 2872 // AND to be folded. 2873 CombineTo(N0.getNode(), Zext); 2874 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2875 } 2876 } 2877 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2878 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2879 // already be zero by virtue of the width of the base type of the load. 2880 // 2881 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2882 // more cases. 2883 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2884 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2885 N0.getOpcode() == ISD::LOAD) { 2886 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2887 N0 : N0.getOperand(0) ); 2888 2889 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2890 // This can be a pure constant or a vector splat, in which case we treat the 2891 // vector as a scalar and use the splat value. 2892 APInt Constant = APInt::getNullValue(1); 2893 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2894 Constant = C->getAPIntValue(); 2895 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2896 APInt SplatValue, SplatUndef; 2897 unsigned SplatBitSize; 2898 bool HasAnyUndefs; 2899 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2900 SplatBitSize, HasAnyUndefs); 2901 if (IsSplat) { 2902 // Undef bits can contribute to a possible optimisation if set, so 2903 // set them. 2904 SplatValue |= SplatUndef; 2905 2906 // The splat value may be something like "0x00FFFFFF", which means 0 for 2907 // the first vector value and FF for the rest, repeating. We need a mask 2908 // that will apply equally to all members of the vector, so AND all the 2909 // lanes of the constant together. 2910 EVT VT = Vector->getValueType(0); 2911 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2912 2913 // If the splat value has been compressed to a bitlength lower 2914 // than the size of the vector lane, we need to re-expand it to 2915 // the lane size. 2916 if (BitWidth > SplatBitSize) 2917 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2918 SplatBitSize < BitWidth; 2919 SplatBitSize = SplatBitSize * 2) 2920 SplatValue |= SplatValue.shl(SplatBitSize); 2921 2922 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 2923 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 2924 if (SplatBitSize % BitWidth == 0) { 2925 Constant = APInt::getAllOnesValue(BitWidth); 2926 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2927 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2928 } 2929 } 2930 } 2931 2932 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2933 // actually legal and isn't going to get expanded, else this is a false 2934 // optimisation. 2935 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2936 Load->getValueType(0), 2937 Load->getMemoryVT()); 2938 2939 // Resize the constant to the same size as the original memory access before 2940 // extension. If it is still the AllOnesValue then this AND is completely 2941 // unneeded. 2942 Constant = 2943 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2944 2945 bool B; 2946 switch (Load->getExtensionType()) { 2947 default: B = false; break; 2948 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2949 case ISD::ZEXTLOAD: 2950 case ISD::NON_EXTLOAD: B = true; break; 2951 } 2952 2953 if (B && Constant.isAllOnesValue()) { 2954 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2955 // preserve semantics once we get rid of the AND. 2956 SDValue NewLoad(Load, 0); 2957 if (Load->getExtensionType() == ISD::EXTLOAD) { 2958 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2959 Load->getValueType(0), SDLoc(Load), 2960 Load->getChain(), Load->getBasePtr(), 2961 Load->getOffset(), Load->getMemoryVT(), 2962 Load->getMemOperand()); 2963 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2964 if (Load->getNumValues() == 3) { 2965 // PRE/POST_INC loads have 3 values. 2966 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2967 NewLoad.getValue(2) }; 2968 CombineTo(Load, To, 3, true); 2969 } else { 2970 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2971 } 2972 } 2973 2974 // Fold the AND away, taking care not to fold to the old load node if we 2975 // replaced it. 2976 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2977 2978 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2979 } 2980 } 2981 2982 // fold (and (load x), 255) -> (zextload x, i8) 2983 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2984 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2985 if (N1C && (N0.getOpcode() == ISD::LOAD || 2986 (N0.getOpcode() == ISD::ANY_EXTEND && 2987 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2988 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2989 LoadSDNode *LN0 = HasAnyExt 2990 ? cast<LoadSDNode>(N0.getOperand(0)) 2991 : cast<LoadSDNode>(N0); 2992 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2993 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2994 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2995 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2996 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2997 EVT LoadedVT = LN0->getMemoryVT(); 2998 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2999 3000 if (ExtVT == LoadedVT && 3001 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3002 ExtVT))) { 3003 3004 SDValue NewLoad = 3005 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3006 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3007 LN0->getMemOperand()); 3008 AddToWorklist(N); 3009 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3010 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3011 } 3012 3013 // Do not change the width of a volatile load. 3014 // Do not generate loads of non-round integer types since these can 3015 // be expensive (and would be wrong if the type is not byte sized). 3016 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 3017 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3018 ExtVT))) { 3019 EVT PtrType = LN0->getOperand(1).getValueType(); 3020 3021 unsigned Alignment = LN0->getAlignment(); 3022 SDValue NewPtr = LN0->getBasePtr(); 3023 3024 // For big endian targets, we need to add an offset to the pointer 3025 // to load the correct bytes. For little endian systems, we merely 3026 // need to read fewer bytes from the same pointer. 3027 if (TLI.isBigEndian()) { 3028 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3029 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3030 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3031 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 3032 NewPtr, DAG.getConstant(PtrOff, PtrType)); 3033 Alignment = MinAlign(Alignment, PtrOff); 3034 } 3035 3036 AddToWorklist(NewPtr.getNode()); 3037 3038 SDValue Load = 3039 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3040 LN0->getChain(), NewPtr, 3041 LN0->getPointerInfo(), 3042 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3043 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3044 AddToWorklist(N); 3045 CombineTo(LN0, Load, Load.getValue(1)); 3046 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3047 } 3048 } 3049 } 3050 } 3051 3052 if (SDValue Combined = visitANDLike(N0, N1, N)) 3053 return Combined; 3054 3055 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3056 if (N0.getOpcode() == N1.getOpcode()) { 3057 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3058 if (Tmp.getNode()) return Tmp; 3059 } 3060 3061 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3062 // fold (and (sra)) -> (and (srl)) when possible. 3063 if (!VT.isVector() && 3064 SimplifyDemandedBits(SDValue(N, 0))) 3065 return SDValue(N, 0); 3066 3067 // fold (zext_inreg (extload x)) -> (zextload x) 3068 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3069 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3070 EVT MemVT = LN0->getMemoryVT(); 3071 // If we zero all the possible extended bits, then we can turn this into 3072 // a zextload if we are running before legalize or the operation is legal. 3073 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3074 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3075 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3076 ((!LegalOperations && !LN0->isVolatile()) || 3077 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3078 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3079 LN0->getChain(), LN0->getBasePtr(), 3080 MemVT, LN0->getMemOperand()); 3081 AddToWorklist(N); 3082 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3083 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3084 } 3085 } 3086 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3087 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3088 N0.hasOneUse()) { 3089 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3090 EVT MemVT = LN0->getMemoryVT(); 3091 // If we zero all the possible extended bits, then we can turn this into 3092 // a zextload if we are running before legalize or the operation is legal. 3093 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3094 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3095 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3096 ((!LegalOperations && !LN0->isVolatile()) || 3097 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3098 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3099 LN0->getChain(), LN0->getBasePtr(), 3100 MemVT, LN0->getMemOperand()); 3101 AddToWorklist(N); 3102 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3103 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3104 } 3105 } 3106 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3107 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3108 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3109 N0.getOperand(1), false); 3110 if (BSwap.getNode()) 3111 return BSwap; 3112 } 3113 3114 return SDValue(); 3115 } 3116 3117 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3118 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3119 bool DemandHighBits) { 3120 if (!LegalOperations) 3121 return SDValue(); 3122 3123 EVT VT = N->getValueType(0); 3124 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3125 return SDValue(); 3126 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3127 return SDValue(); 3128 3129 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3130 bool LookPassAnd0 = false; 3131 bool LookPassAnd1 = false; 3132 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3133 std::swap(N0, N1); 3134 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3135 std::swap(N0, N1); 3136 if (N0.getOpcode() == ISD::AND) { 3137 if (!N0.getNode()->hasOneUse()) 3138 return SDValue(); 3139 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3140 if (!N01C || N01C->getZExtValue() != 0xFF00) 3141 return SDValue(); 3142 N0 = N0.getOperand(0); 3143 LookPassAnd0 = true; 3144 } 3145 3146 if (N1.getOpcode() == ISD::AND) { 3147 if (!N1.getNode()->hasOneUse()) 3148 return SDValue(); 3149 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3150 if (!N11C || N11C->getZExtValue() != 0xFF) 3151 return SDValue(); 3152 N1 = N1.getOperand(0); 3153 LookPassAnd1 = true; 3154 } 3155 3156 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3157 std::swap(N0, N1); 3158 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3159 return SDValue(); 3160 if (!N0.getNode()->hasOneUse() || 3161 !N1.getNode()->hasOneUse()) 3162 return SDValue(); 3163 3164 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3165 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3166 if (!N01C || !N11C) 3167 return SDValue(); 3168 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3169 return SDValue(); 3170 3171 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3172 SDValue N00 = N0->getOperand(0); 3173 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3174 if (!N00.getNode()->hasOneUse()) 3175 return SDValue(); 3176 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3177 if (!N001C || N001C->getZExtValue() != 0xFF) 3178 return SDValue(); 3179 N00 = N00.getOperand(0); 3180 LookPassAnd0 = true; 3181 } 3182 3183 SDValue N10 = N1->getOperand(0); 3184 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3185 if (!N10.getNode()->hasOneUse()) 3186 return SDValue(); 3187 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3188 if (!N101C || N101C->getZExtValue() != 0xFF00) 3189 return SDValue(); 3190 N10 = N10.getOperand(0); 3191 LookPassAnd1 = true; 3192 } 3193 3194 if (N00 != N10) 3195 return SDValue(); 3196 3197 // Make sure everything beyond the low halfword gets set to zero since the SRL 3198 // 16 will clear the top bits. 3199 unsigned OpSizeInBits = VT.getSizeInBits(); 3200 if (DemandHighBits && OpSizeInBits > 16) { 3201 // If the left-shift isn't masked out then the only way this is a bswap is 3202 // if all bits beyond the low 8 are 0. In that case the entire pattern 3203 // reduces to a left shift anyway: leave it for other parts of the combiner. 3204 if (!LookPassAnd0) 3205 return SDValue(); 3206 3207 // However, if the right shift isn't masked out then it might be because 3208 // it's not needed. See if we can spot that too. 3209 if (!LookPassAnd1 && 3210 !DAG.MaskedValueIsZero( 3211 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3212 return SDValue(); 3213 } 3214 3215 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3216 if (OpSizeInBits > 16) 3217 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 3218 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 3219 return Res; 3220 } 3221 3222 /// Return true if the specified node is an element that makes up a 32-bit 3223 /// packed halfword byteswap. 3224 /// ((x & 0x000000ff) << 8) | 3225 /// ((x & 0x0000ff00) >> 8) | 3226 /// ((x & 0x00ff0000) << 8) | 3227 /// ((x & 0xff000000) >> 8) 3228 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3229 if (!N.getNode()->hasOneUse()) 3230 return false; 3231 3232 unsigned Opc = N.getOpcode(); 3233 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3234 return false; 3235 3236 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3237 if (!N1C) 3238 return false; 3239 3240 unsigned Num; 3241 switch (N1C->getZExtValue()) { 3242 default: 3243 return false; 3244 case 0xFF: Num = 0; break; 3245 case 0xFF00: Num = 1; break; 3246 case 0xFF0000: Num = 2; break; 3247 case 0xFF000000: Num = 3; break; 3248 } 3249 3250 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3251 SDValue N0 = N.getOperand(0); 3252 if (Opc == ISD::AND) { 3253 if (Num == 0 || Num == 2) { 3254 // (x >> 8) & 0xff 3255 // (x >> 8) & 0xff0000 3256 if (N0.getOpcode() != ISD::SRL) 3257 return false; 3258 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3259 if (!C || C->getZExtValue() != 8) 3260 return false; 3261 } else { 3262 // (x << 8) & 0xff00 3263 // (x << 8) & 0xff000000 3264 if (N0.getOpcode() != ISD::SHL) 3265 return false; 3266 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3267 if (!C || C->getZExtValue() != 8) 3268 return false; 3269 } 3270 } else if (Opc == ISD::SHL) { 3271 // (x & 0xff) << 8 3272 // (x & 0xff0000) << 8 3273 if (Num != 0 && Num != 2) 3274 return false; 3275 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3276 if (!C || C->getZExtValue() != 8) 3277 return false; 3278 } else { // Opc == ISD::SRL 3279 // (x & 0xff00) >> 8 3280 // (x & 0xff000000) >> 8 3281 if (Num != 1 && Num != 3) 3282 return false; 3283 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3284 if (!C || C->getZExtValue() != 8) 3285 return false; 3286 } 3287 3288 if (Parts[Num]) 3289 return false; 3290 3291 Parts[Num] = N0.getOperand(0).getNode(); 3292 return true; 3293 } 3294 3295 /// Match a 32-bit packed halfword bswap. That is 3296 /// ((x & 0x000000ff) << 8) | 3297 /// ((x & 0x0000ff00) >> 8) | 3298 /// ((x & 0x00ff0000) << 8) | 3299 /// ((x & 0xff000000) >> 8) 3300 /// => (rotl (bswap x), 16) 3301 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3302 if (!LegalOperations) 3303 return SDValue(); 3304 3305 EVT VT = N->getValueType(0); 3306 if (VT != MVT::i32) 3307 return SDValue(); 3308 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3309 return SDValue(); 3310 3311 // Look for either 3312 // (or (or (and), (and)), (or (and), (and))) 3313 // (or (or (or (and), (and)), (and)), (and)) 3314 if (N0.getOpcode() != ISD::OR) 3315 return SDValue(); 3316 SDValue N00 = N0.getOperand(0); 3317 SDValue N01 = N0.getOperand(1); 3318 SDNode *Parts[4] = {}; 3319 3320 if (N1.getOpcode() == ISD::OR && 3321 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3322 // (or (or (and), (and)), (or (and), (and))) 3323 SDValue N000 = N00.getOperand(0); 3324 if (!isBSwapHWordElement(N000, Parts)) 3325 return SDValue(); 3326 3327 SDValue N001 = N00.getOperand(1); 3328 if (!isBSwapHWordElement(N001, Parts)) 3329 return SDValue(); 3330 SDValue N010 = N01.getOperand(0); 3331 if (!isBSwapHWordElement(N010, Parts)) 3332 return SDValue(); 3333 SDValue N011 = N01.getOperand(1); 3334 if (!isBSwapHWordElement(N011, Parts)) 3335 return SDValue(); 3336 } else { 3337 // (or (or (or (and), (and)), (and)), (and)) 3338 if (!isBSwapHWordElement(N1, Parts)) 3339 return SDValue(); 3340 if (!isBSwapHWordElement(N01, Parts)) 3341 return SDValue(); 3342 if (N00.getOpcode() != ISD::OR) 3343 return SDValue(); 3344 SDValue N000 = N00.getOperand(0); 3345 if (!isBSwapHWordElement(N000, Parts)) 3346 return SDValue(); 3347 SDValue N001 = N00.getOperand(1); 3348 if (!isBSwapHWordElement(N001, Parts)) 3349 return SDValue(); 3350 } 3351 3352 // Make sure the parts are all coming from the same node. 3353 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3354 return SDValue(); 3355 3356 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3357 SDValue(Parts[0],0)); 3358 3359 // Result of the bswap should be rotated by 16. If it's not legal, then 3360 // do (x << 16) | (x >> 16). 3361 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3362 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3363 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3364 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3365 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3366 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3367 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3368 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3369 } 3370 3371 /// This contains all DAGCombine rules which reduce two values combined by 3372 /// an Or operation to a single value \see visitANDLike(). 3373 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3374 EVT VT = N1.getValueType(); 3375 // fold (or x, undef) -> -1 3376 if (!LegalOperations && 3377 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3378 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3379 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3380 } 3381 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3382 SDValue LL, LR, RL, RR, CC0, CC1; 3383 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3384 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3385 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3386 3387 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3388 LL.getValueType().isInteger()) { 3389 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3390 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3391 if (cast<ConstantSDNode>(LR)->isNullValue() && 3392 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3393 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3394 LR.getValueType(), LL, RL); 3395 AddToWorklist(ORNode.getNode()); 3396 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3397 } 3398 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3399 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3400 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3401 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3402 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3403 LR.getValueType(), LL, RL); 3404 AddToWorklist(ANDNode.getNode()); 3405 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3406 } 3407 } 3408 // canonicalize equivalent to ll == rl 3409 if (LL == RR && LR == RL) { 3410 Op1 = ISD::getSetCCSwappedOperands(Op1); 3411 std::swap(RL, RR); 3412 } 3413 if (LL == RL && LR == RR) { 3414 bool isInteger = LL.getValueType().isInteger(); 3415 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3416 if (Result != ISD::SETCC_INVALID && 3417 (!LegalOperations || 3418 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3419 TLI.isOperationLegal(ISD::SETCC, 3420 getSetCCResultType(N0.getValueType()))))) 3421 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3422 LL, LR, Result); 3423 } 3424 } 3425 3426 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3427 if (N0.getOpcode() == ISD::AND && 3428 N1.getOpcode() == ISD::AND && 3429 N0.getOperand(1).getOpcode() == ISD::Constant && 3430 N1.getOperand(1).getOpcode() == ISD::Constant && 3431 // Don't increase # computations. 3432 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3433 // We can only do this xform if we know that bits from X that are set in C2 3434 // but not in C1 are already zero. Likewise for Y. 3435 const APInt &LHSMask = 3436 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3437 const APInt &RHSMask = 3438 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3439 3440 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3441 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3442 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3443 N0.getOperand(0), N1.getOperand(0)); 3444 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X, 3445 DAG.getConstant(LHSMask | RHSMask, VT)); 3446 } 3447 } 3448 3449 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3450 if (N0.getOpcode() == ISD::AND && 3451 N1.getOpcode() == ISD::AND && 3452 N0.getOperand(0) == N1.getOperand(0) && 3453 // Don't increase # computations. 3454 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3455 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3456 N0.getOperand(1), N1.getOperand(1)); 3457 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3458 } 3459 3460 return SDValue(); 3461 } 3462 3463 SDValue DAGCombiner::visitOR(SDNode *N) { 3464 SDValue N0 = N->getOperand(0); 3465 SDValue N1 = N->getOperand(1); 3466 EVT VT = N1.getValueType(); 3467 3468 // fold vector ops 3469 if (VT.isVector()) { 3470 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3471 return FoldedVOp; 3472 3473 // fold (or x, 0) -> x, vector edition 3474 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3475 return N1; 3476 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3477 return N0; 3478 3479 // fold (or x, -1) -> -1, vector edition 3480 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3481 // do not return N0, because undef node may exist in N0 3482 return DAG.getConstant( 3483 APInt::getAllOnesValue( 3484 N0.getValueType().getScalarType().getSizeInBits()), 3485 N0.getValueType()); 3486 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3487 // do not return N1, because undef node may exist in N1 3488 return DAG.getConstant( 3489 APInt::getAllOnesValue( 3490 N1.getValueType().getScalarType().getSizeInBits()), 3491 N1.getValueType()); 3492 3493 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3494 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3495 // Do this only if the resulting shuffle is legal. 3496 if (isa<ShuffleVectorSDNode>(N0) && 3497 isa<ShuffleVectorSDNode>(N1) && 3498 // Avoid folding a node with illegal type. 3499 TLI.isTypeLegal(VT) && 3500 N0->getOperand(1) == N1->getOperand(1) && 3501 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3502 bool CanFold = true; 3503 unsigned NumElts = VT.getVectorNumElements(); 3504 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3505 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3506 // We construct two shuffle masks: 3507 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3508 // and N1 as the second operand. 3509 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3510 // and N0 as the second operand. 3511 // We do this because OR is commutable and therefore there might be 3512 // two ways to fold this node into a shuffle. 3513 SmallVector<int,4> Mask1; 3514 SmallVector<int,4> Mask2; 3515 3516 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3517 int M0 = SV0->getMaskElt(i); 3518 int M1 = SV1->getMaskElt(i); 3519 3520 // Both shuffle indexes are undef. Propagate Undef. 3521 if (M0 < 0 && M1 < 0) { 3522 Mask1.push_back(M0); 3523 Mask2.push_back(M0); 3524 continue; 3525 } 3526 3527 if (M0 < 0 || M1 < 0 || 3528 (M0 < (int)NumElts && M1 < (int)NumElts) || 3529 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3530 CanFold = false; 3531 break; 3532 } 3533 3534 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3535 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3536 } 3537 3538 if (CanFold) { 3539 // Fold this sequence only if the resulting shuffle is 'legal'. 3540 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3541 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3542 N1->getOperand(0), &Mask1[0]); 3543 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3544 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3545 N0->getOperand(0), &Mask2[0]); 3546 } 3547 } 3548 } 3549 3550 // fold (or c1, c2) -> c1|c2 3551 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3552 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3553 if (N0C && N1C) 3554 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3555 // canonicalize constant to RHS 3556 if (isConstantIntBuildVectorOrConstantInt(N0) && 3557 !isConstantIntBuildVectorOrConstantInt(N1)) 3558 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3559 // fold (or x, 0) -> x 3560 if (N1C && N1C->isNullValue()) 3561 return N0; 3562 // fold (or x, -1) -> -1 3563 if (N1C && N1C->isAllOnesValue()) 3564 return N1; 3565 // fold (or x, c) -> c iff (x & ~c) == 0 3566 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3567 return N1; 3568 3569 if (SDValue Combined = visitORLike(N0, N1, N)) 3570 return Combined; 3571 3572 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3573 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3574 if (BSwap.getNode()) 3575 return BSwap; 3576 BSwap = MatchBSwapHWordLow(N, N0, N1); 3577 if (BSwap.getNode()) 3578 return BSwap; 3579 3580 // reassociate or 3581 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3582 return ROR; 3583 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3584 // iff (c1 & c2) == 0. 3585 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3586 isa<ConstantSDNode>(N0.getOperand(1))) { 3587 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3588 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3589 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1)) 3590 return DAG.getNode( 3591 ISD::AND, SDLoc(N), VT, 3592 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3593 return SDValue(); 3594 } 3595 } 3596 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3597 if (N0.getOpcode() == N1.getOpcode()) { 3598 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3599 if (Tmp.getNode()) return Tmp; 3600 } 3601 3602 // See if this is some rotate idiom. 3603 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3604 return SDValue(Rot, 0); 3605 3606 // Simplify the operands using demanded-bits information. 3607 if (!VT.isVector() && 3608 SimplifyDemandedBits(SDValue(N, 0))) 3609 return SDValue(N, 0); 3610 3611 return SDValue(); 3612 } 3613 3614 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3615 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3616 if (Op.getOpcode() == ISD::AND) { 3617 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3618 Mask = Op.getOperand(1); 3619 Op = Op.getOperand(0); 3620 } else { 3621 return false; 3622 } 3623 } 3624 3625 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3626 Shift = Op; 3627 return true; 3628 } 3629 3630 return false; 3631 } 3632 3633 // Return true if we can prove that, whenever Neg and Pos are both in the 3634 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3635 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3636 // 3637 // (or (shift1 X, Neg), (shift2 X, Pos)) 3638 // 3639 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3640 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3641 // to consider shift amounts with defined behavior. 3642 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3643 // If OpSize is a power of 2 then: 3644 // 3645 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3646 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3647 // 3648 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3649 // for the stronger condition: 3650 // 3651 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3652 // 3653 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3654 // we can just replace Neg with Neg' for the rest of the function. 3655 // 3656 // In other cases we check for the even stronger condition: 3657 // 3658 // Neg == OpSize - Pos [B] 3659 // 3660 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3661 // behavior if Pos == 0 (and consequently Neg == OpSize). 3662 // 3663 // We could actually use [A] whenever OpSize is a power of 2, but the 3664 // only extra cases that it would match are those uninteresting ones 3665 // where Neg and Pos are never in range at the same time. E.g. for 3666 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3667 // as well as (sub 32, Pos), but: 3668 // 3669 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3670 // 3671 // always invokes undefined behavior for 32-bit X. 3672 // 3673 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3674 unsigned MaskLoBits = 0; 3675 if (Neg.getOpcode() == ISD::AND && 3676 isPowerOf2_64(OpSize) && 3677 Neg.getOperand(1).getOpcode() == ISD::Constant && 3678 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3679 Neg = Neg.getOperand(0); 3680 MaskLoBits = Log2_64(OpSize); 3681 } 3682 3683 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3684 if (Neg.getOpcode() != ISD::SUB) 3685 return 0; 3686 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3687 if (!NegC) 3688 return 0; 3689 SDValue NegOp1 = Neg.getOperand(1); 3690 3691 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3692 // Pos'. The truncation is redundant for the purpose of the equality. 3693 if (MaskLoBits && 3694 Pos.getOpcode() == ISD::AND && 3695 Pos.getOperand(1).getOpcode() == ISD::Constant && 3696 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3697 Pos = Pos.getOperand(0); 3698 3699 // The condition we need is now: 3700 // 3701 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3702 // 3703 // If NegOp1 == Pos then we need: 3704 // 3705 // OpSize & Mask == NegC & Mask 3706 // 3707 // (because "x & Mask" is a truncation and distributes through subtraction). 3708 APInt Width; 3709 if (Pos == NegOp1) 3710 Width = NegC->getAPIntValue(); 3711 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3712 // Then the condition we want to prove becomes: 3713 // 3714 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3715 // 3716 // which, again because "x & Mask" is a truncation, becomes: 3717 // 3718 // NegC & Mask == (OpSize - PosC) & Mask 3719 // OpSize & Mask == (NegC + PosC) & Mask 3720 else if (Pos.getOpcode() == ISD::ADD && 3721 Pos.getOperand(0) == NegOp1 && 3722 Pos.getOperand(1).getOpcode() == ISD::Constant) 3723 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3724 NegC->getAPIntValue()); 3725 else 3726 return false; 3727 3728 // Now we just need to check that OpSize & Mask == Width & Mask. 3729 if (MaskLoBits) 3730 // Opsize & Mask is 0 since Mask is Opsize - 1. 3731 return Width.getLoBits(MaskLoBits) == 0; 3732 return Width == OpSize; 3733 } 3734 3735 // A subroutine of MatchRotate used once we have found an OR of two opposite 3736 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3737 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3738 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3739 // Neg with outer conversions stripped away. 3740 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3741 SDValue Neg, SDValue InnerPos, 3742 SDValue InnerNeg, unsigned PosOpcode, 3743 unsigned NegOpcode, SDLoc DL) { 3744 // fold (or (shl x, (*ext y)), 3745 // (srl x, (*ext (sub 32, y)))) -> 3746 // (rotl x, y) or (rotr x, (sub 32, y)) 3747 // 3748 // fold (or (shl x, (*ext (sub 32, y))), 3749 // (srl x, (*ext y))) -> 3750 // (rotr x, y) or (rotl x, (sub 32, y)) 3751 EVT VT = Shifted.getValueType(); 3752 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3753 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3754 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3755 HasPos ? Pos : Neg).getNode(); 3756 } 3757 3758 return nullptr; 3759 } 3760 3761 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3762 // idioms for rotate, and if the target supports rotation instructions, generate 3763 // a rot[lr]. 3764 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3765 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3766 EVT VT = LHS.getValueType(); 3767 if (!TLI.isTypeLegal(VT)) return nullptr; 3768 3769 // The target must have at least one rotate flavor. 3770 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3771 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3772 if (!HasROTL && !HasROTR) return nullptr; 3773 3774 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3775 SDValue LHSShift; // The shift. 3776 SDValue LHSMask; // AND value if any. 3777 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3778 return nullptr; // Not part of a rotate. 3779 3780 SDValue RHSShift; // The shift. 3781 SDValue RHSMask; // AND value if any. 3782 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3783 return nullptr; // Not part of a rotate. 3784 3785 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3786 return nullptr; // Not shifting the same value. 3787 3788 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3789 return nullptr; // Shifts must disagree. 3790 3791 // Canonicalize shl to left side in a shl/srl pair. 3792 if (RHSShift.getOpcode() == ISD::SHL) { 3793 std::swap(LHS, RHS); 3794 std::swap(LHSShift, RHSShift); 3795 std::swap(LHSMask , RHSMask ); 3796 } 3797 3798 unsigned OpSizeInBits = VT.getSizeInBits(); 3799 SDValue LHSShiftArg = LHSShift.getOperand(0); 3800 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3801 SDValue RHSShiftArg = RHSShift.getOperand(0); 3802 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3803 3804 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3805 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3806 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3807 RHSShiftAmt.getOpcode() == ISD::Constant) { 3808 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3809 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3810 if ((LShVal + RShVal) != OpSizeInBits) 3811 return nullptr; 3812 3813 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3814 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3815 3816 // If there is an AND of either shifted operand, apply it to the result. 3817 if (LHSMask.getNode() || RHSMask.getNode()) { 3818 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3819 3820 if (LHSMask.getNode()) { 3821 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3822 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3823 } 3824 if (RHSMask.getNode()) { 3825 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3826 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3827 } 3828 3829 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3830 } 3831 3832 return Rot.getNode(); 3833 } 3834 3835 // If there is a mask here, and we have a variable shift, we can't be sure 3836 // that we're masking out the right stuff. 3837 if (LHSMask.getNode() || RHSMask.getNode()) 3838 return nullptr; 3839 3840 // If the shift amount is sign/zext/any-extended just peel it off. 3841 SDValue LExtOp0 = LHSShiftAmt; 3842 SDValue RExtOp0 = RHSShiftAmt; 3843 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3844 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3845 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3846 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3847 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3848 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3849 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3850 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3851 LExtOp0 = LHSShiftAmt.getOperand(0); 3852 RExtOp0 = RHSShiftAmt.getOperand(0); 3853 } 3854 3855 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3856 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3857 if (TryL) 3858 return TryL; 3859 3860 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3861 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3862 if (TryR) 3863 return TryR; 3864 3865 return nullptr; 3866 } 3867 3868 SDValue DAGCombiner::visitXOR(SDNode *N) { 3869 SDValue N0 = N->getOperand(0); 3870 SDValue N1 = N->getOperand(1); 3871 EVT VT = N0.getValueType(); 3872 3873 // fold vector ops 3874 if (VT.isVector()) { 3875 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3876 return FoldedVOp; 3877 3878 // fold (xor x, 0) -> x, vector edition 3879 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3880 return N1; 3881 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3882 return N0; 3883 } 3884 3885 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3886 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3887 return DAG.getConstant(0, VT); 3888 // fold (xor x, undef) -> undef 3889 if (N0.getOpcode() == ISD::UNDEF) 3890 return N0; 3891 if (N1.getOpcode() == ISD::UNDEF) 3892 return N1; 3893 // fold (xor c1, c2) -> c1^c2 3894 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3895 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3896 if (N0C && N1C) 3897 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3898 // canonicalize constant to RHS 3899 if (isConstantIntBuildVectorOrConstantInt(N0) && 3900 !isConstantIntBuildVectorOrConstantInt(N1)) 3901 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3902 // fold (xor x, 0) -> x 3903 if (N1C && N1C->isNullValue()) 3904 return N0; 3905 // reassociate xor 3906 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 3907 return RXOR; 3908 3909 // fold !(x cc y) -> (x !cc y) 3910 SDValue LHS, RHS, CC; 3911 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3912 bool isInt = LHS.getValueType().isInteger(); 3913 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3914 isInt); 3915 3916 if (!LegalOperations || 3917 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3918 switch (N0.getOpcode()) { 3919 default: 3920 llvm_unreachable("Unhandled SetCC Equivalent!"); 3921 case ISD::SETCC: 3922 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3923 case ISD::SELECT_CC: 3924 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3925 N0.getOperand(3), NotCC); 3926 } 3927 } 3928 } 3929 3930 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3931 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3932 N0.getNode()->hasOneUse() && 3933 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3934 SDValue V = N0.getOperand(0); 3935 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3936 DAG.getConstant(1, V.getValueType())); 3937 AddToWorklist(V.getNode()); 3938 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3939 } 3940 3941 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3942 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3943 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3944 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3945 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3946 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3947 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3948 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3949 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3950 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3951 } 3952 } 3953 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3954 if (N1C && N1C->isAllOnesValue() && 3955 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3956 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3957 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3958 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3959 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3960 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3961 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3962 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3963 } 3964 } 3965 // fold (xor (and x, y), y) -> (and (not x), y) 3966 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3967 N0->getOperand(1) == N1) { 3968 SDValue X = N0->getOperand(0); 3969 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3970 AddToWorklist(NotX.getNode()); 3971 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3972 } 3973 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3974 if (N1C && N0.getOpcode() == ISD::XOR) { 3975 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3976 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3977 if (N00C) 3978 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3979 DAG.getConstant(N1C->getAPIntValue() ^ 3980 N00C->getAPIntValue(), VT)); 3981 if (N01C) 3982 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3983 DAG.getConstant(N1C->getAPIntValue() ^ 3984 N01C->getAPIntValue(), VT)); 3985 } 3986 // fold (xor x, x) -> 0 3987 if (N0 == N1) 3988 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3989 3990 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 3991 // Here is a concrete example of this equivalence: 3992 // i16 x == 14 3993 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 3994 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 3995 // 3996 // => 3997 // 3998 // i16 ~1 == 0b1111111111111110 3999 // i16 rol(~1, 14) == 0b1011111111111111 4000 // 4001 // Some additional tips to help conceptualize this transform: 4002 // - Try to see the operation as placing a single zero in a value of all ones. 4003 // - There exists no value for x which would allow the result to contain zero. 4004 // - Values of x larger than the bitwidth are undefined and do not require a 4005 // consistent result. 4006 // - Pushing the zero left requires shifting one bits in from the right. 4007 // A rotate left of ~1 is a nice way of achieving the desired result. 4008 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4009 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) 4010 if (N0.getOpcode() == ISD::SHL) 4011 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 4012 if (N1C->isAllOnesValue() && ShlLHS->isOne()) 4013 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT), 4014 N0.getOperand(1)); 4015 4016 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4017 if (N0.getOpcode() == N1.getOpcode()) { 4018 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 4019 if (Tmp.getNode()) return Tmp; 4020 } 4021 4022 // Simplify the expression using non-local knowledge. 4023 if (!VT.isVector() && 4024 SimplifyDemandedBits(SDValue(N, 0))) 4025 return SDValue(N, 0); 4026 4027 return SDValue(); 4028 } 4029 4030 /// Handle transforms common to the three shifts, when the shift amount is a 4031 /// constant. 4032 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4033 // We can't and shouldn't fold opaque constants. 4034 if (Amt->isOpaque()) 4035 return SDValue(); 4036 4037 SDNode *LHS = N->getOperand(0).getNode(); 4038 if (!LHS->hasOneUse()) return SDValue(); 4039 4040 // We want to pull some binops through shifts, so that we have (and (shift)) 4041 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4042 // thing happens with address calculations, so it's important to canonicalize 4043 // it. 4044 bool HighBitSet = false; // Can we transform this if the high bit is set? 4045 4046 switch (LHS->getOpcode()) { 4047 default: return SDValue(); 4048 case ISD::OR: 4049 case ISD::XOR: 4050 HighBitSet = false; // We can only transform sra if the high bit is clear. 4051 break; 4052 case ISD::AND: 4053 HighBitSet = true; // We can only transform sra if the high bit is set. 4054 break; 4055 case ISD::ADD: 4056 if (N->getOpcode() != ISD::SHL) 4057 return SDValue(); // only shl(add) not sr[al](add). 4058 HighBitSet = false; // We can only transform sra if the high bit is clear. 4059 break; 4060 } 4061 4062 // We require the RHS of the binop to be a constant and not opaque as well. 4063 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 4064 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue(); 4065 4066 // FIXME: disable this unless the input to the binop is a shift by a constant. 4067 // If it is not a shift, it pessimizes some common cases like: 4068 // 4069 // void foo(int *X, int i) { X[i & 1235] = 1; } 4070 // int bar(int *X, int i) { return X[i & 255]; } 4071 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4072 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4073 BinOpLHSVal->getOpcode() != ISD::SRA && 4074 BinOpLHSVal->getOpcode() != ISD::SRL) || 4075 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4076 return SDValue(); 4077 4078 EVT VT = N->getValueType(0); 4079 4080 // If this is a signed shift right, and the high bit is modified by the 4081 // logical operation, do not perform the transformation. The highBitSet 4082 // boolean indicates the value of the high bit of the constant which would 4083 // cause it to be modified for this operation. 4084 if (N->getOpcode() == ISD::SRA) { 4085 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4086 if (BinOpRHSSignSet != HighBitSet) 4087 return SDValue(); 4088 } 4089 4090 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4091 return SDValue(); 4092 4093 // Fold the constants, shifting the binop RHS by the shift amount. 4094 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4095 N->getValueType(0), 4096 LHS->getOperand(1), N->getOperand(1)); 4097 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4098 4099 // Create the new shift. 4100 SDValue NewShift = DAG.getNode(N->getOpcode(), 4101 SDLoc(LHS->getOperand(0)), 4102 VT, LHS->getOperand(0), N->getOperand(1)); 4103 4104 // Create the new binop. 4105 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4106 } 4107 4108 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4109 assert(N->getOpcode() == ISD::TRUNCATE); 4110 assert(N->getOperand(0).getOpcode() == ISD::AND); 4111 4112 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4113 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4114 SDValue N01 = N->getOperand(0).getOperand(1); 4115 4116 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4117 EVT TruncVT = N->getValueType(0); 4118 SDValue N00 = N->getOperand(0).getOperand(0); 4119 APInt TruncC = N01C->getAPIntValue(); 4120 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4121 4122 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 4123 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00), 4124 DAG.getConstant(TruncC, TruncVT)); 4125 } 4126 } 4127 4128 return SDValue(); 4129 } 4130 4131 SDValue DAGCombiner::visitRotate(SDNode *N) { 4132 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4133 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4134 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4135 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4136 if (NewOp1.getNode()) 4137 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4138 N->getOperand(0), NewOp1); 4139 } 4140 return SDValue(); 4141 } 4142 4143 SDValue DAGCombiner::visitSHL(SDNode *N) { 4144 SDValue N0 = N->getOperand(0); 4145 SDValue N1 = N->getOperand(1); 4146 EVT VT = N0.getValueType(); 4147 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4148 4149 // fold vector ops 4150 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4151 if (VT.isVector()) { 4152 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4153 return FoldedVOp; 4154 4155 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4156 // If setcc produces all-one true value then: 4157 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4158 if (N1CV && N1CV->isConstant()) { 4159 if (N0.getOpcode() == ISD::AND) { 4160 SDValue N00 = N0->getOperand(0); 4161 SDValue N01 = N0->getOperand(1); 4162 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4163 4164 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4165 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4166 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4167 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV)) 4168 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4169 } 4170 } else { 4171 N1C = isConstOrConstSplat(N1); 4172 } 4173 } 4174 } 4175 4176 // fold (shl c1, c2) -> c1<<c2 4177 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4178 if (N0C && N1C) 4179 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 4180 // fold (shl 0, x) -> 0 4181 if (N0C && N0C->isNullValue()) 4182 return N0; 4183 // fold (shl x, c >= size(x)) -> undef 4184 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4185 return DAG.getUNDEF(VT); 4186 // fold (shl x, 0) -> x 4187 if (N1C && N1C->isNullValue()) 4188 return N0; 4189 // fold (shl undef, x) -> 0 4190 if (N0.getOpcode() == ISD::UNDEF) 4191 return DAG.getConstant(0, VT); 4192 // if (shl x, c) is known to be zero, return 0 4193 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4194 APInt::getAllOnesValue(OpSizeInBits))) 4195 return DAG.getConstant(0, VT); 4196 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4197 if (N1.getOpcode() == ISD::TRUNCATE && 4198 N1.getOperand(0).getOpcode() == ISD::AND) { 4199 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4200 if (NewOp1.getNode()) 4201 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4202 } 4203 4204 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4205 return SDValue(N, 0); 4206 4207 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4208 if (N1C && N0.getOpcode() == ISD::SHL) { 4209 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4210 uint64_t c1 = N0C1->getZExtValue(); 4211 uint64_t c2 = N1C->getZExtValue(); 4212 if (c1 + c2 >= OpSizeInBits) 4213 return DAG.getConstant(0, VT); 4214 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4215 DAG.getConstant(c1 + c2, N1.getValueType())); 4216 } 4217 } 4218 4219 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4220 // For this to be valid, the second form must not preserve any of the bits 4221 // that are shifted out by the inner shift in the first form. This means 4222 // the outer shift size must be >= the number of bits added by the ext. 4223 // As a corollary, we don't care what kind of ext it is. 4224 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4225 N0.getOpcode() == ISD::ANY_EXTEND || 4226 N0.getOpcode() == ISD::SIGN_EXTEND) && 4227 N0.getOperand(0).getOpcode() == ISD::SHL) { 4228 SDValue N0Op0 = N0.getOperand(0); 4229 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4230 uint64_t c1 = N0Op0C1->getZExtValue(); 4231 uint64_t c2 = N1C->getZExtValue(); 4232 EVT InnerShiftVT = N0Op0.getValueType(); 4233 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4234 if (c2 >= OpSizeInBits - InnerShiftSize) { 4235 if (c1 + c2 >= OpSizeInBits) 4236 return DAG.getConstant(0, VT); 4237 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 4238 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 4239 N0Op0->getOperand(0)), 4240 DAG.getConstant(c1 + c2, N1.getValueType())); 4241 } 4242 } 4243 } 4244 4245 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4246 // Only fold this if the inner zext has no other uses to avoid increasing 4247 // the total number of instructions. 4248 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4249 N0.getOperand(0).getOpcode() == ISD::SRL) { 4250 SDValue N0Op0 = N0.getOperand(0); 4251 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4252 uint64_t c1 = N0Op0C1->getZExtValue(); 4253 if (c1 < VT.getScalarSizeInBits()) { 4254 uint64_t c2 = N1C->getZExtValue(); 4255 if (c1 == c2) { 4256 SDValue NewOp0 = N0.getOperand(0); 4257 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4258 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(), 4259 NewOp0, DAG.getConstant(c2, CountVT)); 4260 AddToWorklist(NewSHL.getNode()); 4261 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4262 } 4263 } 4264 } 4265 } 4266 4267 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4268 // (and (srl x, (sub c1, c2), MASK) 4269 // Only fold this if the inner shift has no other uses -- if it does, folding 4270 // this will increase the total number of instructions. 4271 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4272 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4273 uint64_t c1 = N0C1->getZExtValue(); 4274 if (c1 < OpSizeInBits) { 4275 uint64_t c2 = N1C->getZExtValue(); 4276 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4277 SDValue Shift; 4278 if (c2 > c1) { 4279 Mask = Mask.shl(c2 - c1); 4280 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4281 DAG.getConstant(c2 - c1, N1.getValueType())); 4282 } else { 4283 Mask = Mask.lshr(c1 - c2); 4284 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4285 DAG.getConstant(c1 - c2, N1.getValueType())); 4286 } 4287 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 4288 DAG.getConstant(Mask, VT)); 4289 } 4290 } 4291 } 4292 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4293 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4294 unsigned BitSize = VT.getScalarSizeInBits(); 4295 SDValue HiBitsMask = 4296 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4297 BitSize - N1C->getZExtValue()), VT); 4298 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4299 HiBitsMask); 4300 } 4301 4302 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4303 // Variant of version done on multiply, except mul by a power of 2 is turned 4304 // into a shift. 4305 APInt Val; 4306 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4307 (isa<ConstantSDNode>(N0.getOperand(1)) || 4308 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4309 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4310 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4311 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4312 } 4313 4314 if (N1C) { 4315 SDValue NewSHL = visitShiftByConstant(N, N1C); 4316 if (NewSHL.getNode()) 4317 return NewSHL; 4318 } 4319 4320 return SDValue(); 4321 } 4322 4323 SDValue DAGCombiner::visitSRA(SDNode *N) { 4324 SDValue N0 = N->getOperand(0); 4325 SDValue N1 = N->getOperand(1); 4326 EVT VT = N0.getValueType(); 4327 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4328 4329 // fold vector ops 4330 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4331 if (VT.isVector()) { 4332 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4333 return FoldedVOp; 4334 4335 N1C = isConstOrConstSplat(N1); 4336 } 4337 4338 // fold (sra c1, c2) -> (sra c1, c2) 4339 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4340 if (N0C && N1C) 4341 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 4342 // fold (sra 0, x) -> 0 4343 if (N0C && N0C->isNullValue()) 4344 return N0; 4345 // fold (sra -1, x) -> -1 4346 if (N0C && N0C->isAllOnesValue()) 4347 return N0; 4348 // fold (sra x, (setge c, size(x))) -> undef 4349 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4350 return DAG.getUNDEF(VT); 4351 // fold (sra x, 0) -> x 4352 if (N1C && N1C->isNullValue()) 4353 return N0; 4354 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4355 // sext_inreg. 4356 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4357 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4358 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4359 if (VT.isVector()) 4360 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4361 ExtVT, VT.getVectorNumElements()); 4362 if ((!LegalOperations || 4363 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4364 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4365 N0.getOperand(0), DAG.getValueType(ExtVT)); 4366 } 4367 4368 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4369 if (N1C && N0.getOpcode() == ISD::SRA) { 4370 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4371 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4372 if (Sum >= OpSizeInBits) 4373 Sum = OpSizeInBits - 1; 4374 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 4375 DAG.getConstant(Sum, N1.getValueType())); 4376 } 4377 } 4378 4379 // fold (sra (shl X, m), (sub result_size, n)) 4380 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4381 // result_size - n != m. 4382 // If truncate is free for the target sext(shl) is likely to result in better 4383 // code. 4384 if (N0.getOpcode() == ISD::SHL && N1C) { 4385 // Get the two constanst of the shifts, CN0 = m, CN = n. 4386 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4387 if (N01C) { 4388 LLVMContext &Ctx = *DAG.getContext(); 4389 // Determine what the truncate's result bitsize and type would be. 4390 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4391 4392 if (VT.isVector()) 4393 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4394 4395 // Determine the residual right-shift amount. 4396 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4397 4398 // If the shift is not a no-op (in which case this should be just a sign 4399 // extend already), the truncated to type is legal, sign_extend is legal 4400 // on that type, and the truncate to that type is both legal and free, 4401 // perform the transform. 4402 if ((ShiftAmt > 0) && 4403 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4404 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4405 TLI.isTruncateFree(VT, TruncVT)) { 4406 4407 SDValue Amt = DAG.getConstant(ShiftAmt, 4408 getShiftAmountTy(N0.getOperand(0).getValueType())); 4409 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 4410 N0.getOperand(0), Amt); 4411 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 4412 Shift); 4413 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 4414 N->getValueType(0), Trunc); 4415 } 4416 } 4417 } 4418 4419 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4420 if (N1.getOpcode() == ISD::TRUNCATE && 4421 N1.getOperand(0).getOpcode() == ISD::AND) { 4422 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4423 if (NewOp1.getNode()) 4424 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4425 } 4426 4427 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4428 // if c1 is equal to the number of bits the trunc removes 4429 if (N0.getOpcode() == ISD::TRUNCATE && 4430 (N0.getOperand(0).getOpcode() == ISD::SRL || 4431 N0.getOperand(0).getOpcode() == ISD::SRA) && 4432 N0.getOperand(0).hasOneUse() && 4433 N0.getOperand(0).getOperand(1).hasOneUse() && 4434 N1C) { 4435 SDValue N0Op0 = N0.getOperand(0); 4436 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4437 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4438 EVT LargeVT = N0Op0.getValueType(); 4439 4440 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4441 SDValue Amt = 4442 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), 4443 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4444 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 4445 N0Op0.getOperand(0), Amt); 4446 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 4447 } 4448 } 4449 } 4450 4451 // Simplify, based on bits shifted out of the LHS. 4452 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4453 return SDValue(N, 0); 4454 4455 4456 // If the sign bit is known to be zero, switch this to a SRL. 4457 if (DAG.SignBitIsZero(N0)) 4458 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4459 4460 if (N1C) { 4461 SDValue NewSRA = visitShiftByConstant(N, N1C); 4462 if (NewSRA.getNode()) 4463 return NewSRA; 4464 } 4465 4466 return SDValue(); 4467 } 4468 4469 SDValue DAGCombiner::visitSRL(SDNode *N) { 4470 SDValue N0 = N->getOperand(0); 4471 SDValue N1 = N->getOperand(1); 4472 EVT VT = N0.getValueType(); 4473 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4474 4475 // fold vector ops 4476 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4477 if (VT.isVector()) { 4478 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4479 return FoldedVOp; 4480 4481 N1C = isConstOrConstSplat(N1); 4482 } 4483 4484 // fold (srl c1, c2) -> c1 >>u c2 4485 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4486 if (N0C && N1C) 4487 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 4488 // fold (srl 0, x) -> 0 4489 if (N0C && N0C->isNullValue()) 4490 return N0; 4491 // fold (srl x, c >= size(x)) -> undef 4492 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4493 return DAG.getUNDEF(VT); 4494 // fold (srl x, 0) -> x 4495 if (N1C && N1C->isNullValue()) 4496 return N0; 4497 // if (srl x, c) is known to be zero, return 0 4498 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4499 APInt::getAllOnesValue(OpSizeInBits))) 4500 return DAG.getConstant(0, VT); 4501 4502 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4503 if (N1C && N0.getOpcode() == ISD::SRL) { 4504 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4505 uint64_t c1 = N01C->getZExtValue(); 4506 uint64_t c2 = N1C->getZExtValue(); 4507 if (c1 + c2 >= OpSizeInBits) 4508 return DAG.getConstant(0, VT); 4509 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4510 DAG.getConstant(c1 + c2, N1.getValueType())); 4511 } 4512 } 4513 4514 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4515 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4516 N0.getOperand(0).getOpcode() == ISD::SRL && 4517 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4518 uint64_t c1 = 4519 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4520 uint64_t c2 = N1C->getZExtValue(); 4521 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4522 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4523 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4524 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4525 if (c1 + OpSizeInBits == InnerShiftSize) { 4526 if (c1 + c2 >= InnerShiftSize) 4527 return DAG.getConstant(0, VT); 4528 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 4529 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 4530 N0.getOperand(0)->getOperand(0), 4531 DAG.getConstant(c1 + c2, ShiftCountVT))); 4532 } 4533 } 4534 4535 // fold (srl (shl x, c), c) -> (and x, cst2) 4536 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4537 unsigned BitSize = N0.getScalarValueSizeInBits(); 4538 if (BitSize <= 64) { 4539 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4540 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4541 DAG.getConstant(~0ULL >> ShAmt, VT)); 4542 } 4543 } 4544 4545 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4546 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4547 // Shifting in all undef bits? 4548 EVT SmallVT = N0.getOperand(0).getValueType(); 4549 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4550 if (N1C->getZExtValue() >= BitSize) 4551 return DAG.getUNDEF(VT); 4552 4553 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4554 uint64_t ShiftAmt = N1C->getZExtValue(); 4555 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 4556 N0.getOperand(0), 4557 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 4558 AddToWorklist(SmallShift.getNode()); 4559 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4560 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4561 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 4562 DAG.getConstant(Mask, VT)); 4563 } 4564 } 4565 4566 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4567 // bit, which is unmodified by sra. 4568 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4569 if (N0.getOpcode() == ISD::SRA) 4570 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4571 } 4572 4573 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4574 if (N1C && N0.getOpcode() == ISD::CTLZ && 4575 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4576 APInt KnownZero, KnownOne; 4577 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4578 4579 // If any of the input bits are KnownOne, then the input couldn't be all 4580 // zeros, thus the result of the srl will always be zero. 4581 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4582 4583 // If all of the bits input the to ctlz node are known to be zero, then 4584 // the result of the ctlz is "32" and the result of the shift is one. 4585 APInt UnknownBits = ~KnownZero; 4586 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4587 4588 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4589 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4590 // Okay, we know that only that the single bit specified by UnknownBits 4591 // could be set on input to the CTLZ node. If this bit is set, the SRL 4592 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4593 // to an SRL/XOR pair, which is likely to simplify more. 4594 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4595 SDValue Op = N0.getOperand(0); 4596 4597 if (ShAmt) { 4598 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4599 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4600 AddToWorklist(Op.getNode()); 4601 } 4602 4603 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4604 Op, DAG.getConstant(1, VT)); 4605 } 4606 } 4607 4608 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4609 if (N1.getOpcode() == ISD::TRUNCATE && 4610 N1.getOperand(0).getOpcode() == ISD::AND) { 4611 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4612 if (NewOp1.getNode()) 4613 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4614 } 4615 4616 // fold operands of srl based on knowledge that the low bits are not 4617 // demanded. 4618 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4619 return SDValue(N, 0); 4620 4621 if (N1C) { 4622 SDValue NewSRL = visitShiftByConstant(N, N1C); 4623 if (NewSRL.getNode()) 4624 return NewSRL; 4625 } 4626 4627 // Attempt to convert a srl of a load into a narrower zero-extending load. 4628 SDValue NarrowLoad = ReduceLoadWidth(N); 4629 if (NarrowLoad.getNode()) 4630 return NarrowLoad; 4631 4632 // Here is a common situation. We want to optimize: 4633 // 4634 // %a = ... 4635 // %b = and i32 %a, 2 4636 // %c = srl i32 %b, 1 4637 // brcond i32 %c ... 4638 // 4639 // into 4640 // 4641 // %a = ... 4642 // %b = and %a, 2 4643 // %c = setcc eq %b, 0 4644 // brcond %c ... 4645 // 4646 // However when after the source operand of SRL is optimized into AND, the SRL 4647 // itself may not be optimized further. Look for it and add the BRCOND into 4648 // the worklist. 4649 if (N->hasOneUse()) { 4650 SDNode *Use = *N->use_begin(); 4651 if (Use->getOpcode() == ISD::BRCOND) 4652 AddToWorklist(Use); 4653 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4654 // Also look pass the truncate. 4655 Use = *Use->use_begin(); 4656 if (Use->getOpcode() == ISD::BRCOND) 4657 AddToWorklist(Use); 4658 } 4659 } 4660 4661 return SDValue(); 4662 } 4663 4664 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4665 SDValue N0 = N->getOperand(0); 4666 EVT VT = N->getValueType(0); 4667 4668 // fold (ctlz c1) -> c2 4669 if (isa<ConstantSDNode>(N0)) 4670 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4671 return SDValue(); 4672 } 4673 4674 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4675 SDValue N0 = N->getOperand(0); 4676 EVT VT = N->getValueType(0); 4677 4678 // fold (ctlz_zero_undef c1) -> c2 4679 if (isa<ConstantSDNode>(N0)) 4680 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4681 return SDValue(); 4682 } 4683 4684 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4685 SDValue N0 = N->getOperand(0); 4686 EVT VT = N->getValueType(0); 4687 4688 // fold (cttz c1) -> c2 4689 if (isa<ConstantSDNode>(N0)) 4690 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4691 return SDValue(); 4692 } 4693 4694 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4695 SDValue N0 = N->getOperand(0); 4696 EVT VT = N->getValueType(0); 4697 4698 // fold (cttz_zero_undef c1) -> c2 4699 if (isa<ConstantSDNode>(N0)) 4700 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4701 return SDValue(); 4702 } 4703 4704 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4705 SDValue N0 = N->getOperand(0); 4706 EVT VT = N->getValueType(0); 4707 4708 // fold (ctpop c1) -> c2 4709 if (isa<ConstantSDNode>(N0)) 4710 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4711 return SDValue(); 4712 } 4713 4714 4715 /// \brief Generate Min/Max node 4716 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4717 SDValue True, SDValue False, 4718 ISD::CondCode CC, const TargetLowering &TLI, 4719 SelectionDAG &DAG) { 4720 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4721 return SDValue(); 4722 4723 switch (CC) { 4724 case ISD::SETOLT: 4725 case ISD::SETOLE: 4726 case ISD::SETLT: 4727 case ISD::SETLE: 4728 case ISD::SETULT: 4729 case ISD::SETULE: { 4730 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4731 if (TLI.isOperationLegal(Opcode, VT)) 4732 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4733 return SDValue(); 4734 } 4735 case ISD::SETOGT: 4736 case ISD::SETOGE: 4737 case ISD::SETGT: 4738 case ISD::SETGE: 4739 case ISD::SETUGT: 4740 case ISD::SETUGE: { 4741 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4742 if (TLI.isOperationLegal(Opcode, VT)) 4743 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4744 return SDValue(); 4745 } 4746 default: 4747 return SDValue(); 4748 } 4749 } 4750 4751 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4752 SDValue N0 = N->getOperand(0); 4753 SDValue N1 = N->getOperand(1); 4754 SDValue N2 = N->getOperand(2); 4755 EVT VT = N->getValueType(0); 4756 EVT VT0 = N0.getValueType(); 4757 4758 // fold (select C, X, X) -> X 4759 if (N1 == N2) 4760 return N1; 4761 // fold (select true, X, Y) -> X 4762 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4763 if (N0C && !N0C->isNullValue()) 4764 return N1; 4765 // fold (select false, X, Y) -> Y 4766 if (N0C && N0C->isNullValue()) 4767 return N2; 4768 // fold (select C, 1, X) -> (or C, X) 4769 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4770 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4771 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4772 // fold (select C, 0, 1) -> (xor C, 1) 4773 // We can't do this reliably if integer based booleans have different contents 4774 // to floating point based booleans. This is because we can't tell whether we 4775 // have an integer-based boolean or a floating-point-based boolean unless we 4776 // can find the SETCC that produced it and inspect its operands. This is 4777 // fairly easy if C is the SETCC node, but it can potentially be 4778 // undiscoverable (or not reasonably discoverable). For example, it could be 4779 // in another basic block or it could require searching a complicated 4780 // expression. 4781 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4782 if (VT.isInteger() && 4783 (VT0 == MVT::i1 || (VT0.isInteger() && 4784 TLI.getBooleanContents(false, false) == 4785 TLI.getBooleanContents(false, true) && 4786 TLI.getBooleanContents(false, false) == 4787 TargetLowering::ZeroOrOneBooleanContent)) && 4788 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4789 SDValue XORNode; 4790 if (VT == VT0) 4791 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4792 N0, DAG.getConstant(1, VT0)); 4793 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4794 N0, DAG.getConstant(1, VT0)); 4795 AddToWorklist(XORNode.getNode()); 4796 if (VT.bitsGT(VT0)) 4797 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4798 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4799 } 4800 // fold (select C, 0, X) -> (and (not C), X) 4801 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4802 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4803 AddToWorklist(NOTNode.getNode()); 4804 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4805 } 4806 // fold (select C, X, 1) -> (or (not C), X) 4807 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4808 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4809 AddToWorklist(NOTNode.getNode()); 4810 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4811 } 4812 // fold (select C, X, 0) -> (and C, X) 4813 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4814 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4815 // fold (select X, X, Y) -> (or X, Y) 4816 // fold (select X, 1, Y) -> (or X, Y) 4817 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4818 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4819 // fold (select X, Y, X) -> (and X, Y) 4820 // fold (select X, Y, 0) -> (and X, Y) 4821 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4822 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4823 4824 // If we can fold this based on the true/false value, do so. 4825 if (SimplifySelectOps(N, N1, N2)) 4826 return SDValue(N, 0); // Don't revisit N. 4827 4828 // fold selects based on a setcc into other things, such as min/max/abs 4829 if (N0.getOpcode() == ISD::SETCC) { 4830 // select x, y (fcmp lt x, y) -> fminnum x, y 4831 // select x, y (fcmp gt x, y) -> fmaxnum x, y 4832 // 4833 // This is OK if we don't care about what happens if either operand is a 4834 // NaN. 4835 // 4836 4837 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 4838 // no signed zeros as well as no nans. 4839 const TargetOptions &Options = DAG.getTarget().Options; 4840 if (Options.UnsafeFPMath && 4841 VT.isFloatingPoint() && N0.hasOneUse() && 4842 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 4843 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4844 4845 SDValue FMinMax = 4846 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1), 4847 N1, N2, CC, TLI, DAG); 4848 if (FMinMax) 4849 return FMinMax; 4850 } 4851 4852 if ((!LegalOperations && 4853 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 4854 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 4855 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4856 N0.getOperand(0), N0.getOperand(1), 4857 N1, N2, N0.getOperand(2)); 4858 return SimplifySelect(SDLoc(N), N0, N1, N2); 4859 } 4860 4861 if (VT0 == MVT::i1) { 4862 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4863 // select (and Cond0, Cond1), X, Y 4864 // -> select Cond0, (select Cond1, X, Y), Y 4865 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 4866 SDValue Cond0 = N0->getOperand(0); 4867 SDValue Cond1 = N0->getOperand(1); 4868 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 4869 N1.getValueType(), Cond1, N1, N2); 4870 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 4871 InnerSelect, N2); 4872 } 4873 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 4874 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 4875 SDValue Cond0 = N0->getOperand(0); 4876 SDValue Cond1 = N0->getOperand(1); 4877 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 4878 N1.getValueType(), Cond1, N1, N2); 4879 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 4880 InnerSelect); 4881 } 4882 } 4883 4884 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 4885 if (N1->getOpcode() == ISD::SELECT) { 4886 SDValue N1_0 = N1->getOperand(0); 4887 SDValue N1_1 = N1->getOperand(1); 4888 SDValue N1_2 = N1->getOperand(2); 4889 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 4890 // Create the actual and node if we can generate good code for it. 4891 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4892 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 4893 N0, N1_0); 4894 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 4895 N1_1, N2); 4896 } 4897 // Otherwise see if we can optimize the "and" to a better pattern. 4898 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 4899 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 4900 N1_1, N2); 4901 } 4902 } 4903 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 4904 if (N2->getOpcode() == ISD::SELECT) { 4905 SDValue N2_0 = N2->getOperand(0); 4906 SDValue N2_1 = N2->getOperand(1); 4907 SDValue N2_2 = N2->getOperand(2); 4908 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 4909 // Create the actual or node if we can generate good code for it. 4910 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4911 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 4912 N0, N2_0); 4913 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 4914 N1, N2_2); 4915 } 4916 // Otherwise see if we can optimize to a better pattern. 4917 if (SDValue Combined = visitORLike(N0, N2_0, N)) 4918 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 4919 N1, N2_2); 4920 } 4921 } 4922 } 4923 4924 return SDValue(); 4925 } 4926 4927 static 4928 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 4929 SDLoc DL(N); 4930 EVT LoVT, HiVT; 4931 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 4932 4933 // Split the inputs. 4934 SDValue Lo, Hi, LL, LH, RL, RH; 4935 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 4936 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 4937 4938 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 4939 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 4940 4941 return std::make_pair(Lo, Hi); 4942 } 4943 4944 // This function assumes all the vselect's arguments are CONCAT_VECTOR 4945 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 4946 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 4947 SDLoc dl(N); 4948 SDValue Cond = N->getOperand(0); 4949 SDValue LHS = N->getOperand(1); 4950 SDValue RHS = N->getOperand(2); 4951 EVT VT = N->getValueType(0); 4952 int NumElems = VT.getVectorNumElements(); 4953 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 4954 RHS.getOpcode() == ISD::CONCAT_VECTORS && 4955 Cond.getOpcode() == ISD::BUILD_VECTOR); 4956 4957 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 4958 // binary ones here. 4959 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 4960 return SDValue(); 4961 4962 // We're sure we have an even number of elements due to the 4963 // concat_vectors we have as arguments to vselect. 4964 // Skip BV elements until we find one that's not an UNDEF 4965 // After we find an UNDEF element, keep looping until we get to half the 4966 // length of the BV and see if all the non-undef nodes are the same. 4967 ConstantSDNode *BottomHalf = nullptr; 4968 for (int i = 0; i < NumElems / 2; ++i) { 4969 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4970 continue; 4971 4972 if (BottomHalf == nullptr) 4973 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4974 else if (Cond->getOperand(i).getNode() != BottomHalf) 4975 return SDValue(); 4976 } 4977 4978 // Do the same for the second half of the BuildVector 4979 ConstantSDNode *TopHalf = nullptr; 4980 for (int i = NumElems / 2; i < NumElems; ++i) { 4981 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4982 continue; 4983 4984 if (TopHalf == nullptr) 4985 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4986 else if (Cond->getOperand(i).getNode() != TopHalf) 4987 return SDValue(); 4988 } 4989 4990 assert(TopHalf && BottomHalf && 4991 "One half of the selector was all UNDEFs and the other was all the " 4992 "same value. This should have been addressed before this function."); 4993 return DAG.getNode( 4994 ISD::CONCAT_VECTORS, dl, VT, 4995 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 4996 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 4997 } 4998 4999 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5000 5001 if (Level >= AfterLegalizeTypes) 5002 return SDValue(); 5003 5004 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5005 SDValue Mask = MST->getMask(); 5006 SDValue Data = MST->getValue(); 5007 SDLoc DL(N); 5008 5009 // If the MSTORE data type requires splitting and the mask is provided by a 5010 // SETCC, then split both nodes and its operands before legalization. This 5011 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5012 // and enables future optimizations (e.g. min/max pattern matching on X86). 5013 if (Mask.getOpcode() == ISD::SETCC) { 5014 5015 // Check if any splitting is required. 5016 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5017 TargetLowering::TypeSplitVector) 5018 return SDValue(); 5019 5020 SDValue MaskLo, MaskHi, Lo, Hi; 5021 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5022 5023 EVT LoVT, HiVT; 5024 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5025 5026 SDValue Chain = MST->getChain(); 5027 SDValue Ptr = MST->getBasePtr(); 5028 5029 EVT MemoryVT = MST->getMemoryVT(); 5030 unsigned Alignment = MST->getOriginalAlignment(); 5031 5032 // if Alignment is equal to the vector size, 5033 // take the half of it for the second part 5034 unsigned SecondHalfAlignment = 5035 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5036 Alignment/2 : Alignment; 5037 5038 EVT LoMemVT, HiMemVT; 5039 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5040 5041 SDValue DataLo, DataHi; 5042 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5043 5044 MachineMemOperand *MMO = DAG.getMachineFunction(). 5045 getMachineMemOperand(MST->getPointerInfo(), 5046 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5047 Alignment, MST->getAAInfo(), MST->getRanges()); 5048 5049 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5050 MST->isTruncatingStore()); 5051 5052 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5053 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5054 DAG.getConstant(IncrementSize, Ptr.getValueType())); 5055 5056 MMO = DAG.getMachineFunction(). 5057 getMachineMemOperand(MST->getPointerInfo(), 5058 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5059 SecondHalfAlignment, MST->getAAInfo(), 5060 MST->getRanges()); 5061 5062 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5063 MST->isTruncatingStore()); 5064 5065 AddToWorklist(Lo.getNode()); 5066 AddToWorklist(Hi.getNode()); 5067 5068 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5069 } 5070 return SDValue(); 5071 } 5072 5073 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5074 5075 if (Level >= AfterLegalizeTypes) 5076 return SDValue(); 5077 5078 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5079 SDValue Mask = MLD->getMask(); 5080 SDLoc DL(N); 5081 5082 // If the MLOAD result requires splitting and the mask is provided by a 5083 // SETCC, then split both nodes and its operands before legalization. This 5084 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5085 // and enables future optimizations (e.g. min/max pattern matching on X86). 5086 5087 if (Mask.getOpcode() == ISD::SETCC) { 5088 EVT VT = N->getValueType(0); 5089 5090 // Check if any splitting is required. 5091 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5092 TargetLowering::TypeSplitVector) 5093 return SDValue(); 5094 5095 SDValue MaskLo, MaskHi, Lo, Hi; 5096 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5097 5098 SDValue Src0 = MLD->getSrc0(); 5099 SDValue Src0Lo, Src0Hi; 5100 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5101 5102 EVT LoVT, HiVT; 5103 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5104 5105 SDValue Chain = MLD->getChain(); 5106 SDValue Ptr = MLD->getBasePtr(); 5107 EVT MemoryVT = MLD->getMemoryVT(); 5108 unsigned Alignment = MLD->getOriginalAlignment(); 5109 5110 // if Alignment is equal to the vector size, 5111 // take the half of it for the second part 5112 unsigned SecondHalfAlignment = 5113 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5114 Alignment/2 : Alignment; 5115 5116 EVT LoMemVT, HiMemVT; 5117 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5118 5119 MachineMemOperand *MMO = DAG.getMachineFunction(). 5120 getMachineMemOperand(MLD->getPointerInfo(), 5121 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5122 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5123 5124 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5125 ISD::NON_EXTLOAD); 5126 5127 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5128 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5129 DAG.getConstant(IncrementSize, Ptr.getValueType())); 5130 5131 MMO = DAG.getMachineFunction(). 5132 getMachineMemOperand(MLD->getPointerInfo(), 5133 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5134 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5135 5136 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5137 ISD::NON_EXTLOAD); 5138 5139 AddToWorklist(Lo.getNode()); 5140 AddToWorklist(Hi.getNode()); 5141 5142 // Build a factor node to remember that this load is independent of the 5143 // other one. 5144 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5145 Hi.getValue(1)); 5146 5147 // Legalized the chain result - switch anything that used the old chain to 5148 // use the new one. 5149 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5150 5151 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5152 5153 SDValue RetOps[] = { LoadRes, Chain }; 5154 return DAG.getMergeValues(RetOps, DL); 5155 } 5156 return SDValue(); 5157 } 5158 5159 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5160 SDValue N0 = N->getOperand(0); 5161 SDValue N1 = N->getOperand(1); 5162 SDValue N2 = N->getOperand(2); 5163 SDLoc DL(N); 5164 5165 // Canonicalize integer abs. 5166 // vselect (setg[te] X, 0), X, -X -> 5167 // vselect (setgt X, -1), X, -X -> 5168 // vselect (setl[te] X, 0), -X, X -> 5169 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5170 if (N0.getOpcode() == ISD::SETCC) { 5171 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5172 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5173 bool isAbs = false; 5174 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5175 5176 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5177 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5178 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5179 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5180 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5181 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5182 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5183 5184 if (isAbs) { 5185 EVT VT = LHS.getValueType(); 5186 SDValue Shift = DAG.getNode( 5187 ISD::SRA, DL, VT, LHS, 5188 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 5189 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5190 AddToWorklist(Shift.getNode()); 5191 AddToWorklist(Add.getNode()); 5192 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5193 } 5194 } 5195 5196 if (SimplifySelectOps(N, N1, N2)) 5197 return SDValue(N, 0); // Don't revisit N. 5198 5199 // If the VSELECT result requires splitting and the mask is provided by a 5200 // SETCC, then split both nodes and its operands before legalization. This 5201 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5202 // and enables future optimizations (e.g. min/max pattern matching on X86). 5203 if (N0.getOpcode() == ISD::SETCC) { 5204 EVT VT = N->getValueType(0); 5205 5206 // Check if any splitting is required. 5207 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5208 TargetLowering::TypeSplitVector) 5209 return SDValue(); 5210 5211 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5212 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5213 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5214 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5215 5216 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5217 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5218 5219 // Add the new VSELECT nodes to the work list in case they need to be split 5220 // again. 5221 AddToWorklist(Lo.getNode()); 5222 AddToWorklist(Hi.getNode()); 5223 5224 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5225 } 5226 5227 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5228 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5229 return N1; 5230 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5231 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5232 return N2; 5233 5234 // The ConvertSelectToConcatVector function is assuming both the above 5235 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5236 // and addressed. 5237 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5238 N2.getOpcode() == ISD::CONCAT_VECTORS && 5239 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5240 SDValue CV = ConvertSelectToConcatVector(N, DAG); 5241 if (CV.getNode()) 5242 return CV; 5243 } 5244 5245 return SDValue(); 5246 } 5247 5248 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5249 SDValue N0 = N->getOperand(0); 5250 SDValue N1 = N->getOperand(1); 5251 SDValue N2 = N->getOperand(2); 5252 SDValue N3 = N->getOperand(3); 5253 SDValue N4 = N->getOperand(4); 5254 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5255 5256 // fold select_cc lhs, rhs, x, x, cc -> x 5257 if (N2 == N3) 5258 return N2; 5259 5260 // Determine if the condition we're dealing with is constant 5261 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5262 N0, N1, CC, SDLoc(N), false); 5263 if (SCC.getNode()) { 5264 AddToWorklist(SCC.getNode()); 5265 5266 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5267 if (!SCCC->isNullValue()) 5268 return N2; // cond always true -> true val 5269 else 5270 return N3; // cond always false -> false val 5271 } else if (SCC->getOpcode() == ISD::UNDEF) { 5272 // When the condition is UNDEF, just return the first operand. This is 5273 // coherent the DAG creation, no setcc node is created in this case 5274 return N2; 5275 } else if (SCC.getOpcode() == ISD::SETCC) { 5276 // Fold to a simpler select_cc 5277 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5278 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5279 SCC.getOperand(2)); 5280 } 5281 } 5282 5283 // If we can fold this based on the true/false value, do so. 5284 if (SimplifySelectOps(N, N2, N3)) 5285 return SDValue(N, 0); // Don't revisit N. 5286 5287 // fold select_cc into other things, such as min/max/abs 5288 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5289 } 5290 5291 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5292 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5293 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5294 SDLoc(N)); 5295 } 5296 5297 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 5298 // dag node into a ConstantSDNode or a build_vector of constants. 5299 // This function is called by the DAGCombiner when visiting sext/zext/aext 5300 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5301 // Vector extends are not folded if operations are legal; this is to 5302 // avoid introducing illegal build_vector dag nodes. 5303 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5304 SelectionDAG &DAG, bool LegalTypes, 5305 bool LegalOperations) { 5306 unsigned Opcode = N->getOpcode(); 5307 SDValue N0 = N->getOperand(0); 5308 EVT VT = N->getValueType(0); 5309 5310 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5311 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 5312 5313 // fold (sext c1) -> c1 5314 // fold (zext c1) -> c1 5315 // fold (aext c1) -> c1 5316 if (isa<ConstantSDNode>(N0)) 5317 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5318 5319 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5320 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5321 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5322 EVT SVT = VT.getScalarType(); 5323 if (!(VT.isVector() && 5324 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5325 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5326 return nullptr; 5327 5328 // We can fold this node into a build_vector. 5329 unsigned VTBits = SVT.getSizeInBits(); 5330 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5331 unsigned ShAmt = VTBits - EVTBits; 5332 SmallVector<SDValue, 8> Elts; 5333 unsigned NumElts = N0->getNumOperands(); 5334 SDLoc DL(N); 5335 5336 for (unsigned i=0; i != NumElts; ++i) { 5337 SDValue Op = N0->getOperand(i); 5338 if (Op->getOpcode() == ISD::UNDEF) { 5339 Elts.push_back(DAG.getUNDEF(SVT)); 5340 continue; 5341 } 5342 5343 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 5344 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 5345 if (Opcode == ISD::SIGN_EXTEND) 5346 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 5347 SVT)); 5348 else 5349 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 5350 SVT)); 5351 } 5352 5353 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5354 } 5355 5356 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5357 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5358 // transformation. Returns true if extension are possible and the above 5359 // mentioned transformation is profitable. 5360 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5361 unsigned ExtOpc, 5362 SmallVectorImpl<SDNode *> &ExtendNodes, 5363 const TargetLowering &TLI) { 5364 bool HasCopyToRegUses = false; 5365 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5366 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5367 UE = N0.getNode()->use_end(); 5368 UI != UE; ++UI) { 5369 SDNode *User = *UI; 5370 if (User == N) 5371 continue; 5372 if (UI.getUse().getResNo() != N0.getResNo()) 5373 continue; 5374 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5375 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5376 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5377 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5378 // Sign bits will be lost after a zext. 5379 return false; 5380 bool Add = false; 5381 for (unsigned i = 0; i != 2; ++i) { 5382 SDValue UseOp = User->getOperand(i); 5383 if (UseOp == N0) 5384 continue; 5385 if (!isa<ConstantSDNode>(UseOp)) 5386 return false; 5387 Add = true; 5388 } 5389 if (Add) 5390 ExtendNodes.push_back(User); 5391 continue; 5392 } 5393 // If truncates aren't free and there are users we can't 5394 // extend, it isn't worthwhile. 5395 if (!isTruncFree) 5396 return false; 5397 // Remember if this value is live-out. 5398 if (User->getOpcode() == ISD::CopyToReg) 5399 HasCopyToRegUses = true; 5400 } 5401 5402 if (HasCopyToRegUses) { 5403 bool BothLiveOut = false; 5404 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5405 UI != UE; ++UI) { 5406 SDUse &Use = UI.getUse(); 5407 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5408 BothLiveOut = true; 5409 break; 5410 } 5411 } 5412 if (BothLiveOut) 5413 // Both unextended and extended values are live out. There had better be 5414 // a good reason for the transformation. 5415 return ExtendNodes.size(); 5416 } 5417 return true; 5418 } 5419 5420 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5421 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5422 ISD::NodeType ExtType) { 5423 // Extend SetCC uses if necessary. 5424 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5425 SDNode *SetCC = SetCCs[i]; 5426 SmallVector<SDValue, 4> Ops; 5427 5428 for (unsigned j = 0; j != 2; ++j) { 5429 SDValue SOp = SetCC->getOperand(j); 5430 if (SOp == Trunc) 5431 Ops.push_back(ExtLoad); 5432 else 5433 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5434 } 5435 5436 Ops.push_back(SetCC->getOperand(2)); 5437 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5438 } 5439 } 5440 5441 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5442 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5443 SDValue N0 = N->getOperand(0); 5444 EVT DstVT = N->getValueType(0); 5445 EVT SrcVT = N0.getValueType(); 5446 5447 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5448 N->getOpcode() == ISD::ZERO_EXTEND) && 5449 "Unexpected node type (not an extend)!"); 5450 5451 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5452 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5453 // (v8i32 (sext (v8i16 (load x)))) 5454 // into: 5455 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5456 // (v4i32 (sextload (x + 16))))) 5457 // Where uses of the original load, i.e.: 5458 // (v8i16 (load x)) 5459 // are replaced with: 5460 // (v8i16 (truncate 5461 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5462 // (v4i32 (sextload (x + 16))))))) 5463 // 5464 // This combine is only applicable to illegal, but splittable, vectors. 5465 // All legal types, and illegal non-vector types, are handled elsewhere. 5466 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5467 // 5468 if (N0->getOpcode() != ISD::LOAD) 5469 return SDValue(); 5470 5471 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5472 5473 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5474 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5475 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5476 return SDValue(); 5477 5478 SmallVector<SDNode *, 4> SetCCs; 5479 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5480 return SDValue(); 5481 5482 ISD::LoadExtType ExtType = 5483 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5484 5485 // Try to split the vector types to get down to legal types. 5486 EVT SplitSrcVT = SrcVT; 5487 EVT SplitDstVT = DstVT; 5488 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5489 SplitSrcVT.getVectorNumElements() > 1) { 5490 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5491 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5492 } 5493 5494 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5495 return SDValue(); 5496 5497 SDLoc DL(N); 5498 const unsigned NumSplits = 5499 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5500 const unsigned Stride = SplitSrcVT.getStoreSize(); 5501 SmallVector<SDValue, 4> Loads; 5502 SmallVector<SDValue, 4> Chains; 5503 5504 SDValue BasePtr = LN0->getBasePtr(); 5505 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5506 const unsigned Offset = Idx * Stride; 5507 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5508 5509 SDValue SplitLoad = DAG.getExtLoad( 5510 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5511 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5512 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5513 Align, LN0->getAAInfo()); 5514 5515 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5516 DAG.getConstant(Stride, BasePtr.getValueType())); 5517 5518 Loads.push_back(SplitLoad.getValue(0)); 5519 Chains.push_back(SplitLoad.getValue(1)); 5520 } 5521 5522 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5523 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5524 5525 CombineTo(N, NewValue); 5526 5527 // Replace uses of the original load (before extension) 5528 // with a truncate of the concatenated sextloaded vectors. 5529 SDValue Trunc = 5530 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5531 CombineTo(N0.getNode(), Trunc, NewChain); 5532 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5533 (ISD::NodeType)N->getOpcode()); 5534 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5535 } 5536 5537 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5538 SDValue N0 = N->getOperand(0); 5539 EVT VT = N->getValueType(0); 5540 5541 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5542 LegalOperations)) 5543 return SDValue(Res, 0); 5544 5545 // fold (sext (sext x)) -> (sext x) 5546 // fold (sext (aext x)) -> (sext x) 5547 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5548 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5549 N0.getOperand(0)); 5550 5551 if (N0.getOpcode() == ISD::TRUNCATE) { 5552 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5553 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5554 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5555 if (NarrowLoad.getNode()) { 5556 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5557 if (NarrowLoad.getNode() != N0.getNode()) { 5558 CombineTo(N0.getNode(), NarrowLoad); 5559 // CombineTo deleted the truncate, if needed, but not what's under it. 5560 AddToWorklist(oye); 5561 } 5562 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5563 } 5564 5565 // See if the value being truncated is already sign extended. If so, just 5566 // eliminate the trunc/sext pair. 5567 SDValue Op = N0.getOperand(0); 5568 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5569 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5570 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5571 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5572 5573 if (OpBits == DestBits) { 5574 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5575 // bits, it is already ready. 5576 if (NumSignBits > DestBits-MidBits) 5577 return Op; 5578 } else if (OpBits < DestBits) { 5579 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5580 // bits, just sext from i32. 5581 if (NumSignBits > OpBits-MidBits) 5582 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5583 } else { 5584 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5585 // bits, just truncate to i32. 5586 if (NumSignBits > OpBits-MidBits) 5587 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5588 } 5589 5590 // fold (sext (truncate x)) -> (sextinreg x). 5591 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5592 N0.getValueType())) { 5593 if (OpBits < DestBits) 5594 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5595 else if (OpBits > DestBits) 5596 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5597 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5598 DAG.getValueType(N0.getValueType())); 5599 } 5600 } 5601 5602 // fold (sext (load x)) -> (sext (truncate (sextload x))) 5603 // Only generate vector extloads when 1) they're legal, and 2) they are 5604 // deemed desirable by the target. 5605 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5606 ((!LegalOperations && !VT.isVector() && 5607 !cast<LoadSDNode>(N0)->isVolatile()) || 5608 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 5609 bool DoXform = true; 5610 SmallVector<SDNode*, 4> SetCCs; 5611 if (!N0.hasOneUse()) 5612 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5613 if (VT.isVector()) 5614 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5615 if (DoXform) { 5616 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5617 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5618 LN0->getChain(), 5619 LN0->getBasePtr(), N0.getValueType(), 5620 LN0->getMemOperand()); 5621 CombineTo(N, ExtLoad); 5622 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5623 N0.getValueType(), ExtLoad); 5624 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5625 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5626 ISD::SIGN_EXTEND); 5627 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5628 } 5629 } 5630 5631 // fold (sext (load x)) to multiple smaller sextloads. 5632 // Only on illegal but splittable vectors. 5633 if (SDValue ExtLoad = CombineExtLoad(N)) 5634 return ExtLoad; 5635 5636 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5637 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5638 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5639 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5640 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5641 EVT MemVT = LN0->getMemoryVT(); 5642 if ((!LegalOperations && !LN0->isVolatile()) || 5643 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 5644 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5645 LN0->getChain(), 5646 LN0->getBasePtr(), MemVT, 5647 LN0->getMemOperand()); 5648 CombineTo(N, ExtLoad); 5649 CombineTo(N0.getNode(), 5650 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5651 N0.getValueType(), ExtLoad), 5652 ExtLoad.getValue(1)); 5653 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5654 } 5655 } 5656 5657 // fold (sext (and/or/xor (load x), cst)) -> 5658 // (and/or/xor (sextload x), (sext cst)) 5659 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5660 N0.getOpcode() == ISD::XOR) && 5661 isa<LoadSDNode>(N0.getOperand(0)) && 5662 N0.getOperand(1).getOpcode() == ISD::Constant && 5663 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 5664 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5665 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5666 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5667 bool DoXform = true; 5668 SmallVector<SDNode*, 4> SetCCs; 5669 if (!N0.hasOneUse()) 5670 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 5671 SetCCs, TLI); 5672 if (DoXform) { 5673 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 5674 LN0->getChain(), LN0->getBasePtr(), 5675 LN0->getMemoryVT(), 5676 LN0->getMemOperand()); 5677 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5678 Mask = Mask.sext(VT.getSizeInBits()); 5679 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5680 ExtLoad, DAG.getConstant(Mask, VT)); 5681 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5682 SDLoc(N0.getOperand(0)), 5683 N0.getOperand(0).getValueType(), ExtLoad); 5684 CombineTo(N, And); 5685 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5686 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5687 ISD::SIGN_EXTEND); 5688 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5689 } 5690 } 5691 } 5692 5693 if (N0.getOpcode() == ISD::SETCC) { 5694 EVT N0VT = N0.getOperand(0).getValueType(); 5695 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 5696 // Only do this before legalize for now. 5697 if (VT.isVector() && !LegalOperations && 5698 TLI.getBooleanContents(N0VT) == 5699 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5700 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 5701 // of the same size as the compared operands. Only optimize sext(setcc()) 5702 // if this is the case. 5703 EVT SVT = getSetCCResultType(N0VT); 5704 5705 // We know that the # elements of the results is the same as the 5706 // # elements of the compare (and the # elements of the compare result 5707 // for that matter). Check to see that they are the same size. If so, 5708 // we know that the element size of the sext'd result matches the 5709 // element size of the compare operands. 5710 if (VT.getSizeInBits() == SVT.getSizeInBits()) 5711 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5712 N0.getOperand(1), 5713 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5714 5715 // If the desired elements are smaller or larger than the source 5716 // elements we can use a matching integer vector type and then 5717 // truncate/sign extend 5718 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5719 if (SVT == MatchingVectorType) { 5720 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 5721 N0.getOperand(0), N0.getOperand(1), 5722 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5723 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5724 } 5725 } 5726 5727 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 5728 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 5729 SDValue NegOne = 5730 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 5731 SDValue SCC = 5732 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5733 NegOne, DAG.getConstant(0, VT), 5734 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5735 if (SCC.getNode()) return SCC; 5736 5737 if (!VT.isVector()) { 5738 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 5739 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 5740 SDLoc DL(N); 5741 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5742 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 5743 N0.getOperand(0), N0.getOperand(1), CC); 5744 return DAG.getSelect(DL, VT, SetCC, 5745 NegOne, DAG.getConstant(0, VT)); 5746 } 5747 } 5748 } 5749 5750 // fold (sext x) -> (zext x) if the sign bit is known zero. 5751 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 5752 DAG.SignBitIsZero(N0)) 5753 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 5754 5755 return SDValue(); 5756 } 5757 5758 // isTruncateOf - If N is a truncate of some other value, return true, record 5759 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 5760 // This function computes KnownZero to avoid a duplicated call to 5761 // computeKnownBits in the caller. 5762 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 5763 APInt &KnownZero) { 5764 APInt KnownOne; 5765 if (N->getOpcode() == ISD::TRUNCATE) { 5766 Op = N->getOperand(0); 5767 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5768 return true; 5769 } 5770 5771 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 5772 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 5773 return false; 5774 5775 SDValue Op0 = N->getOperand(0); 5776 SDValue Op1 = N->getOperand(1); 5777 assert(Op0.getValueType() == Op1.getValueType()); 5778 5779 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 5780 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 5781 if (COp0 && COp0->isNullValue()) 5782 Op = Op1; 5783 else if (COp1 && COp1->isNullValue()) 5784 Op = Op0; 5785 else 5786 return false; 5787 5788 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5789 5790 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 5791 return false; 5792 5793 return true; 5794 } 5795 5796 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 5797 SDValue N0 = N->getOperand(0); 5798 EVT VT = N->getValueType(0); 5799 5800 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5801 LegalOperations)) 5802 return SDValue(Res, 0); 5803 5804 // fold (zext (zext x)) -> (zext x) 5805 // fold (zext (aext x)) -> (zext x) 5806 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5807 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 5808 N0.getOperand(0)); 5809 5810 // fold (zext (truncate x)) -> (zext x) or 5811 // (zext (truncate x)) -> (truncate x) 5812 // This is valid when the truncated bits of x are already zero. 5813 // FIXME: We should extend this to work for vectors too. 5814 SDValue Op; 5815 APInt KnownZero; 5816 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 5817 APInt TruncatedBits = 5818 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 5819 APInt(Op.getValueSizeInBits(), 0) : 5820 APInt::getBitsSet(Op.getValueSizeInBits(), 5821 N0.getValueSizeInBits(), 5822 std::min(Op.getValueSizeInBits(), 5823 VT.getSizeInBits())); 5824 if (TruncatedBits == (KnownZero & TruncatedBits)) { 5825 if (VT.bitsGT(Op.getValueType())) 5826 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 5827 if (VT.bitsLT(Op.getValueType())) 5828 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5829 5830 return Op; 5831 } 5832 } 5833 5834 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5835 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 5836 if (N0.getOpcode() == ISD::TRUNCATE) { 5837 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5838 if (NarrowLoad.getNode()) { 5839 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5840 if (NarrowLoad.getNode() != N0.getNode()) { 5841 CombineTo(N0.getNode(), NarrowLoad); 5842 // CombineTo deleted the truncate, if needed, but not what's under it. 5843 AddToWorklist(oye); 5844 } 5845 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5846 } 5847 } 5848 5849 // fold (zext (truncate x)) -> (and x, mask) 5850 if (N0.getOpcode() == ISD::TRUNCATE && 5851 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 5852 5853 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5854 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 5855 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5856 if (NarrowLoad.getNode()) { 5857 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5858 if (NarrowLoad.getNode() != N0.getNode()) { 5859 CombineTo(N0.getNode(), NarrowLoad); 5860 // CombineTo deleted the truncate, if needed, but not what's under it. 5861 AddToWorklist(oye); 5862 } 5863 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5864 } 5865 5866 SDValue Op = N0.getOperand(0); 5867 if (Op.getValueType().bitsLT(VT)) { 5868 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 5869 AddToWorklist(Op.getNode()); 5870 } else if (Op.getValueType().bitsGT(VT)) { 5871 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5872 AddToWorklist(Op.getNode()); 5873 } 5874 return DAG.getZeroExtendInReg(Op, SDLoc(N), 5875 N0.getValueType().getScalarType()); 5876 } 5877 5878 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 5879 // if either of the casts is not free. 5880 if (N0.getOpcode() == ISD::AND && 5881 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5882 N0.getOperand(1).getOpcode() == ISD::Constant && 5883 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5884 N0.getValueType()) || 5885 !TLI.isZExtFree(N0.getValueType(), VT))) { 5886 SDValue X = N0.getOperand(0).getOperand(0); 5887 if (X.getValueType().bitsLT(VT)) { 5888 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 5889 } else if (X.getValueType().bitsGT(VT)) { 5890 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5891 } 5892 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5893 Mask = Mask.zext(VT.getSizeInBits()); 5894 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5895 X, DAG.getConstant(Mask, VT)); 5896 } 5897 5898 // fold (zext (load x)) -> (zext (truncate (zextload x))) 5899 // Only generate vector extloads when 1) they're legal, and 2) they are 5900 // deemed desirable by the target. 5901 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5902 ((!LegalOperations && !VT.isVector() && 5903 !cast<LoadSDNode>(N0)->isVolatile()) || 5904 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 5905 bool DoXform = true; 5906 SmallVector<SDNode*, 4> SetCCs; 5907 if (!N0.hasOneUse()) 5908 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 5909 if (VT.isVector()) 5910 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5911 if (DoXform) { 5912 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5913 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5914 LN0->getChain(), 5915 LN0->getBasePtr(), N0.getValueType(), 5916 LN0->getMemOperand()); 5917 CombineTo(N, ExtLoad); 5918 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5919 N0.getValueType(), ExtLoad); 5920 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5921 5922 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5923 ISD::ZERO_EXTEND); 5924 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5925 } 5926 } 5927 5928 // fold (zext (load x)) to multiple smaller zextloads. 5929 // Only on illegal but splittable vectors. 5930 if (SDValue ExtLoad = CombineExtLoad(N)) 5931 return ExtLoad; 5932 5933 // fold (zext (and/or/xor (load x), cst)) -> 5934 // (and/or/xor (zextload x), (zext cst)) 5935 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5936 N0.getOpcode() == ISD::XOR) && 5937 isa<LoadSDNode>(N0.getOperand(0)) && 5938 N0.getOperand(1).getOpcode() == ISD::Constant && 5939 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 5940 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5941 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5942 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 5943 bool DoXform = true; 5944 SmallVector<SDNode*, 4> SetCCs; 5945 if (!N0.hasOneUse()) 5946 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 5947 SetCCs, TLI); 5948 if (DoXform) { 5949 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 5950 LN0->getChain(), LN0->getBasePtr(), 5951 LN0->getMemoryVT(), 5952 LN0->getMemOperand()); 5953 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5954 Mask = Mask.zext(VT.getSizeInBits()); 5955 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5956 ExtLoad, DAG.getConstant(Mask, VT)); 5957 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5958 SDLoc(N0.getOperand(0)), 5959 N0.getOperand(0).getValueType(), ExtLoad); 5960 CombineTo(N, And); 5961 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5962 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5963 ISD::ZERO_EXTEND); 5964 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5965 } 5966 } 5967 } 5968 5969 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 5970 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 5971 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5972 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5973 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5974 EVT MemVT = LN0->getMemoryVT(); 5975 if ((!LegalOperations && !LN0->isVolatile()) || 5976 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 5977 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5978 LN0->getChain(), 5979 LN0->getBasePtr(), MemVT, 5980 LN0->getMemOperand()); 5981 CombineTo(N, ExtLoad); 5982 CombineTo(N0.getNode(), 5983 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 5984 ExtLoad), 5985 ExtLoad.getValue(1)); 5986 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5987 } 5988 } 5989 5990 if (N0.getOpcode() == ISD::SETCC) { 5991 if (!LegalOperations && VT.isVector() && 5992 N0.getValueType().getVectorElementType() == MVT::i1) { 5993 EVT N0VT = N0.getOperand(0).getValueType(); 5994 if (getSetCCResultType(N0VT) == N0.getValueType()) 5995 return SDValue(); 5996 5997 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 5998 // Only do this before legalize for now. 5999 EVT EltVT = VT.getVectorElementType(); 6000 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 6001 DAG.getConstant(1, EltVT)); 6002 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6003 // We know that the # elements of the results is the same as the 6004 // # elements of the compare (and the # elements of the compare result 6005 // for that matter). Check to see that they are the same size. If so, 6006 // we know that the element size of the sext'd result matches the 6007 // element size of the compare operands. 6008 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6009 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6010 N0.getOperand(1), 6011 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6012 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 6013 OneOps)); 6014 6015 // If the desired elements are smaller or larger than the source 6016 // elements we can use a matching integer vector type and then 6017 // truncate/sign extend 6018 EVT MatchingElementType = 6019 EVT::getIntegerVT(*DAG.getContext(), 6020 N0VT.getScalarType().getSizeInBits()); 6021 EVT MatchingVectorType = 6022 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6023 N0VT.getVectorNumElements()); 6024 SDValue VsetCC = 6025 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6026 N0.getOperand(1), 6027 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6028 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6029 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 6030 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps)); 6031 } 6032 6033 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6034 SDValue SCC = 6035 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 6036 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 6037 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6038 if (SCC.getNode()) return SCC; 6039 } 6040 6041 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6042 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6043 isa<ConstantSDNode>(N0.getOperand(1)) && 6044 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6045 N0.hasOneUse()) { 6046 SDValue ShAmt = N0.getOperand(1); 6047 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6048 if (N0.getOpcode() == ISD::SHL) { 6049 SDValue InnerZExt = N0.getOperand(0); 6050 // If the original shl may be shifting out bits, do not perform this 6051 // transformation. 6052 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6053 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6054 if (ShAmtVal > KnownZeroBits) 6055 return SDValue(); 6056 } 6057 6058 SDLoc DL(N); 6059 6060 // Ensure that the shift amount is wide enough for the shifted value. 6061 if (VT.getSizeInBits() >= 256) 6062 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6063 6064 return DAG.getNode(N0.getOpcode(), DL, VT, 6065 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6066 ShAmt); 6067 } 6068 6069 return SDValue(); 6070 } 6071 6072 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6073 SDValue N0 = N->getOperand(0); 6074 EVT VT = N->getValueType(0); 6075 6076 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6077 LegalOperations)) 6078 return SDValue(Res, 0); 6079 6080 // fold (aext (aext x)) -> (aext x) 6081 // fold (aext (zext x)) -> (zext x) 6082 // fold (aext (sext x)) -> (sext x) 6083 if (N0.getOpcode() == ISD::ANY_EXTEND || 6084 N0.getOpcode() == ISD::ZERO_EXTEND || 6085 N0.getOpcode() == ISD::SIGN_EXTEND) 6086 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6087 6088 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6089 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6090 if (N0.getOpcode() == ISD::TRUNCATE) { 6091 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 6092 if (NarrowLoad.getNode()) { 6093 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6094 if (NarrowLoad.getNode() != N0.getNode()) { 6095 CombineTo(N0.getNode(), NarrowLoad); 6096 // CombineTo deleted the truncate, if needed, but not what's under it. 6097 AddToWorklist(oye); 6098 } 6099 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6100 } 6101 } 6102 6103 // fold (aext (truncate x)) 6104 if (N0.getOpcode() == ISD::TRUNCATE) { 6105 SDValue TruncOp = N0.getOperand(0); 6106 if (TruncOp.getValueType() == VT) 6107 return TruncOp; // x iff x size == zext size. 6108 if (TruncOp.getValueType().bitsGT(VT)) 6109 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6110 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6111 } 6112 6113 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6114 // if the trunc is not free. 6115 if (N0.getOpcode() == ISD::AND && 6116 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6117 N0.getOperand(1).getOpcode() == ISD::Constant && 6118 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6119 N0.getValueType())) { 6120 SDValue X = N0.getOperand(0).getOperand(0); 6121 if (X.getValueType().bitsLT(VT)) { 6122 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6123 } else if (X.getValueType().bitsGT(VT)) { 6124 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6125 } 6126 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6127 Mask = Mask.zext(VT.getSizeInBits()); 6128 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6129 X, DAG.getConstant(Mask, VT)); 6130 } 6131 6132 // fold (aext (load x)) -> (aext (truncate (extload x))) 6133 // None of the supported targets knows how to perform load and any_ext 6134 // on vectors in one instruction. We only perform this transformation on 6135 // scalars. 6136 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6137 ISD::isUNINDEXEDLoad(N0.getNode()) && 6138 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6139 bool DoXform = true; 6140 SmallVector<SDNode*, 4> SetCCs; 6141 if (!N0.hasOneUse()) 6142 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6143 if (DoXform) { 6144 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6145 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6146 LN0->getChain(), 6147 LN0->getBasePtr(), N0.getValueType(), 6148 LN0->getMemOperand()); 6149 CombineTo(N, ExtLoad); 6150 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6151 N0.getValueType(), ExtLoad); 6152 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6153 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6154 ISD::ANY_EXTEND); 6155 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6156 } 6157 } 6158 6159 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6160 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6161 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6162 if (N0.getOpcode() == ISD::LOAD && 6163 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6164 N0.hasOneUse()) { 6165 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6166 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6167 EVT MemVT = LN0->getMemoryVT(); 6168 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6169 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6170 VT, LN0->getChain(), LN0->getBasePtr(), 6171 MemVT, LN0->getMemOperand()); 6172 CombineTo(N, ExtLoad); 6173 CombineTo(N0.getNode(), 6174 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6175 N0.getValueType(), ExtLoad), 6176 ExtLoad.getValue(1)); 6177 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6178 } 6179 } 6180 6181 if (N0.getOpcode() == ISD::SETCC) { 6182 // For vectors: 6183 // aext(setcc) -> vsetcc 6184 // aext(setcc) -> truncate(vsetcc) 6185 // aext(setcc) -> aext(vsetcc) 6186 // Only do this before legalize for now. 6187 if (VT.isVector() && !LegalOperations) { 6188 EVT N0VT = N0.getOperand(0).getValueType(); 6189 // We know that the # elements of the results is the same as the 6190 // # elements of the compare (and the # elements of the compare result 6191 // for that matter). Check to see that they are the same size. If so, 6192 // we know that the element size of the sext'd result matches the 6193 // element size of the compare operands. 6194 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6195 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6196 N0.getOperand(1), 6197 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6198 // If the desired elements are smaller or larger than the source 6199 // elements we can use a matching integer vector type and then 6200 // truncate/any extend 6201 else { 6202 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6203 SDValue VsetCC = 6204 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6205 N0.getOperand(1), 6206 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6207 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6208 } 6209 } 6210 6211 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6212 SDValue SCC = 6213 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 6214 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 6215 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6216 if (SCC.getNode()) 6217 return SCC; 6218 } 6219 6220 return SDValue(); 6221 } 6222 6223 /// See if the specified operand can be simplified with the knowledge that only 6224 /// the bits specified by Mask are used. If so, return the simpler operand, 6225 /// otherwise return a null SDValue. 6226 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6227 switch (V.getOpcode()) { 6228 default: break; 6229 case ISD::Constant: { 6230 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6231 assert(CV && "Const value should be ConstSDNode."); 6232 const APInt &CVal = CV->getAPIntValue(); 6233 APInt NewVal = CVal & Mask; 6234 if (NewVal != CVal) 6235 return DAG.getConstant(NewVal, V.getValueType()); 6236 break; 6237 } 6238 case ISD::OR: 6239 case ISD::XOR: 6240 // If the LHS or RHS don't contribute bits to the or, drop them. 6241 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6242 return V.getOperand(1); 6243 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6244 return V.getOperand(0); 6245 break; 6246 case ISD::SRL: 6247 // Only look at single-use SRLs. 6248 if (!V.getNode()->hasOneUse()) 6249 break; 6250 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 6251 // See if we can recursively simplify the LHS. 6252 unsigned Amt = RHSC->getZExtValue(); 6253 6254 // Watch out for shift count overflow though. 6255 if (Amt >= Mask.getBitWidth()) break; 6256 APInt NewMask = Mask << Amt; 6257 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 6258 if (SimplifyLHS.getNode()) 6259 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6260 SimplifyLHS, V.getOperand(1)); 6261 } 6262 } 6263 return SDValue(); 6264 } 6265 6266 /// If the result of a wider load is shifted to right of N bits and then 6267 /// truncated to a narrower type and where N is a multiple of number of bits of 6268 /// the narrower type, transform it to a narrower load from address + N / num of 6269 /// bits of new type. If the result is to be extended, also fold the extension 6270 /// to form a extending load. 6271 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6272 unsigned Opc = N->getOpcode(); 6273 6274 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6275 SDValue N0 = N->getOperand(0); 6276 EVT VT = N->getValueType(0); 6277 EVT ExtVT = VT; 6278 6279 // This transformation isn't valid for vector loads. 6280 if (VT.isVector()) 6281 return SDValue(); 6282 6283 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6284 // extended to VT. 6285 if (Opc == ISD::SIGN_EXTEND_INREG) { 6286 ExtType = ISD::SEXTLOAD; 6287 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6288 } else if (Opc == ISD::SRL) { 6289 // Another special-case: SRL is basically zero-extending a narrower value. 6290 ExtType = ISD::ZEXTLOAD; 6291 N0 = SDValue(N, 0); 6292 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6293 if (!N01) return SDValue(); 6294 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6295 VT.getSizeInBits() - N01->getZExtValue()); 6296 } 6297 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6298 return SDValue(); 6299 6300 unsigned EVTBits = ExtVT.getSizeInBits(); 6301 6302 // Do not generate loads of non-round integer types since these can 6303 // be expensive (and would be wrong if the type is not byte sized). 6304 if (!ExtVT.isRound()) 6305 return SDValue(); 6306 6307 unsigned ShAmt = 0; 6308 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6309 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6310 ShAmt = N01->getZExtValue(); 6311 // Is the shift amount a multiple of size of VT? 6312 if ((ShAmt & (EVTBits-1)) == 0) { 6313 N0 = N0.getOperand(0); 6314 // Is the load width a multiple of size of VT? 6315 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6316 return SDValue(); 6317 } 6318 6319 // At this point, we must have a load or else we can't do the transform. 6320 if (!isa<LoadSDNode>(N0)) return SDValue(); 6321 6322 // Because a SRL must be assumed to *need* to zero-extend the high bits 6323 // (as opposed to anyext the high bits), we can't combine the zextload 6324 // lowering of SRL and an sextload. 6325 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6326 return SDValue(); 6327 6328 // If the shift amount is larger than the input type then we're not 6329 // accessing any of the loaded bytes. If the load was a zextload/extload 6330 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6331 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6332 return SDValue(); 6333 } 6334 } 6335 6336 // If the load is shifted left (and the result isn't shifted back right), 6337 // we can fold the truncate through the shift. 6338 unsigned ShLeftAmt = 0; 6339 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6340 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6341 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6342 ShLeftAmt = N01->getZExtValue(); 6343 N0 = N0.getOperand(0); 6344 } 6345 } 6346 6347 // If we haven't found a load, we can't narrow it. Don't transform one with 6348 // multiple uses, this would require adding a new load. 6349 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6350 return SDValue(); 6351 6352 // Don't change the width of a volatile load. 6353 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6354 if (LN0->isVolatile()) 6355 return SDValue(); 6356 6357 // Verify that we are actually reducing a load width here. 6358 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6359 return SDValue(); 6360 6361 // For the transform to be legal, the load must produce only two values 6362 // (the value loaded and the chain). Don't transform a pre-increment 6363 // load, for example, which produces an extra value. Otherwise the 6364 // transformation is not equivalent, and the downstream logic to replace 6365 // uses gets things wrong. 6366 if (LN0->getNumValues() > 2) 6367 return SDValue(); 6368 6369 // If the load that we're shrinking is an extload and we're not just 6370 // discarding the extension we can't simply shrink the load. Bail. 6371 // TODO: It would be possible to merge the extensions in some cases. 6372 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6373 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6374 return SDValue(); 6375 6376 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6377 return SDValue(); 6378 6379 EVT PtrType = N0.getOperand(1).getValueType(); 6380 6381 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6382 // It's not possible to generate a constant of extended or untyped type. 6383 return SDValue(); 6384 6385 // For big endian targets, we need to adjust the offset to the pointer to 6386 // load the correct bytes. 6387 if (TLI.isBigEndian()) { 6388 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6389 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6390 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6391 } 6392 6393 uint64_t PtrOff = ShAmt / 8; 6394 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6395 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 6396 PtrType, LN0->getBasePtr(), 6397 DAG.getConstant(PtrOff, PtrType)); 6398 AddToWorklist(NewPtr.getNode()); 6399 6400 SDValue Load; 6401 if (ExtType == ISD::NON_EXTLOAD) 6402 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6403 LN0->getPointerInfo().getWithOffset(PtrOff), 6404 LN0->isVolatile(), LN0->isNonTemporal(), 6405 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6406 else 6407 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6408 LN0->getPointerInfo().getWithOffset(PtrOff), 6409 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6410 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6411 6412 // Replace the old load's chain with the new load's chain. 6413 WorklistRemover DeadNodes(*this); 6414 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6415 6416 // Shift the result left, if we've swallowed a left shift. 6417 SDValue Result = Load; 6418 if (ShLeftAmt != 0) { 6419 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6420 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6421 ShImmTy = VT; 6422 // If the shift amount is as large as the result size (but, presumably, 6423 // no larger than the source) then the useful bits of the result are 6424 // zero; we can't simply return the shortened shift, because the result 6425 // of that operation is undefined. 6426 if (ShLeftAmt >= VT.getSizeInBits()) 6427 Result = DAG.getConstant(0, VT); 6428 else 6429 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 6430 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 6431 } 6432 6433 // Return the new loaded value. 6434 return Result; 6435 } 6436 6437 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6438 SDValue N0 = N->getOperand(0); 6439 SDValue N1 = N->getOperand(1); 6440 EVT VT = N->getValueType(0); 6441 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6442 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6443 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6444 6445 // fold (sext_in_reg c1) -> c1 6446 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 6447 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6448 6449 // If the input is already sign extended, just drop the extension. 6450 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6451 return N0; 6452 6453 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6454 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6455 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6456 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6457 N0.getOperand(0), N1); 6458 6459 // fold (sext_in_reg (sext x)) -> (sext x) 6460 // fold (sext_in_reg (aext x)) -> (sext x) 6461 // if x is small enough. 6462 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6463 SDValue N00 = N0.getOperand(0); 6464 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6465 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6466 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6467 } 6468 6469 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6470 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6471 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6472 6473 // fold operands of sext_in_reg based on knowledge that the top bits are not 6474 // demanded. 6475 if (SimplifyDemandedBits(SDValue(N, 0))) 6476 return SDValue(N, 0); 6477 6478 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6479 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6480 SDValue NarrowLoad = ReduceLoadWidth(N); 6481 if (NarrowLoad.getNode()) 6482 return NarrowLoad; 6483 6484 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6485 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6486 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6487 if (N0.getOpcode() == ISD::SRL) { 6488 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6489 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6490 // We can turn this into an SRA iff the input to the SRL is already sign 6491 // extended enough. 6492 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6493 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6494 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6495 N0.getOperand(0), N0.getOperand(1)); 6496 } 6497 } 6498 6499 // fold (sext_inreg (extload x)) -> (sextload x) 6500 if (ISD::isEXTLoad(N0.getNode()) && 6501 ISD::isUNINDEXEDLoad(N0.getNode()) && 6502 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6503 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6504 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6505 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6506 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6507 LN0->getChain(), 6508 LN0->getBasePtr(), EVT, 6509 LN0->getMemOperand()); 6510 CombineTo(N, ExtLoad); 6511 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6512 AddToWorklist(ExtLoad.getNode()); 6513 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6514 } 6515 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6516 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6517 N0.hasOneUse() && 6518 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6519 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6520 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6521 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6522 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6523 LN0->getChain(), 6524 LN0->getBasePtr(), EVT, 6525 LN0->getMemOperand()); 6526 CombineTo(N, ExtLoad); 6527 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6528 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6529 } 6530 6531 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6532 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6533 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6534 N0.getOperand(1), false); 6535 if (BSwap.getNode()) 6536 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6537 BSwap, N1); 6538 } 6539 6540 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 6541 // into a build_vector. 6542 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6543 SmallVector<SDValue, 8> Elts; 6544 unsigned NumElts = N0->getNumOperands(); 6545 unsigned ShAmt = VTBits - EVTBits; 6546 6547 for (unsigned i = 0; i != NumElts; ++i) { 6548 SDValue Op = N0->getOperand(i); 6549 if (Op->getOpcode() == ISD::UNDEF) { 6550 Elts.push_back(Op); 6551 continue; 6552 } 6553 6554 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 6555 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 6556 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 6557 Op.getValueType())); 6558 } 6559 6560 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts); 6561 } 6562 6563 return SDValue(); 6564 } 6565 6566 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6567 SDValue N0 = N->getOperand(0); 6568 EVT VT = N->getValueType(0); 6569 bool isLE = TLI.isLittleEndian(); 6570 6571 // noop truncate 6572 if (N0.getValueType() == N->getValueType(0)) 6573 return N0; 6574 // fold (truncate c1) -> c1 6575 if (isConstantIntBuildVectorOrConstantInt(N0)) 6576 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6577 // fold (truncate (truncate x)) -> (truncate x) 6578 if (N0.getOpcode() == ISD::TRUNCATE) 6579 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6580 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6581 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6582 N0.getOpcode() == ISD::SIGN_EXTEND || 6583 N0.getOpcode() == ISD::ANY_EXTEND) { 6584 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6585 // if the source is smaller than the dest, we still need an extend 6586 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6587 N0.getOperand(0)); 6588 if (N0.getOperand(0).getValueType().bitsGT(VT)) 6589 // if the source is larger than the dest, than we just need the truncate 6590 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6591 // if the source and dest are the same type, we can drop both the extend 6592 // and the truncate. 6593 return N0.getOperand(0); 6594 } 6595 6596 // Fold extract-and-trunc into a narrow extract. For example: 6597 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 6598 // i32 y = TRUNCATE(i64 x) 6599 // -- becomes -- 6600 // v16i8 b = BITCAST (v2i64 val) 6601 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 6602 // 6603 // Note: We only run this optimization after type legalization (which often 6604 // creates this pattern) and before operation legalization after which 6605 // we need to be more careful about the vector instructions that we generate. 6606 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6607 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 6608 6609 EVT VecTy = N0.getOperand(0).getValueType(); 6610 EVT ExTy = N0.getValueType(); 6611 EVT TrTy = N->getValueType(0); 6612 6613 unsigned NumElem = VecTy.getVectorNumElements(); 6614 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 6615 6616 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 6617 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 6618 6619 SDValue EltNo = N0->getOperand(1); 6620 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 6621 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6622 EVT IndexTy = TLI.getVectorIdxTy(); 6623 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6624 6625 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6626 NVT, N0.getOperand(0)); 6627 6628 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6629 SDLoc(N), TrTy, V, 6630 DAG.getConstant(Index, IndexTy)); 6631 } 6632 } 6633 6634 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 6635 if (N0.getOpcode() == ISD::SELECT) { 6636 EVT SrcVT = N0.getValueType(); 6637 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 6638 TLI.isTruncateFree(SrcVT, VT)) { 6639 SDLoc SL(N0); 6640 SDValue Cond = N0.getOperand(0); 6641 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 6642 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 6643 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 6644 } 6645 } 6646 6647 // Fold a series of buildvector, bitcast, and truncate if possible. 6648 // For example fold 6649 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 6650 // (2xi32 (buildvector x, y)). 6651 if (Level == AfterLegalizeVectorOps && VT.isVector() && 6652 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 6653 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 6654 N0.getOperand(0).hasOneUse()) { 6655 6656 SDValue BuildVect = N0.getOperand(0); 6657 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 6658 EVT TruncVecEltTy = VT.getVectorElementType(); 6659 6660 // Check that the element types match. 6661 if (BuildVectEltTy == TruncVecEltTy) { 6662 // Now we only need to compute the offset of the truncated elements. 6663 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 6664 unsigned TruncVecNumElts = VT.getVectorNumElements(); 6665 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 6666 6667 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 6668 "Invalid number of elements"); 6669 6670 SmallVector<SDValue, 8> Opnds; 6671 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 6672 Opnds.push_back(BuildVect.getOperand(i)); 6673 6674 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 6675 } 6676 } 6677 6678 // See if we can simplify the input to this truncate through knowledge that 6679 // only the low bits are being used. 6680 // For example "trunc (or (shl x, 8), y)" // -> trunc y 6681 // Currently we only perform this optimization on scalars because vectors 6682 // may have different active low bits. 6683 if (!VT.isVector()) { 6684 SDValue Shorter = 6685 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 6686 VT.getSizeInBits())); 6687 if (Shorter.getNode()) 6688 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 6689 } 6690 // fold (truncate (load x)) -> (smaller load x) 6691 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 6692 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 6693 SDValue Reduced = ReduceLoadWidth(N); 6694 if (Reduced.getNode()) 6695 return Reduced; 6696 // Handle the case where the load remains an extending load even 6697 // after truncation. 6698 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 6699 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6700 if (!LN0->isVolatile() && 6701 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 6702 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 6703 VT, LN0->getChain(), LN0->getBasePtr(), 6704 LN0->getMemoryVT(), 6705 LN0->getMemOperand()); 6706 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 6707 return NewLoad; 6708 } 6709 } 6710 } 6711 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 6712 // where ... are all 'undef'. 6713 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 6714 SmallVector<EVT, 8> VTs; 6715 SDValue V; 6716 unsigned Idx = 0; 6717 unsigned NumDefs = 0; 6718 6719 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 6720 SDValue X = N0.getOperand(i); 6721 if (X.getOpcode() != ISD::UNDEF) { 6722 V = X; 6723 Idx = i; 6724 NumDefs++; 6725 } 6726 // Stop if more than one members are non-undef. 6727 if (NumDefs > 1) 6728 break; 6729 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 6730 VT.getVectorElementType(), 6731 X.getValueType().getVectorNumElements())); 6732 } 6733 6734 if (NumDefs == 0) 6735 return DAG.getUNDEF(VT); 6736 6737 if (NumDefs == 1) { 6738 assert(V.getNode() && "The single defined operand is empty!"); 6739 SmallVector<SDValue, 8> Opnds; 6740 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 6741 if (i != Idx) { 6742 Opnds.push_back(DAG.getUNDEF(VTs[i])); 6743 continue; 6744 } 6745 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 6746 AddToWorklist(NV.getNode()); 6747 Opnds.push_back(NV); 6748 } 6749 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 6750 } 6751 } 6752 6753 // Simplify the operands using demanded-bits information. 6754 if (!VT.isVector() && 6755 SimplifyDemandedBits(SDValue(N, 0))) 6756 return SDValue(N, 0); 6757 6758 return SDValue(); 6759 } 6760 6761 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 6762 SDValue Elt = N->getOperand(i); 6763 if (Elt.getOpcode() != ISD::MERGE_VALUES) 6764 return Elt.getNode(); 6765 return Elt.getOperand(Elt.getResNo()).getNode(); 6766 } 6767 6768 /// build_pair (load, load) -> load 6769 /// if load locations are consecutive. 6770 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 6771 assert(N->getOpcode() == ISD::BUILD_PAIR); 6772 6773 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 6774 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 6775 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 6776 LD1->getAddressSpace() != LD2->getAddressSpace()) 6777 return SDValue(); 6778 EVT LD1VT = LD1->getValueType(0); 6779 6780 if (ISD::isNON_EXTLoad(LD2) && 6781 LD2->hasOneUse() && 6782 // If both are volatile this would reduce the number of volatile loads. 6783 // If one is volatile it might be ok, but play conservative and bail out. 6784 !LD1->isVolatile() && 6785 !LD2->isVolatile() && 6786 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 6787 unsigned Align = LD1->getAlignment(); 6788 unsigned NewAlign = TLI.getDataLayout()-> 6789 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6790 6791 if (NewAlign <= Align && 6792 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 6793 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 6794 LD1->getBasePtr(), LD1->getPointerInfo(), 6795 false, false, false, Align); 6796 } 6797 6798 return SDValue(); 6799 } 6800 6801 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 6802 SDValue N0 = N->getOperand(0); 6803 EVT VT = N->getValueType(0); 6804 6805 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 6806 // Only do this before legalize, since afterward the target may be depending 6807 // on the bitconvert. 6808 // First check to see if this is all constant. 6809 if (!LegalTypes && 6810 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 6811 VT.isVector()) { 6812 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 6813 6814 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 6815 assert(!DestEltVT.isVector() && 6816 "Element type of vector ValueType must not be vector!"); 6817 if (isSimple) 6818 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 6819 } 6820 6821 // If the input is a constant, let getNode fold it. 6822 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 6823 // If we can't allow illegal operations, we need to check that this is just 6824 // a fp -> int or int -> conversion and that the resulting operation will 6825 // be legal. 6826 if (!LegalOperations || 6827 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 6828 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 6829 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 6830 TLI.isOperationLegal(ISD::Constant, VT))) 6831 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 6832 } 6833 6834 // (conv (conv x, t1), t2) -> (conv x, t2) 6835 if (N0.getOpcode() == ISD::BITCAST) 6836 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 6837 N0.getOperand(0)); 6838 6839 // fold (conv (load x)) -> (load (conv*)x) 6840 // If the resultant load doesn't need a higher alignment than the original! 6841 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 6842 // Do not change the width of a volatile load. 6843 !cast<LoadSDNode>(N0)->isVolatile() && 6844 // Do not remove the cast if the types differ in endian layout. 6845 TLI.hasBigEndianPartOrdering(N0.getValueType()) == 6846 TLI.hasBigEndianPartOrdering(VT) && 6847 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 6848 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 6849 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6850 unsigned Align = TLI.getDataLayout()-> 6851 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6852 unsigned OrigAlign = LN0->getAlignment(); 6853 6854 if (Align <= OrigAlign) { 6855 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 6856 LN0->getBasePtr(), LN0->getPointerInfo(), 6857 LN0->isVolatile(), LN0->isNonTemporal(), 6858 LN0->isInvariant(), OrigAlign, 6859 LN0->getAAInfo()); 6860 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6861 return Load; 6862 } 6863 } 6864 6865 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6866 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6867 // This often reduces constant pool loads. 6868 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 6869 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 6870 N0.getNode()->hasOneUse() && VT.isInteger() && 6871 !VT.isVector() && !N0.getValueType().isVector()) { 6872 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 6873 N0.getOperand(0)); 6874 AddToWorklist(NewConv.getNode()); 6875 6876 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6877 if (N0.getOpcode() == ISD::FNEG) 6878 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 6879 NewConv, DAG.getConstant(SignBit, VT)); 6880 assert(N0.getOpcode() == ISD::FABS); 6881 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6882 NewConv, DAG.getConstant(~SignBit, VT)); 6883 } 6884 6885 // fold (bitconvert (fcopysign cst, x)) -> 6886 // (or (and (bitconvert x), sign), (and cst, (not sign))) 6887 // Note that we don't handle (copysign x, cst) because this can always be 6888 // folded to an fneg or fabs. 6889 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 6890 isa<ConstantFPSDNode>(N0.getOperand(0)) && 6891 VT.isInteger() && !VT.isVector()) { 6892 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 6893 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 6894 if (isTypeLegal(IntXVT)) { 6895 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6896 IntXVT, N0.getOperand(1)); 6897 AddToWorklist(X.getNode()); 6898 6899 // If X has a different width than the result/lhs, sext it or truncate it. 6900 unsigned VTWidth = VT.getSizeInBits(); 6901 if (OrigXWidth < VTWidth) { 6902 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 6903 AddToWorklist(X.getNode()); 6904 } else if (OrigXWidth > VTWidth) { 6905 // To get the sign bit in the right place, we have to shift it right 6906 // before truncating. 6907 X = DAG.getNode(ISD::SRL, SDLoc(X), 6908 X.getValueType(), X, 6909 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 6910 AddToWorklist(X.getNode()); 6911 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6912 AddToWorklist(X.getNode()); 6913 } 6914 6915 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6916 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 6917 X, DAG.getConstant(SignBit, VT)); 6918 AddToWorklist(X.getNode()); 6919 6920 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6921 VT, N0.getOperand(0)); 6922 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 6923 Cst, DAG.getConstant(~SignBit, VT)); 6924 AddToWorklist(Cst.getNode()); 6925 6926 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 6927 } 6928 } 6929 6930 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 6931 if (N0.getOpcode() == ISD::BUILD_PAIR) { 6932 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 6933 if (CombineLD.getNode()) 6934 return CombineLD; 6935 } 6936 6937 return SDValue(); 6938 } 6939 6940 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 6941 EVT VT = N->getValueType(0); 6942 return CombineConsecutiveLoads(N, VT); 6943 } 6944 6945 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 6946 /// operands. DstEltVT indicates the destination element value type. 6947 SDValue DAGCombiner:: 6948 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 6949 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 6950 6951 // If this is already the right type, we're done. 6952 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 6953 6954 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 6955 unsigned DstBitSize = DstEltVT.getSizeInBits(); 6956 6957 // If this is a conversion of N elements of one type to N elements of another 6958 // type, convert each element. This handles FP<->INT cases. 6959 if (SrcBitSize == DstBitSize) { 6960 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6961 BV->getValueType(0).getVectorNumElements()); 6962 6963 // Due to the FP element handling below calling this routine recursively, 6964 // we can end up with a scalar-to-vector node here. 6965 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 6966 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6967 DAG.getNode(ISD::BITCAST, SDLoc(BV), 6968 DstEltVT, BV->getOperand(0))); 6969 6970 SmallVector<SDValue, 8> Ops; 6971 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6972 SDValue Op = BV->getOperand(i); 6973 // If the vector element type is not legal, the BUILD_VECTOR operands 6974 // are promoted and implicitly truncated. Make that explicit here. 6975 if (Op.getValueType() != SrcEltVT) 6976 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 6977 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 6978 DstEltVT, Op)); 6979 AddToWorklist(Ops.back().getNode()); 6980 } 6981 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6982 } 6983 6984 // Otherwise, we're growing or shrinking the elements. To avoid having to 6985 // handle annoying details of growing/shrinking FP values, we convert them to 6986 // int first. 6987 if (SrcEltVT.isFloatingPoint()) { 6988 // Convert the input float vector to a int vector where the elements are the 6989 // same sizes. 6990 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 6991 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 6992 SrcEltVT = IntVT; 6993 } 6994 6995 // Now we know the input is an integer vector. If the output is a FP type, 6996 // convert to integer first, then to FP of the right size. 6997 if (DstEltVT.isFloatingPoint()) { 6998 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 6999 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7000 7001 // Next, convert to FP elements of the same size. 7002 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7003 } 7004 7005 // Okay, we know the src/dst types are both integers of differing types. 7006 // Handling growing first. 7007 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7008 if (SrcBitSize < DstBitSize) { 7009 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7010 7011 SmallVector<SDValue, 8> Ops; 7012 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7013 i += NumInputsPerOutput) { 7014 bool isLE = TLI.isLittleEndian(); 7015 APInt NewBits = APInt(DstBitSize, 0); 7016 bool EltIsUndef = true; 7017 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7018 // Shift the previously computed bits over. 7019 NewBits <<= SrcBitSize; 7020 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7021 if (Op.getOpcode() == ISD::UNDEF) continue; 7022 EltIsUndef = false; 7023 7024 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7025 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7026 } 7027 7028 if (EltIsUndef) 7029 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7030 else 7031 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 7032 } 7033 7034 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7035 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7036 } 7037 7038 // Finally, this must be the case where we are shrinking elements: each input 7039 // turns into multiple outputs. 7040 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7041 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7042 NumOutputsPerInput*BV->getNumOperands()); 7043 SmallVector<SDValue, 8> Ops; 7044 7045 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 7046 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 7047 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7048 continue; 7049 } 7050 7051 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 7052 getAPIntValue().zextOrTrunc(SrcBitSize); 7053 7054 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7055 APInt ThisVal = OpVal.trunc(DstBitSize); 7056 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 7057 OpVal = OpVal.lshr(DstBitSize); 7058 } 7059 7060 // For big endian targets, swap the order of the pieces of each element. 7061 if (TLI.isBigEndian()) 7062 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7063 } 7064 7065 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7066 } 7067 7068 /// Try to perform FMA combining on a given FADD node. 7069 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7070 7071 7072 7073 7074 SDValue N0 = N->getOperand(0); 7075 SDValue N1 = N->getOperand(1); 7076 EVT VT = N->getValueType(0); 7077 SDLoc SL(N); 7078 7079 const TargetOptions &Options = DAG.getTarget().Options; 7080 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast || 7081 Options.UnsafeFPMath); 7082 7083 // Floating-point multiply-add with intermediate rounding. 7084 bool HasFMAD = (LegalOperations && 7085 TLI.isOperationLegal(ISD::FMAD, VT)); 7086 7087 // Floating-point multiply-add without intermediate rounding. 7088 bool HasFMA = ((!LegalOperations || 7089 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) && 7090 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7091 UnsafeFPMath); 7092 7093 // No valid opcode, do not combine. 7094 if (!HasFMAD && !HasFMA) 7095 return SDValue(); 7096 7097 // Always prefer FMAD to FMA for precision. 7098 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7099 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7100 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7101 7102 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7103 if (N0.getOpcode() == ISD::FMUL && 7104 (Aggressive || N0->hasOneUse())) { 7105 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7106 N0.getOperand(0), N0.getOperand(1), N1); 7107 } 7108 7109 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7110 // Note: Commutes FADD operands. 7111 if (N1.getOpcode() == ISD::FMUL && 7112 (Aggressive || N1->hasOneUse())) { 7113 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7114 N1.getOperand(0), N1.getOperand(1), N0); 7115 } 7116 7117 // Look through FP_EXTEND nodes to do more combining. 7118 if (UnsafeFPMath && LookThroughFPExt) { 7119 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7120 if (N0.getOpcode() == ISD::FP_EXTEND) { 7121 SDValue N00 = N0.getOperand(0); 7122 if (N00.getOpcode() == ISD::FMUL) 7123 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7124 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7125 N00.getOperand(0)), 7126 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7127 N00.getOperand(1)), N1); 7128 } 7129 7130 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7131 // Note: Commutes FADD operands. 7132 if (N1.getOpcode() == ISD::FP_EXTEND) { 7133 SDValue N10 = N1.getOperand(0); 7134 if (N10.getOpcode() == ISD::FMUL) 7135 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7136 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7137 N10.getOperand(0)), 7138 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7139 N10.getOperand(1)), N0); 7140 } 7141 } 7142 7143 // More folding opportunities when target permits. 7144 if ((UnsafeFPMath || HasFMAD) && Aggressive) { 7145 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7146 if (N0.getOpcode() == PreferredFusedOpcode && 7147 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7148 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7149 N0.getOperand(0), N0.getOperand(1), 7150 DAG.getNode(PreferredFusedOpcode, SL, VT, 7151 N0.getOperand(2).getOperand(0), 7152 N0.getOperand(2).getOperand(1), 7153 N1)); 7154 } 7155 7156 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7157 if (N1->getOpcode() == PreferredFusedOpcode && 7158 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7159 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7160 N1.getOperand(0), N1.getOperand(1), 7161 DAG.getNode(PreferredFusedOpcode, SL, VT, 7162 N1.getOperand(2).getOperand(0), 7163 N1.getOperand(2).getOperand(1), 7164 N0)); 7165 } 7166 7167 if (LookThroughFPExt) { 7168 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7169 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7170 auto FoldFAddFMAFPExtFMul = [&] ( 7171 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7172 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7173 DAG.getNode(PreferredFusedOpcode, SL, VT, 7174 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7175 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7176 Z)); 7177 }; 7178 if (N0.getOpcode() == PreferredFusedOpcode) { 7179 SDValue N02 = N0.getOperand(2); 7180 if (N02.getOpcode() == ISD::FP_EXTEND) { 7181 SDValue N020 = N02.getOperand(0); 7182 if (N020.getOpcode() == ISD::FMUL) 7183 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7184 N020.getOperand(0), N020.getOperand(1), 7185 N1); 7186 } 7187 } 7188 7189 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7190 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7191 // FIXME: This turns two single-precision and one double-precision 7192 // operation into two double-precision operations, which might not be 7193 // interesting for all targets, especially GPUs. 7194 auto FoldFAddFPExtFMAFMul = [&] ( 7195 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7196 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7197 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7198 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7199 DAG.getNode(PreferredFusedOpcode, SL, VT, 7200 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7201 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7202 Z)); 7203 }; 7204 if (N0.getOpcode() == ISD::FP_EXTEND) { 7205 SDValue N00 = N0.getOperand(0); 7206 if (N00.getOpcode() == PreferredFusedOpcode) { 7207 SDValue N002 = N00.getOperand(2); 7208 if (N002.getOpcode() == ISD::FMUL) 7209 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7210 N002.getOperand(0), N002.getOperand(1), 7211 N1); 7212 } 7213 } 7214 7215 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7216 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7217 if (N1.getOpcode() == PreferredFusedOpcode) { 7218 SDValue N12 = N1.getOperand(2); 7219 if (N12.getOpcode() == ISD::FP_EXTEND) { 7220 SDValue N120 = N12.getOperand(0); 7221 if (N120.getOpcode() == ISD::FMUL) 7222 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7223 N120.getOperand(0), N120.getOperand(1), 7224 N0); 7225 } 7226 } 7227 7228 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7229 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7230 // FIXME: This turns two single-precision and one double-precision 7231 // operation into two double-precision operations, which might not be 7232 // interesting for all targets, especially GPUs. 7233 if (N1.getOpcode() == ISD::FP_EXTEND) { 7234 SDValue N10 = N1.getOperand(0); 7235 if (N10.getOpcode() == PreferredFusedOpcode) { 7236 SDValue N102 = N10.getOperand(2); 7237 if (N102.getOpcode() == ISD::FMUL) 7238 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7239 N102.getOperand(0), N102.getOperand(1), 7240 N0); 7241 } 7242 } 7243 } 7244 } 7245 7246 return SDValue(); 7247 } 7248 7249 /// Try to perform FMA combining on a given FSUB node. 7250 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7251 7252 7253 7254 SDValue N0 = N->getOperand(0); 7255 SDValue N1 = N->getOperand(1); 7256 EVT VT = N->getValueType(0); 7257 7258 SDLoc SL(N); 7259 7260 const TargetOptions &Options = DAG.getTarget().Options; 7261 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast || 7262 Options.UnsafeFPMath); 7263 7264 // Floating-point multiply-add with intermediate rounding. 7265 bool HasFMAD = (LegalOperations && 7266 TLI.isOperationLegal(ISD::FMAD, VT)); 7267 7268 // Floating-point multiply-add without intermediate rounding. 7269 bool HasFMA = ((!LegalOperations || 7270 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) && 7271 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7272 UnsafeFPMath); 7273 7274 // No valid opcode, do not combine. 7275 if (!HasFMAD && !HasFMA) 7276 return SDValue(); 7277 7278 // Always prefer FMAD to FMA for precision. 7279 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7280 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7281 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7282 7283 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7284 if (N0.getOpcode() == ISD::FMUL && 7285 (Aggressive || N0->hasOneUse())) { 7286 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7287 N0.getOperand(0), N0.getOperand(1), 7288 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7289 } 7290 7291 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7292 // Note: Commutes FSUB operands. 7293 if (N1.getOpcode() == ISD::FMUL && 7294 (Aggressive || N1->hasOneUse())) 7295 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7296 DAG.getNode(ISD::FNEG, SL, VT, 7297 N1.getOperand(0)), 7298 N1.getOperand(1), N0); 7299 7300 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7301 if (N0.getOpcode() == ISD::FNEG && 7302 N0.getOperand(0).getOpcode() == ISD::FMUL && 7303 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7304 SDValue N00 = N0.getOperand(0).getOperand(0); 7305 SDValue N01 = N0.getOperand(0).getOperand(1); 7306 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7307 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7308 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7309 } 7310 7311 // Look through FP_EXTEND nodes to do more combining. 7312 if (UnsafeFPMath && LookThroughFPExt) { 7313 // fold (fsub (fpext (fmul x, y)), z) 7314 // -> (fma (fpext x), (fpext y), (fneg z)) 7315 if (N0.getOpcode() == ISD::FP_EXTEND) { 7316 SDValue N00 = N0.getOperand(0); 7317 if (N00.getOpcode() == ISD::FMUL) 7318 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7319 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7320 N00.getOperand(0)), 7321 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7322 N00.getOperand(1)), 7323 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7324 } 7325 7326 // fold (fsub x, (fpext (fmul y, z))) 7327 // -> (fma (fneg (fpext y)), (fpext z), x) 7328 // Note: Commutes FSUB operands. 7329 if (N1.getOpcode() == ISD::FP_EXTEND) { 7330 SDValue N10 = N1.getOperand(0); 7331 if (N10.getOpcode() == ISD::FMUL) 7332 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7333 DAG.getNode(ISD::FNEG, SL, VT, 7334 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7335 N10.getOperand(0))), 7336 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7337 N10.getOperand(1)), 7338 N0); 7339 } 7340 7341 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7342 // -> (fneg (fma (fpext x), (fpext y), z)) 7343 // Note: This could be removed with appropriate canonicalization of the 7344 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7345 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7346 // from implementing the canonicalization in visitFSUB. 7347 if (N0.getOpcode() == ISD::FP_EXTEND) { 7348 SDValue N00 = N0.getOperand(0); 7349 if (N00.getOpcode() == ISD::FNEG) { 7350 SDValue N000 = N00.getOperand(0); 7351 if (N000.getOpcode() == ISD::FMUL) { 7352 return DAG.getNode(ISD::FNEG, SL, VT, 7353 DAG.getNode(PreferredFusedOpcode, SL, VT, 7354 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7355 N000.getOperand(0)), 7356 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7357 N000.getOperand(1)), 7358 N1)); 7359 } 7360 } 7361 } 7362 7363 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7364 // -> (fneg (fma (fpext x)), (fpext y), z) 7365 // Note: This could be removed with appropriate canonicalization of the 7366 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7367 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7368 // from implementing the canonicalization in visitFSUB. 7369 if (N0.getOpcode() == ISD::FNEG) { 7370 SDValue N00 = N0.getOperand(0); 7371 if (N00.getOpcode() == ISD::FP_EXTEND) { 7372 SDValue N000 = N00.getOperand(0); 7373 if (N000.getOpcode() == ISD::FMUL) { 7374 return DAG.getNode(ISD::FNEG, SL, VT, 7375 DAG.getNode(PreferredFusedOpcode, SL, VT, 7376 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7377 N000.getOperand(0)), 7378 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7379 N000.getOperand(1)), 7380 N1)); 7381 } 7382 } 7383 } 7384 7385 } 7386 7387 // More folding opportunities when target permits. 7388 if ((UnsafeFPMath || HasFMAD) && Aggressive) { 7389 // fold (fsub (fma x, y, (fmul u, v)), z) 7390 // -> (fma x, y (fma u, v, (fneg z))) 7391 if (N0.getOpcode() == PreferredFusedOpcode && 7392 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7393 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7394 N0.getOperand(0), N0.getOperand(1), 7395 DAG.getNode(PreferredFusedOpcode, SL, VT, 7396 N0.getOperand(2).getOperand(0), 7397 N0.getOperand(2).getOperand(1), 7398 DAG.getNode(ISD::FNEG, SL, VT, 7399 N1))); 7400 } 7401 7402 // fold (fsub x, (fma y, z, (fmul u, v))) 7403 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7404 if (N1.getOpcode() == PreferredFusedOpcode && 7405 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7406 SDValue N20 = N1.getOperand(2).getOperand(0); 7407 SDValue N21 = N1.getOperand(2).getOperand(1); 7408 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7409 DAG.getNode(ISD::FNEG, SL, VT, 7410 N1.getOperand(0)), 7411 N1.getOperand(1), 7412 DAG.getNode(PreferredFusedOpcode, SL, VT, 7413 DAG.getNode(ISD::FNEG, SL, VT, N20), 7414 7415 N21, N0)); 7416 } 7417 7418 if (LookThroughFPExt) { 7419 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7420 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 7421 if (N0.getOpcode() == PreferredFusedOpcode) { 7422 SDValue N02 = N0.getOperand(2); 7423 if (N02.getOpcode() == ISD::FP_EXTEND) { 7424 SDValue N020 = N02.getOperand(0); 7425 if (N020.getOpcode() == ISD::FMUL) 7426 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7427 N0.getOperand(0), N0.getOperand(1), 7428 DAG.getNode(PreferredFusedOpcode, SL, VT, 7429 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7430 N020.getOperand(0)), 7431 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7432 N020.getOperand(1)), 7433 DAG.getNode(ISD::FNEG, SL, VT, 7434 N1))); 7435 } 7436 } 7437 7438 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 7439 // -> (fma (fpext x), (fpext y), 7440 // (fma (fpext u), (fpext v), (fneg z))) 7441 // FIXME: This turns two single-precision and one double-precision 7442 // operation into two double-precision operations, which might not be 7443 // interesting for all targets, especially GPUs. 7444 if (N0.getOpcode() == ISD::FP_EXTEND) { 7445 SDValue N00 = N0.getOperand(0); 7446 if (N00.getOpcode() == PreferredFusedOpcode) { 7447 SDValue N002 = N00.getOperand(2); 7448 if (N002.getOpcode() == ISD::FMUL) 7449 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7450 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7451 N00.getOperand(0)), 7452 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7453 N00.getOperand(1)), 7454 DAG.getNode(PreferredFusedOpcode, SL, VT, 7455 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7456 N002.getOperand(0)), 7457 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7458 N002.getOperand(1)), 7459 DAG.getNode(ISD::FNEG, SL, VT, 7460 N1))); 7461 } 7462 } 7463 7464 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 7465 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 7466 if (N1.getOpcode() == PreferredFusedOpcode && 7467 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 7468 SDValue N120 = N1.getOperand(2).getOperand(0); 7469 if (N120.getOpcode() == ISD::FMUL) { 7470 SDValue N1200 = N120.getOperand(0); 7471 SDValue N1201 = N120.getOperand(1); 7472 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7473 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 7474 N1.getOperand(1), 7475 DAG.getNode(PreferredFusedOpcode, SL, VT, 7476 DAG.getNode(ISD::FNEG, SL, VT, 7477 DAG.getNode(ISD::FP_EXTEND, SL, 7478 VT, N1200)), 7479 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7480 N1201), 7481 N0)); 7482 } 7483 } 7484 7485 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 7486 // -> (fma (fneg (fpext y)), (fpext z), 7487 // (fma (fneg (fpext u)), (fpext v), x)) 7488 // FIXME: This turns two single-precision and one double-precision 7489 // operation into two double-precision operations, which might not be 7490 // interesting for all targets, especially GPUs. 7491 if (N1.getOpcode() == ISD::FP_EXTEND && 7492 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 7493 SDValue N100 = N1.getOperand(0).getOperand(0); 7494 SDValue N101 = N1.getOperand(0).getOperand(1); 7495 SDValue N102 = N1.getOperand(0).getOperand(2); 7496 if (N102.getOpcode() == ISD::FMUL) { 7497 SDValue N1020 = N102.getOperand(0); 7498 SDValue N1021 = N102.getOperand(1); 7499 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7500 DAG.getNode(ISD::FNEG, SL, VT, 7501 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7502 N100)), 7503 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 7504 DAG.getNode(PreferredFusedOpcode, SL, VT, 7505 DAG.getNode(ISD::FNEG, SL, VT, 7506 DAG.getNode(ISD::FP_EXTEND, SL, 7507 VT, N1020)), 7508 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7509 N1021), 7510 N0)); 7511 } 7512 } 7513 } 7514 } 7515 7516 return SDValue(); 7517 } 7518 7519 SDValue DAGCombiner::visitFADD(SDNode *N) { 7520 SDValue N0 = N->getOperand(0); 7521 SDValue N1 = N->getOperand(1); 7522 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7523 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7524 EVT VT = N->getValueType(0); 7525 const TargetOptions &Options = DAG.getTarget().Options; 7526 7527 // fold vector ops 7528 if (VT.isVector()) 7529 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7530 return FoldedVOp; 7531 7532 // fold (fadd c1, c2) -> c1 + c2 7533 if (N0CFP && N1CFP) 7534 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 7535 7536 // canonicalize constant to RHS 7537 if (N0CFP && !N1CFP) 7538 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 7539 7540 // fold (fadd A, (fneg B)) -> (fsub A, B) 7541 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7542 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 7543 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 7544 GetNegatedExpression(N1, DAG, LegalOperations)); 7545 7546 // fold (fadd (fneg A), B) -> (fsub B, A) 7547 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7548 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 7549 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 7550 GetNegatedExpression(N0, DAG, LegalOperations)); 7551 7552 // If 'unsafe math' is enabled, fold lots of things. 7553 if (Options.UnsafeFPMath) { 7554 // No FP constant should be created after legalization as Instruction 7555 // Selection pass has a hard time dealing with FP constants. 7556 bool AllowNewConst = (Level < AfterLegalizeDAG); 7557 7558 // fold (fadd A, 0) -> A 7559 if (N1CFP && N1CFP->getValueAPF().isZero()) 7560 return N0; 7561 7562 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 7563 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 7564 isa<ConstantFPSDNode>(N0.getOperand(1))) 7565 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 7566 DAG.getNode(ISD::FADD, SDLoc(N), VT, 7567 N0.getOperand(1), N1)); 7568 7569 // If allowed, fold (fadd (fneg x), x) -> 0.0 7570 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 7571 return DAG.getConstantFP(0.0, VT); 7572 7573 // If allowed, fold (fadd x, (fneg x)) -> 0.0 7574 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 7575 return DAG.getConstantFP(0.0, VT); 7576 7577 // We can fold chains of FADD's of the same value into multiplications. 7578 // This transform is not safe in general because we are reducing the number 7579 // of rounding steps. 7580 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 7581 if (N0.getOpcode() == ISD::FMUL) { 7582 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7583 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7584 7585 // (fadd (fmul x, c), x) -> (fmul x, c+1) 7586 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 7587 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7588 SDValue(CFP01, 0), 7589 DAG.getConstantFP(1.0, VT)); 7590 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP); 7591 } 7592 7593 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 7594 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 7595 N1.getOperand(0) == N1.getOperand(1) && 7596 N0.getOperand(0) == N1.getOperand(0)) { 7597 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7598 SDValue(CFP01, 0), 7599 DAG.getConstantFP(2.0, VT)); 7600 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7601 N0.getOperand(0), NewCFP); 7602 } 7603 } 7604 7605 if (N1.getOpcode() == ISD::FMUL) { 7606 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7607 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 7608 7609 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 7610 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 7611 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7612 SDValue(CFP11, 0), 7613 DAG.getConstantFP(1.0, VT)); 7614 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP); 7615 } 7616 7617 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 7618 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 7619 N0.getOperand(0) == N0.getOperand(1) && 7620 N1.getOperand(0) == N0.getOperand(0)) { 7621 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7622 SDValue(CFP11, 0), 7623 DAG.getConstantFP(2.0, VT)); 7624 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP); 7625 } 7626 } 7627 7628 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 7629 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7630 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 7631 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 7632 (N0.getOperand(0) == N1)) 7633 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7634 N1, DAG.getConstantFP(3.0, VT)); 7635 } 7636 7637 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 7638 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7639 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 7640 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 7641 N1.getOperand(0) == N0) 7642 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7643 N0, DAG.getConstantFP(3.0, VT)); 7644 } 7645 7646 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 7647 if (AllowNewConst && 7648 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 7649 N0.getOperand(0) == N0.getOperand(1) && 7650 N1.getOperand(0) == N1.getOperand(1) && 7651 N0.getOperand(0) == N1.getOperand(0)) 7652 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7653 N0.getOperand(0), DAG.getConstantFP(4.0, VT)); 7654 } 7655 } // enable-unsafe-fp-math 7656 7657 // FADD -> FMA combines: 7658 SDValue Fused = visitFADDForFMACombine(N); 7659 if (Fused) { 7660 AddToWorklist(Fused.getNode()); 7661 return Fused; 7662 } 7663 7664 return SDValue(); 7665 } 7666 7667 SDValue DAGCombiner::visitFSUB(SDNode *N) { 7668 SDValue N0 = N->getOperand(0); 7669 SDValue N1 = N->getOperand(1); 7670 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7671 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7672 EVT VT = N->getValueType(0); 7673 SDLoc dl(N); 7674 const TargetOptions &Options = DAG.getTarget().Options; 7675 7676 // fold vector ops 7677 if (VT.isVector()) 7678 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7679 return FoldedVOp; 7680 7681 // fold (fsub c1, c2) -> c1-c2 7682 if (N0CFP && N1CFP) 7683 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 7684 7685 // fold (fsub A, (fneg B)) -> (fadd A, B) 7686 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7687 return DAG.getNode(ISD::FADD, dl, VT, N0, 7688 GetNegatedExpression(N1, DAG, LegalOperations)); 7689 7690 // If 'unsafe math' is enabled, fold lots of things. 7691 if (Options.UnsafeFPMath) { 7692 // (fsub A, 0) -> A 7693 if (N1CFP && N1CFP->getValueAPF().isZero()) 7694 return N0; 7695 7696 // (fsub 0, B) -> -B 7697 if (N0CFP && N0CFP->getValueAPF().isZero()) { 7698 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7699 return GetNegatedExpression(N1, DAG, LegalOperations); 7700 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7701 return DAG.getNode(ISD::FNEG, dl, VT, N1); 7702 } 7703 7704 // (fsub x, x) -> 0.0 7705 if (N0 == N1) 7706 return DAG.getConstantFP(0.0f, VT); 7707 7708 // (fsub x, (fadd x, y)) -> (fneg y) 7709 // (fsub x, (fadd y, x)) -> (fneg y) 7710 if (N1.getOpcode() == ISD::FADD) { 7711 SDValue N10 = N1->getOperand(0); 7712 SDValue N11 = N1->getOperand(1); 7713 7714 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 7715 return GetNegatedExpression(N11, DAG, LegalOperations); 7716 7717 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 7718 return GetNegatedExpression(N10, DAG, LegalOperations); 7719 } 7720 } 7721 7722 // FSUB -> FMA combines: 7723 SDValue Fused = visitFSUBForFMACombine(N); 7724 if (Fused) { 7725 AddToWorklist(Fused.getNode()); 7726 return Fused; 7727 } 7728 7729 return SDValue(); 7730 } 7731 7732 SDValue DAGCombiner::visitFMUL(SDNode *N) { 7733 SDValue N0 = N->getOperand(0); 7734 SDValue N1 = N->getOperand(1); 7735 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7736 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7737 EVT VT = N->getValueType(0); 7738 const TargetOptions &Options = DAG.getTarget().Options; 7739 7740 // fold vector ops 7741 if (VT.isVector()) { 7742 // This just handles C1 * C2 for vectors. Other vector folds are below. 7743 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7744 return FoldedVOp; 7745 } 7746 7747 // fold (fmul c1, c2) -> c1*c2 7748 if (N0CFP && N1CFP) 7749 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 7750 7751 // canonicalize constant to RHS 7752 if (isConstantFPBuildVectorOrConstantFP(N0) && 7753 !isConstantFPBuildVectorOrConstantFP(N1)) 7754 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 7755 7756 // fold (fmul A, 1.0) -> A 7757 if (N1CFP && N1CFP->isExactlyValue(1.0)) 7758 return N0; 7759 7760 if (Options.UnsafeFPMath) { 7761 // fold (fmul A, 0) -> 0 7762 if (N1CFP && N1CFP->getValueAPF().isZero()) 7763 return N1; 7764 7765 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 7766 if (N0.getOpcode() == ISD::FMUL) { 7767 // Fold scalars or any vector constants (not just splats). 7768 // This fold is done in general by InstCombine, but extra fmul insts 7769 // may have been generated during lowering. 7770 SDValue N00 = N0.getOperand(0); 7771 SDValue N01 = N0.getOperand(1); 7772 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 7773 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 7774 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 7775 7776 // Check 1: Make sure that the first operand of the inner multiply is NOT 7777 // a constant. Otherwise, we may induce infinite looping. 7778 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 7779 // Check 2: Make sure that the second operand of the inner multiply and 7780 // the second operand of the outer multiply are constants. 7781 if ((N1CFP && isConstOrConstSplatFP(N01)) || 7782 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 7783 SDLoc SL(N); 7784 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1); 7785 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts); 7786 } 7787 } 7788 } 7789 7790 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 7791 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 7792 // during an early run of DAGCombiner can prevent folding with fmuls 7793 // inserted during lowering. 7794 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) { 7795 SDLoc SL(N); 7796 const SDValue Two = DAG.getConstantFP(2.0, VT); 7797 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1); 7798 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts); 7799 } 7800 } 7801 7802 // fold (fmul X, 2.0) -> (fadd X, X) 7803 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 7804 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 7805 7806 // fold (fmul X, -1.0) -> (fneg X) 7807 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 7808 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7809 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 7810 7811 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 7812 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 7813 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 7814 // Both can be negated for free, check to see if at least one is cheaper 7815 // negated. 7816 if (LHSNeg == 2 || RHSNeg == 2) 7817 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7818 GetNegatedExpression(N0, DAG, LegalOperations), 7819 GetNegatedExpression(N1, DAG, LegalOperations)); 7820 } 7821 } 7822 7823 return SDValue(); 7824 } 7825 7826 SDValue DAGCombiner::visitFMA(SDNode *N) { 7827 SDValue N0 = N->getOperand(0); 7828 SDValue N1 = N->getOperand(1); 7829 SDValue N2 = N->getOperand(2); 7830 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7831 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7832 EVT VT = N->getValueType(0); 7833 SDLoc dl(N); 7834 const TargetOptions &Options = DAG.getTarget().Options; 7835 7836 // Constant fold FMA. 7837 if (isa<ConstantFPSDNode>(N0) && 7838 isa<ConstantFPSDNode>(N1) && 7839 isa<ConstantFPSDNode>(N2)) { 7840 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 7841 } 7842 7843 if (Options.UnsafeFPMath) { 7844 if (N0CFP && N0CFP->isZero()) 7845 return N2; 7846 if (N1CFP && N1CFP->isZero()) 7847 return N2; 7848 } 7849 if (N0CFP && N0CFP->isExactlyValue(1.0)) 7850 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 7851 if (N1CFP && N1CFP->isExactlyValue(1.0)) 7852 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 7853 7854 // Canonicalize (fma c, x, y) -> (fma x, c, y) 7855 if (N0CFP && !N1CFP) 7856 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 7857 7858 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 7859 if (Options.UnsafeFPMath && N1CFP && 7860 N2.getOpcode() == ISD::FMUL && 7861 N0 == N2.getOperand(0) && 7862 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 7863 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7864 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 7865 } 7866 7867 7868 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 7869 if (Options.UnsafeFPMath && 7870 N0.getOpcode() == ISD::FMUL && N1CFP && 7871 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 7872 return DAG.getNode(ISD::FMA, dl, VT, 7873 N0.getOperand(0), 7874 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 7875 N2); 7876 } 7877 7878 // (fma x, 1, y) -> (fadd x, y) 7879 // (fma x, -1, y) -> (fadd (fneg x), y) 7880 if (N1CFP) { 7881 if (N1CFP->isExactlyValue(1.0)) 7882 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 7883 7884 if (N1CFP->isExactlyValue(-1.0) && 7885 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 7886 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 7887 AddToWorklist(RHSNeg.getNode()); 7888 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 7889 } 7890 } 7891 7892 // (fma x, c, x) -> (fmul x, (c+1)) 7893 if (Options.UnsafeFPMath && N1CFP && N0 == N2) 7894 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7895 DAG.getNode(ISD::FADD, dl, VT, 7896 N1, DAG.getConstantFP(1.0, VT))); 7897 7898 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 7899 if (Options.UnsafeFPMath && N1CFP && 7900 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 7901 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7902 DAG.getNode(ISD::FADD, dl, VT, 7903 N1, DAG.getConstantFP(-1.0, VT))); 7904 7905 7906 return SDValue(); 7907 } 7908 7909 SDValue DAGCombiner::visitFDIV(SDNode *N) { 7910 SDValue N0 = N->getOperand(0); 7911 SDValue N1 = N->getOperand(1); 7912 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7913 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7914 EVT VT = N->getValueType(0); 7915 SDLoc DL(N); 7916 const TargetOptions &Options = DAG.getTarget().Options; 7917 7918 // fold vector ops 7919 if (VT.isVector()) 7920 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7921 return FoldedVOp; 7922 7923 // fold (fdiv c1, c2) -> c1/c2 7924 if (N0CFP && N1CFP) 7925 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 7926 7927 if (Options.UnsafeFPMath) { 7928 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 7929 if (N1CFP) { 7930 // Compute the reciprocal 1.0 / c2. 7931 APFloat N1APF = N1CFP->getValueAPF(); 7932 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 7933 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 7934 // Only do the transform if the reciprocal is a legal fp immediate that 7935 // isn't too nasty (eg NaN, denormal, ...). 7936 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 7937 (!LegalOperations || 7938 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 7939 // backend)... we should handle this gracefully after Legalize. 7940 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 7941 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 7942 TLI.isFPImmLegal(Recip, VT))) 7943 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 7944 DAG.getConstantFP(Recip, VT)); 7945 } 7946 7947 // If this FDIV is part of a reciprocal square root, it may be folded 7948 // into a target-specific square root estimate instruction. 7949 if (N1.getOpcode() == ISD::FSQRT) { 7950 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) { 7951 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7952 } 7953 } else if (N1.getOpcode() == ISD::FP_EXTEND && 7954 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7955 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 7956 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 7957 AddToWorklist(RV.getNode()); 7958 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7959 } 7960 } else if (N1.getOpcode() == ISD::FP_ROUND && 7961 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7962 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 7963 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 7964 AddToWorklist(RV.getNode()); 7965 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7966 } 7967 } else if (N1.getOpcode() == ISD::FMUL) { 7968 // Look through an FMUL. Even though this won't remove the FDIV directly, 7969 // it's still worthwhile to get rid of the FSQRT if possible. 7970 SDValue SqrtOp; 7971 SDValue OtherOp; 7972 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7973 SqrtOp = N1.getOperand(0); 7974 OtherOp = N1.getOperand(1); 7975 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 7976 SqrtOp = N1.getOperand(1); 7977 OtherOp = N1.getOperand(0); 7978 } 7979 if (SqrtOp.getNode()) { 7980 // We found a FSQRT, so try to make this fold: 7981 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 7982 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) { 7983 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp); 7984 AddToWorklist(RV.getNode()); 7985 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7986 } 7987 } 7988 } 7989 7990 // Fold into a reciprocal estimate and multiply instead of a real divide. 7991 if (SDValue RV = BuildReciprocalEstimate(N1)) { 7992 AddToWorklist(RV.getNode()); 7993 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7994 } 7995 } 7996 7997 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 7998 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 7999 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8000 // Both can be negated for free, check to see if at least one is cheaper 8001 // negated. 8002 if (LHSNeg == 2 || RHSNeg == 2) 8003 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8004 GetNegatedExpression(N0, DAG, LegalOperations), 8005 GetNegatedExpression(N1, DAG, LegalOperations)); 8006 } 8007 } 8008 8009 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8010 // reciprocal. 8011 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8012 // Notice that this is not always beneficial. One reason is different target 8013 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8014 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8015 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8016 if (Options.UnsafeFPMath) { 8017 // Skip if current node is a reciprocal. 8018 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8019 return SDValue(); 8020 8021 SmallVector<SDNode *, 4> Users; 8022 // Find all FDIV users of the same divisor. 8023 for (SDNode::use_iterator UI = N1.getNode()->use_begin(), 8024 UE = N1.getNode()->use_end(); 8025 UI != UE; ++UI) { 8026 SDNode *User = UI.getUse().getUser(); 8027 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1) 8028 Users.push_back(User); 8029 } 8030 8031 if (TLI.combineRepeatedFPDivisors(Users.size())) { 8032 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0 8033 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1); 8034 8035 // Dividend / Divisor -> Dividend * Reciprocal 8036 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) { 8037 if ((*I)->getOperand(0) != FPOne) { 8038 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT, 8039 (*I)->getOperand(0), Reciprocal); 8040 DAG.ReplaceAllUsesWith(*I, NewNode.getNode()); 8041 } 8042 } 8043 return SDValue(); 8044 } 8045 } 8046 8047 return SDValue(); 8048 } 8049 8050 SDValue DAGCombiner::visitFREM(SDNode *N) { 8051 SDValue N0 = N->getOperand(0); 8052 SDValue N1 = N->getOperand(1); 8053 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8054 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8055 EVT VT = N->getValueType(0); 8056 8057 // fold (frem c1, c2) -> fmod(c1,c2) 8058 if (N0CFP && N1CFP) 8059 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 8060 8061 return SDValue(); 8062 } 8063 8064 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8065 if (DAG.getTarget().Options.UnsafeFPMath && 8066 !TLI.isFsqrtCheap()) { 8067 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8068 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) { 8069 EVT VT = RV.getValueType(); 8070 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV); 8071 AddToWorklist(RV.getNode()); 8072 8073 // Unfortunately, RV is now NaN if the input was exactly 0. 8074 // Select out this case and force the answer to 0. 8075 SDValue Zero = DAG.getConstantFP(0.0, VT); 8076 SDValue ZeroCmp = 8077 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT), 8078 N->getOperand(0), Zero, ISD::SETEQ); 8079 AddToWorklist(ZeroCmp.getNode()); 8080 AddToWorklist(RV.getNode()); 8081 8082 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, 8083 SDLoc(N), VT, ZeroCmp, Zero, RV); 8084 return RV; 8085 } 8086 } 8087 return SDValue(); 8088 } 8089 8090 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8091 SDValue N0 = N->getOperand(0); 8092 SDValue N1 = N->getOperand(1); 8093 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8094 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8095 EVT VT = N->getValueType(0); 8096 8097 if (N0CFP && N1CFP) // Constant fold 8098 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8099 8100 if (N1CFP) { 8101 const APFloat& V = N1CFP->getValueAPF(); 8102 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8103 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8104 if (!V.isNegative()) { 8105 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8106 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8107 } else { 8108 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8109 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8110 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8111 } 8112 } 8113 8114 // copysign(fabs(x), y) -> copysign(x, y) 8115 // copysign(fneg(x), y) -> copysign(x, y) 8116 // copysign(copysign(x,z), y) -> copysign(x, y) 8117 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8118 N0.getOpcode() == ISD::FCOPYSIGN) 8119 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8120 N0.getOperand(0), N1); 8121 8122 // copysign(x, abs(y)) -> abs(x) 8123 if (N1.getOpcode() == ISD::FABS) 8124 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8125 8126 // copysign(x, copysign(y,z)) -> copysign(x, z) 8127 if (N1.getOpcode() == ISD::FCOPYSIGN) 8128 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8129 N0, N1.getOperand(1)); 8130 8131 // copysign(x, fp_extend(y)) -> copysign(x, y) 8132 // copysign(x, fp_round(y)) -> copysign(x, y) 8133 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 8134 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8135 N0, N1.getOperand(0)); 8136 8137 return SDValue(); 8138 } 8139 8140 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8141 SDValue N0 = N->getOperand(0); 8142 EVT VT = N->getValueType(0); 8143 EVT OpVT = N0.getValueType(); 8144 8145 // fold (sint_to_fp c1) -> c1fp 8146 if (isConstantIntBuildVectorOrConstantInt(N0) && 8147 // ...but only if the target supports immediate floating-point values 8148 (!LegalOperations || 8149 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8150 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8151 8152 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8153 // but UINT_TO_FP is legal on this target, try to convert. 8154 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8155 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8156 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8157 if (DAG.SignBitIsZero(N0)) 8158 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8159 } 8160 8161 // The next optimizations are desirable only if SELECT_CC can be lowered. 8162 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8163 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8164 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8165 !VT.isVector() && 8166 (!LegalOperations || 8167 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8168 SDValue Ops[] = 8169 { N0.getOperand(0), N0.getOperand(1), 8170 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 8171 N0.getOperand(2) }; 8172 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 8173 } 8174 8175 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8176 // (select_cc x, y, 1.0, 0.0,, cc) 8177 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8178 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8179 (!LegalOperations || 8180 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8181 SDValue Ops[] = 8182 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8183 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 8184 N0.getOperand(0).getOperand(2) }; 8185 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 8186 } 8187 } 8188 8189 return SDValue(); 8190 } 8191 8192 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8193 SDValue N0 = N->getOperand(0); 8194 EVT VT = N->getValueType(0); 8195 EVT OpVT = N0.getValueType(); 8196 8197 // fold (uint_to_fp c1) -> c1fp 8198 if (isConstantIntBuildVectorOrConstantInt(N0) && 8199 // ...but only if the target supports immediate floating-point values 8200 (!LegalOperations || 8201 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8202 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8203 8204 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8205 // but SINT_TO_FP is legal on this target, try to convert. 8206 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8207 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8208 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8209 if (DAG.SignBitIsZero(N0)) 8210 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8211 } 8212 8213 // The next optimizations are desirable only if SELECT_CC can be lowered. 8214 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8215 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8216 8217 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8218 (!LegalOperations || 8219 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8220 SDValue Ops[] = 8221 { N0.getOperand(0), N0.getOperand(1), 8222 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 8223 N0.getOperand(2) }; 8224 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 8225 } 8226 } 8227 8228 return SDValue(); 8229 } 8230 8231 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8232 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8233 SDValue N0 = N->getOperand(0); 8234 EVT VT = N->getValueType(0); 8235 8236 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8237 return SDValue(); 8238 8239 SDValue Src = N0.getOperand(0); 8240 EVT SrcVT = Src.getValueType(); 8241 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8242 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8243 8244 // We can safely assume the conversion won't overflow the output range, 8245 // because (for example) (uint8_t)18293.f is undefined behavior. 8246 8247 // Since we can assume the conversion won't overflow, our decision as to 8248 // whether the input will fit in the float should depend on the minimum 8249 // of the input range and output range. 8250 8251 // This means this is also safe for a signed input and unsigned output, since 8252 // a negative input would lead to undefined behavior. 8253 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8254 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8255 unsigned ActualSize = std::min(InputSize, OutputSize); 8256 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8257 8258 // We can only fold away the float conversion if the input range can be 8259 // represented exactly in the float range. 8260 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8261 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8262 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8263 : ISD::ZERO_EXTEND; 8264 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8265 } 8266 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8267 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8268 if (SrcVT == VT) 8269 return Src; 8270 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 8271 } 8272 return SDValue(); 8273 } 8274 8275 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8276 SDValue N0 = N->getOperand(0); 8277 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8278 EVT VT = N->getValueType(0); 8279 8280 // fold (fp_to_sint c1fp) -> c1 8281 if (N0CFP) 8282 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8283 8284 return FoldIntToFPToInt(N, DAG); 8285 } 8286 8287 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 8288 SDValue N0 = N->getOperand(0); 8289 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8290 EVT VT = N->getValueType(0); 8291 8292 // fold (fp_to_uint c1fp) -> c1 8293 if (N0CFP) 8294 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 8295 8296 return FoldIntToFPToInt(N, DAG); 8297 } 8298 8299 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 8300 SDValue N0 = N->getOperand(0); 8301 SDValue N1 = N->getOperand(1); 8302 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8303 EVT VT = N->getValueType(0); 8304 8305 // fold (fp_round c1fp) -> c1fp 8306 if (N0CFP) 8307 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 8308 8309 // fold (fp_round (fp_extend x)) -> x 8310 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 8311 return N0.getOperand(0); 8312 8313 // fold (fp_round (fp_round x)) -> (fp_round x) 8314 if (N0.getOpcode() == ISD::FP_ROUND) { 8315 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 8316 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 8317 // If the first fp_round isn't a value preserving truncation, it might 8318 // introduce a tie in the second fp_round, that wouldn't occur in the 8319 // single-step fp_round we want to fold to. 8320 // In other words, double rounding isn't the same as rounding. 8321 // Also, this is a value preserving truncation iff both fp_round's are. 8322 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) 8323 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 8324 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc)); 8325 } 8326 8327 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 8328 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 8329 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 8330 N0.getOperand(0), N1); 8331 AddToWorklist(Tmp.getNode()); 8332 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8333 Tmp, N0.getOperand(1)); 8334 } 8335 8336 return SDValue(); 8337 } 8338 8339 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 8340 SDValue N0 = N->getOperand(0); 8341 EVT VT = N->getValueType(0); 8342 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8343 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8344 8345 // fold (fp_round_inreg c1fp) -> c1fp 8346 if (N0CFP && isTypeLegal(EVT)) { 8347 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 8348 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 8349 } 8350 8351 return SDValue(); 8352 } 8353 8354 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 8355 SDValue N0 = N->getOperand(0); 8356 EVT VT = N->getValueType(0); 8357 8358 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 8359 if (N->hasOneUse() && 8360 N->use_begin()->getOpcode() == ISD::FP_ROUND) 8361 return SDValue(); 8362 8363 // fold (fp_extend c1fp) -> c1fp 8364 if (isConstantFPBuildVectorOrConstantFP(N0)) 8365 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 8366 8367 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 8368 if (N0.getOpcode() == ISD::FP16_TO_FP && 8369 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 8370 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 8371 8372 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 8373 // value of X. 8374 if (N0.getOpcode() == ISD::FP_ROUND 8375 && N0.getNode()->getConstantOperandVal(1) == 1) { 8376 SDValue In = N0.getOperand(0); 8377 if (In.getValueType() == VT) return In; 8378 if (VT.bitsLT(In.getValueType())) 8379 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 8380 In, N0.getOperand(1)); 8381 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 8382 } 8383 8384 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 8385 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8386 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8387 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8388 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8389 LN0->getChain(), 8390 LN0->getBasePtr(), N0.getValueType(), 8391 LN0->getMemOperand()); 8392 CombineTo(N, ExtLoad); 8393 CombineTo(N0.getNode(), 8394 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 8395 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 8396 ExtLoad.getValue(1)); 8397 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8398 } 8399 8400 return SDValue(); 8401 } 8402 8403 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 8404 SDValue N0 = N->getOperand(0); 8405 EVT VT = N->getValueType(0); 8406 8407 // fold (fceil c1) -> fceil(c1) 8408 if (isConstantFPBuildVectorOrConstantFP(N0)) 8409 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 8410 8411 return SDValue(); 8412 } 8413 8414 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 8415 SDValue N0 = N->getOperand(0); 8416 EVT VT = N->getValueType(0); 8417 8418 // fold (ftrunc c1) -> ftrunc(c1) 8419 if (isConstantFPBuildVectorOrConstantFP(N0)) 8420 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 8421 8422 return SDValue(); 8423 } 8424 8425 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 8426 SDValue N0 = N->getOperand(0); 8427 EVT VT = N->getValueType(0); 8428 8429 // fold (ffloor c1) -> ffloor(c1) 8430 if (isConstantFPBuildVectorOrConstantFP(N0)) 8431 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 8432 8433 return SDValue(); 8434 } 8435 8436 // FIXME: FNEG and FABS have a lot in common; refactor. 8437 SDValue DAGCombiner::visitFNEG(SDNode *N) { 8438 SDValue N0 = N->getOperand(0); 8439 EVT VT = N->getValueType(0); 8440 8441 // Constant fold FNEG. 8442 if (isConstantFPBuildVectorOrConstantFP(N0)) 8443 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 8444 8445 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 8446 &DAG.getTarget().Options)) 8447 return GetNegatedExpression(N0, DAG, LegalOperations); 8448 8449 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 8450 // constant pool values. 8451 if (!TLI.isFNegFree(VT) && 8452 N0.getOpcode() == ISD::BITCAST && 8453 N0.getNode()->hasOneUse()) { 8454 SDValue Int = N0.getOperand(0); 8455 EVT IntVT = Int.getValueType(); 8456 if (IntVT.isInteger() && !IntVT.isVector()) { 8457 APInt SignMask; 8458 if (N0.getValueType().isVector()) { 8459 // For a vector, get a mask such as 0x80... per scalar element 8460 // and splat it. 8461 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8462 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8463 } else { 8464 // For a scalar, just generate 0x80... 8465 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 8466 } 8467 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 8468 DAG.getConstant(SignMask, IntVT)); 8469 AddToWorklist(Int.getNode()); 8470 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 8471 } 8472 } 8473 8474 // (fneg (fmul c, x)) -> (fmul -c, x) 8475 if (N0.getOpcode() == ISD::FMUL) { 8476 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8477 if (CFP1) { 8478 APFloat CVal = CFP1->getValueAPF(); 8479 CVal.changeSign(); 8480 if (Level >= AfterLegalizeDAG && 8481 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 8482 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 8483 return DAG.getNode( 8484 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 8485 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1))); 8486 } 8487 } 8488 8489 return SDValue(); 8490 } 8491 8492 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 8493 SDValue N0 = N->getOperand(0); 8494 SDValue N1 = N->getOperand(1); 8495 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8496 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8497 8498 if (N0CFP && N1CFP) { 8499 const APFloat &C0 = N0CFP->getValueAPF(); 8500 const APFloat &C1 = N1CFP->getValueAPF(); 8501 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0)); 8502 } 8503 8504 if (N0CFP) { 8505 EVT VT = N->getValueType(0); 8506 // Canonicalize to constant on RHS. 8507 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 8508 } 8509 8510 return SDValue(); 8511 } 8512 8513 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 8514 SDValue N0 = N->getOperand(0); 8515 SDValue N1 = N->getOperand(1); 8516 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8517 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8518 8519 if (N0CFP && N1CFP) { 8520 const APFloat &C0 = N0CFP->getValueAPF(); 8521 const APFloat &C1 = N1CFP->getValueAPF(); 8522 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0)); 8523 } 8524 8525 if (N0CFP) { 8526 EVT VT = N->getValueType(0); 8527 // Canonicalize to constant on RHS. 8528 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 8529 } 8530 8531 return SDValue(); 8532 } 8533 8534 SDValue DAGCombiner::visitFABS(SDNode *N) { 8535 SDValue N0 = N->getOperand(0); 8536 EVT VT = N->getValueType(0); 8537 8538 // fold (fabs c1) -> fabs(c1) 8539 if (isConstantFPBuildVectorOrConstantFP(N0)) 8540 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8541 8542 // fold (fabs (fabs x)) -> (fabs x) 8543 if (N0.getOpcode() == ISD::FABS) 8544 return N->getOperand(0); 8545 8546 // fold (fabs (fneg x)) -> (fabs x) 8547 // fold (fabs (fcopysign x, y)) -> (fabs x) 8548 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 8549 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 8550 8551 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 8552 // constant pool values. 8553 if (!TLI.isFAbsFree(VT) && 8554 N0.getOpcode() == ISD::BITCAST && 8555 N0.getNode()->hasOneUse()) { 8556 SDValue Int = N0.getOperand(0); 8557 EVT IntVT = Int.getValueType(); 8558 if (IntVT.isInteger() && !IntVT.isVector()) { 8559 APInt SignMask; 8560 if (N0.getValueType().isVector()) { 8561 // For a vector, get a mask such as 0x7f... per scalar element 8562 // and splat it. 8563 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8564 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8565 } else { 8566 // For a scalar, just generate 0x7f... 8567 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 8568 } 8569 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 8570 DAG.getConstant(SignMask, IntVT)); 8571 AddToWorklist(Int.getNode()); 8572 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 8573 } 8574 } 8575 8576 return SDValue(); 8577 } 8578 8579 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 8580 SDValue Chain = N->getOperand(0); 8581 SDValue N1 = N->getOperand(1); 8582 SDValue N2 = N->getOperand(2); 8583 8584 // If N is a constant we could fold this into a fallthrough or unconditional 8585 // branch. However that doesn't happen very often in normal code, because 8586 // Instcombine/SimplifyCFG should have handled the available opportunities. 8587 // If we did this folding here, it would be necessary to update the 8588 // MachineBasicBlock CFG, which is awkward. 8589 8590 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 8591 // on the target. 8592 if (N1.getOpcode() == ISD::SETCC && 8593 TLI.isOperationLegalOrCustom(ISD::BR_CC, 8594 N1.getOperand(0).getValueType())) { 8595 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8596 Chain, N1.getOperand(2), 8597 N1.getOperand(0), N1.getOperand(1), N2); 8598 } 8599 8600 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 8601 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 8602 (N1.getOperand(0).hasOneUse() && 8603 N1.getOperand(0).getOpcode() == ISD::SRL))) { 8604 SDNode *Trunc = nullptr; 8605 if (N1.getOpcode() == ISD::TRUNCATE) { 8606 // Look pass the truncate. 8607 Trunc = N1.getNode(); 8608 N1 = N1.getOperand(0); 8609 } 8610 8611 // Match this pattern so that we can generate simpler code: 8612 // 8613 // %a = ... 8614 // %b = and i32 %a, 2 8615 // %c = srl i32 %b, 1 8616 // brcond i32 %c ... 8617 // 8618 // into 8619 // 8620 // %a = ... 8621 // %b = and i32 %a, 2 8622 // %c = setcc eq %b, 0 8623 // brcond %c ... 8624 // 8625 // This applies only when the AND constant value has one bit set and the 8626 // SRL constant is equal to the log2 of the AND constant. The back-end is 8627 // smart enough to convert the result into a TEST/JMP sequence. 8628 SDValue Op0 = N1.getOperand(0); 8629 SDValue Op1 = N1.getOperand(1); 8630 8631 if (Op0.getOpcode() == ISD::AND && 8632 Op1.getOpcode() == ISD::Constant) { 8633 SDValue AndOp1 = Op0.getOperand(1); 8634 8635 if (AndOp1.getOpcode() == ISD::Constant) { 8636 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 8637 8638 if (AndConst.isPowerOf2() && 8639 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 8640 SDValue SetCC = 8641 DAG.getSetCC(SDLoc(N), 8642 getSetCCResultType(Op0.getValueType()), 8643 Op0, DAG.getConstant(0, Op0.getValueType()), 8644 ISD::SETNE); 8645 8646 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 8647 MVT::Other, Chain, SetCC, N2); 8648 // Don't add the new BRCond into the worklist or else SimplifySelectCC 8649 // will convert it back to (X & C1) >> C2. 8650 CombineTo(N, NewBRCond, false); 8651 // Truncate is dead. 8652 if (Trunc) 8653 deleteAndRecombine(Trunc); 8654 // Replace the uses of SRL with SETCC 8655 WorklistRemover DeadNodes(*this); 8656 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8657 deleteAndRecombine(N1.getNode()); 8658 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8659 } 8660 } 8661 } 8662 8663 if (Trunc) 8664 // Restore N1 if the above transformation doesn't match. 8665 N1 = N->getOperand(1); 8666 } 8667 8668 // Transform br(xor(x, y)) -> br(x != y) 8669 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 8670 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 8671 SDNode *TheXor = N1.getNode(); 8672 SDValue Op0 = TheXor->getOperand(0); 8673 SDValue Op1 = TheXor->getOperand(1); 8674 if (Op0.getOpcode() == Op1.getOpcode()) { 8675 // Avoid missing important xor optimizations. 8676 SDValue Tmp = visitXOR(TheXor); 8677 if (Tmp.getNode()) { 8678 if (Tmp.getNode() != TheXor) { 8679 DEBUG(dbgs() << "\nReplacing.8 "; 8680 TheXor->dump(&DAG); 8681 dbgs() << "\nWith: "; 8682 Tmp.getNode()->dump(&DAG); 8683 dbgs() << '\n'); 8684 WorklistRemover DeadNodes(*this); 8685 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 8686 deleteAndRecombine(TheXor); 8687 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8688 MVT::Other, Chain, Tmp, N2); 8689 } 8690 8691 // visitXOR has changed XOR's operands or replaced the XOR completely, 8692 // bail out. 8693 return SDValue(N, 0); 8694 } 8695 } 8696 8697 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 8698 bool Equal = false; 8699 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 8700 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 8701 Op0.getOpcode() == ISD::XOR) { 8702 TheXor = Op0.getNode(); 8703 Equal = true; 8704 } 8705 8706 EVT SetCCVT = N1.getValueType(); 8707 if (LegalTypes) 8708 SetCCVT = getSetCCResultType(SetCCVT); 8709 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 8710 SetCCVT, 8711 Op0, Op1, 8712 Equal ? ISD::SETEQ : ISD::SETNE); 8713 // Replace the uses of XOR with SETCC 8714 WorklistRemover DeadNodes(*this); 8715 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8716 deleteAndRecombine(N1.getNode()); 8717 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8718 MVT::Other, Chain, SetCC, N2); 8719 } 8720 } 8721 8722 return SDValue(); 8723 } 8724 8725 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 8726 // 8727 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 8728 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 8729 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 8730 8731 // If N is a constant we could fold this into a fallthrough or unconditional 8732 // branch. However that doesn't happen very often in normal code, because 8733 // Instcombine/SimplifyCFG should have handled the available opportunities. 8734 // If we did this folding here, it would be necessary to update the 8735 // MachineBasicBlock CFG, which is awkward. 8736 8737 // Use SimplifySetCC to simplify SETCC's. 8738 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 8739 CondLHS, CondRHS, CC->get(), SDLoc(N), 8740 false); 8741 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 8742 8743 // fold to a simpler setcc 8744 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 8745 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8746 N->getOperand(0), Simp.getOperand(2), 8747 Simp.getOperand(0), Simp.getOperand(1), 8748 N->getOperand(4)); 8749 8750 return SDValue(); 8751 } 8752 8753 /// Return true if 'Use' is a load or a store that uses N as its base pointer 8754 /// and that N may be folded in the load / store addressing mode. 8755 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 8756 SelectionDAG &DAG, 8757 const TargetLowering &TLI) { 8758 EVT VT; 8759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 8760 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 8761 return false; 8762 VT = Use->getValueType(0); 8763 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 8764 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 8765 return false; 8766 VT = ST->getValue().getValueType(); 8767 } else 8768 return false; 8769 8770 TargetLowering::AddrMode AM; 8771 if (N->getOpcode() == ISD::ADD) { 8772 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8773 if (Offset) 8774 // [reg +/- imm] 8775 AM.BaseOffs = Offset->getSExtValue(); 8776 else 8777 // [reg +/- reg] 8778 AM.Scale = 1; 8779 } else if (N->getOpcode() == ISD::SUB) { 8780 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8781 if (Offset) 8782 // [reg +/- imm] 8783 AM.BaseOffs = -Offset->getSExtValue(); 8784 else 8785 // [reg +/- reg] 8786 AM.Scale = 1; 8787 } else 8788 return false; 8789 8790 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 8791 } 8792 8793 /// Try turning a load/store into a pre-indexed load/store when the base 8794 /// pointer is an add or subtract and it has other uses besides the load/store. 8795 /// After the transformation, the new indexed load/store has effectively folded 8796 /// the add/subtract in and all of its other uses are redirected to the 8797 /// new load/store. 8798 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 8799 if (Level < AfterLegalizeDAG) 8800 return false; 8801 8802 bool isLoad = true; 8803 SDValue Ptr; 8804 EVT VT; 8805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8806 if (LD->isIndexed()) 8807 return false; 8808 VT = LD->getMemoryVT(); 8809 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 8810 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 8811 return false; 8812 Ptr = LD->getBasePtr(); 8813 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 8814 if (ST->isIndexed()) 8815 return false; 8816 VT = ST->getMemoryVT(); 8817 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 8818 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 8819 return false; 8820 Ptr = ST->getBasePtr(); 8821 isLoad = false; 8822 } else { 8823 return false; 8824 } 8825 8826 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 8827 // out. There is no reason to make this a preinc/predec. 8828 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 8829 Ptr.getNode()->hasOneUse()) 8830 return false; 8831 8832 // Ask the target to do addressing mode selection. 8833 SDValue BasePtr; 8834 SDValue Offset; 8835 ISD::MemIndexedMode AM = ISD::UNINDEXED; 8836 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 8837 return false; 8838 8839 // Backends without true r+i pre-indexed forms may need to pass a 8840 // constant base with a variable offset so that constant coercion 8841 // will work with the patterns in canonical form. 8842 bool Swapped = false; 8843 if (isa<ConstantSDNode>(BasePtr)) { 8844 std::swap(BasePtr, Offset); 8845 Swapped = true; 8846 } 8847 8848 // Don't create a indexed load / store with zero offset. 8849 if (isa<ConstantSDNode>(Offset) && 8850 cast<ConstantSDNode>(Offset)->isNullValue()) 8851 return false; 8852 8853 // Try turning it into a pre-indexed load / store except when: 8854 // 1) The new base ptr is a frame index. 8855 // 2) If N is a store and the new base ptr is either the same as or is a 8856 // predecessor of the value being stored. 8857 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 8858 // that would create a cycle. 8859 // 4) All uses are load / store ops that use it as old base ptr. 8860 8861 // Check #1. Preinc'ing a frame index would require copying the stack pointer 8862 // (plus the implicit offset) to a register to preinc anyway. 8863 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 8864 return false; 8865 8866 // Check #2. 8867 if (!isLoad) { 8868 SDValue Val = cast<StoreSDNode>(N)->getValue(); 8869 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 8870 return false; 8871 } 8872 8873 // If the offset is a constant, there may be other adds of constants that 8874 // can be folded with this one. We should do this to avoid having to keep 8875 // a copy of the original base pointer. 8876 SmallVector<SDNode *, 16> OtherUses; 8877 if (isa<ConstantSDNode>(Offset)) 8878 for (SDNode *Use : BasePtr.getNode()->uses()) { 8879 if (Use == Ptr.getNode()) 8880 continue; 8881 8882 if (Use->isPredecessorOf(N)) 8883 continue; 8884 8885 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 8886 OtherUses.clear(); 8887 break; 8888 } 8889 8890 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 8891 if (Op1.getNode() == BasePtr.getNode()) 8892 std::swap(Op0, Op1); 8893 assert(Op0.getNode() == BasePtr.getNode() && 8894 "Use of ADD/SUB but not an operand"); 8895 8896 if (!isa<ConstantSDNode>(Op1)) { 8897 OtherUses.clear(); 8898 break; 8899 } 8900 8901 // FIXME: In some cases, we can be smarter about this. 8902 if (Op1.getValueType() != Offset.getValueType()) { 8903 OtherUses.clear(); 8904 break; 8905 } 8906 8907 OtherUses.push_back(Use); 8908 } 8909 8910 if (Swapped) 8911 std::swap(BasePtr, Offset); 8912 8913 // Now check for #3 and #4. 8914 bool RealUse = false; 8915 8916 // Caches for hasPredecessorHelper 8917 SmallPtrSet<const SDNode *, 32> Visited; 8918 SmallVector<const SDNode *, 16> Worklist; 8919 8920 for (SDNode *Use : Ptr.getNode()->uses()) { 8921 if (Use == N) 8922 continue; 8923 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 8924 return false; 8925 8926 // If Ptr may be folded in addressing mode of other use, then it's 8927 // not profitable to do this transformation. 8928 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 8929 RealUse = true; 8930 } 8931 8932 if (!RealUse) 8933 return false; 8934 8935 SDValue Result; 8936 if (isLoad) 8937 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 8938 BasePtr, Offset, AM); 8939 else 8940 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 8941 BasePtr, Offset, AM); 8942 ++PreIndexedNodes; 8943 ++NodesCombined; 8944 DEBUG(dbgs() << "\nReplacing.4 "; 8945 N->dump(&DAG); 8946 dbgs() << "\nWith: "; 8947 Result.getNode()->dump(&DAG); 8948 dbgs() << '\n'); 8949 WorklistRemover DeadNodes(*this); 8950 if (isLoad) { 8951 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 8952 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 8953 } else { 8954 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 8955 } 8956 8957 // Finally, since the node is now dead, remove it from the graph. 8958 deleteAndRecombine(N); 8959 8960 if (Swapped) 8961 std::swap(BasePtr, Offset); 8962 8963 // Replace other uses of BasePtr that can be updated to use Ptr 8964 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 8965 unsigned OffsetIdx = 1; 8966 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 8967 OffsetIdx = 0; 8968 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 8969 BasePtr.getNode() && "Expected BasePtr operand"); 8970 8971 // We need to replace ptr0 in the following expression: 8972 // x0 * offset0 + y0 * ptr0 = t0 8973 // knowing that 8974 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 8975 // 8976 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 8977 // indexed load/store and the expresion that needs to be re-written. 8978 // 8979 // Therefore, we have: 8980 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 8981 8982 ConstantSDNode *CN = 8983 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 8984 int X0, X1, Y0, Y1; 8985 APInt Offset0 = CN->getAPIntValue(); 8986 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 8987 8988 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 8989 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 8990 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 8991 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 8992 8993 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 8994 8995 APInt CNV = Offset0; 8996 if (X0 < 0) CNV = -CNV; 8997 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 8998 else CNV = CNV - Offset1; 8999 9000 // We can now generate the new expression. 9001 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 9002 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9003 9004 SDValue NewUse = DAG.getNode(Opcode, 9005 SDLoc(OtherUses[i]), 9006 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9007 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9008 deleteAndRecombine(OtherUses[i]); 9009 } 9010 9011 // Replace the uses of Ptr with uses of the updated base value. 9012 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9013 deleteAndRecombine(Ptr.getNode()); 9014 9015 return true; 9016 } 9017 9018 /// Try to combine a load/store with a add/sub of the base pointer node into a 9019 /// post-indexed load/store. The transformation folded the add/subtract into the 9020 /// new indexed load/store effectively and all of its uses are redirected to the 9021 /// new load/store. 9022 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9023 if (Level < AfterLegalizeDAG) 9024 return false; 9025 9026 bool isLoad = true; 9027 SDValue Ptr; 9028 EVT VT; 9029 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9030 if (LD->isIndexed()) 9031 return false; 9032 VT = LD->getMemoryVT(); 9033 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9034 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9035 return false; 9036 Ptr = LD->getBasePtr(); 9037 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9038 if (ST->isIndexed()) 9039 return false; 9040 VT = ST->getMemoryVT(); 9041 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9042 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9043 return false; 9044 Ptr = ST->getBasePtr(); 9045 isLoad = false; 9046 } else { 9047 return false; 9048 } 9049 9050 if (Ptr.getNode()->hasOneUse()) 9051 return false; 9052 9053 for (SDNode *Op : Ptr.getNode()->uses()) { 9054 if (Op == N || 9055 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9056 continue; 9057 9058 SDValue BasePtr; 9059 SDValue Offset; 9060 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9061 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9062 // Don't create a indexed load / store with zero offset. 9063 if (isa<ConstantSDNode>(Offset) && 9064 cast<ConstantSDNode>(Offset)->isNullValue()) 9065 continue; 9066 9067 // Try turning it into a post-indexed load / store except when 9068 // 1) All uses are load / store ops that use it as base ptr (and 9069 // it may be folded as addressing mmode). 9070 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9071 // nor a successor of N. Otherwise, if Op is folded that would 9072 // create a cycle. 9073 9074 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9075 continue; 9076 9077 // Check for #1. 9078 bool TryNext = false; 9079 for (SDNode *Use : BasePtr.getNode()->uses()) { 9080 if (Use == Ptr.getNode()) 9081 continue; 9082 9083 // If all the uses are load / store addresses, then don't do the 9084 // transformation. 9085 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9086 bool RealUse = false; 9087 for (SDNode *UseUse : Use->uses()) { 9088 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9089 RealUse = true; 9090 } 9091 9092 if (!RealUse) { 9093 TryNext = true; 9094 break; 9095 } 9096 } 9097 } 9098 9099 if (TryNext) 9100 continue; 9101 9102 // Check for #2 9103 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9104 SDValue Result = isLoad 9105 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9106 BasePtr, Offset, AM) 9107 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9108 BasePtr, Offset, AM); 9109 ++PostIndexedNodes; 9110 ++NodesCombined; 9111 DEBUG(dbgs() << "\nReplacing.5 "; 9112 N->dump(&DAG); 9113 dbgs() << "\nWith: "; 9114 Result.getNode()->dump(&DAG); 9115 dbgs() << '\n'); 9116 WorklistRemover DeadNodes(*this); 9117 if (isLoad) { 9118 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9119 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9120 } else { 9121 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9122 } 9123 9124 // Finally, since the node is now dead, remove it from the graph. 9125 deleteAndRecombine(N); 9126 9127 // Replace the uses of Use with uses of the updated base value. 9128 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9129 Result.getValue(isLoad ? 1 : 0)); 9130 deleteAndRecombine(Op); 9131 return true; 9132 } 9133 } 9134 } 9135 9136 return false; 9137 } 9138 9139 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9140 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9141 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9142 assert(AM != ISD::UNINDEXED); 9143 SDValue BP = LD->getOperand(1); 9144 SDValue Inc = LD->getOperand(2); 9145 9146 // Some backends use TargetConstants for load offsets, but don't expect 9147 // TargetConstants in general ADD nodes. We can convert these constants into 9148 // regular Constants (if the constant is not opaque). 9149 assert((Inc.getOpcode() != ISD::TargetConstant || 9150 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9151 "Cannot split out indexing using opaque target constants"); 9152 if (Inc.getOpcode() == ISD::TargetConstant) { 9153 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9154 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), 9155 ConstInc->getValueType(0)); 9156 } 9157 9158 unsigned Opc = 9159 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9160 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9161 } 9162 9163 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9164 LoadSDNode *LD = cast<LoadSDNode>(N); 9165 SDValue Chain = LD->getChain(); 9166 SDValue Ptr = LD->getBasePtr(); 9167 9168 // If load is not volatile and there are no uses of the loaded value (and 9169 // the updated indexed value in case of indexed loads), change uses of the 9170 // chain value into uses of the chain input (i.e. delete the dead load). 9171 if (!LD->isVolatile()) { 9172 if (N->getValueType(1) == MVT::Other) { 9173 // Unindexed loads. 9174 if (!N->hasAnyUseOfValue(0)) { 9175 // It's not safe to use the two value CombineTo variant here. e.g. 9176 // v1, chain2 = load chain1, loc 9177 // v2, chain3 = load chain2, loc 9178 // v3 = add v2, c 9179 // Now we replace use of chain2 with chain1. This makes the second load 9180 // isomorphic to the one we are deleting, and thus makes this load live. 9181 DEBUG(dbgs() << "\nReplacing.6 "; 9182 N->dump(&DAG); 9183 dbgs() << "\nWith chain: "; 9184 Chain.getNode()->dump(&DAG); 9185 dbgs() << "\n"); 9186 WorklistRemover DeadNodes(*this); 9187 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9188 9189 if (N->use_empty()) 9190 deleteAndRecombine(N); 9191 9192 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9193 } 9194 } else { 9195 // Indexed loads. 9196 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9197 9198 // If this load has an opaque TargetConstant offset, then we cannot split 9199 // the indexing into an add/sub directly (that TargetConstant may not be 9200 // valid for a different type of node, and we cannot convert an opaque 9201 // target constant into a regular constant). 9202 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9203 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9204 9205 if (!N->hasAnyUseOfValue(0) && 9206 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9207 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9208 SDValue Index; 9209 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9210 Index = SplitIndexingFromLoad(LD); 9211 // Try to fold the base pointer arithmetic into subsequent loads and 9212 // stores. 9213 AddUsersToWorklist(N); 9214 } else 9215 Index = DAG.getUNDEF(N->getValueType(1)); 9216 DEBUG(dbgs() << "\nReplacing.7 "; 9217 N->dump(&DAG); 9218 dbgs() << "\nWith: "; 9219 Undef.getNode()->dump(&DAG); 9220 dbgs() << " and 2 other values\n"); 9221 WorklistRemover DeadNodes(*this); 9222 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9223 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9224 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9225 deleteAndRecombine(N); 9226 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9227 } 9228 } 9229 } 9230 9231 // If this load is directly stored, replace the load value with the stored 9232 // value. 9233 // TODO: Handle store large -> read small portion. 9234 // TODO: Handle TRUNCSTORE/LOADEXT 9235 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9236 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9237 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9238 if (PrevST->getBasePtr() == Ptr && 9239 PrevST->getValue().getValueType() == N->getValueType(0)) 9240 return CombineTo(N, Chain.getOperand(1), Chain); 9241 } 9242 } 9243 9244 // Try to infer better alignment information than the load already has. 9245 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9246 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9247 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9248 SDValue NewLoad = 9249 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9250 LD->getValueType(0), 9251 Chain, Ptr, LD->getPointerInfo(), 9252 LD->getMemoryVT(), 9253 LD->isVolatile(), LD->isNonTemporal(), 9254 LD->isInvariant(), Align, LD->getAAInfo()); 9255 if (NewLoad.getNode() != N) 9256 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9257 } 9258 } 9259 } 9260 9261 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 9262 : DAG.getSubtarget().useAA(); 9263 #ifndef NDEBUG 9264 if (CombinerAAOnlyFunc.getNumOccurrences() && 9265 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9266 UseAA = false; 9267 #endif 9268 if (UseAA && LD->isUnindexed()) { 9269 // Walk up chain skipping non-aliasing memory nodes. 9270 SDValue BetterChain = FindBetterChain(N, Chain); 9271 9272 // If there is a better chain. 9273 if (Chain != BetterChain) { 9274 SDValue ReplLoad; 9275 9276 // Replace the chain to void dependency. 9277 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 9278 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 9279 BetterChain, Ptr, LD->getMemOperand()); 9280 } else { 9281 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 9282 LD->getValueType(0), 9283 BetterChain, Ptr, LD->getMemoryVT(), 9284 LD->getMemOperand()); 9285 } 9286 9287 // Create token factor to keep old chain connected. 9288 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9289 MVT::Other, Chain, ReplLoad.getValue(1)); 9290 9291 // Make sure the new and old chains are cleaned up. 9292 AddToWorklist(Token.getNode()); 9293 9294 // Replace uses with load result and token factor. Don't add users 9295 // to work list. 9296 return CombineTo(N, ReplLoad.getValue(0), Token, false); 9297 } 9298 } 9299 9300 // Try transforming N to an indexed load. 9301 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9302 return SDValue(N, 0); 9303 9304 // Try to slice up N to more direct loads if the slices are mapped to 9305 // different register banks or pairing can take place. 9306 if (SliceUpLoad(N)) 9307 return SDValue(N, 0); 9308 9309 return SDValue(); 9310 } 9311 9312 namespace { 9313 /// \brief Helper structure used to slice a load in smaller loads. 9314 /// Basically a slice is obtained from the following sequence: 9315 /// Origin = load Ty1, Base 9316 /// Shift = srl Ty1 Origin, CstTy Amount 9317 /// Inst = trunc Shift to Ty2 9318 /// 9319 /// Then, it will be rewriten into: 9320 /// Slice = load SliceTy, Base + SliceOffset 9321 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 9322 /// 9323 /// SliceTy is deduced from the number of bits that are actually used to 9324 /// build Inst. 9325 struct LoadedSlice { 9326 /// \brief Helper structure used to compute the cost of a slice. 9327 struct Cost { 9328 /// Are we optimizing for code size. 9329 bool ForCodeSize; 9330 /// Various cost. 9331 unsigned Loads; 9332 unsigned Truncates; 9333 unsigned CrossRegisterBanksCopies; 9334 unsigned ZExts; 9335 unsigned Shift; 9336 9337 Cost(bool ForCodeSize = false) 9338 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 9339 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 9340 9341 /// \brief Get the cost of one isolated slice. 9342 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 9343 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 9344 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 9345 EVT TruncType = LS.Inst->getValueType(0); 9346 EVT LoadedType = LS.getLoadedType(); 9347 if (TruncType != LoadedType && 9348 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 9349 ZExts = 1; 9350 } 9351 9352 /// \brief Account for slicing gain in the current cost. 9353 /// Slicing provide a few gains like removing a shift or a 9354 /// truncate. This method allows to grow the cost of the original 9355 /// load with the gain from this slice. 9356 void addSliceGain(const LoadedSlice &LS) { 9357 // Each slice saves a truncate. 9358 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 9359 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 9360 LS.Inst->getOperand(0).getValueType())) 9361 ++Truncates; 9362 // If there is a shift amount, this slice gets rid of it. 9363 if (LS.Shift) 9364 ++Shift; 9365 // If this slice can merge a cross register bank copy, account for it. 9366 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 9367 ++CrossRegisterBanksCopies; 9368 } 9369 9370 Cost &operator+=(const Cost &RHS) { 9371 Loads += RHS.Loads; 9372 Truncates += RHS.Truncates; 9373 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 9374 ZExts += RHS.ZExts; 9375 Shift += RHS.Shift; 9376 return *this; 9377 } 9378 9379 bool operator==(const Cost &RHS) const { 9380 return Loads == RHS.Loads && Truncates == RHS.Truncates && 9381 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 9382 ZExts == RHS.ZExts && Shift == RHS.Shift; 9383 } 9384 9385 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 9386 9387 bool operator<(const Cost &RHS) const { 9388 // Assume cross register banks copies are as expensive as loads. 9389 // FIXME: Do we want some more target hooks? 9390 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 9391 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 9392 // Unless we are optimizing for code size, consider the 9393 // expensive operation first. 9394 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 9395 return ExpensiveOpsLHS < ExpensiveOpsRHS; 9396 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 9397 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 9398 } 9399 9400 bool operator>(const Cost &RHS) const { return RHS < *this; } 9401 9402 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 9403 9404 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 9405 }; 9406 // The last instruction that represent the slice. This should be a 9407 // truncate instruction. 9408 SDNode *Inst; 9409 // The original load instruction. 9410 LoadSDNode *Origin; 9411 // The right shift amount in bits from the original load. 9412 unsigned Shift; 9413 // The DAG from which Origin came from. 9414 // This is used to get some contextual information about legal types, etc. 9415 SelectionDAG *DAG; 9416 9417 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 9418 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 9419 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 9420 9421 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 9422 /// \return Result is \p BitWidth and has used bits set to 1 and 9423 /// not used bits set to 0. 9424 APInt getUsedBits() const { 9425 // Reproduce the trunc(lshr) sequence: 9426 // - Start from the truncated value. 9427 // - Zero extend to the desired bit width. 9428 // - Shift left. 9429 assert(Origin && "No original load to compare against."); 9430 unsigned BitWidth = Origin->getValueSizeInBits(0); 9431 assert(Inst && "This slice is not bound to an instruction"); 9432 assert(Inst->getValueSizeInBits(0) <= BitWidth && 9433 "Extracted slice is bigger than the whole type!"); 9434 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 9435 UsedBits.setAllBits(); 9436 UsedBits = UsedBits.zext(BitWidth); 9437 UsedBits <<= Shift; 9438 return UsedBits; 9439 } 9440 9441 /// \brief Get the size of the slice to be loaded in bytes. 9442 unsigned getLoadedSize() const { 9443 unsigned SliceSize = getUsedBits().countPopulation(); 9444 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 9445 return SliceSize / 8; 9446 } 9447 9448 /// \brief Get the type that will be loaded for this slice. 9449 /// Note: This may not be the final type for the slice. 9450 EVT getLoadedType() const { 9451 assert(DAG && "Missing context"); 9452 LLVMContext &Ctxt = *DAG->getContext(); 9453 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 9454 } 9455 9456 /// \brief Get the alignment of the load used for this slice. 9457 unsigned getAlignment() const { 9458 unsigned Alignment = Origin->getAlignment(); 9459 unsigned Offset = getOffsetFromBase(); 9460 if (Offset != 0) 9461 Alignment = MinAlign(Alignment, Alignment + Offset); 9462 return Alignment; 9463 } 9464 9465 /// \brief Check if this slice can be rewritten with legal operations. 9466 bool isLegal() const { 9467 // An invalid slice is not legal. 9468 if (!Origin || !Inst || !DAG) 9469 return false; 9470 9471 // Offsets are for indexed load only, we do not handle that. 9472 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 9473 return false; 9474 9475 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9476 9477 // Check that the type is legal. 9478 EVT SliceType = getLoadedType(); 9479 if (!TLI.isTypeLegal(SliceType)) 9480 return false; 9481 9482 // Check that the load is legal for this type. 9483 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 9484 return false; 9485 9486 // Check that the offset can be computed. 9487 // 1. Check its type. 9488 EVT PtrType = Origin->getBasePtr().getValueType(); 9489 if (PtrType == MVT::Untyped || PtrType.isExtended()) 9490 return false; 9491 9492 // 2. Check that it fits in the immediate. 9493 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 9494 return false; 9495 9496 // 3. Check that the computation is legal. 9497 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 9498 return false; 9499 9500 // Check that the zext is legal if it needs one. 9501 EVT TruncateType = Inst->getValueType(0); 9502 if (TruncateType != SliceType && 9503 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 9504 return false; 9505 9506 return true; 9507 } 9508 9509 /// \brief Get the offset in bytes of this slice in the original chunk of 9510 /// bits. 9511 /// \pre DAG != nullptr. 9512 uint64_t getOffsetFromBase() const { 9513 assert(DAG && "Missing context."); 9514 bool IsBigEndian = 9515 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 9516 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 9517 uint64_t Offset = Shift / 8; 9518 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 9519 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 9520 "The size of the original loaded type is not a multiple of a" 9521 " byte."); 9522 // If Offset is bigger than TySizeInBytes, it means we are loading all 9523 // zeros. This should have been optimized before in the process. 9524 assert(TySizeInBytes > Offset && 9525 "Invalid shift amount for given loaded size"); 9526 if (IsBigEndian) 9527 Offset = TySizeInBytes - Offset - getLoadedSize(); 9528 return Offset; 9529 } 9530 9531 /// \brief Generate the sequence of instructions to load the slice 9532 /// represented by this object and redirect the uses of this slice to 9533 /// this new sequence of instructions. 9534 /// \pre this->Inst && this->Origin are valid Instructions and this 9535 /// object passed the legal check: LoadedSlice::isLegal returned true. 9536 /// \return The last instruction of the sequence used to load the slice. 9537 SDValue loadSlice() const { 9538 assert(Inst && Origin && "Unable to replace a non-existing slice."); 9539 const SDValue &OldBaseAddr = Origin->getBasePtr(); 9540 SDValue BaseAddr = OldBaseAddr; 9541 // Get the offset in that chunk of bytes w.r.t. the endianess. 9542 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 9543 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 9544 if (Offset) { 9545 // BaseAddr = BaseAddr + Offset. 9546 EVT ArithType = BaseAddr.getValueType(); 9547 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr, 9548 DAG->getConstant(Offset, ArithType)); 9549 } 9550 9551 // Create the type of the loaded slice according to its size. 9552 EVT SliceType = getLoadedType(); 9553 9554 // Create the load for the slice. 9555 SDValue LastInst = DAG->getLoad( 9556 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 9557 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 9558 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 9559 // If the final type is not the same as the loaded type, this means that 9560 // we have to pad with zero. Create a zero extend for that. 9561 EVT FinalType = Inst->getValueType(0); 9562 if (SliceType != FinalType) 9563 LastInst = 9564 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 9565 return LastInst; 9566 } 9567 9568 /// \brief Check if this slice can be merged with an expensive cross register 9569 /// bank copy. E.g., 9570 /// i = load i32 9571 /// f = bitcast i32 i to float 9572 bool canMergeExpensiveCrossRegisterBankCopy() const { 9573 if (!Inst || !Inst->hasOneUse()) 9574 return false; 9575 SDNode *Use = *Inst->use_begin(); 9576 if (Use->getOpcode() != ISD::BITCAST) 9577 return false; 9578 assert(DAG && "Missing context"); 9579 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9580 EVT ResVT = Use->getValueType(0); 9581 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 9582 const TargetRegisterClass *ArgRC = 9583 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 9584 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 9585 return false; 9586 9587 // At this point, we know that we perform a cross-register-bank copy. 9588 // Check if it is expensive. 9589 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 9590 // Assume bitcasts are cheap, unless both register classes do not 9591 // explicitly share a common sub class. 9592 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 9593 return false; 9594 9595 // Check if it will be merged with the load. 9596 // 1. Check the alignment constraint. 9597 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 9598 ResVT.getTypeForEVT(*DAG->getContext())); 9599 9600 if (RequiredAlignment > getAlignment()) 9601 return false; 9602 9603 // 2. Check that the load is a legal operation for that type. 9604 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 9605 return false; 9606 9607 // 3. Check that we do not have a zext in the way. 9608 if (Inst->getValueType(0) != getLoadedType()) 9609 return false; 9610 9611 return true; 9612 } 9613 }; 9614 } 9615 9616 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 9617 /// \p UsedBits looks like 0..0 1..1 0..0. 9618 static bool areUsedBitsDense(const APInt &UsedBits) { 9619 // If all the bits are one, this is dense! 9620 if (UsedBits.isAllOnesValue()) 9621 return true; 9622 9623 // Get rid of the unused bits on the right. 9624 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 9625 // Get rid of the unused bits on the left. 9626 if (NarrowedUsedBits.countLeadingZeros()) 9627 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 9628 // Check that the chunk of bits is completely used. 9629 return NarrowedUsedBits.isAllOnesValue(); 9630 } 9631 9632 /// \brief Check whether or not \p First and \p Second are next to each other 9633 /// in memory. This means that there is no hole between the bits loaded 9634 /// by \p First and the bits loaded by \p Second. 9635 static bool areSlicesNextToEachOther(const LoadedSlice &First, 9636 const LoadedSlice &Second) { 9637 assert(First.Origin == Second.Origin && First.Origin && 9638 "Unable to match different memory origins."); 9639 APInt UsedBits = First.getUsedBits(); 9640 assert((UsedBits & Second.getUsedBits()) == 0 && 9641 "Slices are not supposed to overlap."); 9642 UsedBits |= Second.getUsedBits(); 9643 return areUsedBitsDense(UsedBits); 9644 } 9645 9646 /// \brief Adjust the \p GlobalLSCost according to the target 9647 /// paring capabilities and the layout of the slices. 9648 /// \pre \p GlobalLSCost should account for at least as many loads as 9649 /// there is in the slices in \p LoadedSlices. 9650 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9651 LoadedSlice::Cost &GlobalLSCost) { 9652 unsigned NumberOfSlices = LoadedSlices.size(); 9653 // If there is less than 2 elements, no pairing is possible. 9654 if (NumberOfSlices < 2) 9655 return; 9656 9657 // Sort the slices so that elements that are likely to be next to each 9658 // other in memory are next to each other in the list. 9659 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 9660 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 9661 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 9662 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 9663 }); 9664 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 9665 // First (resp. Second) is the first (resp. Second) potentially candidate 9666 // to be placed in a paired load. 9667 const LoadedSlice *First = nullptr; 9668 const LoadedSlice *Second = nullptr; 9669 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 9670 // Set the beginning of the pair. 9671 First = Second) { 9672 9673 Second = &LoadedSlices[CurrSlice]; 9674 9675 // If First is NULL, it means we start a new pair. 9676 // Get to the next slice. 9677 if (!First) 9678 continue; 9679 9680 EVT LoadedType = First->getLoadedType(); 9681 9682 // If the types of the slices are different, we cannot pair them. 9683 if (LoadedType != Second->getLoadedType()) 9684 continue; 9685 9686 // Check if the target supplies paired loads for this type. 9687 unsigned RequiredAlignment = 0; 9688 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 9689 // move to the next pair, this type is hopeless. 9690 Second = nullptr; 9691 continue; 9692 } 9693 // Check if we meet the alignment requirement. 9694 if (RequiredAlignment > First->getAlignment()) 9695 continue; 9696 9697 // Check that both loads are next to each other in memory. 9698 if (!areSlicesNextToEachOther(*First, *Second)) 9699 continue; 9700 9701 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 9702 --GlobalLSCost.Loads; 9703 // Move to the next pair. 9704 Second = nullptr; 9705 } 9706 } 9707 9708 /// \brief Check the profitability of all involved LoadedSlice. 9709 /// Currently, it is considered profitable if there is exactly two 9710 /// involved slices (1) which are (2) next to each other in memory, and 9711 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 9712 /// 9713 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 9714 /// the elements themselves. 9715 /// 9716 /// FIXME: When the cost model will be mature enough, we can relax 9717 /// constraints (1) and (2). 9718 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9719 const APInt &UsedBits, bool ForCodeSize) { 9720 unsigned NumberOfSlices = LoadedSlices.size(); 9721 if (StressLoadSlicing) 9722 return NumberOfSlices > 1; 9723 9724 // Check (1). 9725 if (NumberOfSlices != 2) 9726 return false; 9727 9728 // Check (2). 9729 if (!areUsedBitsDense(UsedBits)) 9730 return false; 9731 9732 // Check (3). 9733 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 9734 // The original code has one big load. 9735 OrigCost.Loads = 1; 9736 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 9737 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 9738 // Accumulate the cost of all the slices. 9739 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 9740 GlobalSlicingCost += SliceCost; 9741 9742 // Account as cost in the original configuration the gain obtained 9743 // with the current slices. 9744 OrigCost.addSliceGain(LS); 9745 } 9746 9747 // If the target supports paired load, adjust the cost accordingly. 9748 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 9749 return OrigCost > GlobalSlicingCost; 9750 } 9751 9752 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 9753 /// operations, split it in the various pieces being extracted. 9754 /// 9755 /// This sort of thing is introduced by SROA. 9756 /// This slicing takes care not to insert overlapping loads. 9757 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 9758 bool DAGCombiner::SliceUpLoad(SDNode *N) { 9759 if (Level < AfterLegalizeDAG) 9760 return false; 9761 9762 LoadSDNode *LD = cast<LoadSDNode>(N); 9763 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 9764 !LD->getValueType(0).isInteger()) 9765 return false; 9766 9767 // Keep track of already used bits to detect overlapping values. 9768 // In that case, we will just abort the transformation. 9769 APInt UsedBits(LD->getValueSizeInBits(0), 0); 9770 9771 SmallVector<LoadedSlice, 4> LoadedSlices; 9772 9773 // Check if this load is used as several smaller chunks of bits. 9774 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 9775 // of computation for each trunc. 9776 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 9777 UI != UIEnd; ++UI) { 9778 // Skip the uses of the chain. 9779 if (UI.getUse().getResNo() != 0) 9780 continue; 9781 9782 SDNode *User = *UI; 9783 unsigned Shift = 0; 9784 9785 // Check if this is a trunc(lshr). 9786 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 9787 isa<ConstantSDNode>(User->getOperand(1))) { 9788 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 9789 User = *User->use_begin(); 9790 } 9791 9792 // At this point, User is a Truncate, iff we encountered, trunc or 9793 // trunc(lshr). 9794 if (User->getOpcode() != ISD::TRUNCATE) 9795 return false; 9796 9797 // The width of the type must be a power of 2 and greater than 8-bits. 9798 // Otherwise the load cannot be represented in LLVM IR. 9799 // Moreover, if we shifted with a non-8-bits multiple, the slice 9800 // will be across several bytes. We do not support that. 9801 unsigned Width = User->getValueSizeInBits(0); 9802 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 9803 return 0; 9804 9805 // Build the slice for this chain of computations. 9806 LoadedSlice LS(User, LD, Shift, &DAG); 9807 APInt CurrentUsedBits = LS.getUsedBits(); 9808 9809 // Check if this slice overlaps with another. 9810 if ((CurrentUsedBits & UsedBits) != 0) 9811 return false; 9812 // Update the bits used globally. 9813 UsedBits |= CurrentUsedBits; 9814 9815 // Check if the new slice would be legal. 9816 if (!LS.isLegal()) 9817 return false; 9818 9819 // Record the slice. 9820 LoadedSlices.push_back(LS); 9821 } 9822 9823 // Abort slicing if it does not seem to be profitable. 9824 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 9825 return false; 9826 9827 ++SlicedLoads; 9828 9829 // Rewrite each chain to use an independent load. 9830 // By construction, each chain can be represented by a unique load. 9831 9832 // Prepare the argument for the new token factor for all the slices. 9833 SmallVector<SDValue, 8> ArgChains; 9834 for (SmallVectorImpl<LoadedSlice>::const_iterator 9835 LSIt = LoadedSlices.begin(), 9836 LSItEnd = LoadedSlices.end(); 9837 LSIt != LSItEnd; ++LSIt) { 9838 SDValue SliceInst = LSIt->loadSlice(); 9839 CombineTo(LSIt->Inst, SliceInst, true); 9840 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 9841 SliceInst = SliceInst.getOperand(0); 9842 assert(SliceInst->getOpcode() == ISD::LOAD && 9843 "It takes more than a zext to get to the loaded slice!!"); 9844 ArgChains.push_back(SliceInst.getValue(1)); 9845 } 9846 9847 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 9848 ArgChains); 9849 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9850 return true; 9851 } 9852 9853 /// Check to see if V is (and load (ptr), imm), where the load is having 9854 /// specific bytes cleared out. If so, return the byte size being masked out 9855 /// and the shift amount. 9856 static std::pair<unsigned, unsigned> 9857 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 9858 std::pair<unsigned, unsigned> Result(0, 0); 9859 9860 // Check for the structure we're looking for. 9861 if (V->getOpcode() != ISD::AND || 9862 !isa<ConstantSDNode>(V->getOperand(1)) || 9863 !ISD::isNormalLoad(V->getOperand(0).getNode())) 9864 return Result; 9865 9866 // Check the chain and pointer. 9867 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 9868 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 9869 9870 // The store should be chained directly to the load or be an operand of a 9871 // tokenfactor. 9872 if (LD == Chain.getNode()) 9873 ; // ok. 9874 else if (Chain->getOpcode() != ISD::TokenFactor) 9875 return Result; // Fail. 9876 else { 9877 bool isOk = false; 9878 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 9879 if (Chain->getOperand(i).getNode() == LD) { 9880 isOk = true; 9881 break; 9882 } 9883 if (!isOk) return Result; 9884 } 9885 9886 // This only handles simple types. 9887 if (V.getValueType() != MVT::i16 && 9888 V.getValueType() != MVT::i32 && 9889 V.getValueType() != MVT::i64) 9890 return Result; 9891 9892 // Check the constant mask. Invert it so that the bits being masked out are 9893 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 9894 // follow the sign bit for uniformity. 9895 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 9896 unsigned NotMaskLZ = countLeadingZeros(NotMask); 9897 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 9898 unsigned NotMaskTZ = countTrailingZeros(NotMask); 9899 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 9900 if (NotMaskLZ == 64) return Result; // All zero mask. 9901 9902 // See if we have a continuous run of bits. If so, we have 0*1+0* 9903 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 9904 return Result; 9905 9906 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 9907 if (V.getValueType() != MVT::i64 && NotMaskLZ) 9908 NotMaskLZ -= 64-V.getValueSizeInBits(); 9909 9910 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 9911 switch (MaskedBytes) { 9912 case 1: 9913 case 2: 9914 case 4: break; 9915 default: return Result; // All one mask, or 5-byte mask. 9916 } 9917 9918 // Verify that the first bit starts at a multiple of mask so that the access 9919 // is aligned the same as the access width. 9920 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 9921 9922 Result.first = MaskedBytes; 9923 Result.second = NotMaskTZ/8; 9924 return Result; 9925 } 9926 9927 9928 /// Check to see if IVal is something that provides a value as specified by 9929 /// MaskInfo. If so, replace the specified store with a narrower store of 9930 /// truncated IVal. 9931 static SDNode * 9932 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 9933 SDValue IVal, StoreSDNode *St, 9934 DAGCombiner *DC) { 9935 unsigned NumBytes = MaskInfo.first; 9936 unsigned ByteShift = MaskInfo.second; 9937 SelectionDAG &DAG = DC->getDAG(); 9938 9939 // Check to see if IVal is all zeros in the part being masked in by the 'or' 9940 // that uses this. If not, this is not a replacement. 9941 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 9942 ByteShift*8, (ByteShift+NumBytes)*8); 9943 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 9944 9945 // Check that it is legal on the target to do this. It is legal if the new 9946 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 9947 // legalization. 9948 MVT VT = MVT::getIntegerVT(NumBytes*8); 9949 if (!DC->isTypeLegal(VT)) 9950 return nullptr; 9951 9952 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 9953 // shifted by ByteShift and truncated down to NumBytes. 9954 if (ByteShift) 9955 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 9956 DAG.getConstant(ByteShift*8, 9957 DC->getShiftAmountTy(IVal.getValueType()))); 9958 9959 // Figure out the offset for the store and the alignment of the access. 9960 unsigned StOffset; 9961 unsigned NewAlign = St->getAlignment(); 9962 9963 if (DAG.getTargetLoweringInfo().isLittleEndian()) 9964 StOffset = ByteShift; 9965 else 9966 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 9967 9968 SDValue Ptr = St->getBasePtr(); 9969 if (StOffset) { 9970 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 9971 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 9972 NewAlign = MinAlign(NewAlign, StOffset); 9973 } 9974 9975 // Truncate down to the new size. 9976 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 9977 9978 ++OpsNarrowed; 9979 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 9980 St->getPointerInfo().getWithOffset(StOffset), 9981 false, false, NewAlign).getNode(); 9982 } 9983 9984 9985 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 9986 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 9987 /// narrowing the load and store if it would end up being a win for performance 9988 /// or code size. 9989 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 9990 StoreSDNode *ST = cast<StoreSDNode>(N); 9991 if (ST->isVolatile()) 9992 return SDValue(); 9993 9994 SDValue Chain = ST->getChain(); 9995 SDValue Value = ST->getValue(); 9996 SDValue Ptr = ST->getBasePtr(); 9997 EVT VT = Value.getValueType(); 9998 9999 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10000 return SDValue(); 10001 10002 unsigned Opc = Value.getOpcode(); 10003 10004 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10005 // is a byte mask indicating a consecutive number of bytes, check to see if 10006 // Y is known to provide just those bytes. If so, we try to replace the 10007 // load + replace + store sequence with a single (narrower) store, which makes 10008 // the load dead. 10009 if (Opc == ISD::OR) { 10010 std::pair<unsigned, unsigned> MaskedLoad; 10011 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10012 if (MaskedLoad.first) 10013 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10014 Value.getOperand(1), ST,this)) 10015 return SDValue(NewST, 0); 10016 10017 // Or is commutative, so try swapping X and Y. 10018 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10019 if (MaskedLoad.first) 10020 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10021 Value.getOperand(0), ST,this)) 10022 return SDValue(NewST, 0); 10023 } 10024 10025 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10026 Value.getOperand(1).getOpcode() != ISD::Constant) 10027 return SDValue(); 10028 10029 SDValue N0 = Value.getOperand(0); 10030 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10031 Chain == SDValue(N0.getNode(), 1)) { 10032 LoadSDNode *LD = cast<LoadSDNode>(N0); 10033 if (LD->getBasePtr() != Ptr || 10034 LD->getPointerInfo().getAddrSpace() != 10035 ST->getPointerInfo().getAddrSpace()) 10036 return SDValue(); 10037 10038 // Find the type to narrow it the load / op / store to. 10039 SDValue N1 = Value.getOperand(1); 10040 unsigned BitWidth = N1.getValueSizeInBits(); 10041 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10042 if (Opc == ISD::AND) 10043 Imm ^= APInt::getAllOnesValue(BitWidth); 10044 if (Imm == 0 || Imm.isAllOnesValue()) 10045 return SDValue(); 10046 unsigned ShAmt = Imm.countTrailingZeros(); 10047 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10048 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10049 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10050 // The narrowing should be profitable, the load/store operation should be 10051 // legal (or custom) and the store size should be equal to the NewVT width. 10052 while (NewBW < BitWidth && 10053 (NewVT.getStoreSizeInBits() != NewBW || 10054 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10055 !TLI.isNarrowingProfitable(VT, NewVT))) { 10056 NewBW = NextPowerOf2(NewBW); 10057 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10058 } 10059 if (NewBW >= BitWidth) 10060 return SDValue(); 10061 10062 // If the lsb changed does not start at the type bitwidth boundary, 10063 // start at the previous one. 10064 if (ShAmt % NewBW) 10065 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10066 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10067 std::min(BitWidth, ShAmt + NewBW)); 10068 if ((Imm & Mask) == Imm) { 10069 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10070 if (Opc == ISD::AND) 10071 NewImm ^= APInt::getAllOnesValue(NewBW); 10072 uint64_t PtrOff = ShAmt / 8; 10073 // For big endian targets, we need to adjust the offset to the pointer to 10074 // load the correct bytes. 10075 if (TLI.isBigEndian()) 10076 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10077 10078 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10079 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10080 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 10081 return SDValue(); 10082 10083 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10084 Ptr.getValueType(), Ptr, 10085 DAG.getConstant(PtrOff, Ptr.getValueType())); 10086 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10087 LD->getChain(), NewPtr, 10088 LD->getPointerInfo().getWithOffset(PtrOff), 10089 LD->isVolatile(), LD->isNonTemporal(), 10090 LD->isInvariant(), NewAlign, 10091 LD->getAAInfo()); 10092 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10093 DAG.getConstant(NewImm, NewVT)); 10094 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10095 NewVal, NewPtr, 10096 ST->getPointerInfo().getWithOffset(PtrOff), 10097 false, false, NewAlign); 10098 10099 AddToWorklist(NewPtr.getNode()); 10100 AddToWorklist(NewLD.getNode()); 10101 AddToWorklist(NewVal.getNode()); 10102 WorklistRemover DeadNodes(*this); 10103 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10104 ++OpsNarrowed; 10105 return NewST; 10106 } 10107 } 10108 10109 return SDValue(); 10110 } 10111 10112 /// For a given floating point load / store pair, if the load value isn't used 10113 /// by any other operations, then consider transforming the pair to integer 10114 /// load / store operations if the target deems the transformation profitable. 10115 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10116 StoreSDNode *ST = cast<StoreSDNode>(N); 10117 SDValue Chain = ST->getChain(); 10118 SDValue Value = ST->getValue(); 10119 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10120 Value.hasOneUse() && 10121 Chain == SDValue(Value.getNode(), 1)) { 10122 LoadSDNode *LD = cast<LoadSDNode>(Value); 10123 EVT VT = LD->getMemoryVT(); 10124 if (!VT.isFloatingPoint() || 10125 VT != ST->getMemoryVT() || 10126 LD->isNonTemporal() || 10127 ST->isNonTemporal() || 10128 LD->getPointerInfo().getAddrSpace() != 0 || 10129 ST->getPointerInfo().getAddrSpace() != 0) 10130 return SDValue(); 10131 10132 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10133 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10134 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10135 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10136 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10137 return SDValue(); 10138 10139 unsigned LDAlign = LD->getAlignment(); 10140 unsigned STAlign = ST->getAlignment(); 10141 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10142 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 10143 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10144 return SDValue(); 10145 10146 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10147 LD->getChain(), LD->getBasePtr(), 10148 LD->getPointerInfo(), 10149 false, false, false, LDAlign); 10150 10151 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10152 NewLD, ST->getBasePtr(), 10153 ST->getPointerInfo(), 10154 false, false, STAlign); 10155 10156 AddToWorklist(NewLD.getNode()); 10157 AddToWorklist(NewST.getNode()); 10158 WorklistRemover DeadNodes(*this); 10159 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10160 ++LdStFP2Int; 10161 return NewST; 10162 } 10163 10164 return SDValue(); 10165 } 10166 10167 namespace { 10168 /// Helper struct to parse and store a memory address as base + index + offset. 10169 /// We ignore sign extensions when it is safe to do so. 10170 /// The following two expressions are not equivalent. To differentiate we need 10171 /// to store whether there was a sign extension involved in the index 10172 /// computation. 10173 /// (load (i64 add (i64 copyfromreg %c) 10174 /// (i64 signextend (add (i8 load %index) 10175 /// (i8 1)))) 10176 /// vs 10177 /// 10178 /// (load (i64 add (i64 copyfromreg %c) 10179 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10180 /// (i32 1))))) 10181 struct BaseIndexOffset { 10182 SDValue Base; 10183 SDValue Index; 10184 int64_t Offset; 10185 bool IsIndexSignExt; 10186 10187 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10188 10189 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10190 bool IsIndexSignExt) : 10191 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10192 10193 bool equalBaseIndex(const BaseIndexOffset &Other) { 10194 return Other.Base == Base && Other.Index == Index && 10195 Other.IsIndexSignExt == IsIndexSignExt; 10196 } 10197 10198 /// Parses tree in Ptr for base, index, offset addresses. 10199 static BaseIndexOffset match(SDValue Ptr) { 10200 bool IsIndexSignExt = false; 10201 10202 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10203 // instruction, then it could be just the BASE or everything else we don't 10204 // know how to handle. Just use Ptr as BASE and give up. 10205 if (Ptr->getOpcode() != ISD::ADD) 10206 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10207 10208 // We know that we have at least an ADD instruction. Try to pattern match 10209 // the simple case of BASE + OFFSET. 10210 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10211 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10212 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10213 IsIndexSignExt); 10214 } 10215 10216 // Inside a loop the current BASE pointer is calculated using an ADD and a 10217 // MUL instruction. In this case Ptr is the actual BASE pointer. 10218 // (i64 add (i64 %array_ptr) 10219 // (i64 mul (i64 %induction_var) 10220 // (i64 %element_size))) 10221 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10222 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10223 10224 // Look at Base + Index + Offset cases. 10225 SDValue Base = Ptr->getOperand(0); 10226 SDValue IndexOffset = Ptr->getOperand(1); 10227 10228 // Skip signextends. 10229 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10230 IndexOffset = IndexOffset->getOperand(0); 10231 IsIndexSignExt = true; 10232 } 10233 10234 // Either the case of Base + Index (no offset) or something else. 10235 if (IndexOffset->getOpcode() != ISD::ADD) 10236 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10237 10238 // Now we have the case of Base + Index + offset. 10239 SDValue Index = IndexOffset->getOperand(0); 10240 SDValue Offset = IndexOffset->getOperand(1); 10241 10242 if (!isa<ConstantSDNode>(Offset)) 10243 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10244 10245 // Ignore signextends. 10246 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 10247 Index = Index->getOperand(0); 10248 IsIndexSignExt = true; 10249 } else IsIndexSignExt = false; 10250 10251 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 10252 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 10253 } 10254 }; 10255 } // namespace 10256 10257 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 10258 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 10259 unsigned NumElem, bool IsConstantSrc, bool UseVector) { 10260 // Make sure we have something to merge. 10261 if (NumElem < 2) 10262 return false; 10263 10264 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 10265 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10266 unsigned LatestNodeUsed = 0; 10267 10268 for (unsigned i=0; i < NumElem; ++i) { 10269 // Find a chain for the new wide-store operand. Notice that some 10270 // of the store nodes that we found may not be selected for inclusion 10271 // in the wide store. The chain we use needs to be the chain of the 10272 // latest store node which is *used* and replaced by the wide store. 10273 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 10274 LatestNodeUsed = i; 10275 } 10276 10277 // The latest Node in the DAG. 10278 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 10279 SDLoc DL(StoreNodes[0].MemNode); 10280 10281 SDValue StoredVal; 10282 if (UseVector) { 10283 // Find a legal type for the vector store. 10284 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 10285 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 10286 if (IsConstantSrc) { 10287 // A vector store with a constant source implies that the constant is 10288 // zero; we only handle merging stores of constant zeros because the zero 10289 // can be materialized without a load. 10290 // It may be beneficial to loosen this restriction to allow non-zero 10291 // store merging. 10292 StoredVal = DAG.getConstant(0, Ty); 10293 } else { 10294 SmallVector<SDValue, 8> Ops; 10295 for (unsigned i = 0; i < NumElem ; ++i) { 10296 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10297 SDValue Val = St->getValue(); 10298 // All of the operands of a BUILD_VECTOR must have the same type. 10299 if (Val.getValueType() != MemVT) 10300 return false; 10301 Ops.push_back(Val); 10302 } 10303 10304 // Build the extracted vector elements back into a vector. 10305 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops); 10306 } 10307 } else { 10308 // We should always use a vector store when merging extracted vector 10309 // elements, so this path implies a store of constants. 10310 assert(IsConstantSrc && "Merged vector elements should use vector store"); 10311 10312 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 10313 APInt StoreInt(StoreBW, 0); 10314 10315 // Construct a single integer constant which is made of the smaller 10316 // constant inputs. 10317 bool IsLE = TLI.isLittleEndian(); 10318 for (unsigned i = 0; i < NumElem ; ++i) { 10319 unsigned Idx = IsLE ? (NumElem - 1 - i) : i; 10320 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 10321 SDValue Val = St->getValue(); 10322 StoreInt <<= ElementSizeBytes*8; 10323 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 10324 StoreInt |= C->getAPIntValue().zext(StoreBW); 10325 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 10326 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 10327 } else { 10328 llvm_unreachable("Invalid constant element type"); 10329 } 10330 } 10331 10332 // Create the new Load and Store operations. 10333 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10334 StoredVal = DAG.getConstant(StoreInt, StoreTy); 10335 } 10336 10337 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal, 10338 FirstInChain->getBasePtr(), 10339 FirstInChain->getPointerInfo(), 10340 false, false, 10341 FirstInChain->getAlignment()); 10342 10343 // Replace the last store with the new store 10344 CombineTo(LatestOp, NewStore); 10345 // Erase all other stores. 10346 for (unsigned i = 0; i < NumElem ; ++i) { 10347 if (StoreNodes[i].MemNode == LatestOp) 10348 continue; 10349 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10350 // ReplaceAllUsesWith will replace all uses that existed when it was 10351 // called, but graph optimizations may cause new ones to appear. For 10352 // example, the case in pr14333 looks like 10353 // 10354 // St's chain -> St -> another store -> X 10355 // 10356 // And the only difference from St to the other store is the chain. 10357 // When we change it's chain to be St's chain they become identical, 10358 // get CSEed and the net result is that X is now a use of St. 10359 // Since we know that St is redundant, just iterate. 10360 while (!St->use_empty()) 10361 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 10362 deleteAndRecombine(St); 10363 } 10364 10365 return true; 10366 } 10367 10368 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 10369 if (OptLevel == CodeGenOpt::None) 10370 return false; 10371 10372 EVT MemVT = St->getMemoryVT(); 10373 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 10374 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 10375 Attribute::NoImplicitFloat); 10376 10377 // Don't merge vectors into wider inputs. 10378 if (MemVT.isVector() || !MemVT.isSimple()) 10379 return false; 10380 10381 // Perform an early exit check. Do not bother looking at stored values that 10382 // are not constants, loads, or extracted vector elements. 10383 SDValue StoredVal = St->getValue(); 10384 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 10385 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 10386 isa<ConstantFPSDNode>(StoredVal); 10387 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT); 10388 10389 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc) 10390 return false; 10391 10392 // Only look at ends of store sequences. 10393 SDValue Chain = SDValue(St, 0); 10394 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 10395 return false; 10396 10397 // This holds the base pointer, index, and the offset in bytes from the base 10398 // pointer. 10399 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 10400 10401 // We must have a base and an offset. 10402 if (!BasePtr.Base.getNode()) 10403 return false; 10404 10405 // Do not handle stores to undef base pointers. 10406 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 10407 return false; 10408 10409 // Save the LoadSDNodes that we find in the chain. 10410 // We need to make sure that these nodes do not interfere with 10411 // any of the store nodes. 10412 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 10413 10414 // Save the StoreSDNodes that we find in the chain. 10415 SmallVector<MemOpLink, 8> StoreNodes; 10416 10417 // Walk up the chain and look for nodes with offsets from the same 10418 // base pointer. Stop when reaching an instruction with a different kind 10419 // or instruction which has a different base pointer. 10420 unsigned Seq = 0; 10421 StoreSDNode *Index = St; 10422 while (Index) { 10423 // If the chain has more than one use, then we can't reorder the mem ops. 10424 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 10425 break; 10426 10427 // Find the base pointer and offset for this memory node. 10428 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 10429 10430 // Check that the base pointer is the same as the original one. 10431 if (!Ptr.equalBaseIndex(BasePtr)) 10432 break; 10433 10434 // Check that the alignment is the same. 10435 if (Index->getAlignment() != St->getAlignment()) 10436 break; 10437 10438 // The memory operands must not be volatile. 10439 if (Index->isVolatile() || Index->isIndexed()) 10440 break; 10441 10442 // No truncation. 10443 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 10444 if (St->isTruncatingStore()) 10445 break; 10446 10447 // The stored memory type must be the same. 10448 if (Index->getMemoryVT() != MemVT) 10449 break; 10450 10451 // We do not allow unaligned stores because we want to prevent overriding 10452 // stores. 10453 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 10454 break; 10455 10456 // We found a potential memory operand to merge. 10457 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 10458 10459 // Find the next memory operand in the chain. If the next operand in the 10460 // chain is a store then move up and continue the scan with the next 10461 // memory operand. If the next operand is a load save it and use alias 10462 // information to check if it interferes with anything. 10463 SDNode *NextInChain = Index->getChain().getNode(); 10464 while (1) { 10465 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 10466 // We found a store node. Use it for the next iteration. 10467 Index = STn; 10468 break; 10469 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 10470 if (Ldn->isVolatile()) { 10471 Index = nullptr; 10472 break; 10473 } 10474 10475 // Save the load node for later. Continue the scan. 10476 AliasLoadNodes.push_back(Ldn); 10477 NextInChain = Ldn->getChain().getNode(); 10478 continue; 10479 } else { 10480 Index = nullptr; 10481 break; 10482 } 10483 } 10484 } 10485 10486 // Check if there is anything to merge. 10487 if (StoreNodes.size() < 2) 10488 return false; 10489 10490 // Sort the memory operands according to their distance from the base pointer. 10491 std::sort(StoreNodes.begin(), StoreNodes.end(), 10492 [](MemOpLink LHS, MemOpLink RHS) { 10493 return LHS.OffsetFromBase < RHS.OffsetFromBase || 10494 (LHS.OffsetFromBase == RHS.OffsetFromBase && 10495 LHS.SequenceNum > RHS.SequenceNum); 10496 }); 10497 10498 // Scan the memory operations on the chain and find the first non-consecutive 10499 // store memory address. 10500 unsigned LastConsecutiveStore = 0; 10501 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 10502 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 10503 10504 // Check that the addresses are consecutive starting from the second 10505 // element in the list of stores. 10506 if (i > 0) { 10507 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 10508 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10509 break; 10510 } 10511 10512 bool Alias = false; 10513 // Check if this store interferes with any of the loads that we found. 10514 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 10515 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 10516 Alias = true; 10517 break; 10518 } 10519 // We found a load that alias with this store. Stop the sequence. 10520 if (Alias) 10521 break; 10522 10523 // Mark this node as useful. 10524 LastConsecutiveStore = i; 10525 } 10526 10527 // The node with the lowest store address. 10528 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10529 10530 // Store the constants into memory as one consecutive store. 10531 if (IsConstantSrc) { 10532 unsigned LastLegalType = 0; 10533 unsigned LastLegalVectorType = 0; 10534 bool NonZero = false; 10535 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10536 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10537 SDValue StoredVal = St->getValue(); 10538 10539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 10540 NonZero |= !C->isNullValue(); 10541 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 10542 NonZero |= !C->getConstantFPValue()->isNullValue(); 10543 } else { 10544 // Non-constant. 10545 break; 10546 } 10547 10548 // Find a legal type for the constant store. 10549 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10550 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10551 if (TLI.isTypeLegal(StoreTy)) 10552 LastLegalType = i+1; 10553 // Or check whether a truncstore is legal. 10554 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10555 TargetLowering::TypePromoteInteger) { 10556 EVT LegalizedStoredValueTy = 10557 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 10558 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 10559 LastLegalType = i+1; 10560 } 10561 10562 // Find a legal type for the vector store. 10563 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10564 if (TLI.isTypeLegal(Ty)) 10565 LastLegalVectorType = i + 1; 10566 } 10567 10568 // We only use vectors if the constant is known to be zero and the 10569 // function is not marked with the noimplicitfloat attribute. 10570 if (NonZero || NoVectors) 10571 LastLegalVectorType = 0; 10572 10573 // Check if we found a legal integer type to store. 10574 if (LastLegalType == 0 && LastLegalVectorType == 0) 10575 return false; 10576 10577 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 10578 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 10579 10580 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10581 true, UseVector); 10582 } 10583 10584 // When extracting multiple vector elements, try to store them 10585 // in one vector store rather than a sequence of scalar stores. 10586 if (IsExtractVecEltSrc) { 10587 unsigned NumElem = 0; 10588 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 10589 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10590 SDValue StoredVal = St->getValue(); 10591 // This restriction could be loosened. 10592 // Bail out if any stored values are not elements extracted from a vector. 10593 // It should be possible to handle mixed sources, but load sources need 10594 // more careful handling (see the block of code below that handles 10595 // consecutive loads). 10596 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10597 return false; 10598 10599 // Find a legal type for the vector store. 10600 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10601 if (TLI.isTypeLegal(Ty)) 10602 NumElem = i + 1; 10603 } 10604 10605 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10606 false, true); 10607 } 10608 10609 // Below we handle the case of multiple consecutive stores that 10610 // come from multiple consecutive loads. We merge them into a single 10611 // wide load and a single wide store. 10612 10613 // Look for load nodes which are used by the stored values. 10614 SmallVector<MemOpLink, 8> LoadNodes; 10615 10616 // Find acceptable loads. Loads need to have the same chain (token factor), 10617 // must not be zext, volatile, indexed, and they must be consecutive. 10618 BaseIndexOffset LdBasePtr; 10619 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10620 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10621 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 10622 if (!Ld) break; 10623 10624 // Loads must only have one use. 10625 if (!Ld->hasNUsesOfValue(1, 0)) 10626 break; 10627 10628 // Check that the alignment is the same as the stores. 10629 if (Ld->getAlignment() != St->getAlignment()) 10630 break; 10631 10632 // The memory operands must not be volatile. 10633 if (Ld->isVolatile() || Ld->isIndexed()) 10634 break; 10635 10636 // We do not accept ext loads. 10637 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 10638 break; 10639 10640 // The stored memory type must be the same. 10641 if (Ld->getMemoryVT() != MemVT) 10642 break; 10643 10644 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 10645 // If this is not the first ptr that we check. 10646 if (LdBasePtr.Base.getNode()) { 10647 // The base ptr must be the same. 10648 if (!LdPtr.equalBaseIndex(LdBasePtr)) 10649 break; 10650 } else { 10651 // Check that all other base pointers are the same as this one. 10652 LdBasePtr = LdPtr; 10653 } 10654 10655 // We found a potential memory operand to merge. 10656 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 10657 } 10658 10659 if (LoadNodes.size() < 2) 10660 return false; 10661 10662 // If we have load/store pair instructions and we only have two values, 10663 // don't bother. 10664 unsigned RequiredAlignment; 10665 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 10666 St->getAlignment() >= RequiredAlignment) 10667 return false; 10668 10669 // Scan the memory operations on the chain and find the first non-consecutive 10670 // load memory address. These variables hold the index in the store node 10671 // array. 10672 unsigned LastConsecutiveLoad = 0; 10673 // This variable refers to the size and not index in the array. 10674 unsigned LastLegalVectorType = 0; 10675 unsigned LastLegalIntegerType = 0; 10676 StartAddress = LoadNodes[0].OffsetFromBase; 10677 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 10678 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 10679 // All loads much share the same chain. 10680 if (LoadNodes[i].MemNode->getChain() != FirstChain) 10681 break; 10682 10683 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 10684 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10685 break; 10686 LastConsecutiveLoad = i; 10687 10688 // Find a legal type for the vector store. 10689 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10690 if (TLI.isTypeLegal(StoreTy)) 10691 LastLegalVectorType = i + 1; 10692 10693 // Find a legal type for the integer store. 10694 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10695 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10696 if (TLI.isTypeLegal(StoreTy)) 10697 LastLegalIntegerType = i + 1; 10698 // Or check whether a truncstore and extload is legal. 10699 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10700 TargetLowering::TypePromoteInteger) { 10701 EVT LegalizedStoredValueTy = 10702 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 10703 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 10704 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10705 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10706 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy)) 10707 LastLegalIntegerType = i+1; 10708 } 10709 } 10710 10711 // Only use vector types if the vector type is larger than the integer type. 10712 // If they are the same, use integers. 10713 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 10714 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 10715 10716 // We add +1 here because the LastXXX variables refer to location while 10717 // the NumElem refers to array/index size. 10718 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 10719 NumElem = std::min(LastLegalType, NumElem); 10720 10721 if (NumElem < 2) 10722 return false; 10723 10724 // The latest Node in the DAG. 10725 unsigned LatestNodeUsed = 0; 10726 for (unsigned i=1; i<NumElem; ++i) { 10727 // Find a chain for the new wide-store operand. Notice that some 10728 // of the store nodes that we found may not be selected for inclusion 10729 // in the wide store. The chain we use needs to be the chain of the 10730 // latest store node which is *used* and replaced by the wide store. 10731 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 10732 LatestNodeUsed = i; 10733 } 10734 10735 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 10736 10737 // Find if it is better to use vectors or integers to load and store 10738 // to memory. 10739 EVT JointMemOpVT; 10740 if (UseVectorTy) { 10741 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 10742 } else { 10743 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 10744 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10745 } 10746 10747 SDLoc LoadDL(LoadNodes[0].MemNode); 10748 SDLoc StoreDL(StoreNodes[0].MemNode); 10749 10750 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 10751 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 10752 FirstLoad->getChain(), 10753 FirstLoad->getBasePtr(), 10754 FirstLoad->getPointerInfo(), 10755 false, false, false, 10756 FirstLoad->getAlignment()); 10757 10758 SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad, 10759 FirstInChain->getBasePtr(), 10760 FirstInChain->getPointerInfo(), false, false, 10761 FirstInChain->getAlignment()); 10762 10763 // Replace one of the loads with the new load. 10764 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 10765 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 10766 SDValue(NewLoad.getNode(), 1)); 10767 10768 // Remove the rest of the load chains. 10769 for (unsigned i = 1; i < NumElem ; ++i) { 10770 // Replace all chain users of the old load nodes with the chain of the new 10771 // load node. 10772 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 10773 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 10774 } 10775 10776 // Replace the last store with the new store. 10777 CombineTo(LatestOp, NewStore); 10778 // Erase all other stores. 10779 for (unsigned i = 0; i < NumElem ; ++i) { 10780 // Remove all Store nodes. 10781 if (StoreNodes[i].MemNode == LatestOp) 10782 continue; 10783 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10784 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 10785 deleteAndRecombine(St); 10786 } 10787 10788 return true; 10789 } 10790 10791 SDValue DAGCombiner::visitSTORE(SDNode *N) { 10792 StoreSDNode *ST = cast<StoreSDNode>(N); 10793 SDValue Chain = ST->getChain(); 10794 SDValue Value = ST->getValue(); 10795 SDValue Ptr = ST->getBasePtr(); 10796 10797 // If this is a store of a bit convert, store the input value if the 10798 // resultant store does not need a higher alignment than the original. 10799 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 10800 ST->isUnindexed()) { 10801 unsigned OrigAlign = ST->getAlignment(); 10802 EVT SVT = Value.getOperand(0).getValueType(); 10803 unsigned Align = TLI.getDataLayout()-> 10804 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 10805 if (Align <= OrigAlign && 10806 ((!LegalOperations && !ST->isVolatile()) || 10807 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 10808 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 10809 Ptr, ST->getPointerInfo(), ST->isVolatile(), 10810 ST->isNonTemporal(), OrigAlign, 10811 ST->getAAInfo()); 10812 } 10813 10814 // Turn 'store undef, Ptr' -> nothing. 10815 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 10816 return Chain; 10817 10818 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 10819 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 10820 // NOTE: If the original store is volatile, this transform must not increase 10821 // the number of stores. For example, on x86-32 an f64 can be stored in one 10822 // processor operation but an i64 (which is not legal) requires two. So the 10823 // transform should not be done in this case. 10824 if (Value.getOpcode() != ISD::TargetConstantFP) { 10825 SDValue Tmp; 10826 switch (CFP->getSimpleValueType(0).SimpleTy) { 10827 default: llvm_unreachable("Unknown FP type"); 10828 case MVT::f16: // We don't do this for these yet. 10829 case MVT::f80: 10830 case MVT::f128: 10831 case MVT::ppcf128: 10832 break; 10833 case MVT::f32: 10834 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 10835 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 10836 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 10837 bitcastToAPInt().getZExtValue(), MVT::i32); 10838 return DAG.getStore(Chain, SDLoc(N), Tmp, 10839 Ptr, ST->getMemOperand()); 10840 } 10841 break; 10842 case MVT::f64: 10843 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 10844 !ST->isVolatile()) || 10845 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 10846 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 10847 getZExtValue(), MVT::i64); 10848 return DAG.getStore(Chain, SDLoc(N), Tmp, 10849 Ptr, ST->getMemOperand()); 10850 } 10851 10852 if (!ST->isVolatile() && 10853 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 10854 // Many FP stores are not made apparent until after legalize, e.g. for 10855 // argument passing. Since this is so common, custom legalize the 10856 // 64-bit integer store into two 32-bit stores. 10857 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 10858 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 10859 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 10860 if (TLI.isBigEndian()) std::swap(Lo, Hi); 10861 10862 unsigned Alignment = ST->getAlignment(); 10863 bool isVolatile = ST->isVolatile(); 10864 bool isNonTemporal = ST->isNonTemporal(); 10865 AAMDNodes AAInfo = ST->getAAInfo(); 10866 10867 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 10868 Ptr, ST->getPointerInfo(), 10869 isVolatile, isNonTemporal, 10870 ST->getAlignment(), AAInfo); 10871 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 10872 DAG.getConstant(4, Ptr.getValueType())); 10873 Alignment = MinAlign(Alignment, 4U); 10874 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 10875 Ptr, ST->getPointerInfo().getWithOffset(4), 10876 isVolatile, isNonTemporal, 10877 Alignment, AAInfo); 10878 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 10879 St0, St1); 10880 } 10881 10882 break; 10883 } 10884 } 10885 } 10886 10887 // Try to infer better alignment information than the store already has. 10888 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 10889 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10890 if (Align > ST->getAlignment()) { 10891 SDValue NewStore = 10892 DAG.getTruncStore(Chain, SDLoc(N), Value, 10893 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 10894 ST->isVolatile(), ST->isNonTemporal(), Align, 10895 ST->getAAInfo()); 10896 if (NewStore.getNode() != N) 10897 return CombineTo(ST, NewStore, true); 10898 } 10899 } 10900 } 10901 10902 // Try transforming a pair floating point load / store ops to integer 10903 // load / store ops. 10904 SDValue NewST = TransformFPLoadStorePair(N); 10905 if (NewST.getNode()) 10906 return NewST; 10907 10908 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10909 : DAG.getSubtarget().useAA(); 10910 #ifndef NDEBUG 10911 if (CombinerAAOnlyFunc.getNumOccurrences() && 10912 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10913 UseAA = false; 10914 #endif 10915 if (UseAA && ST->isUnindexed()) { 10916 // Walk up chain skipping non-aliasing memory nodes. 10917 SDValue BetterChain = FindBetterChain(N, Chain); 10918 10919 // If there is a better chain. 10920 if (Chain != BetterChain) { 10921 SDValue ReplStore; 10922 10923 // Replace the chain to avoid dependency. 10924 if (ST->isTruncatingStore()) { 10925 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 10926 ST->getMemoryVT(), ST->getMemOperand()); 10927 } else { 10928 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 10929 ST->getMemOperand()); 10930 } 10931 10932 // Create token to keep both nodes around. 10933 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10934 MVT::Other, Chain, ReplStore); 10935 10936 // Make sure the new and old chains are cleaned up. 10937 AddToWorklist(Token.getNode()); 10938 10939 // Don't add users to work list. 10940 return CombineTo(N, Token, false); 10941 } 10942 } 10943 10944 // Try transforming N to an indexed store. 10945 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10946 return SDValue(N, 0); 10947 10948 // FIXME: is there such a thing as a truncating indexed store? 10949 if (ST->isTruncatingStore() && ST->isUnindexed() && 10950 Value.getValueType().isInteger()) { 10951 // See if we can simplify the input to this truncstore with knowledge that 10952 // only the low bits are being used. For example: 10953 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 10954 SDValue Shorter = 10955 GetDemandedBits(Value, 10956 APInt::getLowBitsSet( 10957 Value.getValueType().getScalarType().getSizeInBits(), 10958 ST->getMemoryVT().getScalarType().getSizeInBits())); 10959 AddToWorklist(Value.getNode()); 10960 if (Shorter.getNode()) 10961 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 10962 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 10963 10964 // Otherwise, see if we can simplify the operation with 10965 // SimplifyDemandedBits, which only works if the value has a single use. 10966 if (SimplifyDemandedBits(Value, 10967 APInt::getLowBitsSet( 10968 Value.getValueType().getScalarType().getSizeInBits(), 10969 ST->getMemoryVT().getScalarType().getSizeInBits()))) 10970 return SDValue(N, 0); 10971 } 10972 10973 // If this is a load followed by a store to the same location, then the store 10974 // is dead/noop. 10975 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 10976 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 10977 ST->isUnindexed() && !ST->isVolatile() && 10978 // There can't be any side effects between the load and store, such as 10979 // a call or store. 10980 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 10981 // The store is dead, remove it. 10982 return Chain; 10983 } 10984 } 10985 10986 // If this is a store followed by a store with the same value to the same 10987 // location, then the store is dead/noop. 10988 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 10989 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 10990 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 10991 ST1->isUnindexed() && !ST1->isVolatile()) { 10992 // The store is dead, remove it. 10993 return Chain; 10994 } 10995 } 10996 10997 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 10998 // truncating store. We can do this even if this is already a truncstore. 10999 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 11000 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 11001 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 11002 ST->getMemoryVT())) { 11003 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 11004 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11005 } 11006 11007 // Only perform this optimization before the types are legal, because we 11008 // don't want to perform this optimization on every DAGCombine invocation. 11009 if (!LegalTypes) { 11010 bool EverChanged = false; 11011 11012 do { 11013 // There can be multiple store sequences on the same chain. 11014 // Keep trying to merge store sequences until we are unable to do so 11015 // or until we merge the last store on the chain. 11016 bool Changed = MergeConsecutiveStores(ST); 11017 EverChanged |= Changed; 11018 if (!Changed) break; 11019 } while (ST->getOpcode() != ISD::DELETED_NODE); 11020 11021 if (EverChanged) 11022 return SDValue(N, 0); 11023 } 11024 11025 return ReduceLoadOpStoreWidth(N); 11026 } 11027 11028 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 11029 SDValue InVec = N->getOperand(0); 11030 SDValue InVal = N->getOperand(1); 11031 SDValue EltNo = N->getOperand(2); 11032 SDLoc dl(N); 11033 11034 // If the inserted element is an UNDEF, just use the input vector. 11035 if (InVal.getOpcode() == ISD::UNDEF) 11036 return InVec; 11037 11038 EVT VT = InVec.getValueType(); 11039 11040 // If we can't generate a legal BUILD_VECTOR, exit 11041 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 11042 return SDValue(); 11043 11044 // Check that we know which element is being inserted 11045 if (!isa<ConstantSDNode>(EltNo)) 11046 return SDValue(); 11047 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11048 11049 // Canonicalize insert_vector_elt dag nodes. 11050 // Example: 11051 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 11052 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 11053 // 11054 // Do this only if the child insert_vector node has one use; also 11055 // do this only if indices are both constants and Idx1 < Idx0. 11056 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 11057 && isa<ConstantSDNode>(InVec.getOperand(2))) { 11058 unsigned OtherElt = 11059 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 11060 if (Elt < OtherElt) { 11061 // Swap nodes. 11062 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 11063 InVec.getOperand(0), InVal, EltNo); 11064 AddToWorklist(NewOp.getNode()); 11065 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 11066 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 11067 } 11068 } 11069 11070 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 11071 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 11072 // vector elements. 11073 SmallVector<SDValue, 8> Ops; 11074 // Do not combine these two vectors if the output vector will not replace 11075 // the input vector. 11076 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 11077 Ops.append(InVec.getNode()->op_begin(), 11078 InVec.getNode()->op_end()); 11079 } else if (InVec.getOpcode() == ISD::UNDEF) { 11080 unsigned NElts = VT.getVectorNumElements(); 11081 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 11082 } else { 11083 return SDValue(); 11084 } 11085 11086 // Insert the element 11087 if (Elt < Ops.size()) { 11088 // All the operands of BUILD_VECTOR must have the same type; 11089 // we enforce that here. 11090 EVT OpVT = Ops[0].getValueType(); 11091 if (InVal.getValueType() != OpVT) 11092 InVal = OpVT.bitsGT(InVal.getValueType()) ? 11093 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 11094 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 11095 Ops[Elt] = InVal; 11096 } 11097 11098 // Return the new vector 11099 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 11100 } 11101 11102 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 11103 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 11104 EVT ResultVT = EVE->getValueType(0); 11105 EVT VecEltVT = InVecVT.getVectorElementType(); 11106 unsigned Align = OriginalLoad->getAlignment(); 11107 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment( 11108 VecEltVT.getTypeForEVT(*DAG.getContext())); 11109 11110 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 11111 return SDValue(); 11112 11113 Align = NewAlign; 11114 11115 SDValue NewPtr = OriginalLoad->getBasePtr(); 11116 SDValue Offset; 11117 EVT PtrType = NewPtr.getValueType(); 11118 MachinePointerInfo MPI; 11119 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 11120 int Elt = ConstEltNo->getZExtValue(); 11121 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 11122 if (TLI.isBigEndian()) 11123 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff; 11124 Offset = DAG.getConstant(PtrOff, PtrType); 11125 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 11126 } else { 11127 Offset = DAG.getNode( 11128 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo, 11129 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType())); 11130 if (TLI.isBigEndian()) 11131 Offset = DAG.getNode( 11132 ISD::SUB, SDLoc(EVE), EltNo.getValueType(), 11133 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset); 11134 MPI = OriginalLoad->getPointerInfo(); 11135 } 11136 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset); 11137 11138 // The replacement we need to do here is a little tricky: we need to 11139 // replace an extractelement of a load with a load. 11140 // Use ReplaceAllUsesOfValuesWith to do the replacement. 11141 // Note that this replacement assumes that the extractvalue is the only 11142 // use of the load; that's okay because we don't want to perform this 11143 // transformation in other cases anyway. 11144 SDValue Load; 11145 SDValue Chain; 11146 if (ResultVT.bitsGT(VecEltVT)) { 11147 // If the result type of vextract is wider than the load, then issue an 11148 // extending load instead. 11149 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 11150 VecEltVT) 11151 ? ISD::ZEXTLOAD 11152 : ISD::EXTLOAD; 11153 Load = DAG.getExtLoad( 11154 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 11155 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11156 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11157 Chain = Load.getValue(1); 11158 } else { 11159 Load = DAG.getLoad( 11160 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 11161 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11162 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11163 Chain = Load.getValue(1); 11164 if (ResultVT.bitsLT(VecEltVT)) 11165 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 11166 else 11167 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 11168 } 11169 WorklistRemover DeadNodes(*this); 11170 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 11171 SDValue To[] = { Load, Chain }; 11172 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 11173 // Since we're explicitly calling ReplaceAllUses, add the new node to the 11174 // worklist explicitly as well. 11175 AddToWorklist(Load.getNode()); 11176 AddUsersToWorklist(Load.getNode()); // Add users too 11177 // Make sure to revisit this node to clean it up; it will usually be dead. 11178 AddToWorklist(EVE); 11179 ++OpsNarrowed; 11180 return SDValue(EVE, 0); 11181 } 11182 11183 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 11184 // (vextract (scalar_to_vector val, 0) -> val 11185 SDValue InVec = N->getOperand(0); 11186 EVT VT = InVec.getValueType(); 11187 EVT NVT = N->getValueType(0); 11188 11189 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 11190 // Check if the result type doesn't match the inserted element type. A 11191 // SCALAR_TO_VECTOR may truncate the inserted element and the 11192 // EXTRACT_VECTOR_ELT may widen the extracted vector. 11193 SDValue InOp = InVec.getOperand(0); 11194 if (InOp.getValueType() != NVT) { 11195 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11196 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 11197 } 11198 return InOp; 11199 } 11200 11201 SDValue EltNo = N->getOperand(1); 11202 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 11203 11204 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 11205 // We only perform this optimization before the op legalization phase because 11206 // we may introduce new vector instructions which are not backed by TD 11207 // patterns. For example on AVX, extracting elements from a wide vector 11208 // without using extract_subvector. However, if we can find an underlying 11209 // scalar value, then we can always use that. 11210 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 11211 && ConstEltNo) { 11212 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11213 int NumElem = VT.getVectorNumElements(); 11214 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 11215 // Find the new index to extract from. 11216 int OrigElt = SVOp->getMaskElt(Elt); 11217 11218 // Extracting an undef index is undef. 11219 if (OrigElt == -1) 11220 return DAG.getUNDEF(NVT); 11221 11222 // Select the right vector half to extract from. 11223 SDValue SVInVec; 11224 if (OrigElt < NumElem) { 11225 SVInVec = InVec->getOperand(0); 11226 } else { 11227 SVInVec = InVec->getOperand(1); 11228 OrigElt -= NumElem; 11229 } 11230 11231 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 11232 SDValue InOp = SVInVec.getOperand(OrigElt); 11233 if (InOp.getValueType() != NVT) { 11234 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11235 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 11236 } 11237 11238 return InOp; 11239 } 11240 11241 // FIXME: We should handle recursing on other vector shuffles and 11242 // scalar_to_vector here as well. 11243 11244 if (!LegalOperations) { 11245 EVT IndexTy = TLI.getVectorIdxTy(); 11246 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 11247 SVInVec, DAG.getConstant(OrigElt, IndexTy)); 11248 } 11249 } 11250 11251 bool BCNumEltsChanged = false; 11252 EVT ExtVT = VT.getVectorElementType(); 11253 EVT LVT = ExtVT; 11254 11255 // If the result of load has to be truncated, then it's not necessarily 11256 // profitable. 11257 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 11258 return SDValue(); 11259 11260 if (InVec.getOpcode() == ISD::BITCAST) { 11261 // Don't duplicate a load with other uses. 11262 if (!InVec.hasOneUse()) 11263 return SDValue(); 11264 11265 EVT BCVT = InVec.getOperand(0).getValueType(); 11266 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 11267 return SDValue(); 11268 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 11269 BCNumEltsChanged = true; 11270 InVec = InVec.getOperand(0); 11271 ExtVT = BCVT.getVectorElementType(); 11272 } 11273 11274 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 11275 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 11276 ISD::isNormalLoad(InVec.getNode()) && 11277 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 11278 SDValue Index = N->getOperand(1); 11279 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 11280 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 11281 OrigLoad); 11282 } 11283 11284 // Perform only after legalization to ensure build_vector / vector_shuffle 11285 // optimizations have already been done. 11286 if (!LegalOperations) return SDValue(); 11287 11288 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 11289 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 11290 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 11291 11292 if (ConstEltNo) { 11293 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11294 11295 LoadSDNode *LN0 = nullptr; 11296 const ShuffleVectorSDNode *SVN = nullptr; 11297 if (ISD::isNormalLoad(InVec.getNode())) { 11298 LN0 = cast<LoadSDNode>(InVec); 11299 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 11300 InVec.getOperand(0).getValueType() == ExtVT && 11301 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 11302 // Don't duplicate a load with other uses. 11303 if (!InVec.hasOneUse()) 11304 return SDValue(); 11305 11306 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 11307 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 11308 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 11309 // => 11310 // (load $addr+1*size) 11311 11312 // Don't duplicate a load with other uses. 11313 if (!InVec.hasOneUse()) 11314 return SDValue(); 11315 11316 // If the bit convert changed the number of elements, it is unsafe 11317 // to examine the mask. 11318 if (BCNumEltsChanged) 11319 return SDValue(); 11320 11321 // Select the input vector, guarding against out of range extract vector. 11322 unsigned NumElems = VT.getVectorNumElements(); 11323 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 11324 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 11325 11326 if (InVec.getOpcode() == ISD::BITCAST) { 11327 // Don't duplicate a load with other uses. 11328 if (!InVec.hasOneUse()) 11329 return SDValue(); 11330 11331 InVec = InVec.getOperand(0); 11332 } 11333 if (ISD::isNormalLoad(InVec.getNode())) { 11334 LN0 = cast<LoadSDNode>(InVec); 11335 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 11336 EltNo = DAG.getConstant(Elt, EltNo.getValueType()); 11337 } 11338 } 11339 11340 // Make sure we found a non-volatile load and the extractelement is 11341 // the only use. 11342 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 11343 return SDValue(); 11344 11345 // If Idx was -1 above, Elt is going to be -1, so just return undef. 11346 if (Elt == -1) 11347 return DAG.getUNDEF(LVT); 11348 11349 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 11350 } 11351 11352 return SDValue(); 11353 } 11354 11355 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 11356 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 11357 // We perform this optimization post type-legalization because 11358 // the type-legalizer often scalarizes integer-promoted vectors. 11359 // Performing this optimization before may create bit-casts which 11360 // will be type-legalized to complex code sequences. 11361 // We perform this optimization only before the operation legalizer because we 11362 // may introduce illegal operations. 11363 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 11364 return SDValue(); 11365 11366 unsigned NumInScalars = N->getNumOperands(); 11367 SDLoc dl(N); 11368 EVT VT = N->getValueType(0); 11369 11370 // Check to see if this is a BUILD_VECTOR of a bunch of values 11371 // which come from any_extend or zero_extend nodes. If so, we can create 11372 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 11373 // optimizations. We do not handle sign-extend because we can't fill the sign 11374 // using shuffles. 11375 EVT SourceType = MVT::Other; 11376 bool AllAnyExt = true; 11377 11378 for (unsigned i = 0; i != NumInScalars; ++i) { 11379 SDValue In = N->getOperand(i); 11380 // Ignore undef inputs. 11381 if (In.getOpcode() == ISD::UNDEF) continue; 11382 11383 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 11384 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 11385 11386 // Abort if the element is not an extension. 11387 if (!ZeroExt && !AnyExt) { 11388 SourceType = MVT::Other; 11389 break; 11390 } 11391 11392 // The input is a ZeroExt or AnyExt. Check the original type. 11393 EVT InTy = In.getOperand(0).getValueType(); 11394 11395 // Check that all of the widened source types are the same. 11396 if (SourceType == MVT::Other) 11397 // First time. 11398 SourceType = InTy; 11399 else if (InTy != SourceType) { 11400 // Multiple income types. Abort. 11401 SourceType = MVT::Other; 11402 break; 11403 } 11404 11405 // Check if all of the extends are ANY_EXTENDs. 11406 AllAnyExt &= AnyExt; 11407 } 11408 11409 // In order to have valid types, all of the inputs must be extended from the 11410 // same source type and all of the inputs must be any or zero extend. 11411 // Scalar sizes must be a power of two. 11412 EVT OutScalarTy = VT.getScalarType(); 11413 bool ValidTypes = SourceType != MVT::Other && 11414 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 11415 isPowerOf2_32(SourceType.getSizeInBits()); 11416 11417 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 11418 // turn into a single shuffle instruction. 11419 if (!ValidTypes) 11420 return SDValue(); 11421 11422 bool isLE = TLI.isLittleEndian(); 11423 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 11424 assert(ElemRatio > 1 && "Invalid element size ratio"); 11425 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 11426 DAG.getConstant(0, SourceType); 11427 11428 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 11429 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 11430 11431 // Populate the new build_vector 11432 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11433 SDValue Cast = N->getOperand(i); 11434 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 11435 Cast.getOpcode() == ISD::ZERO_EXTEND || 11436 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 11437 SDValue In; 11438 if (Cast.getOpcode() == ISD::UNDEF) 11439 In = DAG.getUNDEF(SourceType); 11440 else 11441 In = Cast->getOperand(0); 11442 unsigned Index = isLE ? (i * ElemRatio) : 11443 (i * ElemRatio + (ElemRatio - 1)); 11444 11445 assert(Index < Ops.size() && "Invalid index"); 11446 Ops[Index] = In; 11447 } 11448 11449 // The type of the new BUILD_VECTOR node. 11450 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 11451 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 11452 "Invalid vector size"); 11453 // Check if the new vector type is legal. 11454 if (!isTypeLegal(VecVT)) return SDValue(); 11455 11456 // Make the new BUILD_VECTOR. 11457 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 11458 11459 // The new BUILD_VECTOR node has the potential to be further optimized. 11460 AddToWorklist(BV.getNode()); 11461 // Bitcast to the desired type. 11462 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11463 } 11464 11465 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 11466 EVT VT = N->getValueType(0); 11467 11468 unsigned NumInScalars = N->getNumOperands(); 11469 SDLoc dl(N); 11470 11471 EVT SrcVT = MVT::Other; 11472 unsigned Opcode = ISD::DELETED_NODE; 11473 unsigned NumDefs = 0; 11474 11475 for (unsigned i = 0; i != NumInScalars; ++i) { 11476 SDValue In = N->getOperand(i); 11477 unsigned Opc = In.getOpcode(); 11478 11479 if (Opc == ISD::UNDEF) 11480 continue; 11481 11482 // If all scalar values are floats and converted from integers. 11483 if (Opcode == ISD::DELETED_NODE && 11484 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 11485 Opcode = Opc; 11486 } 11487 11488 if (Opc != Opcode) 11489 return SDValue(); 11490 11491 EVT InVT = In.getOperand(0).getValueType(); 11492 11493 // If all scalar values are typed differently, bail out. It's chosen to 11494 // simplify BUILD_VECTOR of integer types. 11495 if (SrcVT == MVT::Other) 11496 SrcVT = InVT; 11497 if (SrcVT != InVT) 11498 return SDValue(); 11499 NumDefs++; 11500 } 11501 11502 // If the vector has just one element defined, it's not worth to fold it into 11503 // a vectorized one. 11504 if (NumDefs < 2) 11505 return SDValue(); 11506 11507 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 11508 && "Should only handle conversion from integer to float."); 11509 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 11510 11511 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 11512 11513 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 11514 return SDValue(); 11515 11516 // Just because the floating-point vector type is legal does not necessarily 11517 // mean that the corresponding integer vector type is. 11518 if (!isTypeLegal(NVT)) 11519 return SDValue(); 11520 11521 SmallVector<SDValue, 8> Opnds; 11522 for (unsigned i = 0; i != NumInScalars; ++i) { 11523 SDValue In = N->getOperand(i); 11524 11525 if (In.getOpcode() == ISD::UNDEF) 11526 Opnds.push_back(DAG.getUNDEF(SrcVT)); 11527 else 11528 Opnds.push_back(In.getOperand(0)); 11529 } 11530 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 11531 AddToWorklist(BV.getNode()); 11532 11533 return DAG.getNode(Opcode, dl, VT, BV); 11534 } 11535 11536 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 11537 unsigned NumInScalars = N->getNumOperands(); 11538 SDLoc dl(N); 11539 EVT VT = N->getValueType(0); 11540 11541 // A vector built entirely of undefs is undef. 11542 if (ISD::allOperandsUndef(N)) 11543 return DAG.getUNDEF(VT); 11544 11545 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 11546 return V; 11547 11548 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 11549 return V; 11550 11551 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 11552 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 11553 // at most two distinct vectors, turn this into a shuffle node. 11554 11555 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 11556 if (!isTypeLegal(VT)) 11557 return SDValue(); 11558 11559 // May only combine to shuffle after legalize if shuffle is legal. 11560 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 11561 return SDValue(); 11562 11563 SDValue VecIn1, VecIn2; 11564 bool UsesZeroVector = false; 11565 for (unsigned i = 0; i != NumInScalars; ++i) { 11566 SDValue Op = N->getOperand(i); 11567 // Ignore undef inputs. 11568 if (Op.getOpcode() == ISD::UNDEF) continue; 11569 11570 // See if we can combine this build_vector into a blend with a zero vector. 11571 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant && 11572 cast<ConstantSDNode>(Op.getNode())->isNullValue()) || 11573 (Op.getOpcode() == ISD::ConstantFP && 11574 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) { 11575 UsesZeroVector = true; 11576 continue; 11577 } 11578 11579 // If this input is something other than a EXTRACT_VECTOR_ELT with a 11580 // constant index, bail out. 11581 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11582 !isa<ConstantSDNode>(Op.getOperand(1))) { 11583 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11584 break; 11585 } 11586 11587 // We allow up to two distinct input vectors. 11588 SDValue ExtractedFromVec = Op.getOperand(0); 11589 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 11590 continue; 11591 11592 if (!VecIn1.getNode()) { 11593 VecIn1 = ExtractedFromVec; 11594 } else if (!VecIn2.getNode() && !UsesZeroVector) { 11595 VecIn2 = ExtractedFromVec; 11596 } else { 11597 // Too many inputs. 11598 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11599 break; 11600 } 11601 } 11602 11603 // If everything is good, we can make a shuffle operation. 11604 if (VecIn1.getNode()) { 11605 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 11606 SmallVector<int, 8> Mask; 11607 for (unsigned i = 0; i != NumInScalars; ++i) { 11608 unsigned Opcode = N->getOperand(i).getOpcode(); 11609 if (Opcode == ISD::UNDEF) { 11610 Mask.push_back(-1); 11611 continue; 11612 } 11613 11614 // Operands can also be zero. 11615 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 11616 assert(UsesZeroVector && 11617 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 11618 "Unexpected node found!"); 11619 Mask.push_back(NumInScalars+i); 11620 continue; 11621 } 11622 11623 // If extracting from the first vector, just use the index directly. 11624 SDValue Extract = N->getOperand(i); 11625 SDValue ExtVal = Extract.getOperand(1); 11626 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 11627 if (Extract.getOperand(0) == VecIn1) { 11628 Mask.push_back(ExtIndex); 11629 continue; 11630 } 11631 11632 // Otherwise, use InIdx + InputVecSize 11633 Mask.push_back(InNumElements + ExtIndex); 11634 } 11635 11636 // Avoid introducing illegal shuffles with zero. 11637 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 11638 return SDValue(); 11639 11640 // We can't generate a shuffle node with mismatched input and output types. 11641 // Attempt to transform a single input vector to the correct type. 11642 if ((VT != VecIn1.getValueType())) { 11643 // If the input vector type has a different base type to the output 11644 // vector type, bail out. 11645 EVT VTElemType = VT.getVectorElementType(); 11646 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 11647 (VecIn2.getNode() && 11648 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 11649 return SDValue(); 11650 11651 // If the input vector is too small, widen it. 11652 // We only support widening of vectors which are half the size of the 11653 // output registers. For example XMM->YMM widening on X86 with AVX. 11654 EVT VecInT = VecIn1.getValueType(); 11655 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 11656 // If we only have one small input, widen it by adding undef values. 11657 if (!VecIn2.getNode()) 11658 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 11659 DAG.getUNDEF(VecIn1.getValueType())); 11660 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 11661 // If we have two small inputs of the same type, try to concat them. 11662 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 11663 VecIn2 = SDValue(nullptr, 0); 11664 } else 11665 return SDValue(); 11666 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 11667 // If the input vector is too large, try to split it. 11668 // We don't support having two input vectors that are too large. 11669 // If the zero vector was used, we can not split the vector, 11670 // since we'd need 3 inputs. 11671 if (UsesZeroVector || VecIn2.getNode()) 11672 return SDValue(); 11673 11674 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 11675 return SDValue(); 11676 11677 // Try to replace VecIn1 with two extract_subvectors 11678 // No need to update the masks, they should still be correct. 11679 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11680 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy())); 11681 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11682 DAG.getConstant(0, TLI.getVectorIdxTy())); 11683 } else 11684 return SDValue(); 11685 } 11686 11687 if (UsesZeroVector) 11688 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) : 11689 DAG.getConstantFP(0.0, VT); 11690 else 11691 // If VecIn2 is unused then change it to undef. 11692 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 11693 11694 // Check that we were able to transform all incoming values to the same 11695 // type. 11696 if (VecIn2.getValueType() != VecIn1.getValueType() || 11697 VecIn1.getValueType() != VT) 11698 return SDValue(); 11699 11700 // Return the new VECTOR_SHUFFLE node. 11701 SDValue Ops[2]; 11702 Ops[0] = VecIn1; 11703 Ops[1] = VecIn2; 11704 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 11705 } 11706 11707 return SDValue(); 11708 } 11709 11710 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 11711 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11712 EVT OpVT = N->getOperand(0).getValueType(); 11713 11714 // If the operands are legal vectors, leave them alone. 11715 if (TLI.isTypeLegal(OpVT)) 11716 return SDValue(); 11717 11718 SDLoc DL(N); 11719 EVT VT = N->getValueType(0); 11720 SmallVector<SDValue, 8> Ops; 11721 11722 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 11723 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 11724 11725 // Keep track of what we encounter. 11726 bool AnyInteger = false; 11727 bool AnyFP = false; 11728 for (const SDValue &Op : N->ops()) { 11729 if (ISD::BITCAST == Op.getOpcode() && 11730 !Op.getOperand(0).getValueType().isVector()) 11731 Ops.push_back(Op.getOperand(0)); 11732 else if (ISD::UNDEF == Op.getOpcode()) 11733 Ops.push_back(ScalarUndef); 11734 else 11735 return SDValue(); 11736 11737 // Note whether we encounter an integer or floating point scalar. 11738 // If it's neither, bail out, it could be something weird like x86mmx. 11739 EVT LastOpVT = Ops.back().getValueType(); 11740 if (LastOpVT.isFloatingPoint()) 11741 AnyFP = true; 11742 else if (LastOpVT.isInteger()) 11743 AnyInteger = true; 11744 else 11745 return SDValue(); 11746 } 11747 11748 // If any of the operands is a floating point scalar bitcast to a vector, 11749 // use floating point types throughout, and bitcast everything. 11750 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 11751 if (AnyFP) { 11752 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 11753 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 11754 if (AnyInteger) { 11755 for (SDValue &Op : Ops) { 11756 if (Op.getValueType() == SVT) 11757 continue; 11758 if (Op.getOpcode() == ISD::UNDEF) 11759 Op = ScalarUndef; 11760 else 11761 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 11762 } 11763 } 11764 } 11765 11766 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 11767 VT.getSizeInBits() / SVT.getSizeInBits()); 11768 return DAG.getNode(ISD::BITCAST, DL, VT, 11769 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 11770 } 11771 11772 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 11773 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 11774 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 11775 // inputs come from at most two distinct vectors, turn this into a shuffle 11776 // node. 11777 11778 // If we only have one input vector, we don't need to do any concatenation. 11779 if (N->getNumOperands() == 1) 11780 return N->getOperand(0); 11781 11782 // Check if all of the operands are undefs. 11783 EVT VT = N->getValueType(0); 11784 if (ISD::allOperandsUndef(N)) 11785 return DAG.getUNDEF(VT); 11786 11787 // Optimize concat_vectors where all but the first of the vectors are undef. 11788 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 11789 return Op.getOpcode() == ISD::UNDEF; 11790 })) { 11791 SDValue In = N->getOperand(0); 11792 assert(In.getValueType().isVector() && "Must concat vectors"); 11793 11794 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 11795 if (In->getOpcode() == ISD::BITCAST && 11796 !In->getOperand(0)->getValueType(0).isVector()) { 11797 SDValue Scalar = In->getOperand(0); 11798 11799 // If the bitcast type isn't legal, it might be a trunc of a legal type; 11800 // look through the trunc so we can still do the transform: 11801 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 11802 if (Scalar->getOpcode() == ISD::TRUNCATE && 11803 !TLI.isTypeLegal(Scalar.getValueType()) && 11804 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 11805 Scalar = Scalar->getOperand(0); 11806 11807 EVT SclTy = Scalar->getValueType(0); 11808 11809 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 11810 return SDValue(); 11811 11812 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 11813 VT.getSizeInBits() / SclTy.getSizeInBits()); 11814 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 11815 return SDValue(); 11816 11817 SDLoc dl = SDLoc(N); 11818 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 11819 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 11820 } 11821 } 11822 11823 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 11824 // We have already tested above for an UNDEF only concatenation. 11825 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 11826 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 11827 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 11828 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 11829 }; 11830 bool AllBuildVectorsOrUndefs = 11831 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 11832 if (AllBuildVectorsOrUndefs) { 11833 SmallVector<SDValue, 8> Opnds; 11834 EVT SVT = VT.getScalarType(); 11835 11836 EVT MinVT = SVT; 11837 if (!SVT.isFloatingPoint()) { 11838 // If BUILD_VECTOR are from built from integer, they may have different 11839 // operand types. Get the smallest type and truncate all operands to it. 11840 bool FoundMinVT = false; 11841 for (const SDValue &Op : N->ops()) 11842 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 11843 EVT OpSVT = Op.getOperand(0)->getValueType(0); 11844 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 11845 FoundMinVT = true; 11846 } 11847 assert(FoundMinVT && "Concat vector type mismatch"); 11848 } 11849 11850 for (const SDValue &Op : N->ops()) { 11851 EVT OpVT = Op.getValueType(); 11852 unsigned NumElts = OpVT.getVectorNumElements(); 11853 11854 if (ISD::UNDEF == Op.getOpcode()) 11855 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 11856 11857 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 11858 if (SVT.isFloatingPoint()) { 11859 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 11860 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 11861 } else { 11862 for (unsigned i = 0; i != NumElts; ++i) 11863 Opnds.push_back( 11864 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 11865 } 11866 } 11867 } 11868 11869 assert(VT.getVectorNumElements() == Opnds.size() && 11870 "Concat vector type mismatch"); 11871 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 11872 } 11873 11874 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 11875 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 11876 return V; 11877 11878 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 11879 // nodes often generate nop CONCAT_VECTOR nodes. 11880 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 11881 // place the incoming vectors at the exact same location. 11882 SDValue SingleSource = SDValue(); 11883 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 11884 11885 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11886 SDValue Op = N->getOperand(i); 11887 11888 if (Op.getOpcode() == ISD::UNDEF) 11889 continue; 11890 11891 // Check if this is the identity extract: 11892 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 11893 return SDValue(); 11894 11895 // Find the single incoming vector for the extract_subvector. 11896 if (SingleSource.getNode()) { 11897 if (Op.getOperand(0) != SingleSource) 11898 return SDValue(); 11899 } else { 11900 SingleSource = Op.getOperand(0); 11901 11902 // Check the source type is the same as the type of the result. 11903 // If not, this concat may extend the vector, so we can not 11904 // optimize it away. 11905 if (SingleSource.getValueType() != N->getValueType(0)) 11906 return SDValue(); 11907 } 11908 11909 unsigned IdentityIndex = i * PartNumElem; 11910 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 11911 // The extract index must be constant. 11912 if (!CS) 11913 return SDValue(); 11914 11915 // Check that we are reading from the identity index. 11916 if (CS->getZExtValue() != IdentityIndex) 11917 return SDValue(); 11918 } 11919 11920 if (SingleSource.getNode()) 11921 return SingleSource; 11922 11923 return SDValue(); 11924 } 11925 11926 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 11927 EVT NVT = N->getValueType(0); 11928 SDValue V = N->getOperand(0); 11929 11930 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 11931 // Combine: 11932 // (extract_subvec (concat V1, V2, ...), i) 11933 // Into: 11934 // Vi if possible 11935 // Only operand 0 is checked as 'concat' assumes all inputs of the same 11936 // type. 11937 if (V->getOperand(0).getValueType() != NVT) 11938 return SDValue(); 11939 unsigned Idx = N->getConstantOperandVal(1); 11940 unsigned NumElems = NVT.getVectorNumElements(); 11941 assert((Idx % NumElems) == 0 && 11942 "IDX in concat is not a multiple of the result vector length."); 11943 return V->getOperand(Idx / NumElems); 11944 } 11945 11946 // Skip bitcasting 11947 if (V->getOpcode() == ISD::BITCAST) 11948 V = V.getOperand(0); 11949 11950 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 11951 SDLoc dl(N); 11952 // Handle only simple case where vector being inserted and vector 11953 // being extracted are of same type, and are half size of larger vectors. 11954 EVT BigVT = V->getOperand(0).getValueType(); 11955 EVT SmallVT = V->getOperand(1).getValueType(); 11956 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 11957 return SDValue(); 11958 11959 // Only handle cases where both indexes are constants with the same type. 11960 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11961 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 11962 11963 if (InsIdx && ExtIdx && 11964 InsIdx->getValueType(0).getSizeInBits() <= 64 && 11965 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 11966 // Combine: 11967 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 11968 // Into: 11969 // indices are equal or bit offsets are equal => V1 11970 // otherwise => (extract_subvec V1, ExtIdx) 11971 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 11972 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 11973 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 11974 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 11975 DAG.getNode(ISD::BITCAST, dl, 11976 N->getOperand(0).getValueType(), 11977 V->getOperand(0)), N->getOperand(1)); 11978 } 11979 } 11980 11981 return SDValue(); 11982 } 11983 11984 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 11985 SDValue V, SelectionDAG &DAG) { 11986 SDLoc DL(V); 11987 EVT VT = V.getValueType(); 11988 11989 switch (V.getOpcode()) { 11990 default: 11991 return V; 11992 11993 case ISD::CONCAT_VECTORS: { 11994 EVT OpVT = V->getOperand(0).getValueType(); 11995 int OpSize = OpVT.getVectorNumElements(); 11996 SmallBitVector OpUsedElements(OpSize, false); 11997 bool FoundSimplification = false; 11998 SmallVector<SDValue, 4> NewOps; 11999 NewOps.reserve(V->getNumOperands()); 12000 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 12001 SDValue Op = V->getOperand(i); 12002 bool OpUsed = false; 12003 for (int j = 0; j < OpSize; ++j) 12004 if (UsedElements[i * OpSize + j]) { 12005 OpUsedElements[j] = true; 12006 OpUsed = true; 12007 } 12008 NewOps.push_back( 12009 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 12010 : DAG.getUNDEF(OpVT)); 12011 FoundSimplification |= Op == NewOps.back(); 12012 OpUsedElements.reset(); 12013 } 12014 if (FoundSimplification) 12015 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 12016 return V; 12017 } 12018 12019 case ISD::INSERT_SUBVECTOR: { 12020 SDValue BaseV = V->getOperand(0); 12021 SDValue SubV = V->getOperand(1); 12022 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12023 if (!IdxN) 12024 return V; 12025 12026 int SubSize = SubV.getValueType().getVectorNumElements(); 12027 int Idx = IdxN->getZExtValue(); 12028 bool SubVectorUsed = false; 12029 SmallBitVector SubUsedElements(SubSize, false); 12030 for (int i = 0; i < SubSize; ++i) 12031 if (UsedElements[i + Idx]) { 12032 SubVectorUsed = true; 12033 SubUsedElements[i] = true; 12034 UsedElements[i + Idx] = false; 12035 } 12036 12037 // Now recurse on both the base and sub vectors. 12038 SDValue SimplifiedSubV = 12039 SubVectorUsed 12040 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 12041 : DAG.getUNDEF(SubV.getValueType()); 12042 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 12043 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 12044 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 12045 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 12046 return V; 12047 } 12048 } 12049 } 12050 12051 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 12052 SDValue N1, SelectionDAG &DAG) { 12053 EVT VT = SVN->getValueType(0); 12054 int NumElts = VT.getVectorNumElements(); 12055 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 12056 for (int M : SVN->getMask()) 12057 if (M >= 0 && M < NumElts) 12058 N0UsedElements[M] = true; 12059 else if (M >= NumElts) 12060 N1UsedElements[M - NumElts] = true; 12061 12062 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 12063 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 12064 if (S0 == N0 && S1 == N1) 12065 return SDValue(); 12066 12067 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 12068 } 12069 12070 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 12071 // or turn a shuffle of a single concat into simpler shuffle then concat. 12072 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 12073 EVT VT = N->getValueType(0); 12074 unsigned NumElts = VT.getVectorNumElements(); 12075 12076 SDValue N0 = N->getOperand(0); 12077 SDValue N1 = N->getOperand(1); 12078 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12079 12080 SmallVector<SDValue, 4> Ops; 12081 EVT ConcatVT = N0.getOperand(0).getValueType(); 12082 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 12083 unsigned NumConcats = NumElts / NumElemsPerConcat; 12084 12085 // Special case: shuffle(concat(A,B)) can be more efficiently represented 12086 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 12087 // half vector elements. 12088 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 12089 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 12090 SVN->getMask().end(), [](int i) { return i == -1; })) { 12091 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 12092 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat)); 12093 N1 = DAG.getUNDEF(ConcatVT); 12094 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 12095 } 12096 12097 // Look at every vector that's inserted. We're looking for exact 12098 // subvector-sized copies from a concatenated vector 12099 for (unsigned I = 0; I != NumConcats; ++I) { 12100 // Make sure we're dealing with a copy. 12101 unsigned Begin = I * NumElemsPerConcat; 12102 bool AllUndef = true, NoUndef = true; 12103 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 12104 if (SVN->getMaskElt(J) >= 0) 12105 AllUndef = false; 12106 else 12107 NoUndef = false; 12108 } 12109 12110 if (NoUndef) { 12111 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 12112 return SDValue(); 12113 12114 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 12115 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 12116 return SDValue(); 12117 12118 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 12119 if (FirstElt < N0.getNumOperands()) 12120 Ops.push_back(N0.getOperand(FirstElt)); 12121 else 12122 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 12123 12124 } else if (AllUndef) { 12125 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 12126 } else { // Mixed with general masks and undefs, can't do optimization. 12127 return SDValue(); 12128 } 12129 } 12130 12131 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 12132 } 12133 12134 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 12135 EVT VT = N->getValueType(0); 12136 unsigned NumElts = VT.getVectorNumElements(); 12137 12138 SDValue N0 = N->getOperand(0); 12139 SDValue N1 = N->getOperand(1); 12140 12141 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 12142 12143 // Canonicalize shuffle undef, undef -> undef 12144 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 12145 return DAG.getUNDEF(VT); 12146 12147 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12148 12149 // Canonicalize shuffle v, v -> v, undef 12150 if (N0 == N1) { 12151 SmallVector<int, 8> NewMask; 12152 for (unsigned i = 0; i != NumElts; ++i) { 12153 int Idx = SVN->getMaskElt(i); 12154 if (Idx >= (int)NumElts) Idx -= NumElts; 12155 NewMask.push_back(Idx); 12156 } 12157 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 12158 &NewMask[0]); 12159 } 12160 12161 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 12162 if (N0.getOpcode() == ISD::UNDEF) { 12163 SmallVector<int, 8> NewMask; 12164 for (unsigned i = 0; i != NumElts; ++i) { 12165 int Idx = SVN->getMaskElt(i); 12166 if (Idx >= 0) { 12167 if (Idx >= (int)NumElts) 12168 Idx -= NumElts; 12169 else 12170 Idx = -1; // remove reference to lhs 12171 } 12172 NewMask.push_back(Idx); 12173 } 12174 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 12175 &NewMask[0]); 12176 } 12177 12178 // Remove references to rhs if it is undef 12179 if (N1.getOpcode() == ISD::UNDEF) { 12180 bool Changed = false; 12181 SmallVector<int, 8> NewMask; 12182 for (unsigned i = 0; i != NumElts; ++i) { 12183 int Idx = SVN->getMaskElt(i); 12184 if (Idx >= (int)NumElts) { 12185 Idx = -1; 12186 Changed = true; 12187 } 12188 NewMask.push_back(Idx); 12189 } 12190 if (Changed) 12191 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 12192 } 12193 12194 // If it is a splat, check if the argument vector is another splat or a 12195 // build_vector. 12196 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 12197 SDNode *V = N0.getNode(); 12198 12199 // If this is a bit convert that changes the element type of the vector but 12200 // not the number of vector elements, look through it. Be careful not to 12201 // look though conversions that change things like v4f32 to v2f64. 12202 if (V->getOpcode() == ISD::BITCAST) { 12203 SDValue ConvInput = V->getOperand(0); 12204 if (ConvInput.getValueType().isVector() && 12205 ConvInput.getValueType().getVectorNumElements() == NumElts) 12206 V = ConvInput.getNode(); 12207 } 12208 12209 if (V->getOpcode() == ISD::BUILD_VECTOR) { 12210 assert(V->getNumOperands() == NumElts && 12211 "BUILD_VECTOR has wrong number of operands"); 12212 SDValue Base; 12213 bool AllSame = true; 12214 for (unsigned i = 0; i != NumElts; ++i) { 12215 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 12216 Base = V->getOperand(i); 12217 break; 12218 } 12219 } 12220 // Splat of <u, u, u, u>, return <u, u, u, u> 12221 if (!Base.getNode()) 12222 return N0; 12223 for (unsigned i = 0; i != NumElts; ++i) { 12224 if (V->getOperand(i) != Base) { 12225 AllSame = false; 12226 break; 12227 } 12228 } 12229 // Splat of <x, x, x, x>, return <x, x, x, x> 12230 if (AllSame) 12231 return N0; 12232 12233 // Canonicalize any other splat as a build_vector. 12234 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 12235 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 12236 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 12237 V->getValueType(0), Ops); 12238 12239 // We may have jumped through bitcasts, so the type of the 12240 // BUILD_VECTOR may not match the type of the shuffle. 12241 if (V->getValueType(0) != VT) 12242 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 12243 return NewBV; 12244 } 12245 } 12246 12247 // There are various patterns used to build up a vector from smaller vectors, 12248 // subvectors, or elements. Scan chains of these and replace unused insertions 12249 // or components with undef. 12250 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 12251 return S; 12252 12253 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 12254 Level < AfterLegalizeVectorOps && 12255 (N1.getOpcode() == ISD::UNDEF || 12256 (N1.getOpcode() == ISD::CONCAT_VECTORS && 12257 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 12258 SDValue V = partitionShuffleOfConcats(N, DAG); 12259 12260 if (V.getNode()) 12261 return V; 12262 } 12263 12264 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 12265 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 12266 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 12267 SmallVector<SDValue, 8> Ops; 12268 for (int M : SVN->getMask()) { 12269 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 12270 if (M >= 0) { 12271 int Idx = M % NumElts; 12272 SDValue &S = (M < (int)NumElts ? N0 : N1); 12273 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 12274 Op = S.getOperand(Idx); 12275 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 12276 if (Idx == 0) 12277 Op = S.getOperand(0); 12278 } else { 12279 // Operand can't be combined - bail out. 12280 break; 12281 } 12282 } 12283 Ops.push_back(Op); 12284 } 12285 if (Ops.size() == VT.getVectorNumElements()) { 12286 // BUILD_VECTOR requires all inputs to be of the same type, find the 12287 // maximum type and extend them all. 12288 EVT SVT = VT.getScalarType(); 12289 if (SVT.isInteger()) 12290 for (SDValue &Op : Ops) 12291 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 12292 if (SVT != VT.getScalarType()) 12293 for (SDValue &Op : Ops) 12294 Op = TLI.isZExtFree(Op.getValueType(), SVT) 12295 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 12296 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 12297 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 12298 } 12299 } 12300 12301 // If this shuffle only has a single input that is a bitcasted shuffle, 12302 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 12303 // back to their original types. 12304 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 12305 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 12306 TLI.isTypeLegal(VT)) { 12307 12308 // Peek through the bitcast only if there is one user. 12309 SDValue BC0 = N0; 12310 while (BC0.getOpcode() == ISD::BITCAST) { 12311 if (!BC0.hasOneUse()) 12312 break; 12313 BC0 = BC0.getOperand(0); 12314 } 12315 12316 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 12317 if (Scale == 1) 12318 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 12319 12320 SmallVector<int, 8> NewMask; 12321 for (int M : Mask) 12322 for (int s = 0; s != Scale; ++s) 12323 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 12324 return NewMask; 12325 }; 12326 12327 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 12328 EVT SVT = VT.getScalarType(); 12329 EVT InnerVT = BC0->getValueType(0); 12330 EVT InnerSVT = InnerVT.getScalarType(); 12331 12332 // Determine which shuffle works with the smaller scalar type. 12333 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 12334 EVT ScaleSVT = ScaleVT.getScalarType(); 12335 12336 if (TLI.isTypeLegal(ScaleVT) && 12337 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 12338 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 12339 12340 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 12341 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 12342 12343 // Scale the shuffle masks to the smaller scalar type. 12344 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 12345 SmallVector<int, 8> InnerMask = 12346 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 12347 SmallVector<int, 8> OuterMask = 12348 ScaleShuffleMask(SVN->getMask(), OuterScale); 12349 12350 // Merge the shuffle masks. 12351 SmallVector<int, 8> NewMask; 12352 for (int M : OuterMask) 12353 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 12354 12355 // Test for shuffle mask legality over both commutations. 12356 SDValue SV0 = BC0->getOperand(0); 12357 SDValue SV1 = BC0->getOperand(1); 12358 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 12359 if (!LegalMask) { 12360 std::swap(SV0, SV1); 12361 ShuffleVectorSDNode::commuteMask(NewMask); 12362 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 12363 } 12364 12365 if (LegalMask) { 12366 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 12367 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 12368 return DAG.getNode( 12369 ISD::BITCAST, SDLoc(N), VT, 12370 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 12371 } 12372 } 12373 } 12374 } 12375 12376 // Canonicalize shuffles according to rules: 12377 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 12378 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 12379 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 12380 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 12381 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 12382 TLI.isTypeLegal(VT)) { 12383 // The incoming shuffle must be of the same type as the result of the 12384 // current shuffle. 12385 assert(N1->getOperand(0).getValueType() == VT && 12386 "Shuffle types don't match"); 12387 12388 SDValue SV0 = N1->getOperand(0); 12389 SDValue SV1 = N1->getOperand(1); 12390 bool HasSameOp0 = N0 == SV0; 12391 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 12392 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 12393 // Commute the operands of this shuffle so that next rule 12394 // will trigger. 12395 return DAG.getCommutedVectorShuffle(*SVN); 12396 } 12397 12398 // Try to fold according to rules: 12399 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12400 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12401 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12402 // Don't try to fold shuffles with illegal type. 12403 // Only fold if this shuffle is the only user of the other shuffle. 12404 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 12405 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 12406 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 12407 12408 // The incoming shuffle must be of the same type as the result of the 12409 // current shuffle. 12410 assert(OtherSV->getOperand(0).getValueType() == VT && 12411 "Shuffle types don't match"); 12412 12413 SDValue SV0, SV1; 12414 SmallVector<int, 4> Mask; 12415 // Compute the combined shuffle mask for a shuffle with SV0 as the first 12416 // operand, and SV1 as the second operand. 12417 for (unsigned i = 0; i != NumElts; ++i) { 12418 int Idx = SVN->getMaskElt(i); 12419 if (Idx < 0) { 12420 // Propagate Undef. 12421 Mask.push_back(Idx); 12422 continue; 12423 } 12424 12425 SDValue CurrentVec; 12426 if (Idx < (int)NumElts) { 12427 // This shuffle index refers to the inner shuffle N0. Lookup the inner 12428 // shuffle mask to identify which vector is actually referenced. 12429 Idx = OtherSV->getMaskElt(Idx); 12430 if (Idx < 0) { 12431 // Propagate Undef. 12432 Mask.push_back(Idx); 12433 continue; 12434 } 12435 12436 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 12437 : OtherSV->getOperand(1); 12438 } else { 12439 // This shuffle index references an element within N1. 12440 CurrentVec = N1; 12441 } 12442 12443 // Simple case where 'CurrentVec' is UNDEF. 12444 if (CurrentVec.getOpcode() == ISD::UNDEF) { 12445 Mask.push_back(-1); 12446 continue; 12447 } 12448 12449 // Canonicalize the shuffle index. We don't know yet if CurrentVec 12450 // will be the first or second operand of the combined shuffle. 12451 Idx = Idx % NumElts; 12452 if (!SV0.getNode() || SV0 == CurrentVec) { 12453 // Ok. CurrentVec is the left hand side. 12454 // Update the mask accordingly. 12455 SV0 = CurrentVec; 12456 Mask.push_back(Idx); 12457 continue; 12458 } 12459 12460 // Bail out if we cannot convert the shuffle pair into a single shuffle. 12461 if (SV1.getNode() && SV1 != CurrentVec) 12462 return SDValue(); 12463 12464 // Ok. CurrentVec is the right hand side. 12465 // Update the mask accordingly. 12466 SV1 = CurrentVec; 12467 Mask.push_back(Idx + NumElts); 12468 } 12469 12470 // Check if all indices in Mask are Undef. In case, propagate Undef. 12471 bool isUndefMask = true; 12472 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 12473 isUndefMask &= Mask[i] < 0; 12474 12475 if (isUndefMask) 12476 return DAG.getUNDEF(VT); 12477 12478 if (!SV0.getNode()) 12479 SV0 = DAG.getUNDEF(VT); 12480 if (!SV1.getNode()) 12481 SV1 = DAG.getUNDEF(VT); 12482 12483 // Avoid introducing shuffles with illegal mask. 12484 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 12485 ShuffleVectorSDNode::commuteMask(Mask); 12486 12487 if (!TLI.isShuffleMaskLegal(Mask, VT)) 12488 return SDValue(); 12489 12490 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 12491 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 12492 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 12493 std::swap(SV0, SV1); 12494 } 12495 12496 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12497 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12498 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12499 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 12500 } 12501 12502 return SDValue(); 12503 } 12504 12505 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 12506 SDValue InVal = N->getOperand(0); 12507 EVT VT = N->getValueType(0); 12508 12509 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 12510 // with a VECTOR_SHUFFLE. 12511 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12512 SDValue InVec = InVal->getOperand(0); 12513 SDValue EltNo = InVal->getOperand(1); 12514 12515 // FIXME: We could support implicit truncation if the shuffle can be 12516 // scaled to a smaller vector scalar type. 12517 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 12518 if (C0 && VT == InVec.getValueType() && 12519 VT.getScalarType() == InVal.getValueType()) { 12520 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 12521 int Elt = C0->getZExtValue(); 12522 NewMask[0] = Elt; 12523 12524 if (TLI.isShuffleMaskLegal(NewMask, VT)) 12525 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 12526 NewMask); 12527 } 12528 } 12529 12530 return SDValue(); 12531 } 12532 12533 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 12534 SDValue N0 = N->getOperand(0); 12535 SDValue N2 = N->getOperand(2); 12536 12537 // If the input vector is a concatenation, and the insert replaces 12538 // one of the halves, we can optimize into a single concat_vectors. 12539 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 12540 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 12541 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 12542 EVT VT = N->getValueType(0); 12543 12544 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12545 // (concat_vectors Z, Y) 12546 if (InsIdx == 0) 12547 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12548 N->getOperand(1), N0.getOperand(1)); 12549 12550 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12551 // (concat_vectors X, Z) 12552 if (InsIdx == VT.getVectorNumElements()/2) 12553 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12554 N0.getOperand(0), N->getOperand(1)); 12555 } 12556 12557 return SDValue(); 12558 } 12559 12560 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 12561 SDValue N0 = N->getOperand(0); 12562 12563 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 12564 if (N0->getOpcode() == ISD::FP16_TO_FP) 12565 return N0->getOperand(0); 12566 12567 return SDValue(); 12568 } 12569 12570 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 12571 /// with the destination vector and a zero vector. 12572 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 12573 /// vector_shuffle V, Zero, <0, 4, 2, 4> 12574 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 12575 EVT VT = N->getValueType(0); 12576 SDValue LHS = N->getOperand(0); 12577 SDValue RHS = N->getOperand(1); 12578 SDLoc dl(N); 12579 12580 // Make sure we're not running after operation legalization where it 12581 // may have custom lowered the vector shuffles. 12582 if (LegalOperations) 12583 return SDValue(); 12584 12585 if (N->getOpcode() != ISD::AND) 12586 return SDValue(); 12587 12588 if (RHS.getOpcode() == ISD::BITCAST) 12589 RHS = RHS.getOperand(0); 12590 12591 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 12592 SmallVector<int, 8> Indices; 12593 unsigned NumElts = RHS.getNumOperands(); 12594 12595 for (unsigned i = 0; i != NumElts; ++i) { 12596 SDValue Elt = RHS.getOperand(i); 12597 if (!isa<ConstantSDNode>(Elt)) 12598 return SDValue(); 12599 12600 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 12601 Indices.push_back(i); 12602 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 12603 Indices.push_back(NumElts+i); 12604 else 12605 return SDValue(); 12606 } 12607 12608 // Let's see if the target supports this vector_shuffle. 12609 EVT RVT = RHS.getValueType(); 12610 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 12611 return SDValue(); 12612 12613 // Return the new VECTOR_SHUFFLE node. 12614 EVT EltVT = RVT.getVectorElementType(); 12615 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 12616 DAG.getConstant(0, EltVT)); 12617 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps); 12618 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 12619 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 12620 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 12621 } 12622 12623 return SDValue(); 12624 } 12625 12626 /// Visit a binary vector operation, like ADD. 12627 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 12628 assert(N->getValueType(0).isVector() && 12629 "SimplifyVBinOp only works on vectors!"); 12630 12631 SDValue LHS = N->getOperand(0); 12632 SDValue RHS = N->getOperand(1); 12633 12634 if (SDValue Shuffle = XformToShuffleWithZero(N)) 12635 return Shuffle; 12636 12637 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 12638 // this operation. 12639 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 12640 RHS.getOpcode() == ISD::BUILD_VECTOR) { 12641 // Check if both vectors are constants. If not bail out. 12642 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 12643 cast<BuildVectorSDNode>(RHS)->isConstant())) 12644 return SDValue(); 12645 12646 SmallVector<SDValue, 8> Ops; 12647 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 12648 SDValue LHSOp = LHS.getOperand(i); 12649 SDValue RHSOp = RHS.getOperand(i); 12650 12651 // Can't fold divide by zero. 12652 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 12653 N->getOpcode() == ISD::FDIV) { 12654 if ((RHSOp.getOpcode() == ISD::Constant && 12655 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 12656 (RHSOp.getOpcode() == ISD::ConstantFP && 12657 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 12658 break; 12659 } 12660 12661 EVT VT = LHSOp.getValueType(); 12662 EVT RVT = RHSOp.getValueType(); 12663 if (RVT != VT) { 12664 // Integer BUILD_VECTOR operands may have types larger than the element 12665 // size (e.g., when the element type is not legal). Prior to type 12666 // legalization, the types may not match between the two BUILD_VECTORS. 12667 // Truncate one of the operands to make them match. 12668 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 12669 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 12670 } else { 12671 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 12672 VT = RVT; 12673 } 12674 } 12675 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 12676 LHSOp, RHSOp); 12677 if (FoldOp.getOpcode() != ISD::UNDEF && 12678 FoldOp.getOpcode() != ISD::Constant && 12679 FoldOp.getOpcode() != ISD::ConstantFP) 12680 break; 12681 Ops.push_back(FoldOp); 12682 AddToWorklist(FoldOp.getNode()); 12683 } 12684 12685 if (Ops.size() == LHS.getNumOperands()) 12686 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 12687 } 12688 12689 // Type legalization might introduce new shuffles in the DAG. 12690 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 12691 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 12692 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 12693 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 12694 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 12695 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 12696 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 12697 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 12698 12699 if (SVN0->getMask().equals(SVN1->getMask())) { 12700 EVT VT = N->getValueType(0); 12701 SDValue UndefVector = LHS.getOperand(1); 12702 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 12703 LHS.getOperand(0), RHS.getOperand(0)); 12704 AddUsersToWorklist(N); 12705 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 12706 &SVN0->getMask()[0]); 12707 } 12708 } 12709 12710 return SDValue(); 12711 } 12712 12713 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 12714 SDValue N1, SDValue N2){ 12715 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 12716 12717 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 12718 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 12719 12720 // If we got a simplified select_cc node back from SimplifySelectCC, then 12721 // break it down into a new SETCC node, and a new SELECT node, and then return 12722 // the SELECT node, since we were called with a SELECT node. 12723 if (SCC.getNode()) { 12724 // Check to see if we got a select_cc back (to turn into setcc/select). 12725 // Otherwise, just return whatever node we got back, like fabs. 12726 if (SCC.getOpcode() == ISD::SELECT_CC) { 12727 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 12728 N0.getValueType(), 12729 SCC.getOperand(0), SCC.getOperand(1), 12730 SCC.getOperand(4)); 12731 AddToWorklist(SETCC.getNode()); 12732 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 12733 SCC.getOperand(2), SCC.getOperand(3)); 12734 } 12735 12736 return SCC; 12737 } 12738 return SDValue(); 12739 } 12740 12741 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 12742 /// being selected between, see if we can simplify the select. Callers of this 12743 /// should assume that TheSelect is deleted if this returns true. As such, they 12744 /// should return the appropriate thing (e.g. the node) back to the top-level of 12745 /// the DAG combiner loop to avoid it being looked at. 12746 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 12747 SDValue RHS) { 12748 12749 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 12750 // The select + setcc is redundant, because fsqrt returns NaN for X < -0. 12751 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 12752 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 12753 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 12754 SDValue Sqrt = RHS; 12755 ISD::CondCode CC; 12756 SDValue CmpLHS; 12757 const ConstantFPSDNode *NegZero = nullptr; 12758 12759 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 12760 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 12761 CmpLHS = TheSelect->getOperand(0); 12762 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 12763 } else { 12764 // SELECT or VSELECT 12765 SDValue Cmp = TheSelect->getOperand(0); 12766 if (Cmp.getOpcode() == ISD::SETCC) { 12767 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 12768 CmpLHS = Cmp.getOperand(0); 12769 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1)); 12770 } 12771 } 12772 if (NegZero && NegZero->isNegative() && NegZero->isZero() && 12773 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 12774 CC == ISD::SETULT || CC == ISD::SETLT)) { 12775 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 12776 CombineTo(TheSelect, Sqrt); 12777 return true; 12778 } 12779 } 12780 } 12781 // Cannot simplify select with vector condition 12782 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 12783 12784 // If this is a select from two identical things, try to pull the operation 12785 // through the select. 12786 if (LHS.getOpcode() != RHS.getOpcode() || 12787 !LHS.hasOneUse() || !RHS.hasOneUse()) 12788 return false; 12789 12790 // If this is a load and the token chain is identical, replace the select 12791 // of two loads with a load through a select of the address to load from. 12792 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 12793 // constants have been dropped into the constant pool. 12794 if (LHS.getOpcode() == ISD::LOAD) { 12795 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 12796 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 12797 12798 // Token chains must be identical. 12799 if (LHS.getOperand(0) != RHS.getOperand(0) || 12800 // Do not let this transformation reduce the number of volatile loads. 12801 LLD->isVolatile() || RLD->isVolatile() || 12802 // If this is an EXTLOAD, the VT's must match. 12803 LLD->getMemoryVT() != RLD->getMemoryVT() || 12804 // If this is an EXTLOAD, the kind of extension must match. 12805 (LLD->getExtensionType() != RLD->getExtensionType() && 12806 // The only exception is if one of the extensions is anyext. 12807 LLD->getExtensionType() != ISD::EXTLOAD && 12808 RLD->getExtensionType() != ISD::EXTLOAD) || 12809 // FIXME: this discards src value information. This is 12810 // over-conservative. It would be beneficial to be able to remember 12811 // both potential memory locations. Since we are discarding 12812 // src value info, don't do the transformation if the memory 12813 // locations are not in the default address space. 12814 LLD->getPointerInfo().getAddrSpace() != 0 || 12815 RLD->getPointerInfo().getAddrSpace() != 0 || 12816 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 12817 LLD->getBasePtr().getValueType())) 12818 return false; 12819 12820 // Check that the select condition doesn't reach either load. If so, 12821 // folding this will induce a cycle into the DAG. If not, this is safe to 12822 // xform, so create a select of the addresses. 12823 SDValue Addr; 12824 if (TheSelect->getOpcode() == ISD::SELECT) { 12825 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 12826 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 12827 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 12828 return false; 12829 // The loads must not depend on one another. 12830 if (LLD->isPredecessorOf(RLD) || 12831 RLD->isPredecessorOf(LLD)) 12832 return false; 12833 Addr = DAG.getSelect(SDLoc(TheSelect), 12834 LLD->getBasePtr().getValueType(), 12835 TheSelect->getOperand(0), LLD->getBasePtr(), 12836 RLD->getBasePtr()); 12837 } else { // Otherwise SELECT_CC 12838 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 12839 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 12840 12841 if ((LLD->hasAnyUseOfValue(1) && 12842 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 12843 (RLD->hasAnyUseOfValue(1) && 12844 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 12845 return false; 12846 12847 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 12848 LLD->getBasePtr().getValueType(), 12849 TheSelect->getOperand(0), 12850 TheSelect->getOperand(1), 12851 LLD->getBasePtr(), RLD->getBasePtr(), 12852 TheSelect->getOperand(4)); 12853 } 12854 12855 SDValue Load; 12856 // It is safe to replace the two loads if they have different alignments, 12857 // but the new load must be the minimum (most restrictive) alignment of the 12858 // inputs. 12859 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 12860 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 12861 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 12862 Load = DAG.getLoad(TheSelect->getValueType(0), 12863 SDLoc(TheSelect), 12864 // FIXME: Discards pointer and AA info. 12865 LLD->getChain(), Addr, MachinePointerInfo(), 12866 LLD->isVolatile(), LLD->isNonTemporal(), 12867 isInvariant, Alignment); 12868 } else { 12869 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 12870 RLD->getExtensionType() : LLD->getExtensionType(), 12871 SDLoc(TheSelect), 12872 TheSelect->getValueType(0), 12873 // FIXME: Discards pointer and AA info. 12874 LLD->getChain(), Addr, MachinePointerInfo(), 12875 LLD->getMemoryVT(), LLD->isVolatile(), 12876 LLD->isNonTemporal(), isInvariant, Alignment); 12877 } 12878 12879 // Users of the select now use the result of the load. 12880 CombineTo(TheSelect, Load); 12881 12882 // Users of the old loads now use the new load's chain. We know the 12883 // old-load value is dead now. 12884 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 12885 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 12886 return true; 12887 } 12888 12889 return false; 12890 } 12891 12892 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 12893 /// where 'cond' is the comparison specified by CC. 12894 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 12895 SDValue N2, SDValue N3, 12896 ISD::CondCode CC, bool NotExtCompare) { 12897 // (x ? y : y) -> y. 12898 if (N2 == N3) return N2; 12899 12900 EVT VT = N2.getValueType(); 12901 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 12902 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 12903 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 12904 12905 // Determine if the condition we're dealing with is constant 12906 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 12907 N0, N1, CC, DL, false); 12908 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 12909 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 12910 12911 // fold select_cc true, x, y -> x 12912 if (SCCC && !SCCC->isNullValue()) 12913 return N2; 12914 // fold select_cc false, x, y -> y 12915 if (SCCC && SCCC->isNullValue()) 12916 return N3; 12917 12918 // Check to see if we can simplify the select into an fabs node 12919 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 12920 // Allow either -0.0 or 0.0 12921 if (CFP->getValueAPF().isZero()) { 12922 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 12923 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 12924 N0 == N2 && N3.getOpcode() == ISD::FNEG && 12925 N2 == N3.getOperand(0)) 12926 return DAG.getNode(ISD::FABS, DL, VT, N0); 12927 12928 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 12929 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 12930 N0 == N3 && N2.getOpcode() == ISD::FNEG && 12931 N2.getOperand(0) == N3) 12932 return DAG.getNode(ISD::FABS, DL, VT, N3); 12933 } 12934 } 12935 12936 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 12937 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 12938 // in it. This is a win when the constant is not otherwise available because 12939 // it replaces two constant pool loads with one. We only do this if the FP 12940 // type is known to be legal, because if it isn't, then we are before legalize 12941 // types an we want the other legalization to happen first (e.g. to avoid 12942 // messing with soft float) and if the ConstantFP is not legal, because if 12943 // it is legal, we may not need to store the FP constant in a constant pool. 12944 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 12945 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 12946 if (TLI.isTypeLegal(N2.getValueType()) && 12947 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 12948 TargetLowering::Legal && 12949 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 12950 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 12951 // If both constants have multiple uses, then we won't need to do an 12952 // extra load, they are likely around in registers for other users. 12953 (TV->hasOneUse() || FV->hasOneUse())) { 12954 Constant *Elts[] = { 12955 const_cast<ConstantFP*>(FV->getConstantFPValue()), 12956 const_cast<ConstantFP*>(TV->getConstantFPValue()) 12957 }; 12958 Type *FPTy = Elts[0]->getType(); 12959 const DataLayout &TD = *TLI.getDataLayout(); 12960 12961 // Create a ConstantArray of the two constants. 12962 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 12963 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 12964 TD.getPrefTypeAlignment(FPTy)); 12965 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 12966 12967 // Get the offsets to the 0 and 1 element of the array so that we can 12968 // select between them. 12969 SDValue Zero = DAG.getIntPtrConstant(0); 12970 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 12971 SDValue One = DAG.getIntPtrConstant(EltSize); 12972 12973 SDValue Cond = DAG.getSetCC(DL, 12974 getSetCCResultType(N0.getValueType()), 12975 N0, N1, CC); 12976 AddToWorklist(Cond.getNode()); 12977 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 12978 Cond, One, Zero); 12979 AddToWorklist(CstOffset.getNode()); 12980 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 12981 CstOffset); 12982 AddToWorklist(CPIdx.getNode()); 12983 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 12984 MachinePointerInfo::getConstantPool(), false, 12985 false, false, Alignment); 12986 12987 } 12988 } 12989 12990 // Check to see if we can perform the "gzip trick", transforming 12991 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 12992 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 12993 (N1C->isNullValue() || // (a < 0) ? b : 0 12994 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 12995 EVT XType = N0.getValueType(); 12996 EVT AType = N2.getValueType(); 12997 if (XType.bitsGE(AType)) { 12998 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 12999 // single-bit constant. 13000 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 13001 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 13002 ShCtV = XType.getSizeInBits()-ShCtV-1; 13003 SDValue ShCt = DAG.getConstant(ShCtV, 13004 getShiftAmountTy(N0.getValueType())); 13005 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 13006 XType, N0, ShCt); 13007 AddToWorklist(Shift.getNode()); 13008 13009 if (XType.bitsGT(AType)) { 13010 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13011 AddToWorklist(Shift.getNode()); 13012 } 13013 13014 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13015 } 13016 13017 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 13018 XType, N0, 13019 DAG.getConstant(XType.getSizeInBits()-1, 13020 getShiftAmountTy(N0.getValueType()))); 13021 AddToWorklist(Shift.getNode()); 13022 13023 if (XType.bitsGT(AType)) { 13024 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13025 AddToWorklist(Shift.getNode()); 13026 } 13027 13028 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13029 } 13030 } 13031 13032 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 13033 // where y is has a single bit set. 13034 // A plaintext description would be, we can turn the SELECT_CC into an AND 13035 // when the condition can be materialized as an all-ones register. Any 13036 // single bit-test can be materialized as an all-ones register with 13037 // shift-left and shift-right-arith. 13038 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 13039 N0->getValueType(0) == VT && 13040 N1C && N1C->isNullValue() && 13041 N2C && N2C->isNullValue()) { 13042 SDValue AndLHS = N0->getOperand(0); 13043 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13044 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 13045 // Shift the tested bit over the sign bit. 13046 APInt AndMask = ConstAndRHS->getAPIntValue(); 13047 SDValue ShlAmt = 13048 DAG.getConstant(AndMask.countLeadingZeros(), 13049 getShiftAmountTy(AndLHS.getValueType())); 13050 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 13051 13052 // Now arithmetic right shift it all the way over, so the result is either 13053 // all-ones, or zero. 13054 SDValue ShrAmt = 13055 DAG.getConstant(AndMask.getBitWidth()-1, 13056 getShiftAmountTy(Shl.getValueType())); 13057 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 13058 13059 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 13060 } 13061 } 13062 13063 // fold select C, 16, 0 -> shl C, 4 13064 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 13065 TLI.getBooleanContents(N0.getValueType()) == 13066 TargetLowering::ZeroOrOneBooleanContent) { 13067 13068 // If the caller doesn't want us to simplify this into a zext of a compare, 13069 // don't do it. 13070 if (NotExtCompare && N2C->getAPIntValue() == 1) 13071 return SDValue(); 13072 13073 // Get a SetCC of the condition 13074 // NOTE: Don't create a SETCC if it's not legal on this target. 13075 if (!LegalOperations || 13076 TLI.isOperationLegal(ISD::SETCC, 13077 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 13078 SDValue Temp, SCC; 13079 // cast from setcc result type to select result type 13080 if (LegalTypes) { 13081 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 13082 N0, N1, CC); 13083 if (N2.getValueType().bitsLT(SCC.getValueType())) 13084 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 13085 N2.getValueType()); 13086 else 13087 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13088 N2.getValueType(), SCC); 13089 } else { 13090 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 13091 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13092 N2.getValueType(), SCC); 13093 } 13094 13095 AddToWorklist(SCC.getNode()); 13096 AddToWorklist(Temp.getNode()); 13097 13098 if (N2C->getAPIntValue() == 1) 13099 return Temp; 13100 13101 // shl setcc result by log2 n2c 13102 return DAG.getNode( 13103 ISD::SHL, DL, N2.getValueType(), Temp, 13104 DAG.getConstant(N2C->getAPIntValue().logBase2(), 13105 getShiftAmountTy(Temp.getValueType()))); 13106 } 13107 } 13108 13109 // Check to see if this is the equivalent of setcc 13110 // FIXME: Turn all of these into setcc if setcc if setcc is legal 13111 // otherwise, go ahead with the folds. 13112 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 13113 EVT XType = N0.getValueType(); 13114 if (!LegalOperations || 13115 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 13116 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 13117 if (Res.getValueType() != VT) 13118 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 13119 return Res; 13120 } 13121 13122 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 13123 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 13124 (!LegalOperations || 13125 TLI.isOperationLegal(ISD::CTLZ, XType))) { 13126 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 13127 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 13128 DAG.getConstant(Log2_32(XType.getSizeInBits()), 13129 getShiftAmountTy(Ctlz.getValueType()))); 13130 } 13131 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 13132 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 13133 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 13134 XType, DAG.getConstant(0, XType), N0); 13135 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 13136 return DAG.getNode(ISD::SRL, DL, XType, 13137 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 13138 DAG.getConstant(XType.getSizeInBits()-1, 13139 getShiftAmountTy(XType))); 13140 } 13141 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 13142 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 13143 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 13144 DAG.getConstant(XType.getSizeInBits()-1, 13145 getShiftAmountTy(N0.getValueType()))); 13146 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 13147 } 13148 } 13149 13150 // Check to see if this is an integer abs. 13151 // select_cc setg[te] X, 0, X, -X -> 13152 // select_cc setgt X, -1, X, -X -> 13153 // select_cc setl[te] X, 0, -X, X -> 13154 // select_cc setlt X, 1, -X, X -> 13155 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 13156 if (N1C) { 13157 ConstantSDNode *SubC = nullptr; 13158 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 13159 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 13160 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 13161 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 13162 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 13163 (N1C->isOne() && CC == ISD::SETLT)) && 13164 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 13165 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 13166 13167 EVT XType = N0.getValueType(); 13168 if (SubC && SubC->isNullValue() && XType.isInteger()) { 13169 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 13170 N0, 13171 DAG.getConstant(XType.getSizeInBits()-1, 13172 getShiftAmountTy(N0.getValueType()))); 13173 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 13174 XType, N0, Shift); 13175 AddToWorklist(Shift.getNode()); 13176 AddToWorklist(Add.getNode()); 13177 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 13178 } 13179 } 13180 13181 return SDValue(); 13182 } 13183 13184 /// This is a stub for TargetLowering::SimplifySetCC. 13185 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 13186 SDValue N1, ISD::CondCode Cond, 13187 SDLoc DL, bool foldBooleans) { 13188 TargetLowering::DAGCombinerInfo 13189 DagCombineInfo(DAG, Level, false, this); 13190 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 13191 } 13192 13193 /// Given an ISD::SDIV node expressing a divide by constant, return 13194 /// a DAG expression to select that will generate the same value by multiplying 13195 /// by a magic number. 13196 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 13197 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 13198 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13199 if (!C) 13200 return SDValue(); 13201 13202 // Avoid division by zero. 13203 if (!C->getAPIntValue()) 13204 return SDValue(); 13205 13206 std::vector<SDNode*> Built; 13207 SDValue S = 13208 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 13209 13210 for (SDNode *N : Built) 13211 AddToWorklist(N); 13212 return S; 13213 } 13214 13215 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 13216 /// DAG expression that will generate the same value by right shifting. 13217 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 13218 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13219 if (!C) 13220 return SDValue(); 13221 13222 // Avoid division by zero. 13223 if (!C->getAPIntValue()) 13224 return SDValue(); 13225 13226 std::vector<SDNode *> Built; 13227 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 13228 13229 for (SDNode *N : Built) 13230 AddToWorklist(N); 13231 return S; 13232 } 13233 13234 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 13235 /// expression that will generate the same value by multiplying by a magic 13236 /// number. 13237 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 13238 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 13239 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13240 if (!C) 13241 return SDValue(); 13242 13243 // Avoid division by zero. 13244 if (!C->getAPIntValue()) 13245 return SDValue(); 13246 13247 std::vector<SDNode*> Built; 13248 SDValue S = 13249 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 13250 13251 for (SDNode *N : Built) 13252 AddToWorklist(N); 13253 return S; 13254 } 13255 13256 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) { 13257 if (Level >= AfterLegalizeDAG) 13258 return SDValue(); 13259 13260 // Expose the DAG combiner to the target combiner implementations. 13261 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 13262 13263 unsigned Iterations = 0; 13264 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 13265 if (Iterations) { 13266 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13267 // For the reciprocal, we need to find the zero of the function: 13268 // F(X) = A X - 1 [which has a zero at X = 1/A] 13269 // => 13270 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 13271 // does not require additional intermediate precision] 13272 EVT VT = Op.getValueType(); 13273 SDLoc DL(Op); 13274 SDValue FPOne = DAG.getConstantFP(1.0, VT); 13275 13276 AddToWorklist(Est.getNode()); 13277 13278 // Newton iterations: Est = Est + Est (1 - Arg * Est) 13279 for (unsigned i = 0; i < Iterations; ++i) { 13280 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est); 13281 AddToWorklist(NewEst.getNode()); 13282 13283 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst); 13284 AddToWorklist(NewEst.getNode()); 13285 13286 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 13287 AddToWorklist(NewEst.getNode()); 13288 13289 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst); 13290 AddToWorklist(Est.getNode()); 13291 } 13292 } 13293 return Est; 13294 } 13295 13296 return SDValue(); 13297 } 13298 13299 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13300 /// For the reciprocal sqrt, we need to find the zero of the function: 13301 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 13302 /// => 13303 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 13304 /// As a result, we precompute A/2 prior to the iteration loop. 13305 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 13306 unsigned Iterations) { 13307 EVT VT = Arg.getValueType(); 13308 SDLoc DL(Arg); 13309 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT); 13310 13311 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 13312 // this entire sequence requires only one FP constant. 13313 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg); 13314 AddToWorklist(HalfArg.getNode()); 13315 13316 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg); 13317 AddToWorklist(HalfArg.getNode()); 13318 13319 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 13320 for (unsigned i = 0; i < Iterations; ++i) { 13321 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 13322 AddToWorklist(NewEst.getNode()); 13323 13324 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst); 13325 AddToWorklist(NewEst.getNode()); 13326 13327 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst); 13328 AddToWorklist(NewEst.getNode()); 13329 13330 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 13331 AddToWorklist(Est.getNode()); 13332 } 13333 return Est; 13334 } 13335 13336 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13337 /// For the reciprocal sqrt, we need to find the zero of the function: 13338 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 13339 /// => 13340 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 13341 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 13342 unsigned Iterations) { 13343 EVT VT = Arg.getValueType(); 13344 SDLoc DL(Arg); 13345 SDValue MinusThree = DAG.getConstantFP(-3.0, VT); 13346 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT); 13347 13348 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 13349 for (unsigned i = 0; i < Iterations; ++i) { 13350 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf); 13351 AddToWorklist(HalfEst.getNode()); 13352 13353 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 13354 AddToWorklist(Est.getNode()); 13355 13356 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg); 13357 AddToWorklist(Est.getNode()); 13358 13359 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree); 13360 AddToWorklist(Est.getNode()); 13361 13362 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst); 13363 AddToWorklist(Est.getNode()); 13364 } 13365 return Est; 13366 } 13367 13368 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) { 13369 if (Level >= AfterLegalizeDAG) 13370 return SDValue(); 13371 13372 // Expose the DAG combiner to the target combiner implementations. 13373 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 13374 unsigned Iterations = 0; 13375 bool UseOneConstNR = false; 13376 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 13377 AddToWorklist(Est.getNode()); 13378 if (Iterations) { 13379 Est = UseOneConstNR ? 13380 BuildRsqrtNROneConst(Op, Est, Iterations) : 13381 BuildRsqrtNRTwoConst(Op, Est, Iterations); 13382 } 13383 return Est; 13384 } 13385 13386 return SDValue(); 13387 } 13388 13389 /// Return true if base is a frame index, which is known not to alias with 13390 /// anything but itself. Provides base object and offset as results. 13391 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 13392 const GlobalValue *&GV, const void *&CV) { 13393 // Assume it is a primitive operation. 13394 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 13395 13396 // If it's an adding a simple constant then integrate the offset. 13397 if (Base.getOpcode() == ISD::ADD) { 13398 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 13399 Base = Base.getOperand(0); 13400 Offset += C->getZExtValue(); 13401 } 13402 } 13403 13404 // Return the underlying GlobalValue, and update the Offset. Return false 13405 // for GlobalAddressSDNode since the same GlobalAddress may be represented 13406 // by multiple nodes with different offsets. 13407 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 13408 GV = G->getGlobal(); 13409 Offset += G->getOffset(); 13410 return false; 13411 } 13412 13413 // Return the underlying Constant value, and update the Offset. Return false 13414 // for ConstantSDNodes since the same constant pool entry may be represented 13415 // by multiple nodes with different offsets. 13416 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 13417 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 13418 : (const void *)C->getConstVal(); 13419 Offset += C->getOffset(); 13420 return false; 13421 } 13422 // If it's any of the following then it can't alias with anything but itself. 13423 return isa<FrameIndexSDNode>(Base); 13424 } 13425 13426 /// Return true if there is any possibility that the two addresses overlap. 13427 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 13428 // If they are the same then they must be aliases. 13429 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 13430 13431 // If they are both volatile then they cannot be reordered. 13432 if (Op0->isVolatile() && Op1->isVolatile()) return true; 13433 13434 // Gather base node and offset information. 13435 SDValue Base1, Base2; 13436 int64_t Offset1, Offset2; 13437 const GlobalValue *GV1, *GV2; 13438 const void *CV1, *CV2; 13439 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 13440 Base1, Offset1, GV1, CV1); 13441 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 13442 Base2, Offset2, GV2, CV2); 13443 13444 // If they have a same base address then check to see if they overlap. 13445 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 13446 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 13447 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 13448 13449 // It is possible for different frame indices to alias each other, mostly 13450 // when tail call optimization reuses return address slots for arguments. 13451 // To catch this case, look up the actual index of frame indices to compute 13452 // the real alias relationship. 13453 if (isFrameIndex1 && isFrameIndex2) { 13454 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 13455 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 13456 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 13457 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 13458 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 13459 } 13460 13461 // Otherwise, if we know what the bases are, and they aren't identical, then 13462 // we know they cannot alias. 13463 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 13464 return false; 13465 13466 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 13467 // compared to the size and offset of the access, we may be able to prove they 13468 // do not alias. This check is conservative for now to catch cases created by 13469 // splitting vector types. 13470 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 13471 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 13472 (Op0->getMemoryVT().getSizeInBits() >> 3 == 13473 Op1->getMemoryVT().getSizeInBits() >> 3) && 13474 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 13475 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 13476 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 13477 13478 // There is no overlap between these relatively aligned accesses of similar 13479 // size, return no alias. 13480 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 13481 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 13482 return false; 13483 } 13484 13485 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 13486 ? CombinerGlobalAA 13487 : DAG.getSubtarget().useAA(); 13488 #ifndef NDEBUG 13489 if (CombinerAAOnlyFunc.getNumOccurrences() && 13490 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 13491 UseAA = false; 13492 #endif 13493 if (UseAA && 13494 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 13495 // Use alias analysis information. 13496 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 13497 Op1->getSrcValueOffset()); 13498 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 13499 Op0->getSrcValueOffset() - MinOffset; 13500 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 13501 Op1->getSrcValueOffset() - MinOffset; 13502 AliasAnalysis::AliasResult AAResult = 13503 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(), 13504 Overlap1, 13505 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 13506 AliasAnalysis::Location(Op1->getMemOperand()->getValue(), 13507 Overlap2, 13508 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 13509 if (AAResult == AliasAnalysis::NoAlias) 13510 return false; 13511 } 13512 13513 // Otherwise we have to assume they alias. 13514 return true; 13515 } 13516 13517 /// Walk up chain skipping non-aliasing memory nodes, 13518 /// looking for aliasing nodes and adding them to the Aliases vector. 13519 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 13520 SmallVectorImpl<SDValue> &Aliases) { 13521 SmallVector<SDValue, 8> Chains; // List of chains to visit. 13522 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 13523 13524 // Get alias information for node. 13525 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 13526 13527 // Starting off. 13528 Chains.push_back(OriginalChain); 13529 unsigned Depth = 0; 13530 13531 // Look at each chain and determine if it is an alias. If so, add it to the 13532 // aliases list. If not, then continue up the chain looking for the next 13533 // candidate. 13534 while (!Chains.empty()) { 13535 SDValue Chain = Chains.back(); 13536 Chains.pop_back(); 13537 13538 // For TokenFactor nodes, look at each operand and only continue up the 13539 // chain until we find two aliases. If we've seen two aliases, assume we'll 13540 // find more and revert to original chain since the xform is unlikely to be 13541 // profitable. 13542 // 13543 // FIXME: The depth check could be made to return the last non-aliasing 13544 // chain we found before we hit a tokenfactor rather than the original 13545 // chain. 13546 if (Depth > 6 || Aliases.size() == 2) { 13547 Aliases.clear(); 13548 Aliases.push_back(OriginalChain); 13549 return; 13550 } 13551 13552 // Don't bother if we've been before. 13553 if (!Visited.insert(Chain.getNode()).second) 13554 continue; 13555 13556 switch (Chain.getOpcode()) { 13557 case ISD::EntryToken: 13558 // Entry token is ideal chain operand, but handled in FindBetterChain. 13559 break; 13560 13561 case ISD::LOAD: 13562 case ISD::STORE: { 13563 // Get alias information for Chain. 13564 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 13565 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 13566 13567 // If chain is alias then stop here. 13568 if (!(IsLoad && IsOpLoad) && 13569 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 13570 Aliases.push_back(Chain); 13571 } else { 13572 // Look further up the chain. 13573 Chains.push_back(Chain.getOperand(0)); 13574 ++Depth; 13575 } 13576 break; 13577 } 13578 13579 case ISD::TokenFactor: 13580 // We have to check each of the operands of the token factor for "small" 13581 // token factors, so we queue them up. Adding the operands to the queue 13582 // (stack) in reverse order maintains the original order and increases the 13583 // likelihood that getNode will find a matching token factor (CSE.) 13584 if (Chain.getNumOperands() > 16) { 13585 Aliases.push_back(Chain); 13586 break; 13587 } 13588 for (unsigned n = Chain.getNumOperands(); n;) 13589 Chains.push_back(Chain.getOperand(--n)); 13590 ++Depth; 13591 break; 13592 13593 default: 13594 // For all other instructions we will just have to take what we can get. 13595 Aliases.push_back(Chain); 13596 break; 13597 } 13598 } 13599 13600 // We need to be careful here to also search for aliases through the 13601 // value operand of a store, etc. Consider the following situation: 13602 // Token1 = ... 13603 // L1 = load Token1, %52 13604 // S1 = store Token1, L1, %51 13605 // L2 = load Token1, %52+8 13606 // S2 = store Token1, L2, %51+8 13607 // Token2 = Token(S1, S2) 13608 // L3 = load Token2, %53 13609 // S3 = store Token2, L3, %52 13610 // L4 = load Token2, %53+8 13611 // S4 = store Token2, L4, %52+8 13612 // If we search for aliases of S3 (which loads address %52), and we look 13613 // only through the chain, then we'll miss the trivial dependence on L1 13614 // (which also loads from %52). We then might change all loads and 13615 // stores to use Token1 as their chain operand, which could result in 13616 // copying %53 into %52 before copying %52 into %51 (which should 13617 // happen first). 13618 // 13619 // The problem is, however, that searching for such data dependencies 13620 // can become expensive, and the cost is not directly related to the 13621 // chain depth. Instead, we'll rule out such configurations here by 13622 // insisting that we've visited all chain users (except for users 13623 // of the original chain, which is not necessary). When doing this, 13624 // we need to look through nodes we don't care about (otherwise, things 13625 // like register copies will interfere with trivial cases). 13626 13627 SmallVector<const SDNode *, 16> Worklist; 13628 for (const SDNode *N : Visited) 13629 if (N != OriginalChain.getNode()) 13630 Worklist.push_back(N); 13631 13632 while (!Worklist.empty()) { 13633 const SDNode *M = Worklist.pop_back_val(); 13634 13635 // We have already visited M, and want to make sure we've visited any uses 13636 // of M that we care about. For uses that we've not visisted, and don't 13637 // care about, queue them to the worklist. 13638 13639 for (SDNode::use_iterator UI = M->use_begin(), 13640 UIE = M->use_end(); UI != UIE; ++UI) 13641 if (UI.getUse().getValueType() == MVT::Other && 13642 Visited.insert(*UI).second) { 13643 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 13644 // We've not visited this use, and we care about it (it could have an 13645 // ordering dependency with the original node). 13646 Aliases.clear(); 13647 Aliases.push_back(OriginalChain); 13648 return; 13649 } 13650 13651 // We've not visited this use, but we don't care about it. Mark it as 13652 // visited and enqueue it to the worklist. 13653 Worklist.push_back(*UI); 13654 } 13655 } 13656 } 13657 13658 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 13659 /// (aliasing node.) 13660 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 13661 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 13662 13663 // Accumulate all the aliases to this node. 13664 GatherAllAliases(N, OldChain, Aliases); 13665 13666 // If no operands then chain to entry token. 13667 if (Aliases.size() == 0) 13668 return DAG.getEntryNode(); 13669 13670 // If a single operand then chain to it. We don't need to revisit it. 13671 if (Aliases.size() == 1) 13672 return Aliases[0]; 13673 13674 // Construct a custom tailored token factor. 13675 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 13676 } 13677 13678 /// This is the entry point for the file. 13679 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 13680 CodeGenOpt::Level OptLevel) { 13681 /// This is the main entry point to this class. 13682 DAGCombiner(*this, AA, OptLevel).Run(Level); 13683 } 13684