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 311 SDValue XformToShuffleWithZero(SDNode *N); 312 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 313 314 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 315 316 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 317 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 318 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 319 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 320 SDValue N3, ISD::CondCode CC, 321 bool NotExtCompare = false); 322 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 323 SDLoc DL, bool foldBooleans = true); 324 325 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 326 SDValue &CC) const; 327 bool isOneUseSetCC(SDValue N) const; 328 329 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 330 unsigned HiOp); 331 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 332 SDValue CombineExtLoad(SDNode *N); 333 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 334 SDValue BuildSDIV(SDNode *N); 335 SDValue BuildSDIVPow2(SDNode *N); 336 SDValue BuildUDIV(SDNode *N); 337 SDValue BuildReciprocalEstimate(SDValue Op); 338 SDValue BuildRsqrtEstimate(SDValue Op); 339 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations); 340 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations); 341 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 342 bool DemandHighBits = true); 343 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 344 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 345 SDValue InnerPos, SDValue InnerNeg, 346 unsigned PosOpcode, unsigned NegOpcode, 347 SDLoc DL); 348 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 349 SDValue ReduceLoadWidth(SDNode *N); 350 SDValue ReduceLoadOpStoreWidth(SDNode *N); 351 SDValue TransformFPLoadStorePair(SDNode *N); 352 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 353 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 354 355 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 356 357 /// Walk up chain skipping non-aliasing memory nodes, 358 /// looking for aliasing nodes and adding them to the Aliases vector. 359 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 360 SmallVectorImpl<SDValue> &Aliases); 361 362 /// Return true if there is any possibility that the two addresses overlap. 363 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 364 365 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 366 /// chain (aliasing node.) 367 SDValue FindBetterChain(SDNode *N, SDValue Chain); 368 369 /// Holds a pointer to an LSBaseSDNode as well as information on where it 370 /// is located in a sequence of memory operations connected by a chain. 371 struct MemOpLink { 372 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 373 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 374 // Ptr to the mem node. 375 LSBaseSDNode *MemNode; 376 // Offset from the base ptr. 377 int64_t OffsetFromBase; 378 // What is the sequence number of this mem node. 379 // Lowest mem operand in the DAG starts at zero. 380 unsigned SequenceNum; 381 }; 382 383 /// This is a helper function for MergeConsecutiveStores. When the source 384 /// elements of the consecutive stores are all constants or all extracted 385 /// vector elements, try to merge them into one larger store. 386 /// \return True if a merged store was created. 387 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 388 EVT MemVT, unsigned NumElem, 389 bool IsConstantSrc, bool UseVector); 390 391 /// Merge consecutive store operations into a wide store. 392 /// This optimization uses wide integers or vectors when possible. 393 /// \return True if some memory operations were changed. 394 bool MergeConsecutiveStores(StoreSDNode *N); 395 396 /// \brief Try to transform a truncation where C is a constant: 397 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 398 /// 399 /// \p N needs to be a truncation and its first operand an AND. Other 400 /// requirements are checked by the function (e.g. that trunc is 401 /// single-use) and if missed an empty SDValue is returned. 402 SDValue distributeTruncateThroughAnd(SDNode *N); 403 404 public: 405 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 406 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 407 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 408 auto *F = DAG.getMachineFunction().getFunction(); 409 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) || 410 F->hasFnAttribute(Attribute::MinSize); 411 } 412 413 /// Runs the dag combiner on all nodes in the work list 414 void Run(CombineLevel AtLevel); 415 416 SelectionDAG &getDAG() const { return DAG; } 417 418 /// Returns a type large enough to hold any valid shift amount - before type 419 /// legalization these can be huge. 420 EVT getShiftAmountTy(EVT LHSTy) { 421 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 422 if (LHSTy.isVector()) 423 return LHSTy; 424 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 425 : TLI.getPointerTy(); 426 } 427 428 /// This method returns true if we are running before type legalization or 429 /// if the specified VT is legal. 430 bool isTypeLegal(const EVT &VT) { 431 if (!LegalTypes) return true; 432 return TLI.isTypeLegal(VT); 433 } 434 435 /// Convenience wrapper around TargetLowering::getSetCCResultType 436 EVT getSetCCResultType(EVT VT) const { 437 return TLI.getSetCCResultType(*DAG.getContext(), VT); 438 } 439 }; 440 } 441 442 443 namespace { 444 /// This class is a DAGUpdateListener that removes any deleted 445 /// nodes from the worklist. 446 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 447 DAGCombiner &DC; 448 public: 449 explicit WorklistRemover(DAGCombiner &dc) 450 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 451 452 void NodeDeleted(SDNode *N, SDNode *E) override { 453 DC.removeFromWorklist(N); 454 } 455 }; 456 } 457 458 //===----------------------------------------------------------------------===// 459 // TargetLowering::DAGCombinerInfo implementation 460 //===----------------------------------------------------------------------===// 461 462 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 463 ((DAGCombiner*)DC)->AddToWorklist(N); 464 } 465 466 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 467 ((DAGCombiner*)DC)->removeFromWorklist(N); 468 } 469 470 SDValue TargetLowering::DAGCombinerInfo:: 471 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 472 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 473 } 474 475 SDValue TargetLowering::DAGCombinerInfo:: 476 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 477 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 478 } 479 480 481 SDValue TargetLowering::DAGCombinerInfo:: 482 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 483 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 484 } 485 486 void TargetLowering::DAGCombinerInfo:: 487 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 488 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 489 } 490 491 //===----------------------------------------------------------------------===// 492 // Helper Functions 493 //===----------------------------------------------------------------------===// 494 495 void DAGCombiner::deleteAndRecombine(SDNode *N) { 496 removeFromWorklist(N); 497 498 // If the operands of this node are only used by the node, they will now be 499 // dead. Make sure to re-visit them and recursively delete dead nodes. 500 for (const SDValue &Op : N->ops()) 501 // For an operand generating multiple values, one of the values may 502 // become dead allowing further simplification (e.g. split index 503 // arithmetic from an indexed load). 504 if (Op->hasOneUse() || Op->getNumValues() > 1) 505 AddToWorklist(Op.getNode()); 506 507 DAG.DeleteNode(N); 508 } 509 510 /// Return 1 if we can compute the negated form of the specified expression for 511 /// the same cost as the expression itself, or 2 if we can compute the negated 512 /// form more cheaply than the expression itself. 513 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 514 const TargetLowering &TLI, 515 const TargetOptions *Options, 516 unsigned Depth = 0) { 517 // fneg is removable even if it has multiple uses. 518 if (Op.getOpcode() == ISD::FNEG) return 2; 519 520 // Don't allow anything with multiple uses. 521 if (!Op.hasOneUse()) return 0; 522 523 // Don't recurse exponentially. 524 if (Depth > 6) return 0; 525 526 switch (Op.getOpcode()) { 527 default: return false; 528 case ISD::ConstantFP: 529 // Don't invert constant FP values after legalize. The negated constant 530 // isn't necessarily legal. 531 return LegalOperations ? 0 : 1; 532 case ISD::FADD: 533 // FIXME: determine better conditions for this xform. 534 if (!Options->UnsafeFPMath) return 0; 535 536 // After operation legalization, it might not be legal to create new FSUBs. 537 if (LegalOperations && 538 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 539 return 0; 540 541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 542 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 543 Options, Depth + 1)) 544 return V; 545 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 546 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 547 Depth + 1); 548 case ISD::FSUB: 549 // We can't turn -(A-B) into B-A when we honor signed zeros. 550 if (!Options->UnsafeFPMath) return 0; 551 552 // fold (fneg (fsub A, B)) -> (fsub B, A) 553 return 1; 554 555 case ISD::FMUL: 556 case ISD::FDIV: 557 if (Options->HonorSignDependentRoundingFPMath()) return 0; 558 559 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 560 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 561 Options, Depth + 1)) 562 return V; 563 564 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 565 Depth + 1); 566 567 case ISD::FP_EXTEND: 568 case ISD::FP_ROUND: 569 case ISD::FSIN: 570 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 571 Depth + 1); 572 } 573 } 574 575 /// If isNegatibleForFree returns true, return the newly negated expression. 576 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 577 bool LegalOperations, unsigned Depth = 0) { 578 const TargetOptions &Options = DAG.getTarget().Options; 579 // fneg is removable even if it has multiple uses. 580 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 581 582 // Don't allow anything with multiple uses. 583 assert(Op.hasOneUse() && "Unknown reuse!"); 584 585 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 586 switch (Op.getOpcode()) { 587 default: llvm_unreachable("Unknown code"); 588 case ISD::ConstantFP: { 589 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 590 V.changeSign(); 591 return DAG.getConstantFP(V, Op.getValueType()); 592 } 593 case ISD::FADD: 594 // FIXME: determine better conditions for this xform. 595 assert(Options.UnsafeFPMath); 596 597 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 598 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 599 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 600 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 601 GetNegatedExpression(Op.getOperand(0), DAG, 602 LegalOperations, Depth+1), 603 Op.getOperand(1)); 604 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 605 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 606 GetNegatedExpression(Op.getOperand(1), DAG, 607 LegalOperations, Depth+1), 608 Op.getOperand(0)); 609 case ISD::FSUB: 610 // We can't turn -(A-B) into B-A when we honor signed zeros. 611 assert(Options.UnsafeFPMath); 612 613 // fold (fneg (fsub 0, B)) -> B 614 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 615 if (N0CFP->getValueAPF().isZero()) 616 return Op.getOperand(1); 617 618 // fold (fneg (fsub A, B)) -> (fsub B, A) 619 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 620 Op.getOperand(1), Op.getOperand(0)); 621 622 case ISD::FMUL: 623 case ISD::FDIV: 624 assert(!Options.HonorSignDependentRoundingFPMath()); 625 626 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 627 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 628 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 629 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 630 GetNegatedExpression(Op.getOperand(0), DAG, 631 LegalOperations, Depth+1), 632 Op.getOperand(1)); 633 634 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 636 Op.getOperand(0), 637 GetNegatedExpression(Op.getOperand(1), DAG, 638 LegalOperations, Depth+1)); 639 640 case ISD::FP_EXTEND: 641 case ISD::FSIN: 642 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 643 GetNegatedExpression(Op.getOperand(0), DAG, 644 LegalOperations, Depth+1)); 645 case ISD::FP_ROUND: 646 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 647 GetNegatedExpression(Op.getOperand(0), DAG, 648 LegalOperations, Depth+1), 649 Op.getOperand(1)); 650 } 651 } 652 653 // Return true if this node is a setcc, or is a select_cc 654 // that selects between the target values used for true and false, making it 655 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 656 // the appropriate nodes based on the type of node we are checking. This 657 // simplifies life a bit for the callers. 658 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 659 SDValue &CC) const { 660 if (N.getOpcode() == ISD::SETCC) { 661 LHS = N.getOperand(0); 662 RHS = N.getOperand(1); 663 CC = N.getOperand(2); 664 return true; 665 } 666 667 if (N.getOpcode() != ISD::SELECT_CC || 668 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 669 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 670 return false; 671 672 if (TLI.getBooleanContents(N.getValueType()) == 673 TargetLowering::UndefinedBooleanContent) 674 return false; 675 676 LHS = N.getOperand(0); 677 RHS = N.getOperand(1); 678 CC = N.getOperand(4); 679 return true; 680 } 681 682 /// Return true if this is a SetCC-equivalent operation with only one use. 683 /// If this is true, it allows the users to invert the operation for free when 684 /// it is profitable to do so. 685 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 686 SDValue N0, N1, N2; 687 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 688 return true; 689 return false; 690 } 691 692 /// Returns true if N is a BUILD_VECTOR node whose 693 /// elements are all the same constant or undefined. 694 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 695 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 696 if (!C) 697 return false; 698 699 APInt SplatUndef; 700 unsigned SplatBitSize; 701 bool HasAnyUndefs; 702 EVT EltVT = N->getValueType(0).getVectorElementType(); 703 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 704 HasAnyUndefs) && 705 EltVT.getSizeInBits() >= SplatBitSize); 706 } 707 708 // \brief Returns the SDNode if it is a constant integer BuildVector 709 // or constant integer. 710 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) { 711 if (isa<ConstantSDNode>(N)) 712 return N.getNode(); 713 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 714 return N.getNode(); 715 return nullptr; 716 } 717 718 // \brief Returns the SDNode if it is a constant float BuildVector 719 // or constant float. 720 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 721 if (isa<ConstantFPSDNode>(N)) 722 return N.getNode(); 723 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 724 return N.getNode(); 725 return nullptr; 726 } 727 728 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 729 // int. 730 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 731 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 732 return CN; 733 734 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 735 BitVector UndefElements; 736 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 737 738 // BuildVectors can truncate their operands. Ignore that case here. 739 // FIXME: We blindly ignore splats which include undef which is overly 740 // pessimistic. 741 if (CN && UndefElements.none() && 742 CN->getValueType(0) == N.getValueType().getScalarType()) 743 return CN; 744 } 745 746 return nullptr; 747 } 748 749 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 750 // float. 751 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 752 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 753 return CN; 754 755 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 756 BitVector UndefElements; 757 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 758 759 if (CN && UndefElements.none()) 760 return CN; 761 } 762 763 return nullptr; 764 } 765 766 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 767 SDValue N0, SDValue N1) { 768 EVT VT = N0.getValueType(); 769 if (N0.getOpcode() == Opc) { 770 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 771 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) { 772 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 773 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R)) 774 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 775 return SDValue(); 776 } 777 if (N0.hasOneUse()) { 778 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 779 // use 780 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 781 if (!OpNode.getNode()) 782 return SDValue(); 783 AddToWorklist(OpNode.getNode()); 784 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 785 } 786 } 787 } 788 789 if (N1.getOpcode() == Opc) { 790 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 791 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) { 792 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 793 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L)) 794 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 795 return SDValue(); 796 } 797 if (N1.hasOneUse()) { 798 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 799 // use 800 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 801 if (!OpNode.getNode()) 802 return SDValue(); 803 AddToWorklist(OpNode.getNode()); 804 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 805 } 806 } 807 } 808 809 return SDValue(); 810 } 811 812 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 813 bool AddTo) { 814 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 815 ++NodesCombined; 816 DEBUG(dbgs() << "\nReplacing.1 "; 817 N->dump(&DAG); 818 dbgs() << "\nWith: "; 819 To[0].getNode()->dump(&DAG); 820 dbgs() << " and " << NumTo-1 << " other values\n"); 821 for (unsigned i = 0, e = NumTo; i != e; ++i) 822 assert((!To[i].getNode() || 823 N->getValueType(i) == To[i].getValueType()) && 824 "Cannot combine value to value of different type!"); 825 826 WorklistRemover DeadNodes(*this); 827 DAG.ReplaceAllUsesWith(N, To); 828 if (AddTo) { 829 // Push the new nodes and any users onto the worklist 830 for (unsigned i = 0, e = NumTo; i != e; ++i) { 831 if (To[i].getNode()) { 832 AddToWorklist(To[i].getNode()); 833 AddUsersToWorklist(To[i].getNode()); 834 } 835 } 836 } 837 838 // Finally, if the node is now dead, remove it from the graph. The node 839 // may not be dead if the replacement process recursively simplified to 840 // something else needing this node. 841 if (N->use_empty()) 842 deleteAndRecombine(N); 843 return SDValue(N, 0); 844 } 845 846 void DAGCombiner:: 847 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 848 // Replace all uses. If any nodes become isomorphic to other nodes and 849 // are deleted, make sure to remove them from our worklist. 850 WorklistRemover DeadNodes(*this); 851 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 852 853 // Push the new node and any (possibly new) users onto the worklist. 854 AddToWorklist(TLO.New.getNode()); 855 AddUsersToWorklist(TLO.New.getNode()); 856 857 // Finally, if the node is now dead, remove it from the graph. The node 858 // may not be dead if the replacement process recursively simplified to 859 // something else needing this node. 860 if (TLO.Old.getNode()->use_empty()) 861 deleteAndRecombine(TLO.Old.getNode()); 862 } 863 864 /// Check the specified integer node value to see if it can be simplified or if 865 /// things it uses can be simplified by bit propagation. If so, return true. 866 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 867 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 868 APInt KnownZero, KnownOne; 869 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 870 return false; 871 872 // Revisit the node. 873 AddToWorklist(Op.getNode()); 874 875 // Replace the old value with the new one. 876 ++NodesCombined; 877 DEBUG(dbgs() << "\nReplacing.2 "; 878 TLO.Old.getNode()->dump(&DAG); 879 dbgs() << "\nWith: "; 880 TLO.New.getNode()->dump(&DAG); 881 dbgs() << '\n'); 882 883 CommitTargetLoweringOpt(TLO); 884 return true; 885 } 886 887 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 888 SDLoc dl(Load); 889 EVT VT = Load->getValueType(0); 890 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 891 892 DEBUG(dbgs() << "\nReplacing.9 "; 893 Load->dump(&DAG); 894 dbgs() << "\nWith: "; 895 Trunc.getNode()->dump(&DAG); 896 dbgs() << '\n'); 897 WorklistRemover DeadNodes(*this); 898 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 899 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 900 deleteAndRecombine(Load); 901 AddToWorklist(Trunc.getNode()); 902 } 903 904 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 905 Replace = false; 906 SDLoc dl(Op); 907 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 908 EVT MemVT = LD->getMemoryVT(); 909 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 910 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 911 : ISD::EXTLOAD) 912 : LD->getExtensionType(); 913 Replace = true; 914 return DAG.getExtLoad(ExtType, dl, PVT, 915 LD->getChain(), LD->getBasePtr(), 916 MemVT, LD->getMemOperand()); 917 } 918 919 unsigned Opc = Op.getOpcode(); 920 switch (Opc) { 921 default: break; 922 case ISD::AssertSext: 923 return DAG.getNode(ISD::AssertSext, dl, PVT, 924 SExtPromoteOperand(Op.getOperand(0), PVT), 925 Op.getOperand(1)); 926 case ISD::AssertZext: 927 return DAG.getNode(ISD::AssertZext, dl, PVT, 928 ZExtPromoteOperand(Op.getOperand(0), PVT), 929 Op.getOperand(1)); 930 case ISD::Constant: { 931 unsigned ExtOpc = 932 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 933 return DAG.getNode(ExtOpc, dl, PVT, Op); 934 } 935 } 936 937 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 938 return SDValue(); 939 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 940 } 941 942 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 943 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 944 return SDValue(); 945 EVT OldVT = Op.getValueType(); 946 SDLoc dl(Op); 947 bool Replace = false; 948 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 949 if (!NewOp.getNode()) 950 return SDValue(); 951 AddToWorklist(NewOp.getNode()); 952 953 if (Replace) 954 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 955 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 956 DAG.getValueType(OldVT)); 957 } 958 959 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 960 EVT OldVT = Op.getValueType(); 961 SDLoc dl(Op); 962 bool Replace = false; 963 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 964 if (!NewOp.getNode()) 965 return SDValue(); 966 AddToWorklist(NewOp.getNode()); 967 968 if (Replace) 969 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 970 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 971 } 972 973 /// Promote the specified integer binary operation if the target indicates it is 974 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 975 /// i32 since i16 instructions are longer. 976 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 977 if (!LegalOperations) 978 return SDValue(); 979 980 EVT VT = Op.getValueType(); 981 if (VT.isVector() || !VT.isInteger()) 982 return SDValue(); 983 984 // If operation type is 'undesirable', e.g. i16 on x86, consider 985 // promoting it. 986 unsigned Opc = Op.getOpcode(); 987 if (TLI.isTypeDesirableForOp(Opc, VT)) 988 return SDValue(); 989 990 EVT PVT = VT; 991 // Consult target whether it is a good idea to promote this operation and 992 // what's the right type to promote it to. 993 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 994 assert(PVT != VT && "Don't know what type to promote to!"); 995 996 bool Replace0 = false; 997 SDValue N0 = Op.getOperand(0); 998 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 999 if (!NN0.getNode()) 1000 return SDValue(); 1001 1002 bool Replace1 = false; 1003 SDValue N1 = Op.getOperand(1); 1004 SDValue NN1; 1005 if (N0 == N1) 1006 NN1 = NN0; 1007 else { 1008 NN1 = PromoteOperand(N1, PVT, Replace1); 1009 if (!NN1.getNode()) 1010 return SDValue(); 1011 } 1012 1013 AddToWorklist(NN0.getNode()); 1014 if (NN1.getNode()) 1015 AddToWorklist(NN1.getNode()); 1016 1017 if (Replace0) 1018 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1019 if (Replace1) 1020 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1021 1022 DEBUG(dbgs() << "\nPromoting "; 1023 Op.getNode()->dump(&DAG)); 1024 SDLoc dl(Op); 1025 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1026 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1027 } 1028 return SDValue(); 1029 } 1030 1031 /// Promote the specified integer shift operation if the target indicates it is 1032 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1033 /// i32 since i16 instructions are longer. 1034 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1035 if (!LegalOperations) 1036 return SDValue(); 1037 1038 EVT VT = Op.getValueType(); 1039 if (VT.isVector() || !VT.isInteger()) 1040 return SDValue(); 1041 1042 // If operation type is 'undesirable', e.g. i16 on x86, consider 1043 // promoting it. 1044 unsigned Opc = Op.getOpcode(); 1045 if (TLI.isTypeDesirableForOp(Opc, VT)) 1046 return SDValue(); 1047 1048 EVT PVT = VT; 1049 // Consult target whether it is a good idea to promote this operation and 1050 // what's the right type to promote it to. 1051 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1052 assert(PVT != VT && "Don't know what type to promote to!"); 1053 1054 bool Replace = false; 1055 SDValue N0 = Op.getOperand(0); 1056 if (Opc == ISD::SRA) 1057 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1058 else if (Opc == ISD::SRL) 1059 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1060 else 1061 N0 = PromoteOperand(N0, PVT, Replace); 1062 if (!N0.getNode()) 1063 return SDValue(); 1064 1065 AddToWorklist(N0.getNode()); 1066 if (Replace) 1067 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1068 1069 DEBUG(dbgs() << "\nPromoting "; 1070 Op.getNode()->dump(&DAG)); 1071 SDLoc dl(Op); 1072 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1073 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1074 } 1075 return SDValue(); 1076 } 1077 1078 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1079 if (!LegalOperations) 1080 return SDValue(); 1081 1082 EVT VT = Op.getValueType(); 1083 if (VT.isVector() || !VT.isInteger()) 1084 return SDValue(); 1085 1086 // If operation type is 'undesirable', e.g. i16 on x86, consider 1087 // promoting it. 1088 unsigned Opc = Op.getOpcode(); 1089 if (TLI.isTypeDesirableForOp(Opc, VT)) 1090 return SDValue(); 1091 1092 EVT PVT = VT; 1093 // Consult target whether it is a good idea to promote this operation and 1094 // what's the right type to promote it to. 1095 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1096 assert(PVT != VT && "Don't know what type to promote to!"); 1097 // fold (aext (aext x)) -> (aext x) 1098 // fold (aext (zext x)) -> (zext x) 1099 // fold (aext (sext x)) -> (sext x) 1100 DEBUG(dbgs() << "\nPromoting "; 1101 Op.getNode()->dump(&DAG)); 1102 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1103 } 1104 return SDValue(); 1105 } 1106 1107 bool DAGCombiner::PromoteLoad(SDValue Op) { 1108 if (!LegalOperations) 1109 return false; 1110 1111 EVT VT = Op.getValueType(); 1112 if (VT.isVector() || !VT.isInteger()) 1113 return false; 1114 1115 // If operation type is 'undesirable', e.g. i16 on x86, consider 1116 // promoting it. 1117 unsigned Opc = Op.getOpcode(); 1118 if (TLI.isTypeDesirableForOp(Opc, VT)) 1119 return false; 1120 1121 EVT PVT = VT; 1122 // Consult target whether it is a good idea to promote this operation and 1123 // what's the right type to promote it to. 1124 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1125 assert(PVT != VT && "Don't know what type to promote to!"); 1126 1127 SDLoc dl(Op); 1128 SDNode *N = Op.getNode(); 1129 LoadSDNode *LD = cast<LoadSDNode>(N); 1130 EVT MemVT = LD->getMemoryVT(); 1131 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1132 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1133 : ISD::EXTLOAD) 1134 : LD->getExtensionType(); 1135 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1136 LD->getChain(), LD->getBasePtr(), 1137 MemVT, LD->getMemOperand()); 1138 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1139 1140 DEBUG(dbgs() << "\nPromoting "; 1141 N->dump(&DAG); 1142 dbgs() << "\nTo: "; 1143 Result.getNode()->dump(&DAG); 1144 dbgs() << '\n'); 1145 WorklistRemover DeadNodes(*this); 1146 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1147 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1148 deleteAndRecombine(N); 1149 AddToWorklist(Result.getNode()); 1150 return true; 1151 } 1152 return false; 1153 } 1154 1155 /// \brief Recursively delete a node which has no uses and any operands for 1156 /// which it is the only use. 1157 /// 1158 /// Note that this both deletes the nodes and removes them from the worklist. 1159 /// It also adds any nodes who have had a user deleted to the worklist as they 1160 /// may now have only one use and subject to other combines. 1161 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1162 if (!N->use_empty()) 1163 return false; 1164 1165 SmallSetVector<SDNode *, 16> Nodes; 1166 Nodes.insert(N); 1167 do { 1168 N = Nodes.pop_back_val(); 1169 if (!N) 1170 continue; 1171 1172 if (N->use_empty()) { 1173 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1174 Nodes.insert(N->getOperand(i).getNode()); 1175 1176 removeFromWorklist(N); 1177 DAG.DeleteNode(N); 1178 } else { 1179 AddToWorklist(N); 1180 } 1181 } while (!Nodes.empty()); 1182 return true; 1183 } 1184 1185 //===----------------------------------------------------------------------===// 1186 // Main DAG Combiner implementation 1187 //===----------------------------------------------------------------------===// 1188 1189 void DAGCombiner::Run(CombineLevel AtLevel) { 1190 // set the instance variables, so that the various visit routines may use it. 1191 Level = AtLevel; 1192 LegalOperations = Level >= AfterLegalizeVectorOps; 1193 LegalTypes = Level >= AfterLegalizeTypes; 1194 1195 // Add all the dag nodes to the worklist. 1196 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1197 E = DAG.allnodes_end(); I != E; ++I) 1198 AddToWorklist(I); 1199 1200 // Create a dummy node (which is not added to allnodes), that adds a reference 1201 // to the root node, preventing it from being deleted, and tracking any 1202 // changes of the root. 1203 HandleSDNode Dummy(DAG.getRoot()); 1204 1205 // while the worklist isn't empty, find a node and 1206 // try and combine it. 1207 while (!WorklistMap.empty()) { 1208 SDNode *N; 1209 // The Worklist holds the SDNodes in order, but it may contain null entries. 1210 do { 1211 N = Worklist.pop_back_val(); 1212 } while (!N); 1213 1214 bool GoodWorklistEntry = WorklistMap.erase(N); 1215 (void)GoodWorklistEntry; 1216 assert(GoodWorklistEntry && 1217 "Found a worklist entry without a corresponding map entry!"); 1218 1219 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1220 // N is deleted from the DAG, since they too may now be dead or may have a 1221 // reduced number of uses, allowing other xforms. 1222 if (recursivelyDeleteUnusedNodes(N)) 1223 continue; 1224 1225 WorklistRemover DeadNodes(*this); 1226 1227 // If this combine is running after legalizing the DAG, re-legalize any 1228 // nodes pulled off the worklist. 1229 if (Level == AfterLegalizeDAG) { 1230 SmallSetVector<SDNode *, 16> UpdatedNodes; 1231 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1232 1233 for (SDNode *LN : UpdatedNodes) { 1234 AddToWorklist(LN); 1235 AddUsersToWorklist(LN); 1236 } 1237 if (!NIsValid) 1238 continue; 1239 } 1240 1241 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1242 1243 // Add any operands of the new node which have not yet been combined to the 1244 // worklist as well. Because the worklist uniques things already, this 1245 // won't repeatedly process the same operand. 1246 CombinedNodes.insert(N); 1247 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1248 if (!CombinedNodes.count(N->getOperand(i).getNode())) 1249 AddToWorklist(N->getOperand(i).getNode()); 1250 1251 SDValue RV = combine(N); 1252 1253 if (!RV.getNode()) 1254 continue; 1255 1256 ++NodesCombined; 1257 1258 // If we get back the same node we passed in, rather than a new node or 1259 // zero, we know that the node must have defined multiple values and 1260 // CombineTo was used. Since CombineTo takes care of the worklist 1261 // mechanics for us, we have no work to do in this case. 1262 if (RV.getNode() == N) 1263 continue; 1264 1265 assert(N->getOpcode() != ISD::DELETED_NODE && 1266 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1267 "Node was deleted but visit returned new node!"); 1268 1269 DEBUG(dbgs() << " ... into: "; 1270 RV.getNode()->dump(&DAG)); 1271 1272 // Transfer debug value. 1273 DAG.TransferDbgValues(SDValue(N, 0), RV); 1274 if (N->getNumValues() == RV.getNode()->getNumValues()) 1275 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1276 else { 1277 assert(N->getValueType(0) == RV.getValueType() && 1278 N->getNumValues() == 1 && "Type mismatch"); 1279 SDValue OpV = RV; 1280 DAG.ReplaceAllUsesWith(N, &OpV); 1281 } 1282 1283 // Push the new node and any users onto the worklist 1284 AddToWorklist(RV.getNode()); 1285 AddUsersToWorklist(RV.getNode()); 1286 1287 // Finally, if the node is now dead, remove it from the graph. The node 1288 // may not be dead if the replacement process recursively simplified to 1289 // something else needing this node. This will also take care of adding any 1290 // operands which have lost a user to the worklist. 1291 recursivelyDeleteUnusedNodes(N); 1292 } 1293 1294 // If the root changed (e.g. it was a dead load, update the root). 1295 DAG.setRoot(Dummy.getValue()); 1296 DAG.RemoveDeadNodes(); 1297 } 1298 1299 SDValue DAGCombiner::visit(SDNode *N) { 1300 switch (N->getOpcode()) { 1301 default: break; 1302 case ISD::TokenFactor: return visitTokenFactor(N); 1303 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1304 case ISD::ADD: return visitADD(N); 1305 case ISD::SUB: return visitSUB(N); 1306 case ISD::ADDC: return visitADDC(N); 1307 case ISD::SUBC: return visitSUBC(N); 1308 case ISD::ADDE: return visitADDE(N); 1309 case ISD::SUBE: return visitSUBE(N); 1310 case ISD::MUL: return visitMUL(N); 1311 case ISD::SDIV: return visitSDIV(N); 1312 case ISD::UDIV: return visitUDIV(N); 1313 case ISD::SREM: return visitSREM(N); 1314 case ISD::UREM: return visitUREM(N); 1315 case ISD::MULHU: return visitMULHU(N); 1316 case ISD::MULHS: return visitMULHS(N); 1317 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1318 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1319 case ISD::SMULO: return visitSMULO(N); 1320 case ISD::UMULO: return visitUMULO(N); 1321 case ISD::SDIVREM: return visitSDIVREM(N); 1322 case ISD::UDIVREM: return visitUDIVREM(N); 1323 case ISD::AND: return visitAND(N); 1324 case ISD::OR: return visitOR(N); 1325 case ISD::XOR: return visitXOR(N); 1326 case ISD::SHL: return visitSHL(N); 1327 case ISD::SRA: return visitSRA(N); 1328 case ISD::SRL: return visitSRL(N); 1329 case ISD::ROTR: 1330 case ISD::ROTL: return visitRotate(N); 1331 case ISD::CTLZ: return visitCTLZ(N); 1332 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1333 case ISD::CTTZ: return visitCTTZ(N); 1334 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1335 case ISD::CTPOP: return visitCTPOP(N); 1336 case ISD::SELECT: return visitSELECT(N); 1337 case ISD::VSELECT: return visitVSELECT(N); 1338 case ISD::SELECT_CC: return visitSELECT_CC(N); 1339 case ISD::SETCC: return visitSETCC(N); 1340 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1341 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1342 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1343 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1344 case ISD::TRUNCATE: return visitTRUNCATE(N); 1345 case ISD::BITCAST: return visitBITCAST(N); 1346 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1347 case ISD::FADD: return visitFADD(N); 1348 case ISD::FSUB: return visitFSUB(N); 1349 case ISD::FMUL: return visitFMUL(N); 1350 case ISD::FMA: return visitFMA(N); 1351 case ISD::FDIV: return visitFDIV(N); 1352 case ISD::FREM: return visitFREM(N); 1353 case ISD::FSQRT: return visitFSQRT(N); 1354 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1355 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1356 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1357 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1358 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1359 case ISD::FP_ROUND: return visitFP_ROUND(N); 1360 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1361 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1362 case ISD::FNEG: return visitFNEG(N); 1363 case ISD::FABS: return visitFABS(N); 1364 case ISD::FFLOOR: return visitFFLOOR(N); 1365 case ISD::FMINNUM: return visitFMINNUM(N); 1366 case ISD::FMAXNUM: return visitFMAXNUM(N); 1367 case ISD::FCEIL: return visitFCEIL(N); 1368 case ISD::FTRUNC: return visitFTRUNC(N); 1369 case ISD::BRCOND: return visitBRCOND(N); 1370 case ISD::BR_CC: return visitBR_CC(N); 1371 case ISD::LOAD: return visitLOAD(N); 1372 case ISD::STORE: return visitSTORE(N); 1373 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1374 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1375 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1376 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1377 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1378 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1379 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1380 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1381 case ISD::MLOAD: return visitMLOAD(N); 1382 case ISD::MSTORE: return visitMSTORE(N); 1383 } 1384 return SDValue(); 1385 } 1386 1387 SDValue DAGCombiner::combine(SDNode *N) { 1388 SDValue RV = visit(N); 1389 1390 // If nothing happened, try a target-specific DAG combine. 1391 if (!RV.getNode()) { 1392 assert(N->getOpcode() != ISD::DELETED_NODE && 1393 "Node was deleted but visit returned NULL!"); 1394 1395 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1396 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1397 1398 // Expose the DAG combiner to the target combiner impls. 1399 TargetLowering::DAGCombinerInfo 1400 DagCombineInfo(DAG, Level, false, this); 1401 1402 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1403 } 1404 } 1405 1406 // If nothing happened still, try promoting the operation. 1407 if (!RV.getNode()) { 1408 switch (N->getOpcode()) { 1409 default: break; 1410 case ISD::ADD: 1411 case ISD::SUB: 1412 case ISD::MUL: 1413 case ISD::AND: 1414 case ISD::OR: 1415 case ISD::XOR: 1416 RV = PromoteIntBinOp(SDValue(N, 0)); 1417 break; 1418 case ISD::SHL: 1419 case ISD::SRA: 1420 case ISD::SRL: 1421 RV = PromoteIntShiftOp(SDValue(N, 0)); 1422 break; 1423 case ISD::SIGN_EXTEND: 1424 case ISD::ZERO_EXTEND: 1425 case ISD::ANY_EXTEND: 1426 RV = PromoteExtend(SDValue(N, 0)); 1427 break; 1428 case ISD::LOAD: 1429 if (PromoteLoad(SDValue(N, 0))) 1430 RV = SDValue(N, 0); 1431 break; 1432 } 1433 } 1434 1435 // If N is a commutative binary node, try commuting it to enable more 1436 // sdisel CSE. 1437 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1438 N->getNumValues() == 1) { 1439 SDValue N0 = N->getOperand(0); 1440 SDValue N1 = N->getOperand(1); 1441 1442 // Constant operands are canonicalized to RHS. 1443 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1444 SDValue Ops[] = {N1, N0}; 1445 SDNode *CSENode; 1446 if (const BinaryWithFlagsSDNode *BinNode = 1447 dyn_cast<BinaryWithFlagsSDNode>(N)) { 1448 CSENode = DAG.getNodeIfExists( 1449 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(), 1450 BinNode->hasNoSignedWrap(), BinNode->isExact()); 1451 } else { 1452 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops); 1453 } 1454 if (CSENode) 1455 return SDValue(CSENode, 0); 1456 } 1457 } 1458 1459 return RV; 1460 } 1461 1462 /// Given a node, return its input chain if it has one, otherwise return a null 1463 /// sd operand. 1464 static SDValue getInputChainForNode(SDNode *N) { 1465 if (unsigned NumOps = N->getNumOperands()) { 1466 if (N->getOperand(0).getValueType() == MVT::Other) 1467 return N->getOperand(0); 1468 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1469 return N->getOperand(NumOps-1); 1470 for (unsigned i = 1; i < NumOps-1; ++i) 1471 if (N->getOperand(i).getValueType() == MVT::Other) 1472 return N->getOperand(i); 1473 } 1474 return SDValue(); 1475 } 1476 1477 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1478 // If N has two operands, where one has an input chain equal to the other, 1479 // the 'other' chain is redundant. 1480 if (N->getNumOperands() == 2) { 1481 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1482 return N->getOperand(0); 1483 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1484 return N->getOperand(1); 1485 } 1486 1487 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1488 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1489 SmallPtrSet<SDNode*, 16> SeenOps; 1490 bool Changed = false; // If we should replace this token factor. 1491 1492 // Start out with this token factor. 1493 TFs.push_back(N); 1494 1495 // Iterate through token factors. The TFs grows when new token factors are 1496 // encountered. 1497 for (unsigned i = 0; i < TFs.size(); ++i) { 1498 SDNode *TF = TFs[i]; 1499 1500 // Check each of the operands. 1501 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1502 SDValue Op = TF->getOperand(i); 1503 1504 switch (Op.getOpcode()) { 1505 case ISD::EntryToken: 1506 // Entry tokens don't need to be added to the list. They are 1507 // redundant. 1508 Changed = true; 1509 break; 1510 1511 case ISD::TokenFactor: 1512 if (Op.hasOneUse() && 1513 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1514 // Queue up for processing. 1515 TFs.push_back(Op.getNode()); 1516 // Clean up in case the token factor is removed. 1517 AddToWorklist(Op.getNode()); 1518 Changed = true; 1519 break; 1520 } 1521 // Fall thru 1522 1523 default: 1524 // Only add if it isn't already in the list. 1525 if (SeenOps.insert(Op.getNode()).second) 1526 Ops.push_back(Op); 1527 else 1528 Changed = true; 1529 break; 1530 } 1531 } 1532 } 1533 1534 SDValue Result; 1535 1536 // If we've changed things around then replace token factor. 1537 if (Changed) { 1538 if (Ops.empty()) { 1539 // The entry token is the only possible outcome. 1540 Result = DAG.getEntryNode(); 1541 } else { 1542 // New and improved token factor. 1543 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1544 } 1545 1546 // Add users to worklist if AA is enabled, since it may introduce 1547 // a lot of new chained token factors while removing memory deps. 1548 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1549 : DAG.getSubtarget().useAA(); 1550 return CombineTo(N, Result, UseAA /*add to worklist*/); 1551 } 1552 1553 return Result; 1554 } 1555 1556 /// MERGE_VALUES can always be eliminated. 1557 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1558 WorklistRemover DeadNodes(*this); 1559 // Replacing results may cause a different MERGE_VALUES to suddenly 1560 // be CSE'd with N, and carry its uses with it. Iterate until no 1561 // uses remain, to ensure that the node can be safely deleted. 1562 // First add the users of this node to the work list so that they 1563 // can be tried again once they have new operands. 1564 AddUsersToWorklist(N); 1565 do { 1566 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1567 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1568 } while (!N->use_empty()); 1569 deleteAndRecombine(N); 1570 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1571 } 1572 1573 SDValue DAGCombiner::visitADD(SDNode *N) { 1574 SDValue N0 = N->getOperand(0); 1575 SDValue N1 = N->getOperand(1); 1576 EVT VT = N0.getValueType(); 1577 1578 // fold vector ops 1579 if (VT.isVector()) { 1580 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1581 return FoldedVOp; 1582 1583 // fold (add x, 0) -> x, vector edition 1584 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1585 return N0; 1586 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1587 return N1; 1588 } 1589 1590 // fold (add x, undef) -> undef 1591 if (N0.getOpcode() == ISD::UNDEF) 1592 return N0; 1593 if (N1.getOpcode() == ISD::UNDEF) 1594 return N1; 1595 // fold (add c1, c2) -> c1+c2 1596 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1597 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1598 if (N0C && N1C) 1599 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1600 // canonicalize constant to RHS 1601 if (isConstantIntBuildVectorOrConstantInt(N0) && 1602 !isConstantIntBuildVectorOrConstantInt(N1)) 1603 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1604 // fold (add x, 0) -> x 1605 if (N1C && N1C->isNullValue()) 1606 return N0; 1607 // fold (add Sym, c) -> Sym+c 1608 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1609 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1610 GA->getOpcode() == ISD::GlobalAddress) 1611 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1612 GA->getOffset() + 1613 (uint64_t)N1C->getSExtValue()); 1614 // fold ((c1-A)+c2) -> (c1+c2)-A 1615 if (N1C && N0.getOpcode() == ISD::SUB) 1616 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1617 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1618 DAG.getConstant(N1C->getAPIntValue()+ 1619 N0C->getAPIntValue(), VT), 1620 N0.getOperand(1)); 1621 // reassociate add 1622 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1623 return RADD; 1624 // fold ((0-A) + B) -> B-A 1625 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1626 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1627 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1628 // fold (A + (0-B)) -> A-B 1629 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1630 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1631 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1632 // fold (A+(B-A)) -> B 1633 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1634 return N1.getOperand(0); 1635 // fold ((B-A)+A) -> B 1636 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1637 return N0.getOperand(0); 1638 // fold (A+(B-(A+C))) to (B-C) 1639 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1640 N0 == N1.getOperand(1).getOperand(0)) 1641 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1642 N1.getOperand(1).getOperand(1)); 1643 // fold (A+(B-(C+A))) to (B-C) 1644 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1645 N0 == N1.getOperand(1).getOperand(1)) 1646 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1647 N1.getOperand(1).getOperand(0)); 1648 // fold (A+((B-A)+or-C)) to (B+or-C) 1649 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1650 N1.getOperand(0).getOpcode() == ISD::SUB && 1651 N0 == N1.getOperand(0).getOperand(1)) 1652 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1653 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1654 1655 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1656 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1657 SDValue N00 = N0.getOperand(0); 1658 SDValue N01 = N0.getOperand(1); 1659 SDValue N10 = N1.getOperand(0); 1660 SDValue N11 = N1.getOperand(1); 1661 1662 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1663 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1664 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1665 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1666 } 1667 1668 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1669 return SDValue(N, 0); 1670 1671 // fold (a+b) -> (a|b) iff a and b share no bits. 1672 if (VT.isInteger() && !VT.isVector()) { 1673 APInt LHSZero, LHSOne; 1674 APInt RHSZero, RHSOne; 1675 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1676 1677 if (LHSZero.getBoolValue()) { 1678 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1679 1680 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1681 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1682 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1683 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1684 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1685 } 1686 } 1687 } 1688 1689 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1690 if (N1.getOpcode() == ISD::SHL && 1691 N1.getOperand(0).getOpcode() == ISD::SUB) 1692 if (ConstantSDNode *C = 1693 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1694 if (C->getAPIntValue() == 0) 1695 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1696 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1697 N1.getOperand(0).getOperand(1), 1698 N1.getOperand(1))); 1699 if (N0.getOpcode() == ISD::SHL && 1700 N0.getOperand(0).getOpcode() == ISD::SUB) 1701 if (ConstantSDNode *C = 1702 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1703 if (C->getAPIntValue() == 0) 1704 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1705 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1706 N0.getOperand(0).getOperand(1), 1707 N0.getOperand(1))); 1708 1709 if (N1.getOpcode() == ISD::AND) { 1710 SDValue AndOp0 = N1.getOperand(0); 1711 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1712 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1713 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1714 1715 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1716 // and similar xforms where the inner op is either ~0 or 0. 1717 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1718 SDLoc DL(N); 1719 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1720 } 1721 } 1722 1723 // add (sext i1), X -> sub X, (zext i1) 1724 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1725 N0.getOperand(0).getValueType() == MVT::i1 && 1726 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1727 SDLoc DL(N); 1728 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1729 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1730 } 1731 1732 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1733 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1734 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1735 if (TN->getVT() == MVT::i1) { 1736 SDLoc DL(N); 1737 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1738 DAG.getConstant(1, VT)); 1739 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1740 } 1741 } 1742 1743 return SDValue(); 1744 } 1745 1746 SDValue DAGCombiner::visitADDC(SDNode *N) { 1747 SDValue N0 = N->getOperand(0); 1748 SDValue N1 = N->getOperand(1); 1749 EVT VT = N0.getValueType(); 1750 1751 // If the flag result is dead, turn this into an ADD. 1752 if (!N->hasAnyUseOfValue(1)) 1753 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1754 DAG.getNode(ISD::CARRY_FALSE, 1755 SDLoc(N), MVT::Glue)); 1756 1757 // canonicalize constant to RHS. 1758 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1759 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1760 if (N0C && !N1C) 1761 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1762 1763 // fold (addc x, 0) -> x + no carry out 1764 if (N1C && N1C->isNullValue()) 1765 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1766 SDLoc(N), MVT::Glue)); 1767 1768 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1769 APInt LHSZero, LHSOne; 1770 APInt RHSZero, RHSOne; 1771 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1772 1773 if (LHSZero.getBoolValue()) { 1774 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1775 1776 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1777 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1778 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1779 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1780 DAG.getNode(ISD::CARRY_FALSE, 1781 SDLoc(N), MVT::Glue)); 1782 } 1783 1784 return SDValue(); 1785 } 1786 1787 SDValue DAGCombiner::visitADDE(SDNode *N) { 1788 SDValue N0 = N->getOperand(0); 1789 SDValue N1 = N->getOperand(1); 1790 SDValue CarryIn = N->getOperand(2); 1791 1792 // canonicalize constant to RHS 1793 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1794 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1795 if (N0C && !N1C) 1796 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1797 N1, N0, CarryIn); 1798 1799 // fold (adde x, y, false) -> (addc x, y) 1800 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1801 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1802 1803 return SDValue(); 1804 } 1805 1806 // Since it may not be valid to emit a fold to zero for vector initializers 1807 // check if we can before folding. 1808 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1809 SelectionDAG &DAG, 1810 bool LegalOperations, bool LegalTypes) { 1811 if (!VT.isVector()) 1812 return DAG.getConstant(0, VT); 1813 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1814 return DAG.getConstant(0, VT); 1815 return SDValue(); 1816 } 1817 1818 SDValue DAGCombiner::visitSUB(SDNode *N) { 1819 SDValue N0 = N->getOperand(0); 1820 SDValue N1 = N->getOperand(1); 1821 EVT VT = N0.getValueType(); 1822 1823 // fold vector ops 1824 if (VT.isVector()) { 1825 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1826 return FoldedVOp; 1827 1828 // fold (sub x, 0) -> x, vector edition 1829 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1830 return N0; 1831 } 1832 1833 // fold (sub x, x) -> 0 1834 // FIXME: Refactor this and xor and other similar operations together. 1835 if (N0 == N1) 1836 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1837 // fold (sub c1, c2) -> c1-c2 1838 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1839 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1840 if (N0C && N1C) 1841 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1842 // fold (sub x, c) -> (add x, -c) 1843 if (N1C) 1844 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1845 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1846 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1847 if (N0C && N0C->isAllOnesValue()) 1848 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1849 // fold A-(A-B) -> B 1850 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1851 return N1.getOperand(1); 1852 // fold (A+B)-A -> B 1853 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1854 return N0.getOperand(1); 1855 // fold (A+B)-B -> A 1856 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1857 return N0.getOperand(0); 1858 // fold C2-(A+C1) -> (C2-C1)-A 1859 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1860 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1861 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1862 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1863 VT); 1864 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1865 N1.getOperand(0)); 1866 } 1867 // fold ((A+(B+or-C))-B) -> A+or-C 1868 if (N0.getOpcode() == ISD::ADD && 1869 (N0.getOperand(1).getOpcode() == ISD::SUB || 1870 N0.getOperand(1).getOpcode() == ISD::ADD) && 1871 N0.getOperand(1).getOperand(0) == N1) 1872 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1873 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1874 // fold ((A+(C+B))-B) -> A+C 1875 if (N0.getOpcode() == ISD::ADD && 1876 N0.getOperand(1).getOpcode() == ISD::ADD && 1877 N0.getOperand(1).getOperand(1) == N1) 1878 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1879 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1880 // fold ((A-(B-C))-C) -> A-B 1881 if (N0.getOpcode() == ISD::SUB && 1882 N0.getOperand(1).getOpcode() == ISD::SUB && 1883 N0.getOperand(1).getOperand(1) == N1) 1884 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1885 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1886 1887 // If either operand of a sub is undef, the result is undef 1888 if (N0.getOpcode() == ISD::UNDEF) 1889 return N0; 1890 if (N1.getOpcode() == ISD::UNDEF) 1891 return N1; 1892 1893 // If the relocation model supports it, consider symbol offsets. 1894 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1895 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1896 // fold (sub Sym, c) -> Sym-c 1897 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1898 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1899 GA->getOffset() - 1900 (uint64_t)N1C->getSExtValue()); 1901 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1902 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1903 if (GA->getGlobal() == GB->getGlobal()) 1904 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1905 VT); 1906 } 1907 1908 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1909 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1910 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1911 if (TN->getVT() == MVT::i1) { 1912 SDLoc DL(N); 1913 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1914 DAG.getConstant(1, VT)); 1915 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1916 } 1917 } 1918 1919 return SDValue(); 1920 } 1921 1922 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1923 SDValue N0 = N->getOperand(0); 1924 SDValue N1 = N->getOperand(1); 1925 EVT VT = N0.getValueType(); 1926 1927 // If the flag result is dead, turn this into an SUB. 1928 if (!N->hasAnyUseOfValue(1)) 1929 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1930 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1931 MVT::Glue)); 1932 1933 // fold (subc x, x) -> 0 + no borrow 1934 if (N0 == N1) 1935 return CombineTo(N, DAG.getConstant(0, VT), 1936 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1937 MVT::Glue)); 1938 1939 // fold (subc x, 0) -> x + no borrow 1940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1941 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1942 if (N1C && N1C->isNullValue()) 1943 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1944 MVT::Glue)); 1945 1946 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1947 if (N0C && N0C->isAllOnesValue()) 1948 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1949 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1950 MVT::Glue)); 1951 1952 return SDValue(); 1953 } 1954 1955 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1956 SDValue N0 = N->getOperand(0); 1957 SDValue N1 = N->getOperand(1); 1958 SDValue CarryIn = N->getOperand(2); 1959 1960 // fold (sube x, y, false) -> (subc x, y) 1961 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1962 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1963 1964 return SDValue(); 1965 } 1966 1967 SDValue DAGCombiner::visitMUL(SDNode *N) { 1968 SDValue N0 = N->getOperand(0); 1969 SDValue N1 = N->getOperand(1); 1970 EVT VT = N0.getValueType(); 1971 1972 // fold (mul x, undef) -> 0 1973 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1974 return DAG.getConstant(0, VT); 1975 1976 bool N0IsConst = false; 1977 bool N1IsConst = false; 1978 APInt ConstValue0, ConstValue1; 1979 // fold vector ops 1980 if (VT.isVector()) { 1981 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1982 return FoldedVOp; 1983 1984 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1985 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1986 } else { 1987 N0IsConst = isa<ConstantSDNode>(N0); 1988 if (N0IsConst) 1989 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 1990 N1IsConst = isa<ConstantSDNode>(N1); 1991 if (N1IsConst) 1992 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 1993 } 1994 1995 // fold (mul c1, c2) -> c1*c2 1996 if (N0IsConst && N1IsConst) 1997 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 1998 1999 // canonicalize constant to RHS (vector doesn't have to splat) 2000 if (isConstantIntBuildVectorOrConstantInt(N0) && 2001 !isConstantIntBuildVectorOrConstantInt(N1)) 2002 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2003 // fold (mul x, 0) -> 0 2004 if (N1IsConst && ConstValue1 == 0) 2005 return N1; 2006 // We require a splat of the entire scalar bit width for non-contiguous 2007 // bit patterns. 2008 bool IsFullSplat = 2009 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2010 // fold (mul x, 1) -> x 2011 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2012 return N0; 2013 // fold (mul x, -1) -> 0-x 2014 if (N1IsConst && ConstValue1.isAllOnesValue()) 2015 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2016 DAG.getConstant(0, VT), N0); 2017 // fold (mul x, (1 << c)) -> x << c 2018 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) 2019 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 2020 DAG.getConstant(ConstValue1.logBase2(), 2021 getShiftAmountTy(N0.getValueType()))); 2022 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2023 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 2024 unsigned Log2Val = (-ConstValue1).logBase2(); 2025 // FIXME: If the input is something that is easily negated (e.g. a 2026 // single-use add), we should put the negate there. 2027 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2028 DAG.getConstant(0, VT), 2029 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 2030 DAG.getConstant(Log2Val, 2031 getShiftAmountTy(N0.getValueType())))); 2032 } 2033 2034 APInt Val; 2035 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2036 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2037 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2038 isa<ConstantSDNode>(N0.getOperand(1)))) { 2039 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2040 N1, N0.getOperand(1)); 2041 AddToWorklist(C3.getNode()); 2042 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2043 N0.getOperand(0), C3); 2044 } 2045 2046 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2047 // use. 2048 { 2049 SDValue Sh(nullptr,0), Y(nullptr,0); 2050 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2051 if (N0.getOpcode() == ISD::SHL && 2052 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2053 isa<ConstantSDNode>(N0.getOperand(1))) && 2054 N0.getNode()->hasOneUse()) { 2055 Sh = N0; Y = N1; 2056 } else if (N1.getOpcode() == ISD::SHL && 2057 isa<ConstantSDNode>(N1.getOperand(1)) && 2058 N1.getNode()->hasOneUse()) { 2059 Sh = N1; Y = N0; 2060 } 2061 2062 if (Sh.getNode()) { 2063 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2064 Sh.getOperand(0), Y); 2065 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2066 Mul, Sh.getOperand(1)); 2067 } 2068 } 2069 2070 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2071 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 2072 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2073 isa<ConstantSDNode>(N0.getOperand(1)))) 2074 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2075 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2076 N0.getOperand(0), N1), 2077 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2078 N0.getOperand(1), N1)); 2079 2080 // reassociate mul 2081 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2082 return RMUL; 2083 2084 return SDValue(); 2085 } 2086 2087 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2088 SDValue N0 = N->getOperand(0); 2089 SDValue N1 = N->getOperand(1); 2090 EVT VT = N->getValueType(0); 2091 2092 // fold vector ops 2093 if (VT.isVector()) 2094 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2095 return FoldedVOp; 2096 2097 // fold (sdiv c1, c2) -> c1/c2 2098 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2099 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2100 if (N0C && N1C && !N1C->isNullValue()) 2101 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 2102 // fold (sdiv X, 1) -> X 2103 if (N1C && N1C->getAPIntValue() == 1LL) 2104 return N0; 2105 // fold (sdiv X, -1) -> 0-X 2106 if (N1C && N1C->isAllOnesValue()) 2107 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2108 DAG.getConstant(0, VT), N0); 2109 // If we know the sign bits of both operands are zero, strength reduce to a 2110 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2111 if (!VT.isVector()) { 2112 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2113 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2114 N0, N1); 2115 } 2116 2117 // fold (sdiv X, pow2) -> simple ops after legalize 2118 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() || 2119 (-N1C->getAPIntValue()).isPowerOf2())) { 2120 // If dividing by powers of two is cheap, then don't perform the following 2121 // fold. 2122 if (TLI.isPow2SDivCheap()) 2123 return SDValue(); 2124 2125 // Target-specific implementation of sdiv x, pow2. 2126 SDValue Res = BuildSDIVPow2(N); 2127 if (Res.getNode()) 2128 return Res; 2129 2130 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2131 2132 // Splat the sign bit into the register 2133 SDValue SGN = 2134 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 2135 DAG.getConstant(VT.getScalarSizeInBits() - 1, 2136 getShiftAmountTy(N0.getValueType()))); 2137 AddToWorklist(SGN.getNode()); 2138 2139 // Add (N0 < 0) ? abs2 - 1 : 0; 2140 SDValue SRL = 2141 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 2142 DAG.getConstant(VT.getScalarSizeInBits() - lg2, 2143 getShiftAmountTy(SGN.getValueType()))); 2144 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 2145 AddToWorklist(SRL.getNode()); 2146 AddToWorklist(ADD.getNode()); // Divide by pow2 2147 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 2148 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 2149 2150 // If we're dividing by a positive value, we're done. Otherwise, we must 2151 // negate the result. 2152 if (N1C->getAPIntValue().isNonNegative()) 2153 return SRA; 2154 2155 AddToWorklist(SRA.getNode()); 2156 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA); 2157 } 2158 2159 // If integer divide is expensive and we satisfy the requirements, emit an 2160 // alternate sequence. 2161 if (N1C && !TLI.isIntDivCheap()) { 2162 SDValue Op = BuildSDIV(N); 2163 if (Op.getNode()) return Op; 2164 } 2165 2166 // undef / X -> 0 2167 if (N0.getOpcode() == ISD::UNDEF) 2168 return DAG.getConstant(0, VT); 2169 // X / undef -> undef 2170 if (N1.getOpcode() == ISD::UNDEF) 2171 return N1; 2172 2173 return SDValue(); 2174 } 2175 2176 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2177 SDValue N0 = N->getOperand(0); 2178 SDValue N1 = N->getOperand(1); 2179 EVT VT = N->getValueType(0); 2180 2181 // fold vector ops 2182 if (VT.isVector()) 2183 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2184 return FoldedVOp; 2185 2186 // fold (udiv c1, c2) -> c1/c2 2187 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2188 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2189 if (N0C && N1C && !N1C->isNullValue()) 2190 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2191 // fold (udiv x, (1 << c)) -> x >>u c 2192 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2193 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2194 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2195 getShiftAmountTy(N0.getValueType()))); 2196 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2197 if (N1.getOpcode() == ISD::SHL) { 2198 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2199 if (SHC->getAPIntValue().isPowerOf2()) { 2200 EVT ADDVT = N1.getOperand(1).getValueType(); 2201 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2202 N1.getOperand(1), 2203 DAG.getConstant(SHC->getAPIntValue() 2204 .logBase2(), 2205 ADDVT)); 2206 AddToWorklist(Add.getNode()); 2207 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2208 } 2209 } 2210 } 2211 // fold (udiv x, c) -> alternate 2212 if (N1C && !TLI.isIntDivCheap()) { 2213 SDValue Op = BuildUDIV(N); 2214 if (Op.getNode()) return Op; 2215 } 2216 2217 // undef / X -> 0 2218 if (N0.getOpcode() == ISD::UNDEF) 2219 return DAG.getConstant(0, VT); 2220 // X / undef -> undef 2221 if (N1.getOpcode() == ISD::UNDEF) 2222 return N1; 2223 2224 return SDValue(); 2225 } 2226 2227 SDValue DAGCombiner::visitSREM(SDNode *N) { 2228 SDValue N0 = N->getOperand(0); 2229 SDValue N1 = N->getOperand(1); 2230 EVT VT = N->getValueType(0); 2231 2232 // fold (srem c1, c2) -> c1%c2 2233 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2234 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2235 if (N0C && N1C && !N1C->isNullValue()) 2236 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2237 // If we know the sign bits of both operands are zero, strength reduce to a 2238 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2239 if (!VT.isVector()) { 2240 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2241 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2242 } 2243 2244 // If X/C can be simplified by the division-by-constant logic, lower 2245 // X%C to the equivalent of X-X/C*C. 2246 if (N1C && !N1C->isNullValue()) { 2247 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2248 AddToWorklist(Div.getNode()); 2249 SDValue OptimizedDiv = combine(Div.getNode()); 2250 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2251 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2252 OptimizedDiv, N1); 2253 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2254 AddToWorklist(Mul.getNode()); 2255 return Sub; 2256 } 2257 } 2258 2259 // undef % X -> 0 2260 if (N0.getOpcode() == ISD::UNDEF) 2261 return DAG.getConstant(0, VT); 2262 // X % undef -> undef 2263 if (N1.getOpcode() == ISD::UNDEF) 2264 return N1; 2265 2266 return SDValue(); 2267 } 2268 2269 SDValue DAGCombiner::visitUREM(SDNode *N) { 2270 SDValue N0 = N->getOperand(0); 2271 SDValue N1 = N->getOperand(1); 2272 EVT VT = N->getValueType(0); 2273 2274 // fold (urem c1, c2) -> c1%c2 2275 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2276 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2277 if (N0C && N1C && !N1C->isNullValue()) 2278 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2279 // fold (urem x, pow2) -> (and x, pow2-1) 2280 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2281 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2282 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2283 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2284 if (N1.getOpcode() == ISD::SHL) { 2285 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2286 if (SHC->getAPIntValue().isPowerOf2()) { 2287 SDValue Add = 2288 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2289 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2290 VT)); 2291 AddToWorklist(Add.getNode()); 2292 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2293 } 2294 } 2295 } 2296 2297 // If X/C can be simplified by the division-by-constant logic, lower 2298 // X%C to the equivalent of X-X/C*C. 2299 if (N1C && !N1C->isNullValue()) { 2300 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2301 AddToWorklist(Div.getNode()); 2302 SDValue OptimizedDiv = combine(Div.getNode()); 2303 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2304 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2305 OptimizedDiv, N1); 2306 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2307 AddToWorklist(Mul.getNode()); 2308 return Sub; 2309 } 2310 } 2311 2312 // undef % X -> 0 2313 if (N0.getOpcode() == ISD::UNDEF) 2314 return DAG.getConstant(0, VT); 2315 // X % undef -> undef 2316 if (N1.getOpcode() == ISD::UNDEF) 2317 return N1; 2318 2319 return SDValue(); 2320 } 2321 2322 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2323 SDValue N0 = N->getOperand(0); 2324 SDValue N1 = N->getOperand(1); 2325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2326 EVT VT = N->getValueType(0); 2327 SDLoc DL(N); 2328 2329 // fold (mulhs x, 0) -> 0 2330 if (N1C && N1C->isNullValue()) 2331 return N1; 2332 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2333 if (N1C && N1C->getAPIntValue() == 1) 2334 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2335 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2336 getShiftAmountTy(N0.getValueType()))); 2337 // fold (mulhs x, undef) -> 0 2338 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2339 return DAG.getConstant(0, VT); 2340 2341 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2342 // plus a shift. 2343 if (VT.isSimple() && !VT.isVector()) { 2344 MVT Simple = VT.getSimpleVT(); 2345 unsigned SimpleSize = Simple.getSizeInBits(); 2346 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2347 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2348 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2349 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2350 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2351 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2352 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2353 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2354 } 2355 } 2356 2357 return SDValue(); 2358 } 2359 2360 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2361 SDValue N0 = N->getOperand(0); 2362 SDValue N1 = N->getOperand(1); 2363 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2364 EVT VT = N->getValueType(0); 2365 SDLoc DL(N); 2366 2367 // fold (mulhu x, 0) -> 0 2368 if (N1C && N1C->isNullValue()) 2369 return N1; 2370 // fold (mulhu x, 1) -> 0 2371 if (N1C && N1C->getAPIntValue() == 1) 2372 return DAG.getConstant(0, N0.getValueType()); 2373 // fold (mulhu x, undef) -> 0 2374 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2375 return DAG.getConstant(0, VT); 2376 2377 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2378 // plus a shift. 2379 if (VT.isSimple() && !VT.isVector()) { 2380 MVT Simple = VT.getSimpleVT(); 2381 unsigned SimpleSize = Simple.getSizeInBits(); 2382 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2383 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2384 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2385 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2386 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2387 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2388 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2389 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2390 } 2391 } 2392 2393 return SDValue(); 2394 } 2395 2396 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2397 /// give the opcodes for the two computations that are being performed. Return 2398 /// true if a simplification was made. 2399 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2400 unsigned HiOp) { 2401 // If the high half is not needed, just compute the low half. 2402 bool HiExists = N->hasAnyUseOfValue(1); 2403 if (!HiExists && 2404 (!LegalOperations || 2405 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2406 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2407 return CombineTo(N, Res, Res); 2408 } 2409 2410 // If the low half is not needed, just compute the high half. 2411 bool LoExists = N->hasAnyUseOfValue(0); 2412 if (!LoExists && 2413 (!LegalOperations || 2414 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2415 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2416 return CombineTo(N, Res, Res); 2417 } 2418 2419 // If both halves are used, return as it is. 2420 if (LoExists && HiExists) 2421 return SDValue(); 2422 2423 // If the two computed results can be simplified separately, separate them. 2424 if (LoExists) { 2425 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2426 AddToWorklist(Lo.getNode()); 2427 SDValue LoOpt = combine(Lo.getNode()); 2428 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2429 (!LegalOperations || 2430 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2431 return CombineTo(N, LoOpt, LoOpt); 2432 } 2433 2434 if (HiExists) { 2435 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2436 AddToWorklist(Hi.getNode()); 2437 SDValue HiOpt = combine(Hi.getNode()); 2438 if (HiOpt.getNode() && HiOpt != Hi && 2439 (!LegalOperations || 2440 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2441 return CombineTo(N, HiOpt, HiOpt); 2442 } 2443 2444 return SDValue(); 2445 } 2446 2447 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2448 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2449 if (Res.getNode()) return Res; 2450 2451 EVT VT = N->getValueType(0); 2452 SDLoc DL(N); 2453 2454 // If the type is twice as wide is legal, transform the mulhu to a wider 2455 // multiply plus a shift. 2456 if (VT.isSimple() && !VT.isVector()) { 2457 MVT Simple = VT.getSimpleVT(); 2458 unsigned SimpleSize = Simple.getSizeInBits(); 2459 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2460 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2461 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2462 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2463 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2464 // Compute the high part as N1. 2465 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2466 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2467 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2468 // Compute the low part as N0. 2469 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2470 return CombineTo(N, Lo, Hi); 2471 } 2472 } 2473 2474 return SDValue(); 2475 } 2476 2477 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2478 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2479 if (Res.getNode()) return Res; 2480 2481 EVT VT = N->getValueType(0); 2482 SDLoc DL(N); 2483 2484 // If the type is twice as wide is legal, transform the mulhu to a wider 2485 // multiply plus a shift. 2486 if (VT.isSimple() && !VT.isVector()) { 2487 MVT Simple = VT.getSimpleVT(); 2488 unsigned SimpleSize = Simple.getSizeInBits(); 2489 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2490 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2491 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2492 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2493 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2494 // Compute the high part as N1. 2495 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2496 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2497 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2498 // Compute the low part as N0. 2499 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2500 return CombineTo(N, Lo, Hi); 2501 } 2502 } 2503 2504 return SDValue(); 2505 } 2506 2507 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2508 // (smulo x, 2) -> (saddo x, x) 2509 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2510 if (C2->getAPIntValue() == 2) 2511 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2512 N->getOperand(0), N->getOperand(0)); 2513 2514 return SDValue(); 2515 } 2516 2517 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2518 // (umulo x, 2) -> (uaddo x, x) 2519 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2520 if (C2->getAPIntValue() == 2) 2521 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2522 N->getOperand(0), N->getOperand(0)); 2523 2524 return SDValue(); 2525 } 2526 2527 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2528 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2529 if (Res.getNode()) return Res; 2530 2531 return SDValue(); 2532 } 2533 2534 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2535 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2536 if (Res.getNode()) return Res; 2537 2538 return SDValue(); 2539 } 2540 2541 /// If this is a binary operator with two operands of the same opcode, try to 2542 /// simplify it. 2543 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2544 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2545 EVT VT = N0.getValueType(); 2546 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2547 2548 // Bail early if none of these transforms apply. 2549 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2550 2551 // For each of OP in AND/OR/XOR: 2552 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2553 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2554 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2555 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2556 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2557 // 2558 // do not sink logical op inside of a vector extend, since it may combine 2559 // into a vsetcc. 2560 EVT Op0VT = N0.getOperand(0).getValueType(); 2561 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2562 N0.getOpcode() == ISD::SIGN_EXTEND || 2563 N0.getOpcode() == ISD::BSWAP || 2564 // Avoid infinite looping with PromoteIntBinOp. 2565 (N0.getOpcode() == ISD::ANY_EXTEND && 2566 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2567 (N0.getOpcode() == ISD::TRUNCATE && 2568 (!TLI.isZExtFree(VT, Op0VT) || 2569 !TLI.isTruncateFree(Op0VT, VT)) && 2570 TLI.isTypeLegal(Op0VT))) && 2571 !VT.isVector() && 2572 Op0VT == N1.getOperand(0).getValueType() && 2573 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2574 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2575 N0.getOperand(0).getValueType(), 2576 N0.getOperand(0), N1.getOperand(0)); 2577 AddToWorklist(ORNode.getNode()); 2578 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2579 } 2580 2581 // For each of OP in SHL/SRL/SRA/AND... 2582 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2583 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2584 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2585 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2586 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2587 N0.getOperand(1) == N1.getOperand(1)) { 2588 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2589 N0.getOperand(0).getValueType(), 2590 N0.getOperand(0), N1.getOperand(0)); 2591 AddToWorklist(ORNode.getNode()); 2592 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2593 ORNode, N0.getOperand(1)); 2594 } 2595 2596 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2597 // Only perform this optimization after type legalization and before 2598 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2599 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2600 // we don't want to undo this promotion. 2601 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2602 // on scalars. 2603 if ((N0.getOpcode() == ISD::BITCAST || 2604 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2605 Level == AfterLegalizeTypes) { 2606 SDValue In0 = N0.getOperand(0); 2607 SDValue In1 = N1.getOperand(0); 2608 EVT In0Ty = In0.getValueType(); 2609 EVT In1Ty = In1.getValueType(); 2610 SDLoc DL(N); 2611 // If both incoming values are integers, and the original types are the 2612 // same. 2613 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2614 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2615 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2616 AddToWorklist(Op.getNode()); 2617 return BC; 2618 } 2619 } 2620 2621 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2622 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2623 // If both shuffles use the same mask, and both shuffle within a single 2624 // vector, then it is worthwhile to move the swizzle after the operation. 2625 // The type-legalizer generates this pattern when loading illegal 2626 // vector types from memory. In many cases this allows additional shuffle 2627 // optimizations. 2628 // There are other cases where moving the shuffle after the xor/and/or 2629 // is profitable even if shuffles don't perform a swizzle. 2630 // If both shuffles use the same mask, and both shuffles have the same first 2631 // or second operand, then it might still be profitable to move the shuffle 2632 // after the xor/and/or operation. 2633 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2634 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2635 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2636 2637 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2638 "Inputs to shuffles are not the same type"); 2639 2640 // Check that both shuffles use the same mask. The masks are known to be of 2641 // the same length because the result vector type is the same. 2642 // Check also that shuffles have only one use to avoid introducing extra 2643 // instructions. 2644 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2645 SVN0->getMask().equals(SVN1->getMask())) { 2646 SDValue ShOp = N0->getOperand(1); 2647 2648 // Don't try to fold this node if it requires introducing a 2649 // build vector of all zeros that might be illegal at this stage. 2650 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2651 if (!LegalTypes) 2652 ShOp = DAG.getConstant(0, VT); 2653 else 2654 ShOp = SDValue(); 2655 } 2656 2657 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2658 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2659 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2660 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2661 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2662 N0->getOperand(0), N1->getOperand(0)); 2663 AddToWorklist(NewNode.getNode()); 2664 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2665 &SVN0->getMask()[0]); 2666 } 2667 2668 // Don't try to fold this node if it requires introducing a 2669 // build vector of all zeros that might be illegal at this stage. 2670 ShOp = N0->getOperand(0); 2671 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2672 if (!LegalTypes) 2673 ShOp = DAG.getConstant(0, VT); 2674 else 2675 ShOp = SDValue(); 2676 } 2677 2678 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2679 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2680 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2681 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2682 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2683 N0->getOperand(1), N1->getOperand(1)); 2684 AddToWorklist(NewNode.getNode()); 2685 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2686 &SVN0->getMask()[0]); 2687 } 2688 } 2689 } 2690 2691 return SDValue(); 2692 } 2693 2694 /// This contains all DAGCombine rules which reduce two values combined by 2695 /// an And operation to a single value. This makes them reusable in the context 2696 /// of visitSELECT(). Rules involving constants are not included as 2697 /// visitSELECT() already handles those cases. 2698 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2699 SDNode *LocReference) { 2700 EVT VT = N1.getValueType(); 2701 2702 // fold (and x, undef) -> 0 2703 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2704 return DAG.getConstant(0, VT); 2705 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2706 SDValue LL, LR, RL, RR, CC0, CC1; 2707 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2708 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2709 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2710 2711 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2712 LL.getValueType().isInteger()) { 2713 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2714 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2715 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2716 LR.getValueType(), LL, RL); 2717 AddToWorklist(ORNode.getNode()); 2718 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2719 } 2720 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2721 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2722 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2723 LR.getValueType(), LL, RL); 2724 AddToWorklist(ANDNode.getNode()); 2725 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2726 } 2727 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2728 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2729 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2730 LR.getValueType(), LL, RL); 2731 AddToWorklist(ORNode.getNode()); 2732 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2733 } 2734 } 2735 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2736 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2737 Op0 == Op1 && LL.getValueType().isInteger() && 2738 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2739 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2740 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2741 cast<ConstantSDNode>(RR)->isNullValue()))) { 2742 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2743 LL, DAG.getConstant(1, LL.getValueType())); 2744 AddToWorklist(ADDNode.getNode()); 2745 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2746 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2747 } 2748 // canonicalize equivalent to ll == rl 2749 if (LL == RR && LR == RL) { 2750 Op1 = ISD::getSetCCSwappedOperands(Op1); 2751 std::swap(RL, RR); 2752 } 2753 if (LL == RL && LR == RR) { 2754 bool isInteger = LL.getValueType().isInteger(); 2755 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2756 if (Result != ISD::SETCC_INVALID && 2757 (!LegalOperations || 2758 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2759 TLI.isOperationLegal(ISD::SETCC, 2760 getSetCCResultType(N0.getSimpleValueType()))))) 2761 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2762 LL, LR, Result); 2763 } 2764 } 2765 2766 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2767 VT.getSizeInBits() <= 64) { 2768 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2769 APInt ADDC = ADDI->getAPIntValue(); 2770 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2771 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2772 // immediate for an add, but it is legal if its top c2 bits are set, 2773 // transform the ADD so the immediate doesn't need to be materialized 2774 // in a register. 2775 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2776 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2777 SRLI->getZExtValue()); 2778 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2779 ADDC |= Mask; 2780 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2781 SDValue NewAdd = 2782 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 2783 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 2784 CombineTo(N0.getNode(), NewAdd); 2785 // Return N so it doesn't get rechecked! 2786 return SDValue(LocReference, 0); 2787 } 2788 } 2789 } 2790 } 2791 } 2792 } 2793 2794 return SDValue(); 2795 } 2796 2797 SDValue DAGCombiner::visitAND(SDNode *N) { 2798 SDValue N0 = N->getOperand(0); 2799 SDValue N1 = N->getOperand(1); 2800 EVT VT = N1.getValueType(); 2801 2802 // fold vector ops 2803 if (VT.isVector()) { 2804 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2805 return FoldedVOp; 2806 2807 // fold (and x, 0) -> 0, vector edition 2808 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2809 // do not return N0, because undef node may exist in N0 2810 return DAG.getConstant( 2811 APInt::getNullValue( 2812 N0.getValueType().getScalarType().getSizeInBits()), 2813 N0.getValueType()); 2814 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2815 // do not return N1, because undef node may exist in N1 2816 return DAG.getConstant( 2817 APInt::getNullValue( 2818 N1.getValueType().getScalarType().getSizeInBits()), 2819 N1.getValueType()); 2820 2821 // fold (and x, -1) -> x, vector edition 2822 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2823 return N1; 2824 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2825 return N0; 2826 } 2827 2828 // fold (and c1, c2) -> c1&c2 2829 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2830 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2831 if (N0C && N1C) 2832 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2833 // canonicalize constant to RHS 2834 if (isConstantIntBuildVectorOrConstantInt(N0) && 2835 !isConstantIntBuildVectorOrConstantInt(N1)) 2836 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2837 // fold (and x, -1) -> x 2838 if (N1C && N1C->isAllOnesValue()) 2839 return N0; 2840 // if (and x, c) is known to be zero, return 0 2841 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2842 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2843 APInt::getAllOnesValue(BitWidth))) 2844 return DAG.getConstant(0, VT); 2845 // reassociate and 2846 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 2847 return RAND; 2848 // fold (and (or x, C), D) -> D if (C & D) == D 2849 if (N1C && N0.getOpcode() == ISD::OR) 2850 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2851 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2852 return N1; 2853 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2854 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2855 SDValue N0Op0 = N0.getOperand(0); 2856 APInt Mask = ~N1C->getAPIntValue(); 2857 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2858 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2859 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2860 N0.getValueType(), N0Op0); 2861 2862 // Replace uses of the AND with uses of the Zero extend node. 2863 CombineTo(N, Zext); 2864 2865 // We actually want to replace all uses of the any_extend with the 2866 // zero_extend, to avoid duplicating things. This will later cause this 2867 // AND to be folded. 2868 CombineTo(N0.getNode(), Zext); 2869 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2870 } 2871 } 2872 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2873 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2874 // already be zero by virtue of the width of the base type of the load. 2875 // 2876 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2877 // more cases. 2878 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2879 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2880 N0.getOpcode() == ISD::LOAD) { 2881 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2882 N0 : N0.getOperand(0) ); 2883 2884 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2885 // This can be a pure constant or a vector splat, in which case we treat the 2886 // vector as a scalar and use the splat value. 2887 APInt Constant = APInt::getNullValue(1); 2888 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2889 Constant = C->getAPIntValue(); 2890 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2891 APInt SplatValue, SplatUndef; 2892 unsigned SplatBitSize; 2893 bool HasAnyUndefs; 2894 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2895 SplatBitSize, HasAnyUndefs); 2896 if (IsSplat) { 2897 // Undef bits can contribute to a possible optimisation if set, so 2898 // set them. 2899 SplatValue |= SplatUndef; 2900 2901 // The splat value may be something like "0x00FFFFFF", which means 0 for 2902 // the first vector value and FF for the rest, repeating. We need a mask 2903 // that will apply equally to all members of the vector, so AND all the 2904 // lanes of the constant together. 2905 EVT VT = Vector->getValueType(0); 2906 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2907 2908 // If the splat value has been compressed to a bitlength lower 2909 // than the size of the vector lane, we need to re-expand it to 2910 // the lane size. 2911 if (BitWidth > SplatBitSize) 2912 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2913 SplatBitSize < BitWidth; 2914 SplatBitSize = SplatBitSize * 2) 2915 SplatValue |= SplatValue.shl(SplatBitSize); 2916 2917 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 2918 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 2919 if (SplatBitSize % BitWidth == 0) { 2920 Constant = APInt::getAllOnesValue(BitWidth); 2921 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2922 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2923 } 2924 } 2925 } 2926 2927 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2928 // actually legal and isn't going to get expanded, else this is a false 2929 // optimisation. 2930 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2931 Load->getValueType(0), 2932 Load->getMemoryVT()); 2933 2934 // Resize the constant to the same size as the original memory access before 2935 // extension. If it is still the AllOnesValue then this AND is completely 2936 // unneeded. 2937 Constant = 2938 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2939 2940 bool B; 2941 switch (Load->getExtensionType()) { 2942 default: B = false; break; 2943 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2944 case ISD::ZEXTLOAD: 2945 case ISD::NON_EXTLOAD: B = true; break; 2946 } 2947 2948 if (B && Constant.isAllOnesValue()) { 2949 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2950 // preserve semantics once we get rid of the AND. 2951 SDValue NewLoad(Load, 0); 2952 if (Load->getExtensionType() == ISD::EXTLOAD) { 2953 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2954 Load->getValueType(0), SDLoc(Load), 2955 Load->getChain(), Load->getBasePtr(), 2956 Load->getOffset(), Load->getMemoryVT(), 2957 Load->getMemOperand()); 2958 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2959 if (Load->getNumValues() == 3) { 2960 // PRE/POST_INC loads have 3 values. 2961 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2962 NewLoad.getValue(2) }; 2963 CombineTo(Load, To, 3, true); 2964 } else { 2965 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2966 } 2967 } 2968 2969 // Fold the AND away, taking care not to fold to the old load node if we 2970 // replaced it. 2971 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2972 2973 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2974 } 2975 } 2976 2977 // fold (and (load x), 255) -> (zextload x, i8) 2978 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2979 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2980 if (N1C && (N0.getOpcode() == ISD::LOAD || 2981 (N0.getOpcode() == ISD::ANY_EXTEND && 2982 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2983 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2984 LoadSDNode *LN0 = HasAnyExt 2985 ? cast<LoadSDNode>(N0.getOperand(0)) 2986 : cast<LoadSDNode>(N0); 2987 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2988 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2989 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2990 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2991 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2992 EVT LoadedVT = LN0->getMemoryVT(); 2993 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2994 2995 if (ExtVT == LoadedVT && 2996 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 2997 ExtVT))) { 2998 2999 SDValue NewLoad = 3000 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3001 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3002 LN0->getMemOperand()); 3003 AddToWorklist(N); 3004 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3005 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3006 } 3007 3008 // Do not change the width of a volatile load. 3009 // Do not generate loads of non-round integer types since these can 3010 // be expensive (and would be wrong if the type is not byte sized). 3011 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 3012 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3013 ExtVT))) { 3014 EVT PtrType = LN0->getOperand(1).getValueType(); 3015 3016 unsigned Alignment = LN0->getAlignment(); 3017 SDValue NewPtr = LN0->getBasePtr(); 3018 3019 // For big endian targets, we need to add an offset to the pointer 3020 // to load the correct bytes. For little endian systems, we merely 3021 // need to read fewer bytes from the same pointer. 3022 if (TLI.isBigEndian()) { 3023 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3024 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3025 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3026 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 3027 NewPtr, DAG.getConstant(PtrOff, PtrType)); 3028 Alignment = MinAlign(Alignment, PtrOff); 3029 } 3030 3031 AddToWorklist(NewPtr.getNode()); 3032 3033 SDValue Load = 3034 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3035 LN0->getChain(), NewPtr, 3036 LN0->getPointerInfo(), 3037 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3038 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3039 AddToWorklist(N); 3040 CombineTo(LN0, Load, Load.getValue(1)); 3041 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3042 } 3043 } 3044 } 3045 } 3046 3047 if (SDValue Combined = visitANDLike(N0, N1, N)) 3048 return Combined; 3049 3050 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3051 if (N0.getOpcode() == N1.getOpcode()) { 3052 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3053 if (Tmp.getNode()) return Tmp; 3054 } 3055 3056 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3057 // fold (and (sra)) -> (and (srl)) when possible. 3058 if (!VT.isVector() && 3059 SimplifyDemandedBits(SDValue(N, 0))) 3060 return SDValue(N, 0); 3061 3062 // fold (zext_inreg (extload x)) -> (zextload x) 3063 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3064 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3065 EVT MemVT = LN0->getMemoryVT(); 3066 // If we zero all the possible extended bits, then we can turn this into 3067 // a zextload if we are running before legalize or the operation is legal. 3068 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3069 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3070 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3071 ((!LegalOperations && !LN0->isVolatile()) || 3072 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3073 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3074 LN0->getChain(), LN0->getBasePtr(), 3075 MemVT, LN0->getMemOperand()); 3076 AddToWorklist(N); 3077 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3078 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3079 } 3080 } 3081 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3082 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3083 N0.hasOneUse()) { 3084 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3085 EVT MemVT = LN0->getMemoryVT(); 3086 // If we zero all the possible extended bits, then we can turn this into 3087 // a zextload if we are running before legalize or the operation is legal. 3088 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3089 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3090 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3091 ((!LegalOperations && !LN0->isVolatile()) || 3092 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3093 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3094 LN0->getChain(), LN0->getBasePtr(), 3095 MemVT, LN0->getMemOperand()); 3096 AddToWorklist(N); 3097 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3098 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3099 } 3100 } 3101 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3102 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3103 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3104 N0.getOperand(1), false); 3105 if (BSwap.getNode()) 3106 return BSwap; 3107 } 3108 3109 return SDValue(); 3110 } 3111 3112 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3113 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3114 bool DemandHighBits) { 3115 if (!LegalOperations) 3116 return SDValue(); 3117 3118 EVT VT = N->getValueType(0); 3119 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3120 return SDValue(); 3121 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3122 return SDValue(); 3123 3124 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3125 bool LookPassAnd0 = false; 3126 bool LookPassAnd1 = false; 3127 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3128 std::swap(N0, N1); 3129 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3130 std::swap(N0, N1); 3131 if (N0.getOpcode() == ISD::AND) { 3132 if (!N0.getNode()->hasOneUse()) 3133 return SDValue(); 3134 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3135 if (!N01C || N01C->getZExtValue() != 0xFF00) 3136 return SDValue(); 3137 N0 = N0.getOperand(0); 3138 LookPassAnd0 = true; 3139 } 3140 3141 if (N1.getOpcode() == ISD::AND) { 3142 if (!N1.getNode()->hasOneUse()) 3143 return SDValue(); 3144 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3145 if (!N11C || N11C->getZExtValue() != 0xFF) 3146 return SDValue(); 3147 N1 = N1.getOperand(0); 3148 LookPassAnd1 = true; 3149 } 3150 3151 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3152 std::swap(N0, N1); 3153 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3154 return SDValue(); 3155 if (!N0.getNode()->hasOneUse() || 3156 !N1.getNode()->hasOneUse()) 3157 return SDValue(); 3158 3159 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3160 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3161 if (!N01C || !N11C) 3162 return SDValue(); 3163 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3164 return SDValue(); 3165 3166 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3167 SDValue N00 = N0->getOperand(0); 3168 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3169 if (!N00.getNode()->hasOneUse()) 3170 return SDValue(); 3171 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3172 if (!N001C || N001C->getZExtValue() != 0xFF) 3173 return SDValue(); 3174 N00 = N00.getOperand(0); 3175 LookPassAnd0 = true; 3176 } 3177 3178 SDValue N10 = N1->getOperand(0); 3179 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3180 if (!N10.getNode()->hasOneUse()) 3181 return SDValue(); 3182 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3183 if (!N101C || N101C->getZExtValue() != 0xFF00) 3184 return SDValue(); 3185 N10 = N10.getOperand(0); 3186 LookPassAnd1 = true; 3187 } 3188 3189 if (N00 != N10) 3190 return SDValue(); 3191 3192 // Make sure everything beyond the low halfword gets set to zero since the SRL 3193 // 16 will clear the top bits. 3194 unsigned OpSizeInBits = VT.getSizeInBits(); 3195 if (DemandHighBits && OpSizeInBits > 16) { 3196 // If the left-shift isn't masked out then the only way this is a bswap is 3197 // if all bits beyond the low 8 are 0. In that case the entire pattern 3198 // reduces to a left shift anyway: leave it for other parts of the combiner. 3199 if (!LookPassAnd0) 3200 return SDValue(); 3201 3202 // However, if the right shift isn't masked out then it might be because 3203 // it's not needed. See if we can spot that too. 3204 if (!LookPassAnd1 && 3205 !DAG.MaskedValueIsZero( 3206 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3207 return SDValue(); 3208 } 3209 3210 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3211 if (OpSizeInBits > 16) 3212 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 3213 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 3214 return Res; 3215 } 3216 3217 /// Return true if the specified node is an element that makes up a 32-bit 3218 /// packed halfword byteswap. 3219 /// ((x & 0x000000ff) << 8) | 3220 /// ((x & 0x0000ff00) >> 8) | 3221 /// ((x & 0x00ff0000) << 8) | 3222 /// ((x & 0xff000000) >> 8) 3223 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3224 if (!N.getNode()->hasOneUse()) 3225 return false; 3226 3227 unsigned Opc = N.getOpcode(); 3228 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3229 return false; 3230 3231 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3232 if (!N1C) 3233 return false; 3234 3235 unsigned Num; 3236 switch (N1C->getZExtValue()) { 3237 default: 3238 return false; 3239 case 0xFF: Num = 0; break; 3240 case 0xFF00: Num = 1; break; 3241 case 0xFF0000: Num = 2; break; 3242 case 0xFF000000: Num = 3; break; 3243 } 3244 3245 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3246 SDValue N0 = N.getOperand(0); 3247 if (Opc == ISD::AND) { 3248 if (Num == 0 || Num == 2) { 3249 // (x >> 8) & 0xff 3250 // (x >> 8) & 0xff0000 3251 if (N0.getOpcode() != ISD::SRL) 3252 return false; 3253 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3254 if (!C || C->getZExtValue() != 8) 3255 return false; 3256 } else { 3257 // (x << 8) & 0xff00 3258 // (x << 8) & 0xff000000 3259 if (N0.getOpcode() != ISD::SHL) 3260 return false; 3261 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3262 if (!C || C->getZExtValue() != 8) 3263 return false; 3264 } 3265 } else if (Opc == ISD::SHL) { 3266 // (x & 0xff) << 8 3267 // (x & 0xff0000) << 8 3268 if (Num != 0 && Num != 2) 3269 return false; 3270 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3271 if (!C || C->getZExtValue() != 8) 3272 return false; 3273 } else { // Opc == ISD::SRL 3274 // (x & 0xff00) >> 8 3275 // (x & 0xff000000) >> 8 3276 if (Num != 1 && Num != 3) 3277 return false; 3278 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3279 if (!C || C->getZExtValue() != 8) 3280 return false; 3281 } 3282 3283 if (Parts[Num]) 3284 return false; 3285 3286 Parts[Num] = N0.getOperand(0).getNode(); 3287 return true; 3288 } 3289 3290 /// Match a 32-bit packed halfword bswap. That is 3291 /// ((x & 0x000000ff) << 8) | 3292 /// ((x & 0x0000ff00) >> 8) | 3293 /// ((x & 0x00ff0000) << 8) | 3294 /// ((x & 0xff000000) >> 8) 3295 /// => (rotl (bswap x), 16) 3296 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3297 if (!LegalOperations) 3298 return SDValue(); 3299 3300 EVT VT = N->getValueType(0); 3301 if (VT != MVT::i32) 3302 return SDValue(); 3303 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3304 return SDValue(); 3305 3306 // Look for either 3307 // (or (or (and), (and)), (or (and), (and))) 3308 // (or (or (or (and), (and)), (and)), (and)) 3309 if (N0.getOpcode() != ISD::OR) 3310 return SDValue(); 3311 SDValue N00 = N0.getOperand(0); 3312 SDValue N01 = N0.getOperand(1); 3313 SDNode *Parts[4] = {}; 3314 3315 if (N1.getOpcode() == ISD::OR && 3316 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3317 // (or (or (and), (and)), (or (and), (and))) 3318 SDValue N000 = N00.getOperand(0); 3319 if (!isBSwapHWordElement(N000, Parts)) 3320 return SDValue(); 3321 3322 SDValue N001 = N00.getOperand(1); 3323 if (!isBSwapHWordElement(N001, Parts)) 3324 return SDValue(); 3325 SDValue N010 = N01.getOperand(0); 3326 if (!isBSwapHWordElement(N010, Parts)) 3327 return SDValue(); 3328 SDValue N011 = N01.getOperand(1); 3329 if (!isBSwapHWordElement(N011, Parts)) 3330 return SDValue(); 3331 } else { 3332 // (or (or (or (and), (and)), (and)), (and)) 3333 if (!isBSwapHWordElement(N1, Parts)) 3334 return SDValue(); 3335 if (!isBSwapHWordElement(N01, Parts)) 3336 return SDValue(); 3337 if (N00.getOpcode() != ISD::OR) 3338 return SDValue(); 3339 SDValue N000 = N00.getOperand(0); 3340 if (!isBSwapHWordElement(N000, Parts)) 3341 return SDValue(); 3342 SDValue N001 = N00.getOperand(1); 3343 if (!isBSwapHWordElement(N001, Parts)) 3344 return SDValue(); 3345 } 3346 3347 // Make sure the parts are all coming from the same node. 3348 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3349 return SDValue(); 3350 3351 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3352 SDValue(Parts[0],0)); 3353 3354 // Result of the bswap should be rotated by 16. If it's not legal, then 3355 // do (x << 16) | (x >> 16). 3356 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3357 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3358 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3359 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3360 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3361 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3362 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3363 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3364 } 3365 3366 /// This contains all DAGCombine rules which reduce two values combined by 3367 /// an Or operation to a single value \see visitANDLike(). 3368 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3369 EVT VT = N1.getValueType(); 3370 // fold (or x, undef) -> -1 3371 if (!LegalOperations && 3372 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3373 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3374 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3375 } 3376 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3377 SDValue LL, LR, RL, RR, CC0, CC1; 3378 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3379 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3380 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3381 3382 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3383 LL.getValueType().isInteger()) { 3384 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3385 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3386 if (cast<ConstantSDNode>(LR)->isNullValue() && 3387 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3388 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3389 LR.getValueType(), LL, RL); 3390 AddToWorklist(ORNode.getNode()); 3391 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3392 } 3393 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3394 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3395 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3396 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3397 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3398 LR.getValueType(), LL, RL); 3399 AddToWorklist(ANDNode.getNode()); 3400 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3401 } 3402 } 3403 // canonicalize equivalent to ll == rl 3404 if (LL == RR && LR == RL) { 3405 Op1 = ISD::getSetCCSwappedOperands(Op1); 3406 std::swap(RL, RR); 3407 } 3408 if (LL == RL && LR == RR) { 3409 bool isInteger = LL.getValueType().isInteger(); 3410 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3411 if (Result != ISD::SETCC_INVALID && 3412 (!LegalOperations || 3413 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3414 TLI.isOperationLegal(ISD::SETCC, 3415 getSetCCResultType(N0.getValueType()))))) 3416 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3417 LL, LR, Result); 3418 } 3419 } 3420 3421 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3422 if (N0.getOpcode() == ISD::AND && 3423 N1.getOpcode() == ISD::AND && 3424 N0.getOperand(1).getOpcode() == ISD::Constant && 3425 N1.getOperand(1).getOpcode() == ISD::Constant && 3426 // Don't increase # computations. 3427 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3428 // We can only do this xform if we know that bits from X that are set in C2 3429 // but not in C1 are already zero. Likewise for Y. 3430 const APInt &LHSMask = 3431 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3432 const APInt &RHSMask = 3433 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3434 3435 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3436 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3437 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3438 N0.getOperand(0), N1.getOperand(0)); 3439 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X, 3440 DAG.getConstant(LHSMask | RHSMask, VT)); 3441 } 3442 } 3443 3444 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3445 if (N0.getOpcode() == ISD::AND && 3446 N1.getOpcode() == ISD::AND && 3447 N0.getOperand(0) == N1.getOperand(0) && 3448 // Don't increase # computations. 3449 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3450 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3451 N0.getOperand(1), N1.getOperand(1)); 3452 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3453 } 3454 3455 return SDValue(); 3456 } 3457 3458 SDValue DAGCombiner::visitOR(SDNode *N) { 3459 SDValue N0 = N->getOperand(0); 3460 SDValue N1 = N->getOperand(1); 3461 EVT VT = N1.getValueType(); 3462 3463 // fold vector ops 3464 if (VT.isVector()) { 3465 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3466 return FoldedVOp; 3467 3468 // fold (or x, 0) -> x, vector edition 3469 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3470 return N1; 3471 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3472 return N0; 3473 3474 // fold (or x, -1) -> -1, vector edition 3475 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3476 // do not return N0, because undef node may exist in N0 3477 return DAG.getConstant( 3478 APInt::getAllOnesValue( 3479 N0.getValueType().getScalarType().getSizeInBits()), 3480 N0.getValueType()); 3481 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3482 // do not return N1, because undef node may exist in N1 3483 return DAG.getConstant( 3484 APInt::getAllOnesValue( 3485 N1.getValueType().getScalarType().getSizeInBits()), 3486 N1.getValueType()); 3487 3488 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3489 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3490 // Do this only if the resulting shuffle is legal. 3491 if (isa<ShuffleVectorSDNode>(N0) && 3492 isa<ShuffleVectorSDNode>(N1) && 3493 // Avoid folding a node with illegal type. 3494 TLI.isTypeLegal(VT) && 3495 N0->getOperand(1) == N1->getOperand(1) && 3496 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3497 bool CanFold = true; 3498 unsigned NumElts = VT.getVectorNumElements(); 3499 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3500 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3501 // We construct two shuffle masks: 3502 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3503 // and N1 as the second operand. 3504 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3505 // and N0 as the second operand. 3506 // We do this because OR is commutable and therefore there might be 3507 // two ways to fold this node into a shuffle. 3508 SmallVector<int,4> Mask1; 3509 SmallVector<int,4> Mask2; 3510 3511 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3512 int M0 = SV0->getMaskElt(i); 3513 int M1 = SV1->getMaskElt(i); 3514 3515 // Both shuffle indexes are undef. Propagate Undef. 3516 if (M0 < 0 && M1 < 0) { 3517 Mask1.push_back(M0); 3518 Mask2.push_back(M0); 3519 continue; 3520 } 3521 3522 if (M0 < 0 || M1 < 0 || 3523 (M0 < (int)NumElts && M1 < (int)NumElts) || 3524 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3525 CanFold = false; 3526 break; 3527 } 3528 3529 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3530 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3531 } 3532 3533 if (CanFold) { 3534 // Fold this sequence only if the resulting shuffle is 'legal'. 3535 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3536 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3537 N1->getOperand(0), &Mask1[0]); 3538 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3539 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3540 N0->getOperand(0), &Mask2[0]); 3541 } 3542 } 3543 } 3544 3545 // fold (or c1, c2) -> c1|c2 3546 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3547 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3548 if (N0C && N1C) 3549 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3550 // canonicalize constant to RHS 3551 if (isConstantIntBuildVectorOrConstantInt(N0) && 3552 !isConstantIntBuildVectorOrConstantInt(N1)) 3553 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3554 // fold (or x, 0) -> x 3555 if (N1C && N1C->isNullValue()) 3556 return N0; 3557 // fold (or x, -1) -> -1 3558 if (N1C && N1C->isAllOnesValue()) 3559 return N1; 3560 // fold (or x, c) -> c iff (x & ~c) == 0 3561 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3562 return N1; 3563 3564 if (SDValue Combined = visitORLike(N0, N1, N)) 3565 return Combined; 3566 3567 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3568 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3569 if (BSwap.getNode()) 3570 return BSwap; 3571 BSwap = MatchBSwapHWordLow(N, N0, N1); 3572 if (BSwap.getNode()) 3573 return BSwap; 3574 3575 // reassociate or 3576 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3577 return ROR; 3578 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3579 // iff (c1 & c2) == 0. 3580 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3581 isa<ConstantSDNode>(N0.getOperand(1))) { 3582 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3583 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3584 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1)) 3585 return DAG.getNode( 3586 ISD::AND, SDLoc(N), VT, 3587 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3588 return SDValue(); 3589 } 3590 } 3591 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3592 if (N0.getOpcode() == N1.getOpcode()) { 3593 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3594 if (Tmp.getNode()) return Tmp; 3595 } 3596 3597 // See if this is some rotate idiom. 3598 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3599 return SDValue(Rot, 0); 3600 3601 // Simplify the operands using demanded-bits information. 3602 if (!VT.isVector() && 3603 SimplifyDemandedBits(SDValue(N, 0))) 3604 return SDValue(N, 0); 3605 3606 return SDValue(); 3607 } 3608 3609 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3610 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3611 if (Op.getOpcode() == ISD::AND) { 3612 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3613 Mask = Op.getOperand(1); 3614 Op = Op.getOperand(0); 3615 } else { 3616 return false; 3617 } 3618 } 3619 3620 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3621 Shift = Op; 3622 return true; 3623 } 3624 3625 return false; 3626 } 3627 3628 // Return true if we can prove that, whenever Neg and Pos are both in the 3629 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3630 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3631 // 3632 // (or (shift1 X, Neg), (shift2 X, Pos)) 3633 // 3634 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3635 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3636 // to consider shift amounts with defined behavior. 3637 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3638 // If OpSize is a power of 2 then: 3639 // 3640 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3641 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3642 // 3643 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3644 // for the stronger condition: 3645 // 3646 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3647 // 3648 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3649 // we can just replace Neg with Neg' for the rest of the function. 3650 // 3651 // In other cases we check for the even stronger condition: 3652 // 3653 // Neg == OpSize - Pos [B] 3654 // 3655 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3656 // behavior if Pos == 0 (and consequently Neg == OpSize). 3657 // 3658 // We could actually use [A] whenever OpSize is a power of 2, but the 3659 // only extra cases that it would match are those uninteresting ones 3660 // where Neg and Pos are never in range at the same time. E.g. for 3661 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3662 // as well as (sub 32, Pos), but: 3663 // 3664 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3665 // 3666 // always invokes undefined behavior for 32-bit X. 3667 // 3668 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3669 unsigned MaskLoBits = 0; 3670 if (Neg.getOpcode() == ISD::AND && 3671 isPowerOf2_64(OpSize) && 3672 Neg.getOperand(1).getOpcode() == ISD::Constant && 3673 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3674 Neg = Neg.getOperand(0); 3675 MaskLoBits = Log2_64(OpSize); 3676 } 3677 3678 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3679 if (Neg.getOpcode() != ISD::SUB) 3680 return 0; 3681 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3682 if (!NegC) 3683 return 0; 3684 SDValue NegOp1 = Neg.getOperand(1); 3685 3686 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3687 // Pos'. The truncation is redundant for the purpose of the equality. 3688 if (MaskLoBits && 3689 Pos.getOpcode() == ISD::AND && 3690 Pos.getOperand(1).getOpcode() == ISD::Constant && 3691 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3692 Pos = Pos.getOperand(0); 3693 3694 // The condition we need is now: 3695 // 3696 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3697 // 3698 // If NegOp1 == Pos then we need: 3699 // 3700 // OpSize & Mask == NegC & Mask 3701 // 3702 // (because "x & Mask" is a truncation and distributes through subtraction). 3703 APInt Width; 3704 if (Pos == NegOp1) 3705 Width = NegC->getAPIntValue(); 3706 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3707 // Then the condition we want to prove becomes: 3708 // 3709 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3710 // 3711 // which, again because "x & Mask" is a truncation, becomes: 3712 // 3713 // NegC & Mask == (OpSize - PosC) & Mask 3714 // OpSize & Mask == (NegC + PosC) & Mask 3715 else if (Pos.getOpcode() == ISD::ADD && 3716 Pos.getOperand(0) == NegOp1 && 3717 Pos.getOperand(1).getOpcode() == ISD::Constant) 3718 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3719 NegC->getAPIntValue()); 3720 else 3721 return false; 3722 3723 // Now we just need to check that OpSize & Mask == Width & Mask. 3724 if (MaskLoBits) 3725 // Opsize & Mask is 0 since Mask is Opsize - 1. 3726 return Width.getLoBits(MaskLoBits) == 0; 3727 return Width == OpSize; 3728 } 3729 3730 // A subroutine of MatchRotate used once we have found an OR of two opposite 3731 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3732 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3733 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3734 // Neg with outer conversions stripped away. 3735 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3736 SDValue Neg, SDValue InnerPos, 3737 SDValue InnerNeg, unsigned PosOpcode, 3738 unsigned NegOpcode, SDLoc DL) { 3739 // fold (or (shl x, (*ext y)), 3740 // (srl x, (*ext (sub 32, y)))) -> 3741 // (rotl x, y) or (rotr x, (sub 32, y)) 3742 // 3743 // fold (or (shl x, (*ext (sub 32, y))), 3744 // (srl x, (*ext y))) -> 3745 // (rotr x, y) or (rotl x, (sub 32, y)) 3746 EVT VT = Shifted.getValueType(); 3747 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3748 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3749 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3750 HasPos ? Pos : Neg).getNode(); 3751 } 3752 3753 return nullptr; 3754 } 3755 3756 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3757 // idioms for rotate, and if the target supports rotation instructions, generate 3758 // a rot[lr]. 3759 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3760 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3761 EVT VT = LHS.getValueType(); 3762 if (!TLI.isTypeLegal(VT)) return nullptr; 3763 3764 // The target must have at least one rotate flavor. 3765 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3766 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3767 if (!HasROTL && !HasROTR) return nullptr; 3768 3769 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3770 SDValue LHSShift; // The shift. 3771 SDValue LHSMask; // AND value if any. 3772 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3773 return nullptr; // Not part of a rotate. 3774 3775 SDValue RHSShift; // The shift. 3776 SDValue RHSMask; // AND value if any. 3777 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3778 return nullptr; // Not part of a rotate. 3779 3780 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3781 return nullptr; // Not shifting the same value. 3782 3783 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3784 return nullptr; // Shifts must disagree. 3785 3786 // Canonicalize shl to left side in a shl/srl pair. 3787 if (RHSShift.getOpcode() == ISD::SHL) { 3788 std::swap(LHS, RHS); 3789 std::swap(LHSShift, RHSShift); 3790 std::swap(LHSMask , RHSMask ); 3791 } 3792 3793 unsigned OpSizeInBits = VT.getSizeInBits(); 3794 SDValue LHSShiftArg = LHSShift.getOperand(0); 3795 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3796 SDValue RHSShiftArg = RHSShift.getOperand(0); 3797 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3798 3799 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3800 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3801 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3802 RHSShiftAmt.getOpcode() == ISD::Constant) { 3803 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3804 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3805 if ((LShVal + RShVal) != OpSizeInBits) 3806 return nullptr; 3807 3808 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3809 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3810 3811 // If there is an AND of either shifted operand, apply it to the result. 3812 if (LHSMask.getNode() || RHSMask.getNode()) { 3813 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3814 3815 if (LHSMask.getNode()) { 3816 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3817 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3818 } 3819 if (RHSMask.getNode()) { 3820 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3821 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3822 } 3823 3824 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3825 } 3826 3827 return Rot.getNode(); 3828 } 3829 3830 // If there is a mask here, and we have a variable shift, we can't be sure 3831 // that we're masking out the right stuff. 3832 if (LHSMask.getNode() || RHSMask.getNode()) 3833 return nullptr; 3834 3835 // If the shift amount is sign/zext/any-extended just peel it off. 3836 SDValue LExtOp0 = LHSShiftAmt; 3837 SDValue RExtOp0 = RHSShiftAmt; 3838 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3839 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3840 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3841 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3842 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3843 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3844 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3845 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3846 LExtOp0 = LHSShiftAmt.getOperand(0); 3847 RExtOp0 = RHSShiftAmt.getOperand(0); 3848 } 3849 3850 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3851 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3852 if (TryL) 3853 return TryL; 3854 3855 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3856 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3857 if (TryR) 3858 return TryR; 3859 3860 return nullptr; 3861 } 3862 3863 SDValue DAGCombiner::visitXOR(SDNode *N) { 3864 SDValue N0 = N->getOperand(0); 3865 SDValue N1 = N->getOperand(1); 3866 EVT VT = N0.getValueType(); 3867 3868 // fold vector ops 3869 if (VT.isVector()) { 3870 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3871 return FoldedVOp; 3872 3873 // fold (xor x, 0) -> x, vector edition 3874 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3875 return N1; 3876 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3877 return N0; 3878 } 3879 3880 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3881 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3882 return DAG.getConstant(0, VT); 3883 // fold (xor x, undef) -> undef 3884 if (N0.getOpcode() == ISD::UNDEF) 3885 return N0; 3886 if (N1.getOpcode() == ISD::UNDEF) 3887 return N1; 3888 // fold (xor c1, c2) -> c1^c2 3889 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3890 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3891 if (N0C && N1C) 3892 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3893 // canonicalize constant to RHS 3894 if (isConstantIntBuildVectorOrConstantInt(N0) && 3895 !isConstantIntBuildVectorOrConstantInt(N1)) 3896 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3897 // fold (xor x, 0) -> x 3898 if (N1C && N1C->isNullValue()) 3899 return N0; 3900 // reassociate xor 3901 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 3902 return RXOR; 3903 3904 // fold !(x cc y) -> (x !cc y) 3905 SDValue LHS, RHS, CC; 3906 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3907 bool isInt = LHS.getValueType().isInteger(); 3908 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3909 isInt); 3910 3911 if (!LegalOperations || 3912 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3913 switch (N0.getOpcode()) { 3914 default: 3915 llvm_unreachable("Unhandled SetCC Equivalent!"); 3916 case ISD::SETCC: 3917 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3918 case ISD::SELECT_CC: 3919 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3920 N0.getOperand(3), NotCC); 3921 } 3922 } 3923 } 3924 3925 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3926 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3927 N0.getNode()->hasOneUse() && 3928 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3929 SDValue V = N0.getOperand(0); 3930 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3931 DAG.getConstant(1, V.getValueType())); 3932 AddToWorklist(V.getNode()); 3933 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3934 } 3935 3936 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3937 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3938 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3939 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3940 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3941 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3942 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3943 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3944 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3945 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3946 } 3947 } 3948 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3949 if (N1C && N1C->isAllOnesValue() && 3950 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3951 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3952 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3953 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3954 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3955 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3956 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3957 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3958 } 3959 } 3960 // fold (xor (and x, y), y) -> (and (not x), y) 3961 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3962 N0->getOperand(1) == N1) { 3963 SDValue X = N0->getOperand(0); 3964 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3965 AddToWorklist(NotX.getNode()); 3966 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3967 } 3968 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3969 if (N1C && N0.getOpcode() == ISD::XOR) { 3970 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3971 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3972 if (N00C) 3973 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3974 DAG.getConstant(N1C->getAPIntValue() ^ 3975 N00C->getAPIntValue(), VT)); 3976 if (N01C) 3977 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3978 DAG.getConstant(N1C->getAPIntValue() ^ 3979 N01C->getAPIntValue(), VT)); 3980 } 3981 // fold (xor x, x) -> 0 3982 if (N0 == N1) 3983 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3984 3985 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 3986 // Here is a concrete example of this equivalence: 3987 // i16 x == 14 3988 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 3989 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 3990 // 3991 // => 3992 // 3993 // i16 ~1 == 0b1111111111111110 3994 // i16 rol(~1, 14) == 0b1011111111111111 3995 // 3996 // Some additional tips to help conceptualize this transform: 3997 // - Try to see the operation as placing a single zero in a value of all ones. 3998 // - There exists no value for x which would allow the result to contain zero. 3999 // - Values of x larger than the bitwidth are undefined and do not require a 4000 // consistent result. 4001 // - Pushing the zero left requires shifting one bits in from the right. 4002 // A rotate left of ~1 is a nice way of achieving the desired result. 4003 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 4004 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) 4005 if (N0.getOpcode() == ISD::SHL) 4006 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 4007 if (N1C->isAllOnesValue() && ShlLHS->isOne()) 4008 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT), 4009 N0.getOperand(1)); 4010 4011 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4012 if (N0.getOpcode() == N1.getOpcode()) { 4013 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 4014 if (Tmp.getNode()) return Tmp; 4015 } 4016 4017 // Simplify the expression using non-local knowledge. 4018 if (!VT.isVector() && 4019 SimplifyDemandedBits(SDValue(N, 0))) 4020 return SDValue(N, 0); 4021 4022 return SDValue(); 4023 } 4024 4025 /// Handle transforms common to the three shifts, when the shift amount is a 4026 /// constant. 4027 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4028 // We can't and shouldn't fold opaque constants. 4029 if (Amt->isOpaque()) 4030 return SDValue(); 4031 4032 SDNode *LHS = N->getOperand(0).getNode(); 4033 if (!LHS->hasOneUse()) return SDValue(); 4034 4035 // We want to pull some binops through shifts, so that we have (and (shift)) 4036 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4037 // thing happens with address calculations, so it's important to canonicalize 4038 // it. 4039 bool HighBitSet = false; // Can we transform this if the high bit is set? 4040 4041 switch (LHS->getOpcode()) { 4042 default: return SDValue(); 4043 case ISD::OR: 4044 case ISD::XOR: 4045 HighBitSet = false; // We can only transform sra if the high bit is clear. 4046 break; 4047 case ISD::AND: 4048 HighBitSet = true; // We can only transform sra if the high bit is set. 4049 break; 4050 case ISD::ADD: 4051 if (N->getOpcode() != ISD::SHL) 4052 return SDValue(); // only shl(add) not sr[al](add). 4053 HighBitSet = false; // We can only transform sra if the high bit is clear. 4054 break; 4055 } 4056 4057 // We require the RHS of the binop to be a constant and not opaque as well. 4058 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 4059 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue(); 4060 4061 // FIXME: disable this unless the input to the binop is a shift by a constant. 4062 // If it is not a shift, it pessimizes some common cases like: 4063 // 4064 // void foo(int *X, int i) { X[i & 1235] = 1; } 4065 // int bar(int *X, int i) { return X[i & 255]; } 4066 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4067 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4068 BinOpLHSVal->getOpcode() != ISD::SRA && 4069 BinOpLHSVal->getOpcode() != ISD::SRL) || 4070 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4071 return SDValue(); 4072 4073 EVT VT = N->getValueType(0); 4074 4075 // If this is a signed shift right, and the high bit is modified by the 4076 // logical operation, do not perform the transformation. The highBitSet 4077 // boolean indicates the value of the high bit of the constant which would 4078 // cause it to be modified for this operation. 4079 if (N->getOpcode() == ISD::SRA) { 4080 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4081 if (BinOpRHSSignSet != HighBitSet) 4082 return SDValue(); 4083 } 4084 4085 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4086 return SDValue(); 4087 4088 // Fold the constants, shifting the binop RHS by the shift amount. 4089 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4090 N->getValueType(0), 4091 LHS->getOperand(1), N->getOperand(1)); 4092 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4093 4094 // Create the new shift. 4095 SDValue NewShift = DAG.getNode(N->getOpcode(), 4096 SDLoc(LHS->getOperand(0)), 4097 VT, LHS->getOperand(0), N->getOperand(1)); 4098 4099 // Create the new binop. 4100 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4101 } 4102 4103 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4104 assert(N->getOpcode() == ISD::TRUNCATE); 4105 assert(N->getOperand(0).getOpcode() == ISD::AND); 4106 4107 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4108 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4109 SDValue N01 = N->getOperand(0).getOperand(1); 4110 4111 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4112 EVT TruncVT = N->getValueType(0); 4113 SDValue N00 = N->getOperand(0).getOperand(0); 4114 APInt TruncC = N01C->getAPIntValue(); 4115 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4116 4117 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 4118 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00), 4119 DAG.getConstant(TruncC, TruncVT)); 4120 } 4121 } 4122 4123 return SDValue(); 4124 } 4125 4126 SDValue DAGCombiner::visitRotate(SDNode *N) { 4127 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4128 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4129 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4130 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4131 if (NewOp1.getNode()) 4132 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4133 N->getOperand(0), NewOp1); 4134 } 4135 return SDValue(); 4136 } 4137 4138 SDValue DAGCombiner::visitSHL(SDNode *N) { 4139 SDValue N0 = N->getOperand(0); 4140 SDValue N1 = N->getOperand(1); 4141 EVT VT = N0.getValueType(); 4142 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4143 4144 // fold vector ops 4145 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4146 if (VT.isVector()) { 4147 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4148 return FoldedVOp; 4149 4150 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4151 // If setcc produces all-one true value then: 4152 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4153 if (N1CV && N1CV->isConstant()) { 4154 if (N0.getOpcode() == ISD::AND) { 4155 SDValue N00 = N0->getOperand(0); 4156 SDValue N01 = N0->getOperand(1); 4157 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4158 4159 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4160 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4161 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4162 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV)) 4163 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4164 } 4165 } else { 4166 N1C = isConstOrConstSplat(N1); 4167 } 4168 } 4169 } 4170 4171 // fold (shl c1, c2) -> c1<<c2 4172 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4173 if (N0C && N1C) 4174 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 4175 // fold (shl 0, x) -> 0 4176 if (N0C && N0C->isNullValue()) 4177 return N0; 4178 // fold (shl x, c >= size(x)) -> undef 4179 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4180 return DAG.getUNDEF(VT); 4181 // fold (shl x, 0) -> x 4182 if (N1C && N1C->isNullValue()) 4183 return N0; 4184 // fold (shl undef, x) -> 0 4185 if (N0.getOpcode() == ISD::UNDEF) 4186 return DAG.getConstant(0, VT); 4187 // if (shl x, c) is known to be zero, return 0 4188 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4189 APInt::getAllOnesValue(OpSizeInBits))) 4190 return DAG.getConstant(0, VT); 4191 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4192 if (N1.getOpcode() == ISD::TRUNCATE && 4193 N1.getOperand(0).getOpcode() == ISD::AND) { 4194 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4195 if (NewOp1.getNode()) 4196 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4197 } 4198 4199 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4200 return SDValue(N, 0); 4201 4202 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4203 if (N1C && N0.getOpcode() == ISD::SHL) { 4204 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4205 uint64_t c1 = N0C1->getZExtValue(); 4206 uint64_t c2 = N1C->getZExtValue(); 4207 if (c1 + c2 >= OpSizeInBits) 4208 return DAG.getConstant(0, VT); 4209 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4210 DAG.getConstant(c1 + c2, N1.getValueType())); 4211 } 4212 } 4213 4214 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4215 // For this to be valid, the second form must not preserve any of the bits 4216 // that are shifted out by the inner shift in the first form. This means 4217 // the outer shift size must be >= the number of bits added by the ext. 4218 // As a corollary, we don't care what kind of ext it is. 4219 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4220 N0.getOpcode() == ISD::ANY_EXTEND || 4221 N0.getOpcode() == ISD::SIGN_EXTEND) && 4222 N0.getOperand(0).getOpcode() == ISD::SHL) { 4223 SDValue N0Op0 = N0.getOperand(0); 4224 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4225 uint64_t c1 = N0Op0C1->getZExtValue(); 4226 uint64_t c2 = N1C->getZExtValue(); 4227 EVT InnerShiftVT = N0Op0.getValueType(); 4228 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4229 if (c2 >= OpSizeInBits - InnerShiftSize) { 4230 if (c1 + c2 >= OpSizeInBits) 4231 return DAG.getConstant(0, VT); 4232 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 4233 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 4234 N0Op0->getOperand(0)), 4235 DAG.getConstant(c1 + c2, N1.getValueType())); 4236 } 4237 } 4238 } 4239 4240 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4241 // Only fold this if the inner zext has no other uses to avoid increasing 4242 // the total number of instructions. 4243 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4244 N0.getOperand(0).getOpcode() == ISD::SRL) { 4245 SDValue N0Op0 = N0.getOperand(0); 4246 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4247 uint64_t c1 = N0Op0C1->getZExtValue(); 4248 if (c1 < VT.getScalarSizeInBits()) { 4249 uint64_t c2 = N1C->getZExtValue(); 4250 if (c1 == c2) { 4251 SDValue NewOp0 = N0.getOperand(0); 4252 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4253 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(), 4254 NewOp0, DAG.getConstant(c2, CountVT)); 4255 AddToWorklist(NewSHL.getNode()); 4256 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4257 } 4258 } 4259 } 4260 } 4261 4262 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4263 // (and (srl x, (sub c1, c2), MASK) 4264 // Only fold this if the inner shift has no other uses -- if it does, folding 4265 // this will increase the total number of instructions. 4266 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4267 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4268 uint64_t c1 = N0C1->getZExtValue(); 4269 if (c1 < OpSizeInBits) { 4270 uint64_t c2 = N1C->getZExtValue(); 4271 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4272 SDValue Shift; 4273 if (c2 > c1) { 4274 Mask = Mask.shl(c2 - c1); 4275 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4276 DAG.getConstant(c2 - c1, N1.getValueType())); 4277 } else { 4278 Mask = Mask.lshr(c1 - c2); 4279 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4280 DAG.getConstant(c1 - c2, N1.getValueType())); 4281 } 4282 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 4283 DAG.getConstant(Mask, VT)); 4284 } 4285 } 4286 } 4287 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4288 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4289 unsigned BitSize = VT.getScalarSizeInBits(); 4290 SDValue HiBitsMask = 4291 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4292 BitSize - N1C->getZExtValue()), VT); 4293 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4294 HiBitsMask); 4295 } 4296 4297 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4298 // Variant of version done on multiply, except mul by a power of 2 is turned 4299 // into a shift. 4300 APInt Val; 4301 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4302 (isa<ConstantSDNode>(N0.getOperand(1)) || 4303 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4304 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4305 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4306 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4307 } 4308 4309 if (N1C) { 4310 SDValue NewSHL = visitShiftByConstant(N, N1C); 4311 if (NewSHL.getNode()) 4312 return NewSHL; 4313 } 4314 4315 return SDValue(); 4316 } 4317 4318 SDValue DAGCombiner::visitSRA(SDNode *N) { 4319 SDValue N0 = N->getOperand(0); 4320 SDValue N1 = N->getOperand(1); 4321 EVT VT = N0.getValueType(); 4322 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4323 4324 // fold vector ops 4325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4326 if (VT.isVector()) { 4327 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4328 return FoldedVOp; 4329 4330 N1C = isConstOrConstSplat(N1); 4331 } 4332 4333 // fold (sra c1, c2) -> (sra c1, c2) 4334 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4335 if (N0C && N1C) 4336 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 4337 // fold (sra 0, x) -> 0 4338 if (N0C && N0C->isNullValue()) 4339 return N0; 4340 // fold (sra -1, x) -> -1 4341 if (N0C && N0C->isAllOnesValue()) 4342 return N0; 4343 // fold (sra x, (setge c, size(x))) -> undef 4344 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4345 return DAG.getUNDEF(VT); 4346 // fold (sra x, 0) -> x 4347 if (N1C && N1C->isNullValue()) 4348 return N0; 4349 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4350 // sext_inreg. 4351 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4352 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4353 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4354 if (VT.isVector()) 4355 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4356 ExtVT, VT.getVectorNumElements()); 4357 if ((!LegalOperations || 4358 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4359 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4360 N0.getOperand(0), DAG.getValueType(ExtVT)); 4361 } 4362 4363 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4364 if (N1C && N0.getOpcode() == ISD::SRA) { 4365 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4366 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4367 if (Sum >= OpSizeInBits) 4368 Sum = OpSizeInBits - 1; 4369 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 4370 DAG.getConstant(Sum, N1.getValueType())); 4371 } 4372 } 4373 4374 // fold (sra (shl X, m), (sub result_size, n)) 4375 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4376 // result_size - n != m. 4377 // If truncate is free for the target sext(shl) is likely to result in better 4378 // code. 4379 if (N0.getOpcode() == ISD::SHL && N1C) { 4380 // Get the two constanst of the shifts, CN0 = m, CN = n. 4381 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4382 if (N01C) { 4383 LLVMContext &Ctx = *DAG.getContext(); 4384 // Determine what the truncate's result bitsize and type would be. 4385 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4386 4387 if (VT.isVector()) 4388 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4389 4390 // Determine the residual right-shift amount. 4391 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4392 4393 // If the shift is not a no-op (in which case this should be just a sign 4394 // extend already), the truncated to type is legal, sign_extend is legal 4395 // on that type, and the truncate to that type is both legal and free, 4396 // perform the transform. 4397 if ((ShiftAmt > 0) && 4398 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4399 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4400 TLI.isTruncateFree(VT, TruncVT)) { 4401 4402 SDValue Amt = DAG.getConstant(ShiftAmt, 4403 getShiftAmountTy(N0.getOperand(0).getValueType())); 4404 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 4405 N0.getOperand(0), Amt); 4406 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 4407 Shift); 4408 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 4409 N->getValueType(0), Trunc); 4410 } 4411 } 4412 } 4413 4414 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4415 if (N1.getOpcode() == ISD::TRUNCATE && 4416 N1.getOperand(0).getOpcode() == ISD::AND) { 4417 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4418 if (NewOp1.getNode()) 4419 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4420 } 4421 4422 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4423 // if c1 is equal to the number of bits the trunc removes 4424 if (N0.getOpcode() == ISD::TRUNCATE && 4425 (N0.getOperand(0).getOpcode() == ISD::SRL || 4426 N0.getOperand(0).getOpcode() == ISD::SRA) && 4427 N0.getOperand(0).hasOneUse() && 4428 N0.getOperand(0).getOperand(1).hasOneUse() && 4429 N1C) { 4430 SDValue N0Op0 = N0.getOperand(0); 4431 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4432 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4433 EVT LargeVT = N0Op0.getValueType(); 4434 4435 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4436 SDValue Amt = 4437 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), 4438 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4439 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 4440 N0Op0.getOperand(0), Amt); 4441 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 4442 } 4443 } 4444 } 4445 4446 // Simplify, based on bits shifted out of the LHS. 4447 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4448 return SDValue(N, 0); 4449 4450 4451 // If the sign bit is known to be zero, switch this to a SRL. 4452 if (DAG.SignBitIsZero(N0)) 4453 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4454 4455 if (N1C) { 4456 SDValue NewSRA = visitShiftByConstant(N, N1C); 4457 if (NewSRA.getNode()) 4458 return NewSRA; 4459 } 4460 4461 return SDValue(); 4462 } 4463 4464 SDValue DAGCombiner::visitSRL(SDNode *N) { 4465 SDValue N0 = N->getOperand(0); 4466 SDValue N1 = N->getOperand(1); 4467 EVT VT = N0.getValueType(); 4468 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4469 4470 // fold vector ops 4471 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4472 if (VT.isVector()) { 4473 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4474 return FoldedVOp; 4475 4476 N1C = isConstOrConstSplat(N1); 4477 } 4478 4479 // fold (srl c1, c2) -> c1 >>u c2 4480 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4481 if (N0C && N1C) 4482 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 4483 // fold (srl 0, x) -> 0 4484 if (N0C && N0C->isNullValue()) 4485 return N0; 4486 // fold (srl x, c >= size(x)) -> undef 4487 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4488 return DAG.getUNDEF(VT); 4489 // fold (srl x, 0) -> x 4490 if (N1C && N1C->isNullValue()) 4491 return N0; 4492 // if (srl x, c) is known to be zero, return 0 4493 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4494 APInt::getAllOnesValue(OpSizeInBits))) 4495 return DAG.getConstant(0, VT); 4496 4497 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4498 if (N1C && N0.getOpcode() == ISD::SRL) { 4499 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4500 uint64_t c1 = N01C->getZExtValue(); 4501 uint64_t c2 = N1C->getZExtValue(); 4502 if (c1 + c2 >= OpSizeInBits) 4503 return DAG.getConstant(0, VT); 4504 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4505 DAG.getConstant(c1 + c2, N1.getValueType())); 4506 } 4507 } 4508 4509 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4510 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4511 N0.getOperand(0).getOpcode() == ISD::SRL && 4512 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4513 uint64_t c1 = 4514 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4515 uint64_t c2 = N1C->getZExtValue(); 4516 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4517 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4518 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4519 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4520 if (c1 + OpSizeInBits == InnerShiftSize) { 4521 if (c1 + c2 >= InnerShiftSize) 4522 return DAG.getConstant(0, VT); 4523 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 4524 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 4525 N0.getOperand(0)->getOperand(0), 4526 DAG.getConstant(c1 + c2, ShiftCountVT))); 4527 } 4528 } 4529 4530 // fold (srl (shl x, c), c) -> (and x, cst2) 4531 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4532 unsigned BitSize = N0.getScalarValueSizeInBits(); 4533 if (BitSize <= 64) { 4534 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4535 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4536 DAG.getConstant(~0ULL >> ShAmt, VT)); 4537 } 4538 } 4539 4540 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4541 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4542 // Shifting in all undef bits? 4543 EVT SmallVT = N0.getOperand(0).getValueType(); 4544 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4545 if (N1C->getZExtValue() >= BitSize) 4546 return DAG.getUNDEF(VT); 4547 4548 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4549 uint64_t ShiftAmt = N1C->getZExtValue(); 4550 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 4551 N0.getOperand(0), 4552 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 4553 AddToWorklist(SmallShift.getNode()); 4554 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4555 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4556 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 4557 DAG.getConstant(Mask, VT)); 4558 } 4559 } 4560 4561 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4562 // bit, which is unmodified by sra. 4563 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4564 if (N0.getOpcode() == ISD::SRA) 4565 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4566 } 4567 4568 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4569 if (N1C && N0.getOpcode() == ISD::CTLZ && 4570 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4571 APInt KnownZero, KnownOne; 4572 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4573 4574 // If any of the input bits are KnownOne, then the input couldn't be all 4575 // zeros, thus the result of the srl will always be zero. 4576 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4577 4578 // If all of the bits input the to ctlz node are known to be zero, then 4579 // the result of the ctlz is "32" and the result of the shift is one. 4580 APInt UnknownBits = ~KnownZero; 4581 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4582 4583 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4584 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4585 // Okay, we know that only that the single bit specified by UnknownBits 4586 // could be set on input to the CTLZ node. If this bit is set, the SRL 4587 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4588 // to an SRL/XOR pair, which is likely to simplify more. 4589 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4590 SDValue Op = N0.getOperand(0); 4591 4592 if (ShAmt) { 4593 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4594 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4595 AddToWorklist(Op.getNode()); 4596 } 4597 4598 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4599 Op, DAG.getConstant(1, VT)); 4600 } 4601 } 4602 4603 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4604 if (N1.getOpcode() == ISD::TRUNCATE && 4605 N1.getOperand(0).getOpcode() == ISD::AND) { 4606 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4607 if (NewOp1.getNode()) 4608 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4609 } 4610 4611 // fold operands of srl based on knowledge that the low bits are not 4612 // demanded. 4613 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4614 return SDValue(N, 0); 4615 4616 if (N1C) { 4617 SDValue NewSRL = visitShiftByConstant(N, N1C); 4618 if (NewSRL.getNode()) 4619 return NewSRL; 4620 } 4621 4622 // Attempt to convert a srl of a load into a narrower zero-extending load. 4623 SDValue NarrowLoad = ReduceLoadWidth(N); 4624 if (NarrowLoad.getNode()) 4625 return NarrowLoad; 4626 4627 // Here is a common situation. We want to optimize: 4628 // 4629 // %a = ... 4630 // %b = and i32 %a, 2 4631 // %c = srl i32 %b, 1 4632 // brcond i32 %c ... 4633 // 4634 // into 4635 // 4636 // %a = ... 4637 // %b = and %a, 2 4638 // %c = setcc eq %b, 0 4639 // brcond %c ... 4640 // 4641 // However when after the source operand of SRL is optimized into AND, the SRL 4642 // itself may not be optimized further. Look for it and add the BRCOND into 4643 // the worklist. 4644 if (N->hasOneUse()) { 4645 SDNode *Use = *N->use_begin(); 4646 if (Use->getOpcode() == ISD::BRCOND) 4647 AddToWorklist(Use); 4648 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4649 // Also look pass the truncate. 4650 Use = *Use->use_begin(); 4651 if (Use->getOpcode() == ISD::BRCOND) 4652 AddToWorklist(Use); 4653 } 4654 } 4655 4656 return SDValue(); 4657 } 4658 4659 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4660 SDValue N0 = N->getOperand(0); 4661 EVT VT = N->getValueType(0); 4662 4663 // fold (ctlz c1) -> c2 4664 if (isa<ConstantSDNode>(N0)) 4665 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4666 return SDValue(); 4667 } 4668 4669 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4670 SDValue N0 = N->getOperand(0); 4671 EVT VT = N->getValueType(0); 4672 4673 // fold (ctlz_zero_undef c1) -> c2 4674 if (isa<ConstantSDNode>(N0)) 4675 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4676 return SDValue(); 4677 } 4678 4679 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4680 SDValue N0 = N->getOperand(0); 4681 EVT VT = N->getValueType(0); 4682 4683 // fold (cttz c1) -> c2 4684 if (isa<ConstantSDNode>(N0)) 4685 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4686 return SDValue(); 4687 } 4688 4689 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4690 SDValue N0 = N->getOperand(0); 4691 EVT VT = N->getValueType(0); 4692 4693 // fold (cttz_zero_undef c1) -> c2 4694 if (isa<ConstantSDNode>(N0)) 4695 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4696 return SDValue(); 4697 } 4698 4699 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4700 SDValue N0 = N->getOperand(0); 4701 EVT VT = N->getValueType(0); 4702 4703 // fold (ctpop c1) -> c2 4704 if (isa<ConstantSDNode>(N0)) 4705 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4706 return SDValue(); 4707 } 4708 4709 4710 /// \brief Generate Min/Max node 4711 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4712 SDValue True, SDValue False, 4713 ISD::CondCode CC, const TargetLowering &TLI, 4714 SelectionDAG &DAG) { 4715 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4716 return SDValue(); 4717 4718 switch (CC) { 4719 case ISD::SETOLT: 4720 case ISD::SETOLE: 4721 case ISD::SETLT: 4722 case ISD::SETLE: 4723 case ISD::SETULT: 4724 case ISD::SETULE: { 4725 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4726 if (TLI.isOperationLegal(Opcode, VT)) 4727 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4728 return SDValue(); 4729 } 4730 case ISD::SETOGT: 4731 case ISD::SETOGE: 4732 case ISD::SETGT: 4733 case ISD::SETGE: 4734 case ISD::SETUGT: 4735 case ISD::SETUGE: { 4736 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4737 if (TLI.isOperationLegal(Opcode, VT)) 4738 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4739 return SDValue(); 4740 } 4741 default: 4742 return SDValue(); 4743 } 4744 } 4745 4746 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4747 SDValue N0 = N->getOperand(0); 4748 SDValue N1 = N->getOperand(1); 4749 SDValue N2 = N->getOperand(2); 4750 EVT VT = N->getValueType(0); 4751 EVT VT0 = N0.getValueType(); 4752 4753 // fold (select C, X, X) -> X 4754 if (N1 == N2) 4755 return N1; 4756 // fold (select true, X, Y) -> X 4757 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4758 if (N0C && !N0C->isNullValue()) 4759 return N1; 4760 // fold (select false, X, Y) -> Y 4761 if (N0C && N0C->isNullValue()) 4762 return N2; 4763 // fold (select C, 1, X) -> (or C, X) 4764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4765 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4766 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4767 // fold (select C, 0, 1) -> (xor C, 1) 4768 // We can't do this reliably if integer based booleans have different contents 4769 // to floating point based booleans. This is because we can't tell whether we 4770 // have an integer-based boolean or a floating-point-based boolean unless we 4771 // can find the SETCC that produced it and inspect its operands. This is 4772 // fairly easy if C is the SETCC node, but it can potentially be 4773 // undiscoverable (or not reasonably discoverable). For example, it could be 4774 // in another basic block or it could require searching a complicated 4775 // expression. 4776 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4777 if (VT.isInteger() && 4778 (VT0 == MVT::i1 || (VT0.isInteger() && 4779 TLI.getBooleanContents(false, false) == 4780 TLI.getBooleanContents(false, true) && 4781 TLI.getBooleanContents(false, false) == 4782 TargetLowering::ZeroOrOneBooleanContent)) && 4783 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4784 SDValue XORNode; 4785 if (VT == VT0) 4786 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4787 N0, DAG.getConstant(1, VT0)); 4788 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4789 N0, DAG.getConstant(1, VT0)); 4790 AddToWorklist(XORNode.getNode()); 4791 if (VT.bitsGT(VT0)) 4792 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4793 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4794 } 4795 // fold (select C, 0, X) -> (and (not C), X) 4796 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4797 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4798 AddToWorklist(NOTNode.getNode()); 4799 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4800 } 4801 // fold (select C, X, 1) -> (or (not C), X) 4802 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4803 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4804 AddToWorklist(NOTNode.getNode()); 4805 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4806 } 4807 // fold (select C, X, 0) -> (and C, X) 4808 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4809 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4810 // fold (select X, X, Y) -> (or X, Y) 4811 // fold (select X, 1, Y) -> (or X, Y) 4812 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4813 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4814 // fold (select X, Y, X) -> (and X, Y) 4815 // fold (select X, Y, 0) -> (and X, Y) 4816 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4817 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4818 4819 // If we can fold this based on the true/false value, do so. 4820 if (SimplifySelectOps(N, N1, N2)) 4821 return SDValue(N, 0); // Don't revisit N. 4822 4823 // fold selects based on a setcc into other things, such as min/max/abs 4824 if (N0.getOpcode() == ISD::SETCC) { 4825 // select x, y (fcmp lt x, y) -> fminnum x, y 4826 // select x, y (fcmp gt x, y) -> fmaxnum x, y 4827 // 4828 // This is OK if we don't care about what happens if either operand is a 4829 // NaN. 4830 // 4831 4832 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 4833 // no signed zeros as well as no nans. 4834 const TargetOptions &Options = DAG.getTarget().Options; 4835 if (Options.UnsafeFPMath && 4836 VT.isFloatingPoint() && N0.hasOneUse() && 4837 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 4838 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4839 4840 SDValue FMinMax = 4841 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1), 4842 N1, N2, CC, TLI, DAG); 4843 if (FMinMax) 4844 return FMinMax; 4845 } 4846 4847 if ((!LegalOperations && 4848 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 4849 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 4850 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4851 N0.getOperand(0), N0.getOperand(1), 4852 N1, N2, N0.getOperand(2)); 4853 return SimplifySelect(SDLoc(N), N0, N1, N2); 4854 } 4855 4856 if (VT0 == MVT::i1) { 4857 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4858 // select (and Cond0, Cond1), X, Y 4859 // -> select Cond0, (select Cond1, X, Y), Y 4860 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 4861 SDValue Cond0 = N0->getOperand(0); 4862 SDValue Cond1 = N0->getOperand(1); 4863 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 4864 N1.getValueType(), Cond1, N1, N2); 4865 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 4866 InnerSelect, N2); 4867 } 4868 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 4869 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 4870 SDValue Cond0 = N0->getOperand(0); 4871 SDValue Cond1 = N0->getOperand(1); 4872 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 4873 N1.getValueType(), Cond1, N1, N2); 4874 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 4875 InnerSelect); 4876 } 4877 } 4878 4879 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 4880 if (N1->getOpcode() == ISD::SELECT) { 4881 SDValue N1_0 = N1->getOperand(0); 4882 SDValue N1_1 = N1->getOperand(1); 4883 SDValue N1_2 = N1->getOperand(2); 4884 if (N1_2 == N2) { 4885 // Create the actual and node if we can generate good code for it. 4886 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4887 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 4888 N0, N1_0); 4889 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 4890 N1_1, N2); 4891 } 4892 // Otherwise see if we can optimize the "and" to a better pattern. 4893 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 4894 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 4895 N1_1, N2); 4896 } 4897 } 4898 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 4899 if (N2->getOpcode() == ISD::SELECT) { 4900 SDValue N2_0 = N2->getOperand(0); 4901 SDValue N2_1 = N2->getOperand(1); 4902 SDValue N2_2 = N2->getOperand(2); 4903 if (N2_1 == N1) { 4904 // Create the actual or node if we can generate good code for it. 4905 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4906 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 4907 N0, N2_0); 4908 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 4909 N1, N2_2); 4910 } 4911 // Otherwise see if we can optimize to a better pattern. 4912 if (SDValue Combined = visitORLike(N0, N2_0, N)) 4913 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 4914 N1, N2_2); 4915 } 4916 } 4917 } 4918 4919 return SDValue(); 4920 } 4921 4922 static 4923 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 4924 SDLoc DL(N); 4925 EVT LoVT, HiVT; 4926 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 4927 4928 // Split the inputs. 4929 SDValue Lo, Hi, LL, LH, RL, RH; 4930 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 4931 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 4932 4933 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 4934 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 4935 4936 return std::make_pair(Lo, Hi); 4937 } 4938 4939 // This function assumes all the vselect's arguments are CONCAT_VECTOR 4940 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 4941 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 4942 SDLoc dl(N); 4943 SDValue Cond = N->getOperand(0); 4944 SDValue LHS = N->getOperand(1); 4945 SDValue RHS = N->getOperand(2); 4946 EVT VT = N->getValueType(0); 4947 int NumElems = VT.getVectorNumElements(); 4948 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 4949 RHS.getOpcode() == ISD::CONCAT_VECTORS && 4950 Cond.getOpcode() == ISD::BUILD_VECTOR); 4951 4952 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 4953 // binary ones here. 4954 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 4955 return SDValue(); 4956 4957 // We're sure we have an even number of elements due to the 4958 // concat_vectors we have as arguments to vselect. 4959 // Skip BV elements until we find one that's not an UNDEF 4960 // After we find an UNDEF element, keep looping until we get to half the 4961 // length of the BV and see if all the non-undef nodes are the same. 4962 ConstantSDNode *BottomHalf = nullptr; 4963 for (int i = 0; i < NumElems / 2; ++i) { 4964 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4965 continue; 4966 4967 if (BottomHalf == nullptr) 4968 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4969 else if (Cond->getOperand(i).getNode() != BottomHalf) 4970 return SDValue(); 4971 } 4972 4973 // Do the same for the second half of the BuildVector 4974 ConstantSDNode *TopHalf = nullptr; 4975 for (int i = NumElems / 2; i < NumElems; ++i) { 4976 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4977 continue; 4978 4979 if (TopHalf == nullptr) 4980 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4981 else if (Cond->getOperand(i).getNode() != TopHalf) 4982 return SDValue(); 4983 } 4984 4985 assert(TopHalf && BottomHalf && 4986 "One half of the selector was all UNDEFs and the other was all the " 4987 "same value. This should have been addressed before this function."); 4988 return DAG.getNode( 4989 ISD::CONCAT_VECTORS, dl, VT, 4990 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 4991 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 4992 } 4993 4994 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 4995 4996 if (Level >= AfterLegalizeTypes) 4997 return SDValue(); 4998 4999 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5000 SDValue Mask = MST->getMask(); 5001 SDValue Data = MST->getValue(); 5002 SDLoc DL(N); 5003 5004 // If the MSTORE data type requires splitting and the mask is provided by a 5005 // SETCC, then split both nodes and its operands before legalization. This 5006 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5007 // and enables future optimizations (e.g. min/max pattern matching on X86). 5008 if (Mask.getOpcode() == ISD::SETCC) { 5009 5010 // Check if any splitting is required. 5011 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5012 TargetLowering::TypeSplitVector) 5013 return SDValue(); 5014 5015 SDValue MaskLo, MaskHi, Lo, Hi; 5016 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5017 5018 EVT LoVT, HiVT; 5019 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5020 5021 SDValue Chain = MST->getChain(); 5022 SDValue Ptr = MST->getBasePtr(); 5023 5024 EVT MemoryVT = MST->getMemoryVT(); 5025 unsigned Alignment = MST->getOriginalAlignment(); 5026 5027 // if Alignment is equal to the vector size, 5028 // take the half of it for the second part 5029 unsigned SecondHalfAlignment = 5030 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5031 Alignment/2 : Alignment; 5032 5033 EVT LoMemVT, HiMemVT; 5034 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5035 5036 SDValue DataLo, DataHi; 5037 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5038 5039 MachineMemOperand *MMO = DAG.getMachineFunction(). 5040 getMachineMemOperand(MST->getPointerInfo(), 5041 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5042 Alignment, MST->getAAInfo(), MST->getRanges()); 5043 5044 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5045 MST->isTruncatingStore()); 5046 5047 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5048 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5049 DAG.getConstant(IncrementSize, Ptr.getValueType())); 5050 5051 MMO = DAG.getMachineFunction(). 5052 getMachineMemOperand(MST->getPointerInfo(), 5053 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5054 SecondHalfAlignment, MST->getAAInfo(), 5055 MST->getRanges()); 5056 5057 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5058 MST->isTruncatingStore()); 5059 5060 AddToWorklist(Lo.getNode()); 5061 AddToWorklist(Hi.getNode()); 5062 5063 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5064 } 5065 return SDValue(); 5066 } 5067 5068 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5069 5070 if (Level >= AfterLegalizeTypes) 5071 return SDValue(); 5072 5073 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5074 SDValue Mask = MLD->getMask(); 5075 SDLoc DL(N); 5076 5077 // If the MLOAD result requires splitting and the mask is provided by a 5078 // SETCC, then split both nodes and its operands before legalization. This 5079 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5080 // and enables future optimizations (e.g. min/max pattern matching on X86). 5081 5082 if (Mask.getOpcode() == ISD::SETCC) { 5083 EVT VT = N->getValueType(0); 5084 5085 // Check if any splitting is required. 5086 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5087 TargetLowering::TypeSplitVector) 5088 return SDValue(); 5089 5090 SDValue MaskLo, MaskHi, Lo, Hi; 5091 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5092 5093 SDValue Src0 = MLD->getSrc0(); 5094 SDValue Src0Lo, Src0Hi; 5095 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5096 5097 EVT LoVT, HiVT; 5098 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5099 5100 SDValue Chain = MLD->getChain(); 5101 SDValue Ptr = MLD->getBasePtr(); 5102 EVT MemoryVT = MLD->getMemoryVT(); 5103 unsigned Alignment = MLD->getOriginalAlignment(); 5104 5105 // if Alignment is equal to the vector size, 5106 // take the half of it for the second part 5107 unsigned SecondHalfAlignment = 5108 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5109 Alignment/2 : Alignment; 5110 5111 EVT LoMemVT, HiMemVT; 5112 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5113 5114 MachineMemOperand *MMO = DAG.getMachineFunction(). 5115 getMachineMemOperand(MLD->getPointerInfo(), 5116 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5117 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5118 5119 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5120 ISD::NON_EXTLOAD); 5121 5122 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5123 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5124 DAG.getConstant(IncrementSize, Ptr.getValueType())); 5125 5126 MMO = DAG.getMachineFunction(). 5127 getMachineMemOperand(MLD->getPointerInfo(), 5128 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5129 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5130 5131 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5132 ISD::NON_EXTLOAD); 5133 5134 AddToWorklist(Lo.getNode()); 5135 AddToWorklist(Hi.getNode()); 5136 5137 // Build a factor node to remember that this load is independent of the 5138 // other one. 5139 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5140 Hi.getValue(1)); 5141 5142 // Legalized the chain result - switch anything that used the old chain to 5143 // use the new one. 5144 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5145 5146 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5147 5148 SDValue RetOps[] = { LoadRes, Chain }; 5149 return DAG.getMergeValues(RetOps, DL); 5150 } 5151 return SDValue(); 5152 } 5153 5154 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5155 SDValue N0 = N->getOperand(0); 5156 SDValue N1 = N->getOperand(1); 5157 SDValue N2 = N->getOperand(2); 5158 SDLoc DL(N); 5159 5160 // Canonicalize integer abs. 5161 // vselect (setg[te] X, 0), X, -X -> 5162 // vselect (setgt X, -1), X, -X -> 5163 // vselect (setl[te] X, 0), -X, X -> 5164 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5165 if (N0.getOpcode() == ISD::SETCC) { 5166 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5167 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5168 bool isAbs = false; 5169 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5170 5171 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5172 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5173 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5174 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5175 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5176 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5177 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5178 5179 if (isAbs) { 5180 EVT VT = LHS.getValueType(); 5181 SDValue Shift = DAG.getNode( 5182 ISD::SRA, DL, VT, LHS, 5183 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 5184 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5185 AddToWorklist(Shift.getNode()); 5186 AddToWorklist(Add.getNode()); 5187 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5188 } 5189 } 5190 5191 // If the VSELECT result requires splitting and the mask is provided by a 5192 // SETCC, then split both nodes and its operands before legalization. This 5193 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5194 // and enables future optimizations (e.g. min/max pattern matching on X86). 5195 if (N0.getOpcode() == ISD::SETCC) { 5196 EVT VT = N->getValueType(0); 5197 5198 // Check if any splitting is required. 5199 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5200 TargetLowering::TypeSplitVector) 5201 return SDValue(); 5202 5203 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5204 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5205 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5206 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5207 5208 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5209 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5210 5211 // Add the new VSELECT nodes to the work list in case they need to be split 5212 // again. 5213 AddToWorklist(Lo.getNode()); 5214 AddToWorklist(Hi.getNode()); 5215 5216 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5217 } 5218 5219 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5220 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5221 return N1; 5222 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5223 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5224 return N2; 5225 5226 // The ConvertSelectToConcatVector function is assuming both the above 5227 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5228 // and addressed. 5229 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5230 N2.getOpcode() == ISD::CONCAT_VECTORS && 5231 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5232 SDValue CV = ConvertSelectToConcatVector(N, DAG); 5233 if (CV.getNode()) 5234 return CV; 5235 } 5236 5237 return SDValue(); 5238 } 5239 5240 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5241 SDValue N0 = N->getOperand(0); 5242 SDValue N1 = N->getOperand(1); 5243 SDValue N2 = N->getOperand(2); 5244 SDValue N3 = N->getOperand(3); 5245 SDValue N4 = N->getOperand(4); 5246 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5247 5248 // fold select_cc lhs, rhs, x, x, cc -> x 5249 if (N2 == N3) 5250 return N2; 5251 5252 // Determine if the condition we're dealing with is constant 5253 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5254 N0, N1, CC, SDLoc(N), false); 5255 if (SCC.getNode()) { 5256 AddToWorklist(SCC.getNode()); 5257 5258 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5259 if (!SCCC->isNullValue()) 5260 return N2; // cond always true -> true val 5261 else 5262 return N3; // cond always false -> false val 5263 } else if (SCC->getOpcode() == ISD::UNDEF) { 5264 // When the condition is UNDEF, just return the first operand. This is 5265 // coherent the DAG creation, no setcc node is created in this case 5266 return N2; 5267 } else if (SCC.getOpcode() == ISD::SETCC) { 5268 // Fold to a simpler select_cc 5269 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5270 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5271 SCC.getOperand(2)); 5272 } 5273 } 5274 5275 // If we can fold this based on the true/false value, do so. 5276 if (SimplifySelectOps(N, N2, N3)) 5277 return SDValue(N, 0); // Don't revisit N. 5278 5279 // fold select_cc into other things, such as min/max/abs 5280 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5281 } 5282 5283 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5284 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5285 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5286 SDLoc(N)); 5287 } 5288 5289 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 5290 // dag node into a ConstantSDNode or a build_vector of constants. 5291 // This function is called by the DAGCombiner when visiting sext/zext/aext 5292 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5293 // Vector extends are not folded if operations are legal; this is to 5294 // avoid introducing illegal build_vector dag nodes. 5295 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5296 SelectionDAG &DAG, bool LegalTypes, 5297 bool LegalOperations) { 5298 unsigned Opcode = N->getOpcode(); 5299 SDValue N0 = N->getOperand(0); 5300 EVT VT = N->getValueType(0); 5301 5302 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5303 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 5304 5305 // fold (sext c1) -> c1 5306 // fold (zext c1) -> c1 5307 // fold (aext c1) -> c1 5308 if (isa<ConstantSDNode>(N0)) 5309 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5310 5311 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5312 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5313 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5314 EVT SVT = VT.getScalarType(); 5315 if (!(VT.isVector() && 5316 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5317 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5318 return nullptr; 5319 5320 // We can fold this node into a build_vector. 5321 unsigned VTBits = SVT.getSizeInBits(); 5322 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5323 unsigned ShAmt = VTBits - EVTBits; 5324 SmallVector<SDValue, 8> Elts; 5325 unsigned NumElts = N0->getNumOperands(); 5326 SDLoc DL(N); 5327 5328 for (unsigned i=0; i != NumElts; ++i) { 5329 SDValue Op = N0->getOperand(i); 5330 if (Op->getOpcode() == ISD::UNDEF) { 5331 Elts.push_back(DAG.getUNDEF(SVT)); 5332 continue; 5333 } 5334 5335 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 5336 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 5337 if (Opcode == ISD::SIGN_EXTEND) 5338 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 5339 SVT)); 5340 else 5341 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 5342 SVT)); 5343 } 5344 5345 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5346 } 5347 5348 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5349 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5350 // transformation. Returns true if extension are possible and the above 5351 // mentioned transformation is profitable. 5352 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5353 unsigned ExtOpc, 5354 SmallVectorImpl<SDNode *> &ExtendNodes, 5355 const TargetLowering &TLI) { 5356 bool HasCopyToRegUses = false; 5357 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5358 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5359 UE = N0.getNode()->use_end(); 5360 UI != UE; ++UI) { 5361 SDNode *User = *UI; 5362 if (User == N) 5363 continue; 5364 if (UI.getUse().getResNo() != N0.getResNo()) 5365 continue; 5366 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5367 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5368 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5369 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5370 // Sign bits will be lost after a zext. 5371 return false; 5372 bool Add = false; 5373 for (unsigned i = 0; i != 2; ++i) { 5374 SDValue UseOp = User->getOperand(i); 5375 if (UseOp == N0) 5376 continue; 5377 if (!isa<ConstantSDNode>(UseOp)) 5378 return false; 5379 Add = true; 5380 } 5381 if (Add) 5382 ExtendNodes.push_back(User); 5383 continue; 5384 } 5385 // If truncates aren't free and there are users we can't 5386 // extend, it isn't worthwhile. 5387 if (!isTruncFree) 5388 return false; 5389 // Remember if this value is live-out. 5390 if (User->getOpcode() == ISD::CopyToReg) 5391 HasCopyToRegUses = true; 5392 } 5393 5394 if (HasCopyToRegUses) { 5395 bool BothLiveOut = false; 5396 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5397 UI != UE; ++UI) { 5398 SDUse &Use = UI.getUse(); 5399 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5400 BothLiveOut = true; 5401 break; 5402 } 5403 } 5404 if (BothLiveOut) 5405 // Both unextended and extended values are live out. There had better be 5406 // a good reason for the transformation. 5407 return ExtendNodes.size(); 5408 } 5409 return true; 5410 } 5411 5412 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5413 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5414 ISD::NodeType ExtType) { 5415 // Extend SetCC uses if necessary. 5416 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5417 SDNode *SetCC = SetCCs[i]; 5418 SmallVector<SDValue, 4> Ops; 5419 5420 for (unsigned j = 0; j != 2; ++j) { 5421 SDValue SOp = SetCC->getOperand(j); 5422 if (SOp == Trunc) 5423 Ops.push_back(ExtLoad); 5424 else 5425 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5426 } 5427 5428 Ops.push_back(SetCC->getOperand(2)); 5429 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5430 } 5431 } 5432 5433 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5434 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5435 SDValue N0 = N->getOperand(0); 5436 EVT DstVT = N->getValueType(0); 5437 EVT SrcVT = N0.getValueType(); 5438 5439 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5440 N->getOpcode() == ISD::ZERO_EXTEND) && 5441 "Unexpected node type (not an extend)!"); 5442 5443 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5444 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5445 // (v8i32 (sext (v8i16 (load x)))) 5446 // into: 5447 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5448 // (v4i32 (sextload (x + 16))))) 5449 // Where uses of the original load, i.e.: 5450 // (v8i16 (load x)) 5451 // are replaced with: 5452 // (v8i16 (truncate 5453 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5454 // (v4i32 (sextload (x + 16))))))) 5455 // 5456 // This combine is only applicable to illegal, but splittable, vectors. 5457 // All legal types, and illegal non-vector types, are handled elsewhere. 5458 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5459 // 5460 if (N0->getOpcode() != ISD::LOAD) 5461 return SDValue(); 5462 5463 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5464 5465 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5466 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5467 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5468 return SDValue(); 5469 5470 SmallVector<SDNode *, 4> SetCCs; 5471 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5472 return SDValue(); 5473 5474 ISD::LoadExtType ExtType = 5475 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5476 5477 // Try to split the vector types to get down to legal types. 5478 EVT SplitSrcVT = SrcVT; 5479 EVT SplitDstVT = DstVT; 5480 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5481 SplitSrcVT.getVectorNumElements() > 1) { 5482 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5483 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5484 } 5485 5486 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5487 return SDValue(); 5488 5489 SDLoc DL(N); 5490 const unsigned NumSplits = 5491 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5492 const unsigned Stride = SplitSrcVT.getStoreSize(); 5493 SmallVector<SDValue, 4> Loads; 5494 SmallVector<SDValue, 4> Chains; 5495 5496 SDValue BasePtr = LN0->getBasePtr(); 5497 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5498 const unsigned Offset = Idx * Stride; 5499 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5500 5501 SDValue SplitLoad = DAG.getExtLoad( 5502 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5503 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5504 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5505 Align, LN0->getAAInfo()); 5506 5507 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5508 DAG.getConstant(Stride, BasePtr.getValueType())); 5509 5510 Loads.push_back(SplitLoad.getValue(0)); 5511 Chains.push_back(SplitLoad.getValue(1)); 5512 } 5513 5514 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5515 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5516 5517 CombineTo(N, NewValue); 5518 5519 // Replace uses of the original load (before extension) 5520 // with a truncate of the concatenated sextloaded vectors. 5521 SDValue Trunc = 5522 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5523 CombineTo(N0.getNode(), Trunc, NewChain); 5524 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5525 (ISD::NodeType)N->getOpcode()); 5526 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5527 } 5528 5529 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5530 SDValue N0 = N->getOperand(0); 5531 EVT VT = N->getValueType(0); 5532 5533 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5534 LegalOperations)) 5535 return SDValue(Res, 0); 5536 5537 // fold (sext (sext x)) -> (sext x) 5538 // fold (sext (aext x)) -> (sext x) 5539 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5540 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5541 N0.getOperand(0)); 5542 5543 if (N0.getOpcode() == ISD::TRUNCATE) { 5544 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5545 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5546 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5547 if (NarrowLoad.getNode()) { 5548 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5549 if (NarrowLoad.getNode() != N0.getNode()) { 5550 CombineTo(N0.getNode(), NarrowLoad); 5551 // CombineTo deleted the truncate, if needed, but not what's under it. 5552 AddToWorklist(oye); 5553 } 5554 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5555 } 5556 5557 // See if the value being truncated is already sign extended. If so, just 5558 // eliminate the trunc/sext pair. 5559 SDValue Op = N0.getOperand(0); 5560 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5561 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5562 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5563 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5564 5565 if (OpBits == DestBits) { 5566 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5567 // bits, it is already ready. 5568 if (NumSignBits > DestBits-MidBits) 5569 return Op; 5570 } else if (OpBits < DestBits) { 5571 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5572 // bits, just sext from i32. 5573 if (NumSignBits > OpBits-MidBits) 5574 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5575 } else { 5576 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5577 // bits, just truncate to i32. 5578 if (NumSignBits > OpBits-MidBits) 5579 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5580 } 5581 5582 // fold (sext (truncate x)) -> (sextinreg x). 5583 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5584 N0.getValueType())) { 5585 if (OpBits < DestBits) 5586 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5587 else if (OpBits > DestBits) 5588 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5589 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5590 DAG.getValueType(N0.getValueType())); 5591 } 5592 } 5593 5594 // fold (sext (load x)) -> (sext (truncate (sextload x))) 5595 // Only generate vector extloads when 1) they're legal, and 2) they are 5596 // deemed desirable by the target. 5597 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5598 ((!LegalOperations && !VT.isVector() && 5599 !cast<LoadSDNode>(N0)->isVolatile()) || 5600 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 5601 bool DoXform = true; 5602 SmallVector<SDNode*, 4> SetCCs; 5603 if (!N0.hasOneUse()) 5604 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5605 if (VT.isVector()) 5606 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5607 if (DoXform) { 5608 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5609 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5610 LN0->getChain(), 5611 LN0->getBasePtr(), N0.getValueType(), 5612 LN0->getMemOperand()); 5613 CombineTo(N, ExtLoad); 5614 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5615 N0.getValueType(), ExtLoad); 5616 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5617 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5618 ISD::SIGN_EXTEND); 5619 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5620 } 5621 } 5622 5623 // fold (sext (load x)) to multiple smaller sextloads. 5624 // Only on illegal but splittable vectors. 5625 if (SDValue ExtLoad = CombineExtLoad(N)) 5626 return ExtLoad; 5627 5628 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5629 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5630 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5631 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5632 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5633 EVT MemVT = LN0->getMemoryVT(); 5634 if ((!LegalOperations && !LN0->isVolatile()) || 5635 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 5636 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5637 LN0->getChain(), 5638 LN0->getBasePtr(), MemVT, 5639 LN0->getMemOperand()); 5640 CombineTo(N, ExtLoad); 5641 CombineTo(N0.getNode(), 5642 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5643 N0.getValueType(), ExtLoad), 5644 ExtLoad.getValue(1)); 5645 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5646 } 5647 } 5648 5649 // fold (sext (and/or/xor (load x), cst)) -> 5650 // (and/or/xor (sextload x), (sext cst)) 5651 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5652 N0.getOpcode() == ISD::XOR) && 5653 isa<LoadSDNode>(N0.getOperand(0)) && 5654 N0.getOperand(1).getOpcode() == ISD::Constant && 5655 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 5656 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5657 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5658 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5659 bool DoXform = true; 5660 SmallVector<SDNode*, 4> SetCCs; 5661 if (!N0.hasOneUse()) 5662 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 5663 SetCCs, TLI); 5664 if (DoXform) { 5665 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 5666 LN0->getChain(), LN0->getBasePtr(), 5667 LN0->getMemoryVT(), 5668 LN0->getMemOperand()); 5669 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5670 Mask = Mask.sext(VT.getSizeInBits()); 5671 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5672 ExtLoad, DAG.getConstant(Mask, VT)); 5673 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5674 SDLoc(N0.getOperand(0)), 5675 N0.getOperand(0).getValueType(), ExtLoad); 5676 CombineTo(N, And); 5677 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5678 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5679 ISD::SIGN_EXTEND); 5680 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5681 } 5682 } 5683 } 5684 5685 if (N0.getOpcode() == ISD::SETCC) { 5686 EVT N0VT = N0.getOperand(0).getValueType(); 5687 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 5688 // Only do this before legalize for now. 5689 if (VT.isVector() && !LegalOperations && 5690 TLI.getBooleanContents(N0VT) == 5691 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5692 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 5693 // of the same size as the compared operands. Only optimize sext(setcc()) 5694 // if this is the case. 5695 EVT SVT = getSetCCResultType(N0VT); 5696 5697 // We know that the # elements of the results is the same as the 5698 // # elements of the compare (and the # elements of the compare result 5699 // for that matter). Check to see that they are the same size. If so, 5700 // we know that the element size of the sext'd result matches the 5701 // element size of the compare operands. 5702 if (VT.getSizeInBits() == SVT.getSizeInBits()) 5703 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5704 N0.getOperand(1), 5705 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5706 5707 // If the desired elements are smaller or larger than the source 5708 // elements we can use a matching integer vector type and then 5709 // truncate/sign extend 5710 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5711 if (SVT == MatchingVectorType) { 5712 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 5713 N0.getOperand(0), N0.getOperand(1), 5714 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5715 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5716 } 5717 } 5718 5719 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 5720 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 5721 SDValue NegOne = 5722 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 5723 SDValue SCC = 5724 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5725 NegOne, DAG.getConstant(0, VT), 5726 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5727 if (SCC.getNode()) return SCC; 5728 5729 if (!VT.isVector()) { 5730 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 5731 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 5732 SDLoc DL(N); 5733 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5734 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 5735 N0.getOperand(0), N0.getOperand(1), CC); 5736 return DAG.getSelect(DL, VT, SetCC, 5737 NegOne, DAG.getConstant(0, VT)); 5738 } 5739 } 5740 } 5741 5742 // fold (sext x) -> (zext x) if the sign bit is known zero. 5743 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 5744 DAG.SignBitIsZero(N0)) 5745 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 5746 5747 return SDValue(); 5748 } 5749 5750 // isTruncateOf - If N is a truncate of some other value, return true, record 5751 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 5752 // This function computes KnownZero to avoid a duplicated call to 5753 // computeKnownBits in the caller. 5754 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 5755 APInt &KnownZero) { 5756 APInt KnownOne; 5757 if (N->getOpcode() == ISD::TRUNCATE) { 5758 Op = N->getOperand(0); 5759 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5760 return true; 5761 } 5762 5763 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 5764 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 5765 return false; 5766 5767 SDValue Op0 = N->getOperand(0); 5768 SDValue Op1 = N->getOperand(1); 5769 assert(Op0.getValueType() == Op1.getValueType()); 5770 5771 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 5772 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 5773 if (COp0 && COp0->isNullValue()) 5774 Op = Op1; 5775 else if (COp1 && COp1->isNullValue()) 5776 Op = Op0; 5777 else 5778 return false; 5779 5780 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5781 5782 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 5783 return false; 5784 5785 return true; 5786 } 5787 5788 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 5789 SDValue N0 = N->getOperand(0); 5790 EVT VT = N->getValueType(0); 5791 5792 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5793 LegalOperations)) 5794 return SDValue(Res, 0); 5795 5796 // fold (zext (zext x)) -> (zext x) 5797 // fold (zext (aext x)) -> (zext x) 5798 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5799 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 5800 N0.getOperand(0)); 5801 5802 // fold (zext (truncate x)) -> (zext x) or 5803 // (zext (truncate x)) -> (truncate x) 5804 // This is valid when the truncated bits of x are already zero. 5805 // FIXME: We should extend this to work for vectors too. 5806 SDValue Op; 5807 APInt KnownZero; 5808 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 5809 APInt TruncatedBits = 5810 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 5811 APInt(Op.getValueSizeInBits(), 0) : 5812 APInt::getBitsSet(Op.getValueSizeInBits(), 5813 N0.getValueSizeInBits(), 5814 std::min(Op.getValueSizeInBits(), 5815 VT.getSizeInBits())); 5816 if (TruncatedBits == (KnownZero & TruncatedBits)) { 5817 if (VT.bitsGT(Op.getValueType())) 5818 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 5819 if (VT.bitsLT(Op.getValueType())) 5820 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5821 5822 return Op; 5823 } 5824 } 5825 5826 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5827 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 5828 if (N0.getOpcode() == ISD::TRUNCATE) { 5829 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5830 if (NarrowLoad.getNode()) { 5831 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5832 if (NarrowLoad.getNode() != N0.getNode()) { 5833 CombineTo(N0.getNode(), NarrowLoad); 5834 // CombineTo deleted the truncate, if needed, but not what's under it. 5835 AddToWorklist(oye); 5836 } 5837 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5838 } 5839 } 5840 5841 // fold (zext (truncate x)) -> (and x, mask) 5842 if (N0.getOpcode() == ISD::TRUNCATE && 5843 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 5844 5845 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5846 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 5847 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5848 if (NarrowLoad.getNode()) { 5849 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5850 if (NarrowLoad.getNode() != N0.getNode()) { 5851 CombineTo(N0.getNode(), NarrowLoad); 5852 // CombineTo deleted the truncate, if needed, but not what's under it. 5853 AddToWorklist(oye); 5854 } 5855 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5856 } 5857 5858 SDValue Op = N0.getOperand(0); 5859 if (Op.getValueType().bitsLT(VT)) { 5860 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 5861 AddToWorklist(Op.getNode()); 5862 } else if (Op.getValueType().bitsGT(VT)) { 5863 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5864 AddToWorklist(Op.getNode()); 5865 } 5866 return DAG.getZeroExtendInReg(Op, SDLoc(N), 5867 N0.getValueType().getScalarType()); 5868 } 5869 5870 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 5871 // if either of the casts is not free. 5872 if (N0.getOpcode() == ISD::AND && 5873 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5874 N0.getOperand(1).getOpcode() == ISD::Constant && 5875 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5876 N0.getValueType()) || 5877 !TLI.isZExtFree(N0.getValueType(), VT))) { 5878 SDValue X = N0.getOperand(0).getOperand(0); 5879 if (X.getValueType().bitsLT(VT)) { 5880 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 5881 } else if (X.getValueType().bitsGT(VT)) { 5882 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5883 } 5884 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5885 Mask = Mask.zext(VT.getSizeInBits()); 5886 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5887 X, DAG.getConstant(Mask, VT)); 5888 } 5889 5890 // fold (zext (load x)) -> (zext (truncate (zextload x))) 5891 // Only generate vector extloads when 1) they're legal, and 2) they are 5892 // deemed desirable by the target. 5893 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5894 ((!LegalOperations && !VT.isVector() && 5895 !cast<LoadSDNode>(N0)->isVolatile()) || 5896 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 5897 bool DoXform = true; 5898 SmallVector<SDNode*, 4> SetCCs; 5899 if (!N0.hasOneUse()) 5900 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 5901 if (VT.isVector()) 5902 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5903 if (DoXform) { 5904 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5905 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5906 LN0->getChain(), 5907 LN0->getBasePtr(), N0.getValueType(), 5908 LN0->getMemOperand()); 5909 CombineTo(N, ExtLoad); 5910 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5911 N0.getValueType(), ExtLoad); 5912 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5913 5914 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5915 ISD::ZERO_EXTEND); 5916 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5917 } 5918 } 5919 5920 // fold (zext (load x)) to multiple smaller zextloads. 5921 // Only on illegal but splittable vectors. 5922 if (SDValue ExtLoad = CombineExtLoad(N)) 5923 return ExtLoad; 5924 5925 // fold (zext (and/or/xor (load x), cst)) -> 5926 // (and/or/xor (zextload x), (zext cst)) 5927 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5928 N0.getOpcode() == ISD::XOR) && 5929 isa<LoadSDNode>(N0.getOperand(0)) && 5930 N0.getOperand(1).getOpcode() == ISD::Constant && 5931 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 5932 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5933 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5934 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 5935 bool DoXform = true; 5936 SmallVector<SDNode*, 4> SetCCs; 5937 if (!N0.hasOneUse()) 5938 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 5939 SetCCs, TLI); 5940 if (DoXform) { 5941 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 5942 LN0->getChain(), LN0->getBasePtr(), 5943 LN0->getMemoryVT(), 5944 LN0->getMemOperand()); 5945 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5946 Mask = Mask.zext(VT.getSizeInBits()); 5947 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5948 ExtLoad, DAG.getConstant(Mask, VT)); 5949 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5950 SDLoc(N0.getOperand(0)), 5951 N0.getOperand(0).getValueType(), ExtLoad); 5952 CombineTo(N, And); 5953 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5954 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5955 ISD::ZERO_EXTEND); 5956 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5957 } 5958 } 5959 } 5960 5961 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 5962 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 5963 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5964 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5965 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5966 EVT MemVT = LN0->getMemoryVT(); 5967 if ((!LegalOperations && !LN0->isVolatile()) || 5968 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 5969 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5970 LN0->getChain(), 5971 LN0->getBasePtr(), MemVT, 5972 LN0->getMemOperand()); 5973 CombineTo(N, ExtLoad); 5974 CombineTo(N0.getNode(), 5975 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 5976 ExtLoad), 5977 ExtLoad.getValue(1)); 5978 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5979 } 5980 } 5981 5982 if (N0.getOpcode() == ISD::SETCC) { 5983 if (!LegalOperations && VT.isVector() && 5984 N0.getValueType().getVectorElementType() == MVT::i1) { 5985 EVT N0VT = N0.getOperand(0).getValueType(); 5986 if (getSetCCResultType(N0VT) == N0.getValueType()) 5987 return SDValue(); 5988 5989 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 5990 // Only do this before legalize for now. 5991 EVT EltVT = VT.getVectorElementType(); 5992 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 5993 DAG.getConstant(1, EltVT)); 5994 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5995 // We know that the # elements of the results is the same as the 5996 // # elements of the compare (and the # elements of the compare result 5997 // for that matter). Check to see that they are the same size. If so, 5998 // we know that the element size of the sext'd result matches the 5999 // element size of the compare operands. 6000 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6001 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6002 N0.getOperand(1), 6003 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6004 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 6005 OneOps)); 6006 6007 // If the desired elements are smaller or larger than the source 6008 // elements we can use a matching integer vector type and then 6009 // truncate/sign extend 6010 EVT MatchingElementType = 6011 EVT::getIntegerVT(*DAG.getContext(), 6012 N0VT.getScalarType().getSizeInBits()); 6013 EVT MatchingVectorType = 6014 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6015 N0VT.getVectorNumElements()); 6016 SDValue VsetCC = 6017 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6018 N0.getOperand(1), 6019 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6020 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6021 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 6022 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps)); 6023 } 6024 6025 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6026 SDValue SCC = 6027 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 6028 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 6029 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6030 if (SCC.getNode()) return SCC; 6031 } 6032 6033 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6034 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6035 isa<ConstantSDNode>(N0.getOperand(1)) && 6036 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6037 N0.hasOneUse()) { 6038 SDValue ShAmt = N0.getOperand(1); 6039 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6040 if (N0.getOpcode() == ISD::SHL) { 6041 SDValue InnerZExt = N0.getOperand(0); 6042 // If the original shl may be shifting out bits, do not perform this 6043 // transformation. 6044 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6045 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6046 if (ShAmtVal > KnownZeroBits) 6047 return SDValue(); 6048 } 6049 6050 SDLoc DL(N); 6051 6052 // Ensure that the shift amount is wide enough for the shifted value. 6053 if (VT.getSizeInBits() >= 256) 6054 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6055 6056 return DAG.getNode(N0.getOpcode(), DL, VT, 6057 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6058 ShAmt); 6059 } 6060 6061 return SDValue(); 6062 } 6063 6064 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6065 SDValue N0 = N->getOperand(0); 6066 EVT VT = N->getValueType(0); 6067 6068 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6069 LegalOperations)) 6070 return SDValue(Res, 0); 6071 6072 // fold (aext (aext x)) -> (aext x) 6073 // fold (aext (zext x)) -> (zext x) 6074 // fold (aext (sext x)) -> (sext x) 6075 if (N0.getOpcode() == ISD::ANY_EXTEND || 6076 N0.getOpcode() == ISD::ZERO_EXTEND || 6077 N0.getOpcode() == ISD::SIGN_EXTEND) 6078 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6079 6080 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6081 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6082 if (N0.getOpcode() == ISD::TRUNCATE) { 6083 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 6084 if (NarrowLoad.getNode()) { 6085 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6086 if (NarrowLoad.getNode() != N0.getNode()) { 6087 CombineTo(N0.getNode(), NarrowLoad); 6088 // CombineTo deleted the truncate, if needed, but not what's under it. 6089 AddToWorklist(oye); 6090 } 6091 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6092 } 6093 } 6094 6095 // fold (aext (truncate x)) 6096 if (N0.getOpcode() == ISD::TRUNCATE) { 6097 SDValue TruncOp = N0.getOperand(0); 6098 if (TruncOp.getValueType() == VT) 6099 return TruncOp; // x iff x size == zext size. 6100 if (TruncOp.getValueType().bitsGT(VT)) 6101 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6102 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6103 } 6104 6105 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6106 // if the trunc is not free. 6107 if (N0.getOpcode() == ISD::AND && 6108 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6109 N0.getOperand(1).getOpcode() == ISD::Constant && 6110 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6111 N0.getValueType())) { 6112 SDValue X = N0.getOperand(0).getOperand(0); 6113 if (X.getValueType().bitsLT(VT)) { 6114 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6115 } else if (X.getValueType().bitsGT(VT)) { 6116 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6117 } 6118 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6119 Mask = Mask.zext(VT.getSizeInBits()); 6120 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6121 X, DAG.getConstant(Mask, VT)); 6122 } 6123 6124 // fold (aext (load x)) -> (aext (truncate (extload x))) 6125 // None of the supported targets knows how to perform load and any_ext 6126 // on vectors in one instruction. We only perform this transformation on 6127 // scalars. 6128 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6129 ISD::isUNINDEXEDLoad(N0.getNode()) && 6130 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6131 bool DoXform = true; 6132 SmallVector<SDNode*, 4> SetCCs; 6133 if (!N0.hasOneUse()) 6134 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6135 if (DoXform) { 6136 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6137 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6138 LN0->getChain(), 6139 LN0->getBasePtr(), N0.getValueType(), 6140 LN0->getMemOperand()); 6141 CombineTo(N, ExtLoad); 6142 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6143 N0.getValueType(), ExtLoad); 6144 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6145 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6146 ISD::ANY_EXTEND); 6147 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6148 } 6149 } 6150 6151 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6152 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6153 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6154 if (N0.getOpcode() == ISD::LOAD && 6155 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6156 N0.hasOneUse()) { 6157 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6158 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6159 EVT MemVT = LN0->getMemoryVT(); 6160 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6161 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6162 VT, LN0->getChain(), LN0->getBasePtr(), 6163 MemVT, LN0->getMemOperand()); 6164 CombineTo(N, ExtLoad); 6165 CombineTo(N0.getNode(), 6166 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6167 N0.getValueType(), ExtLoad), 6168 ExtLoad.getValue(1)); 6169 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6170 } 6171 } 6172 6173 if (N0.getOpcode() == ISD::SETCC) { 6174 // For vectors: 6175 // aext(setcc) -> vsetcc 6176 // aext(setcc) -> truncate(vsetcc) 6177 // aext(setcc) -> aext(vsetcc) 6178 // Only do this before legalize for now. 6179 if (VT.isVector() && !LegalOperations) { 6180 EVT N0VT = N0.getOperand(0).getValueType(); 6181 // We know that the # elements of the results is the same as the 6182 // # elements of the compare (and the # elements of the compare result 6183 // for that matter). Check to see that they are the same size. If so, 6184 // we know that the element size of the sext'd result matches the 6185 // element size of the compare operands. 6186 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6187 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6188 N0.getOperand(1), 6189 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6190 // If the desired elements are smaller or larger than the source 6191 // elements we can use a matching integer vector type and then 6192 // truncate/any extend 6193 else { 6194 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6195 SDValue VsetCC = 6196 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6197 N0.getOperand(1), 6198 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6199 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6200 } 6201 } 6202 6203 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6204 SDValue SCC = 6205 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 6206 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 6207 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6208 if (SCC.getNode()) 6209 return SCC; 6210 } 6211 6212 return SDValue(); 6213 } 6214 6215 /// See if the specified operand can be simplified with the knowledge that only 6216 /// the bits specified by Mask are used. If so, return the simpler operand, 6217 /// otherwise return a null SDValue. 6218 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6219 switch (V.getOpcode()) { 6220 default: break; 6221 case ISD::Constant: { 6222 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6223 assert(CV && "Const value should be ConstSDNode."); 6224 const APInt &CVal = CV->getAPIntValue(); 6225 APInt NewVal = CVal & Mask; 6226 if (NewVal != CVal) 6227 return DAG.getConstant(NewVal, V.getValueType()); 6228 break; 6229 } 6230 case ISD::OR: 6231 case ISD::XOR: 6232 // If the LHS or RHS don't contribute bits to the or, drop them. 6233 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6234 return V.getOperand(1); 6235 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6236 return V.getOperand(0); 6237 break; 6238 case ISD::SRL: 6239 // Only look at single-use SRLs. 6240 if (!V.getNode()->hasOneUse()) 6241 break; 6242 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 6243 // See if we can recursively simplify the LHS. 6244 unsigned Amt = RHSC->getZExtValue(); 6245 6246 // Watch out for shift count overflow though. 6247 if (Amt >= Mask.getBitWidth()) break; 6248 APInt NewMask = Mask << Amt; 6249 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 6250 if (SimplifyLHS.getNode()) 6251 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6252 SimplifyLHS, V.getOperand(1)); 6253 } 6254 } 6255 return SDValue(); 6256 } 6257 6258 /// If the result of a wider load is shifted to right of N bits and then 6259 /// truncated to a narrower type and where N is a multiple of number of bits of 6260 /// the narrower type, transform it to a narrower load from address + N / num of 6261 /// bits of new type. If the result is to be extended, also fold the extension 6262 /// to form a extending load. 6263 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6264 unsigned Opc = N->getOpcode(); 6265 6266 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6267 SDValue N0 = N->getOperand(0); 6268 EVT VT = N->getValueType(0); 6269 EVT ExtVT = VT; 6270 6271 // This transformation isn't valid for vector loads. 6272 if (VT.isVector()) 6273 return SDValue(); 6274 6275 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6276 // extended to VT. 6277 if (Opc == ISD::SIGN_EXTEND_INREG) { 6278 ExtType = ISD::SEXTLOAD; 6279 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6280 } else if (Opc == ISD::SRL) { 6281 // Another special-case: SRL is basically zero-extending a narrower value. 6282 ExtType = ISD::ZEXTLOAD; 6283 N0 = SDValue(N, 0); 6284 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6285 if (!N01) return SDValue(); 6286 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6287 VT.getSizeInBits() - N01->getZExtValue()); 6288 } 6289 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6290 return SDValue(); 6291 6292 unsigned EVTBits = ExtVT.getSizeInBits(); 6293 6294 // Do not generate loads of non-round integer types since these can 6295 // be expensive (and would be wrong if the type is not byte sized). 6296 if (!ExtVT.isRound()) 6297 return SDValue(); 6298 6299 unsigned ShAmt = 0; 6300 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6301 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6302 ShAmt = N01->getZExtValue(); 6303 // Is the shift amount a multiple of size of VT? 6304 if ((ShAmt & (EVTBits-1)) == 0) { 6305 N0 = N0.getOperand(0); 6306 // Is the load width a multiple of size of VT? 6307 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6308 return SDValue(); 6309 } 6310 6311 // At this point, we must have a load or else we can't do the transform. 6312 if (!isa<LoadSDNode>(N0)) return SDValue(); 6313 6314 // Because a SRL must be assumed to *need* to zero-extend the high bits 6315 // (as opposed to anyext the high bits), we can't combine the zextload 6316 // lowering of SRL and an sextload. 6317 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6318 return SDValue(); 6319 6320 // If the shift amount is larger than the input type then we're not 6321 // accessing any of the loaded bytes. If the load was a zextload/extload 6322 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6323 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6324 return SDValue(); 6325 } 6326 } 6327 6328 // If the load is shifted left (and the result isn't shifted back right), 6329 // we can fold the truncate through the shift. 6330 unsigned ShLeftAmt = 0; 6331 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6332 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6333 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6334 ShLeftAmt = N01->getZExtValue(); 6335 N0 = N0.getOperand(0); 6336 } 6337 } 6338 6339 // If we haven't found a load, we can't narrow it. Don't transform one with 6340 // multiple uses, this would require adding a new load. 6341 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6342 return SDValue(); 6343 6344 // Don't change the width of a volatile load. 6345 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6346 if (LN0->isVolatile()) 6347 return SDValue(); 6348 6349 // Verify that we are actually reducing a load width here. 6350 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6351 return SDValue(); 6352 6353 // For the transform to be legal, the load must produce only two values 6354 // (the value loaded and the chain). Don't transform a pre-increment 6355 // load, for example, which produces an extra value. Otherwise the 6356 // transformation is not equivalent, and the downstream logic to replace 6357 // uses gets things wrong. 6358 if (LN0->getNumValues() > 2) 6359 return SDValue(); 6360 6361 // If the load that we're shrinking is an extload and we're not just 6362 // discarding the extension we can't simply shrink the load. Bail. 6363 // TODO: It would be possible to merge the extensions in some cases. 6364 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6365 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6366 return SDValue(); 6367 6368 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6369 return SDValue(); 6370 6371 EVT PtrType = N0.getOperand(1).getValueType(); 6372 6373 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6374 // It's not possible to generate a constant of extended or untyped type. 6375 return SDValue(); 6376 6377 // For big endian targets, we need to adjust the offset to the pointer to 6378 // load the correct bytes. 6379 if (TLI.isBigEndian()) { 6380 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6381 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6382 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6383 } 6384 6385 uint64_t PtrOff = ShAmt / 8; 6386 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6387 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 6388 PtrType, LN0->getBasePtr(), 6389 DAG.getConstant(PtrOff, PtrType)); 6390 AddToWorklist(NewPtr.getNode()); 6391 6392 SDValue Load; 6393 if (ExtType == ISD::NON_EXTLOAD) 6394 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6395 LN0->getPointerInfo().getWithOffset(PtrOff), 6396 LN0->isVolatile(), LN0->isNonTemporal(), 6397 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6398 else 6399 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6400 LN0->getPointerInfo().getWithOffset(PtrOff), 6401 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6402 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6403 6404 // Replace the old load's chain with the new load's chain. 6405 WorklistRemover DeadNodes(*this); 6406 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6407 6408 // Shift the result left, if we've swallowed a left shift. 6409 SDValue Result = Load; 6410 if (ShLeftAmt != 0) { 6411 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6412 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6413 ShImmTy = VT; 6414 // If the shift amount is as large as the result size (but, presumably, 6415 // no larger than the source) then the useful bits of the result are 6416 // zero; we can't simply return the shortened shift, because the result 6417 // of that operation is undefined. 6418 if (ShLeftAmt >= VT.getSizeInBits()) 6419 Result = DAG.getConstant(0, VT); 6420 else 6421 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 6422 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 6423 } 6424 6425 // Return the new loaded value. 6426 return Result; 6427 } 6428 6429 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6430 SDValue N0 = N->getOperand(0); 6431 SDValue N1 = N->getOperand(1); 6432 EVT VT = N->getValueType(0); 6433 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6434 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6435 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6436 6437 // fold (sext_in_reg c1) -> c1 6438 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 6439 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6440 6441 // If the input is already sign extended, just drop the extension. 6442 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6443 return N0; 6444 6445 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6446 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6447 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6448 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6449 N0.getOperand(0), N1); 6450 6451 // fold (sext_in_reg (sext x)) -> (sext x) 6452 // fold (sext_in_reg (aext x)) -> (sext x) 6453 // if x is small enough. 6454 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6455 SDValue N00 = N0.getOperand(0); 6456 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6457 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6458 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6459 } 6460 6461 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6462 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6463 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6464 6465 // fold operands of sext_in_reg based on knowledge that the top bits are not 6466 // demanded. 6467 if (SimplifyDemandedBits(SDValue(N, 0))) 6468 return SDValue(N, 0); 6469 6470 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6471 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6472 SDValue NarrowLoad = ReduceLoadWidth(N); 6473 if (NarrowLoad.getNode()) 6474 return NarrowLoad; 6475 6476 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6477 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6478 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6479 if (N0.getOpcode() == ISD::SRL) { 6480 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6481 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6482 // We can turn this into an SRA iff the input to the SRL is already sign 6483 // extended enough. 6484 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6485 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6486 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6487 N0.getOperand(0), N0.getOperand(1)); 6488 } 6489 } 6490 6491 // fold (sext_inreg (extload x)) -> (sextload x) 6492 if (ISD::isEXTLoad(N0.getNode()) && 6493 ISD::isUNINDEXEDLoad(N0.getNode()) && 6494 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6495 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6496 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6497 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6498 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6499 LN0->getChain(), 6500 LN0->getBasePtr(), EVT, 6501 LN0->getMemOperand()); 6502 CombineTo(N, ExtLoad); 6503 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6504 AddToWorklist(ExtLoad.getNode()); 6505 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6506 } 6507 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6508 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6509 N0.hasOneUse() && 6510 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6511 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6512 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6513 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6514 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6515 LN0->getChain(), 6516 LN0->getBasePtr(), EVT, 6517 LN0->getMemOperand()); 6518 CombineTo(N, ExtLoad); 6519 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6520 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6521 } 6522 6523 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6524 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6525 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6526 N0.getOperand(1), false); 6527 if (BSwap.getNode()) 6528 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6529 BSwap, N1); 6530 } 6531 6532 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 6533 // into a build_vector. 6534 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6535 SmallVector<SDValue, 8> Elts; 6536 unsigned NumElts = N0->getNumOperands(); 6537 unsigned ShAmt = VTBits - EVTBits; 6538 6539 for (unsigned i = 0; i != NumElts; ++i) { 6540 SDValue Op = N0->getOperand(i); 6541 if (Op->getOpcode() == ISD::UNDEF) { 6542 Elts.push_back(Op); 6543 continue; 6544 } 6545 6546 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 6547 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 6548 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 6549 Op.getValueType())); 6550 } 6551 6552 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts); 6553 } 6554 6555 return SDValue(); 6556 } 6557 6558 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6559 SDValue N0 = N->getOperand(0); 6560 EVT VT = N->getValueType(0); 6561 bool isLE = TLI.isLittleEndian(); 6562 6563 // noop truncate 6564 if (N0.getValueType() == N->getValueType(0)) 6565 return N0; 6566 // fold (truncate c1) -> c1 6567 if (isConstantIntBuildVectorOrConstantInt(N0)) 6568 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6569 // fold (truncate (truncate x)) -> (truncate x) 6570 if (N0.getOpcode() == ISD::TRUNCATE) 6571 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6572 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6573 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6574 N0.getOpcode() == ISD::SIGN_EXTEND || 6575 N0.getOpcode() == ISD::ANY_EXTEND) { 6576 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6577 // if the source is smaller than the dest, we still need an extend 6578 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6579 N0.getOperand(0)); 6580 if (N0.getOperand(0).getValueType().bitsGT(VT)) 6581 // if the source is larger than the dest, than we just need the truncate 6582 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6583 // if the source and dest are the same type, we can drop both the extend 6584 // and the truncate. 6585 return N0.getOperand(0); 6586 } 6587 6588 // Fold extract-and-trunc into a narrow extract. For example: 6589 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 6590 // i32 y = TRUNCATE(i64 x) 6591 // -- becomes -- 6592 // v16i8 b = BITCAST (v2i64 val) 6593 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 6594 // 6595 // Note: We only run this optimization after type legalization (which often 6596 // creates this pattern) and before operation legalization after which 6597 // we need to be more careful about the vector instructions that we generate. 6598 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6599 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 6600 6601 EVT VecTy = N0.getOperand(0).getValueType(); 6602 EVT ExTy = N0.getValueType(); 6603 EVT TrTy = N->getValueType(0); 6604 6605 unsigned NumElem = VecTy.getVectorNumElements(); 6606 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 6607 6608 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 6609 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 6610 6611 SDValue EltNo = N0->getOperand(1); 6612 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 6613 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6614 EVT IndexTy = TLI.getVectorIdxTy(); 6615 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6616 6617 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6618 NVT, N0.getOperand(0)); 6619 6620 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6621 SDLoc(N), TrTy, V, 6622 DAG.getConstant(Index, IndexTy)); 6623 } 6624 } 6625 6626 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 6627 if (N0.getOpcode() == ISD::SELECT) { 6628 EVT SrcVT = N0.getValueType(); 6629 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 6630 TLI.isTruncateFree(SrcVT, VT)) { 6631 SDLoc SL(N0); 6632 SDValue Cond = N0.getOperand(0); 6633 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 6634 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 6635 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 6636 } 6637 } 6638 6639 // Fold a series of buildvector, bitcast, and truncate if possible. 6640 // For example fold 6641 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 6642 // (2xi32 (buildvector x, y)). 6643 if (Level == AfterLegalizeVectorOps && VT.isVector() && 6644 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 6645 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 6646 N0.getOperand(0).hasOneUse()) { 6647 6648 SDValue BuildVect = N0.getOperand(0); 6649 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 6650 EVT TruncVecEltTy = VT.getVectorElementType(); 6651 6652 // Check that the element types match. 6653 if (BuildVectEltTy == TruncVecEltTy) { 6654 // Now we only need to compute the offset of the truncated elements. 6655 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 6656 unsigned TruncVecNumElts = VT.getVectorNumElements(); 6657 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 6658 6659 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 6660 "Invalid number of elements"); 6661 6662 SmallVector<SDValue, 8> Opnds; 6663 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 6664 Opnds.push_back(BuildVect.getOperand(i)); 6665 6666 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 6667 } 6668 } 6669 6670 // See if we can simplify the input to this truncate through knowledge that 6671 // only the low bits are being used. 6672 // For example "trunc (or (shl x, 8), y)" // -> trunc y 6673 // Currently we only perform this optimization on scalars because vectors 6674 // may have different active low bits. 6675 if (!VT.isVector()) { 6676 SDValue Shorter = 6677 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 6678 VT.getSizeInBits())); 6679 if (Shorter.getNode()) 6680 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 6681 } 6682 // fold (truncate (load x)) -> (smaller load x) 6683 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 6684 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 6685 SDValue Reduced = ReduceLoadWidth(N); 6686 if (Reduced.getNode()) 6687 return Reduced; 6688 // Handle the case where the load remains an extending load even 6689 // after truncation. 6690 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 6691 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6692 if (!LN0->isVolatile() && 6693 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 6694 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 6695 VT, LN0->getChain(), LN0->getBasePtr(), 6696 LN0->getMemoryVT(), 6697 LN0->getMemOperand()); 6698 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 6699 return NewLoad; 6700 } 6701 } 6702 } 6703 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 6704 // where ... are all 'undef'. 6705 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 6706 SmallVector<EVT, 8> VTs; 6707 SDValue V; 6708 unsigned Idx = 0; 6709 unsigned NumDefs = 0; 6710 6711 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 6712 SDValue X = N0.getOperand(i); 6713 if (X.getOpcode() != ISD::UNDEF) { 6714 V = X; 6715 Idx = i; 6716 NumDefs++; 6717 } 6718 // Stop if more than one members are non-undef. 6719 if (NumDefs > 1) 6720 break; 6721 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 6722 VT.getVectorElementType(), 6723 X.getValueType().getVectorNumElements())); 6724 } 6725 6726 if (NumDefs == 0) 6727 return DAG.getUNDEF(VT); 6728 6729 if (NumDefs == 1) { 6730 assert(V.getNode() && "The single defined operand is empty!"); 6731 SmallVector<SDValue, 8> Opnds; 6732 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 6733 if (i != Idx) { 6734 Opnds.push_back(DAG.getUNDEF(VTs[i])); 6735 continue; 6736 } 6737 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 6738 AddToWorklist(NV.getNode()); 6739 Opnds.push_back(NV); 6740 } 6741 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 6742 } 6743 } 6744 6745 // Simplify the operands using demanded-bits information. 6746 if (!VT.isVector() && 6747 SimplifyDemandedBits(SDValue(N, 0))) 6748 return SDValue(N, 0); 6749 6750 return SDValue(); 6751 } 6752 6753 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 6754 SDValue Elt = N->getOperand(i); 6755 if (Elt.getOpcode() != ISD::MERGE_VALUES) 6756 return Elt.getNode(); 6757 return Elt.getOperand(Elt.getResNo()).getNode(); 6758 } 6759 6760 /// build_pair (load, load) -> load 6761 /// if load locations are consecutive. 6762 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 6763 assert(N->getOpcode() == ISD::BUILD_PAIR); 6764 6765 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 6766 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 6767 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 6768 LD1->getAddressSpace() != LD2->getAddressSpace()) 6769 return SDValue(); 6770 EVT LD1VT = LD1->getValueType(0); 6771 6772 if (ISD::isNON_EXTLoad(LD2) && 6773 LD2->hasOneUse() && 6774 // If both are volatile this would reduce the number of volatile loads. 6775 // If one is volatile it might be ok, but play conservative and bail out. 6776 !LD1->isVolatile() && 6777 !LD2->isVolatile() && 6778 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 6779 unsigned Align = LD1->getAlignment(); 6780 unsigned NewAlign = TLI.getDataLayout()-> 6781 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6782 6783 if (NewAlign <= Align && 6784 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 6785 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 6786 LD1->getBasePtr(), LD1->getPointerInfo(), 6787 false, false, false, Align); 6788 } 6789 6790 return SDValue(); 6791 } 6792 6793 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 6794 SDValue N0 = N->getOperand(0); 6795 EVT VT = N->getValueType(0); 6796 6797 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 6798 // Only do this before legalize, since afterward the target may be depending 6799 // on the bitconvert. 6800 // First check to see if this is all constant. 6801 if (!LegalTypes && 6802 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 6803 VT.isVector()) { 6804 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 6805 6806 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 6807 assert(!DestEltVT.isVector() && 6808 "Element type of vector ValueType must not be vector!"); 6809 if (isSimple) 6810 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 6811 } 6812 6813 // If the input is a constant, let getNode fold it. 6814 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 6815 // If we can't allow illegal operations, we need to check that this is just 6816 // a fp -> int or int -> conversion and that the resulting operation will 6817 // be legal. 6818 if (!LegalOperations || 6819 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 6820 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 6821 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 6822 TLI.isOperationLegal(ISD::Constant, VT))) 6823 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 6824 } 6825 6826 // (conv (conv x, t1), t2) -> (conv x, t2) 6827 if (N0.getOpcode() == ISD::BITCAST) 6828 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 6829 N0.getOperand(0)); 6830 6831 // fold (conv (load x)) -> (load (conv*)x) 6832 // If the resultant load doesn't need a higher alignment than the original! 6833 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 6834 // Do not change the width of a volatile load. 6835 !cast<LoadSDNode>(N0)->isVolatile() && 6836 // Do not remove the cast if the types differ in endian layout. 6837 TLI.hasBigEndianPartOrdering(N0.getValueType()) == 6838 TLI.hasBigEndianPartOrdering(VT) && 6839 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 6840 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 6841 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6842 unsigned Align = TLI.getDataLayout()-> 6843 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6844 unsigned OrigAlign = LN0->getAlignment(); 6845 6846 if (Align <= OrigAlign) { 6847 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 6848 LN0->getBasePtr(), LN0->getPointerInfo(), 6849 LN0->isVolatile(), LN0->isNonTemporal(), 6850 LN0->isInvariant(), OrigAlign, 6851 LN0->getAAInfo()); 6852 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6853 return Load; 6854 } 6855 } 6856 6857 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6858 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6859 // This often reduces constant pool loads. 6860 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 6861 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 6862 N0.getNode()->hasOneUse() && VT.isInteger() && 6863 !VT.isVector() && !N0.getValueType().isVector()) { 6864 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 6865 N0.getOperand(0)); 6866 AddToWorklist(NewConv.getNode()); 6867 6868 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6869 if (N0.getOpcode() == ISD::FNEG) 6870 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 6871 NewConv, DAG.getConstant(SignBit, VT)); 6872 assert(N0.getOpcode() == ISD::FABS); 6873 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6874 NewConv, DAG.getConstant(~SignBit, VT)); 6875 } 6876 6877 // fold (bitconvert (fcopysign cst, x)) -> 6878 // (or (and (bitconvert x), sign), (and cst, (not sign))) 6879 // Note that we don't handle (copysign x, cst) because this can always be 6880 // folded to an fneg or fabs. 6881 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 6882 isa<ConstantFPSDNode>(N0.getOperand(0)) && 6883 VT.isInteger() && !VT.isVector()) { 6884 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 6885 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 6886 if (isTypeLegal(IntXVT)) { 6887 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6888 IntXVT, N0.getOperand(1)); 6889 AddToWorklist(X.getNode()); 6890 6891 // If X has a different width than the result/lhs, sext it or truncate it. 6892 unsigned VTWidth = VT.getSizeInBits(); 6893 if (OrigXWidth < VTWidth) { 6894 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 6895 AddToWorklist(X.getNode()); 6896 } else if (OrigXWidth > VTWidth) { 6897 // To get the sign bit in the right place, we have to shift it right 6898 // before truncating. 6899 X = DAG.getNode(ISD::SRL, SDLoc(X), 6900 X.getValueType(), X, 6901 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 6902 AddToWorklist(X.getNode()); 6903 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6904 AddToWorklist(X.getNode()); 6905 } 6906 6907 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6908 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 6909 X, DAG.getConstant(SignBit, VT)); 6910 AddToWorklist(X.getNode()); 6911 6912 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6913 VT, N0.getOperand(0)); 6914 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 6915 Cst, DAG.getConstant(~SignBit, VT)); 6916 AddToWorklist(Cst.getNode()); 6917 6918 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 6919 } 6920 } 6921 6922 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 6923 if (N0.getOpcode() == ISD::BUILD_PAIR) { 6924 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 6925 if (CombineLD.getNode()) 6926 return CombineLD; 6927 } 6928 6929 return SDValue(); 6930 } 6931 6932 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 6933 EVT VT = N->getValueType(0); 6934 return CombineConsecutiveLoads(N, VT); 6935 } 6936 6937 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 6938 /// operands. DstEltVT indicates the destination element value type. 6939 SDValue DAGCombiner:: 6940 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 6941 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 6942 6943 // If this is already the right type, we're done. 6944 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 6945 6946 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 6947 unsigned DstBitSize = DstEltVT.getSizeInBits(); 6948 6949 // If this is a conversion of N elements of one type to N elements of another 6950 // type, convert each element. This handles FP<->INT cases. 6951 if (SrcBitSize == DstBitSize) { 6952 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6953 BV->getValueType(0).getVectorNumElements()); 6954 6955 // Due to the FP element handling below calling this routine recursively, 6956 // we can end up with a scalar-to-vector node here. 6957 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 6958 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6959 DAG.getNode(ISD::BITCAST, SDLoc(BV), 6960 DstEltVT, BV->getOperand(0))); 6961 6962 SmallVector<SDValue, 8> Ops; 6963 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6964 SDValue Op = BV->getOperand(i); 6965 // If the vector element type is not legal, the BUILD_VECTOR operands 6966 // are promoted and implicitly truncated. Make that explicit here. 6967 if (Op.getValueType() != SrcEltVT) 6968 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 6969 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 6970 DstEltVT, Op)); 6971 AddToWorklist(Ops.back().getNode()); 6972 } 6973 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6974 } 6975 6976 // Otherwise, we're growing or shrinking the elements. To avoid having to 6977 // handle annoying details of growing/shrinking FP values, we convert them to 6978 // int first. 6979 if (SrcEltVT.isFloatingPoint()) { 6980 // Convert the input float vector to a int vector where the elements are the 6981 // same sizes. 6982 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 6983 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 6984 SrcEltVT = IntVT; 6985 } 6986 6987 // Now we know the input is an integer vector. If the output is a FP type, 6988 // convert to integer first, then to FP of the right size. 6989 if (DstEltVT.isFloatingPoint()) { 6990 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 6991 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 6992 6993 // Next, convert to FP elements of the same size. 6994 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 6995 } 6996 6997 // Okay, we know the src/dst types are both integers of differing types. 6998 // Handling growing first. 6999 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7000 if (SrcBitSize < DstBitSize) { 7001 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7002 7003 SmallVector<SDValue, 8> Ops; 7004 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7005 i += NumInputsPerOutput) { 7006 bool isLE = TLI.isLittleEndian(); 7007 APInt NewBits = APInt(DstBitSize, 0); 7008 bool EltIsUndef = true; 7009 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7010 // Shift the previously computed bits over. 7011 NewBits <<= SrcBitSize; 7012 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7013 if (Op.getOpcode() == ISD::UNDEF) continue; 7014 EltIsUndef = false; 7015 7016 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7017 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7018 } 7019 7020 if (EltIsUndef) 7021 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7022 else 7023 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 7024 } 7025 7026 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7027 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7028 } 7029 7030 // Finally, this must be the case where we are shrinking elements: each input 7031 // turns into multiple outputs. 7032 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7033 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7034 NumOutputsPerInput*BV->getNumOperands()); 7035 SmallVector<SDValue, 8> Ops; 7036 7037 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 7038 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 7039 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7040 continue; 7041 } 7042 7043 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 7044 getAPIntValue().zextOrTrunc(SrcBitSize); 7045 7046 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7047 APInt ThisVal = OpVal.trunc(DstBitSize); 7048 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 7049 OpVal = OpVal.lshr(DstBitSize); 7050 } 7051 7052 // For big endian targets, swap the order of the pieces of each element. 7053 if (TLI.isBigEndian()) 7054 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7055 } 7056 7057 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7058 } 7059 7060 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad 7061 static SDValue performFaddFmulCombines(unsigned FusedOpcode, 7062 bool Aggressive, 7063 SDNode *N, 7064 const TargetLowering &TLI, 7065 SelectionDAG &DAG) { 7066 SDValue N0 = N->getOperand(0); 7067 SDValue N1 = N->getOperand(1); 7068 EVT VT = N->getValueType(0); 7069 7070 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7071 if (N0.getOpcode() == ISD::FMUL && 7072 (Aggressive || N0->hasOneUse())) { 7073 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 7074 N0.getOperand(0), N0.getOperand(1), N1); 7075 } 7076 7077 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7078 // Note: Commutes FADD operands. 7079 if (N1.getOpcode() == ISD::FMUL && 7080 (Aggressive || N1->hasOneUse())) { 7081 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 7082 N1.getOperand(0), N1.getOperand(1), N0); 7083 } 7084 7085 // More folding opportunities when target permits. 7086 if (Aggressive) { 7087 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7088 if (N0.getOpcode() == ISD::FMA && 7089 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7090 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 7091 N0.getOperand(0), N0.getOperand(1), 7092 DAG.getNode(FusedOpcode, SDLoc(N), VT, 7093 N0.getOperand(2).getOperand(0), 7094 N0.getOperand(2).getOperand(1), 7095 N1)); 7096 } 7097 7098 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7099 if (N1->getOpcode() == ISD::FMA && 7100 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7101 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 7102 N1.getOperand(0), N1.getOperand(1), 7103 DAG.getNode(FusedOpcode, SDLoc(N), VT, 7104 N1.getOperand(2).getOperand(0), 7105 N1.getOperand(2).getOperand(1), 7106 N0)); 7107 } 7108 } 7109 7110 return SDValue(); 7111 } 7112 7113 static SDValue performFsubFmulCombines(unsigned FusedOpcode, 7114 bool Aggressive, 7115 SDNode *N, 7116 const TargetLowering &TLI, 7117 SelectionDAG &DAG) { 7118 SDValue N0 = N->getOperand(0); 7119 SDValue N1 = N->getOperand(1); 7120 EVT VT = N->getValueType(0); 7121 7122 SDLoc SL(N); 7123 7124 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7125 if (N0.getOpcode() == ISD::FMUL && 7126 (Aggressive || N0->hasOneUse())) { 7127 return DAG.getNode(FusedOpcode, SL, VT, 7128 N0.getOperand(0), N0.getOperand(1), 7129 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7130 } 7131 7132 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7133 // Note: Commutes FSUB operands. 7134 if (N1.getOpcode() == ISD::FMUL && 7135 (Aggressive || N1->hasOneUse())) 7136 return DAG.getNode(FusedOpcode, SL, VT, 7137 DAG.getNode(ISD::FNEG, SL, VT, 7138 N1.getOperand(0)), 7139 N1.getOperand(1), N0); 7140 7141 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7142 if (N0.getOpcode() == ISD::FNEG && 7143 N0.getOperand(0).getOpcode() == ISD::FMUL && 7144 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7145 SDValue N00 = N0.getOperand(0).getOperand(0); 7146 SDValue N01 = N0.getOperand(0).getOperand(1); 7147 return DAG.getNode(FusedOpcode, SL, VT, 7148 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7149 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7150 } 7151 7152 // More folding opportunities when target permits. 7153 if (Aggressive) { 7154 // fold (fsub (fma x, y, (fmul u, v)), z) 7155 // -> (fma x, y (fma u, v, (fneg z))) 7156 if (N0.getOpcode() == FusedOpcode && 7157 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7158 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 7159 N0.getOperand(0), N0.getOperand(1), 7160 DAG.getNode(FusedOpcode, SDLoc(N), VT, 7161 N0.getOperand(2).getOperand(0), 7162 N0.getOperand(2).getOperand(1), 7163 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7164 N1))); 7165 } 7166 7167 // fold (fsub x, (fma y, z, (fmul u, v))) 7168 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7169 if (N1.getOpcode() == FusedOpcode && 7170 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7171 SDValue N20 = N1.getOperand(2).getOperand(0); 7172 SDValue N21 = N1.getOperand(2).getOperand(1); 7173 return DAG.getNode(FusedOpcode, SDLoc(N), VT, 7174 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7175 N1.getOperand(0)), 7176 N1.getOperand(1), 7177 DAG.getNode(FusedOpcode, SDLoc(N), VT, 7178 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7179 N20), 7180 N21, N0)); 7181 } 7182 } 7183 7184 return SDValue(); 7185 } 7186 7187 SDValue DAGCombiner::visitFADD(SDNode *N) { 7188 SDValue N0 = N->getOperand(0); 7189 SDValue N1 = N->getOperand(1); 7190 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7191 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7192 EVT VT = N->getValueType(0); 7193 const TargetOptions &Options = DAG.getTarget().Options; 7194 7195 // fold vector ops 7196 if (VT.isVector()) 7197 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7198 return FoldedVOp; 7199 7200 // fold (fadd c1, c2) -> c1 + c2 7201 if (N0CFP && N1CFP) 7202 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 7203 7204 // canonicalize constant to RHS 7205 if (N0CFP && !N1CFP) 7206 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 7207 7208 // fold (fadd A, (fneg B)) -> (fsub A, B) 7209 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7210 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 7211 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 7212 GetNegatedExpression(N1, DAG, LegalOperations)); 7213 7214 // fold (fadd (fneg A), B) -> (fsub B, A) 7215 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7216 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 7217 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 7218 GetNegatedExpression(N0, DAG, LegalOperations)); 7219 7220 // If 'unsafe math' is enabled, fold lots of things. 7221 if (Options.UnsafeFPMath) { 7222 // No FP constant should be created after legalization as Instruction 7223 // Selection pass has a hard time dealing with FP constants. 7224 bool AllowNewConst = (Level < AfterLegalizeDAG); 7225 7226 // fold (fadd A, 0) -> A 7227 if (N1CFP && N1CFP->getValueAPF().isZero()) 7228 return N0; 7229 7230 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 7231 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 7232 isa<ConstantFPSDNode>(N0.getOperand(1))) 7233 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 7234 DAG.getNode(ISD::FADD, SDLoc(N), VT, 7235 N0.getOperand(1), N1)); 7236 7237 // If allowed, fold (fadd (fneg x), x) -> 0.0 7238 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 7239 return DAG.getConstantFP(0.0, VT); 7240 7241 // If allowed, fold (fadd x, (fneg x)) -> 0.0 7242 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 7243 return DAG.getConstantFP(0.0, VT); 7244 7245 // We can fold chains of FADD's of the same value into multiplications. 7246 // This transform is not safe in general because we are reducing the number 7247 // of rounding steps. 7248 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 7249 if (N0.getOpcode() == ISD::FMUL) { 7250 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7251 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7252 7253 // (fadd (fmul x, c), x) -> (fmul x, c+1) 7254 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 7255 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7256 SDValue(CFP01, 0), 7257 DAG.getConstantFP(1.0, VT)); 7258 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP); 7259 } 7260 7261 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 7262 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 7263 N1.getOperand(0) == N1.getOperand(1) && 7264 N0.getOperand(0) == N1.getOperand(0)) { 7265 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7266 SDValue(CFP01, 0), 7267 DAG.getConstantFP(2.0, VT)); 7268 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7269 N0.getOperand(0), NewCFP); 7270 } 7271 } 7272 7273 if (N1.getOpcode() == ISD::FMUL) { 7274 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7275 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 7276 7277 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 7278 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 7279 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7280 SDValue(CFP11, 0), 7281 DAG.getConstantFP(1.0, VT)); 7282 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP); 7283 } 7284 7285 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 7286 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 7287 N0.getOperand(0) == N0.getOperand(1) && 7288 N1.getOperand(0) == N0.getOperand(0)) { 7289 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 7290 SDValue(CFP11, 0), 7291 DAG.getConstantFP(2.0, VT)); 7292 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP); 7293 } 7294 } 7295 7296 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 7297 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7298 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 7299 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 7300 (N0.getOperand(0) == N1)) 7301 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7302 N1, DAG.getConstantFP(3.0, VT)); 7303 } 7304 7305 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 7306 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7307 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 7308 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 7309 N1.getOperand(0) == N0) 7310 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7311 N0, DAG.getConstantFP(3.0, VT)); 7312 } 7313 7314 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 7315 if (AllowNewConst && 7316 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 7317 N0.getOperand(0) == N0.getOperand(1) && 7318 N1.getOperand(0) == N1.getOperand(1) && 7319 N0.getOperand(0) == N1.getOperand(0)) 7320 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7321 N0.getOperand(0), DAG.getConstantFP(4.0, VT)); 7322 } 7323 } // enable-unsafe-fp-math 7324 7325 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) { 7326 // Assume if there is an fmad instruction that it should be aggressively 7327 // used. 7328 if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG)) 7329 return Fused; 7330 } 7331 7332 // FADD -> FMA combines: 7333 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 7334 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7335 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 7336 7337 if (!TLI.isOperationLegal(ISD::FMAD, VT)) { 7338 // Don't form FMA if we are preferring FMAD. 7339 if (SDValue Fused 7340 = performFaddFmulCombines(ISD::FMA, 7341 TLI.enableAggressiveFMAFusion(VT), 7342 N, TLI, DAG)) { 7343 return Fused; 7344 } 7345 } 7346 7347 // When FP_EXTEND nodes are free on the target, and there is an opportunity 7348 // to combine into FMA, arrange such nodes accordingly. 7349 if (TLI.isFPExtFree(VT)) { 7350 7351 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7352 if (N0.getOpcode() == ISD::FP_EXTEND) { 7353 SDValue N00 = N0.getOperand(0); 7354 if (N00.getOpcode() == ISD::FMUL) 7355 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7356 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7357 N00.getOperand(0)), 7358 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7359 N00.getOperand(1)), N1); 7360 } 7361 7362 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x) 7363 // Note: Commutes FADD operands. 7364 if (N1.getOpcode() == ISD::FP_EXTEND) { 7365 SDValue N10 = N1.getOperand(0); 7366 if (N10.getOpcode() == ISD::FMUL) 7367 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7368 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7369 N10.getOperand(0)), 7370 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7371 N10.getOperand(1)), N0); 7372 } 7373 } 7374 } 7375 7376 return SDValue(); 7377 } 7378 7379 SDValue DAGCombiner::visitFSUB(SDNode *N) { 7380 SDValue N0 = N->getOperand(0); 7381 SDValue N1 = N->getOperand(1); 7382 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7383 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7384 EVT VT = N->getValueType(0); 7385 SDLoc dl(N); 7386 const TargetOptions &Options = DAG.getTarget().Options; 7387 7388 // fold vector ops 7389 if (VT.isVector()) 7390 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7391 return FoldedVOp; 7392 7393 // fold (fsub c1, c2) -> c1-c2 7394 if (N0CFP && N1CFP) 7395 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 7396 7397 // fold (fsub A, (fneg B)) -> (fadd A, B) 7398 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7399 return DAG.getNode(ISD::FADD, dl, VT, N0, 7400 GetNegatedExpression(N1, DAG, LegalOperations)); 7401 7402 // If 'unsafe math' is enabled, fold lots of things. 7403 if (Options.UnsafeFPMath) { 7404 // (fsub A, 0) -> A 7405 if (N1CFP && N1CFP->getValueAPF().isZero()) 7406 return N0; 7407 7408 // (fsub 0, B) -> -B 7409 if (N0CFP && N0CFP->getValueAPF().isZero()) { 7410 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7411 return GetNegatedExpression(N1, DAG, LegalOperations); 7412 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7413 return DAG.getNode(ISD::FNEG, dl, VT, N1); 7414 } 7415 7416 // (fsub x, x) -> 0.0 7417 if (N0 == N1) 7418 return DAG.getConstantFP(0.0f, VT); 7419 7420 // (fsub x, (fadd x, y)) -> (fneg y) 7421 // (fsub x, (fadd y, x)) -> (fneg y) 7422 if (N1.getOpcode() == ISD::FADD) { 7423 SDValue N10 = N1->getOperand(0); 7424 SDValue N11 = N1->getOperand(1); 7425 7426 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 7427 return GetNegatedExpression(N11, DAG, LegalOperations); 7428 7429 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 7430 return GetNegatedExpression(N10, DAG, LegalOperations); 7431 } 7432 } 7433 7434 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) { 7435 // Assume if there is an fmad instruction that it should be aggressively 7436 // used. 7437 if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG)) 7438 return Fused; 7439 } 7440 7441 // FSUB -> FMA combines: 7442 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 7443 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7444 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 7445 7446 if (!TLI.isOperationLegal(ISD::FMAD, VT)) { 7447 // Don't form FMA if we are preferring FMAD. 7448 7449 if (SDValue Fused 7450 = performFsubFmulCombines(ISD::FMA, 7451 TLI.enableAggressiveFMAFusion(VT), 7452 N, TLI, DAG)) { 7453 return Fused; 7454 } 7455 } 7456 7457 // When FP_EXTEND nodes are free on the target, and there is an opportunity 7458 // to combine into FMA, arrange such nodes accordingly. 7459 if (TLI.isFPExtFree(VT)) { 7460 // fold (fsub (fpext (fmul x, y)), z) 7461 // -> (fma (fpext x), (fpext y), (fneg z)) 7462 if (N0.getOpcode() == ISD::FP_EXTEND) { 7463 SDValue N00 = N0.getOperand(0); 7464 if (N00.getOpcode() == ISD::FMUL) 7465 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7466 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7467 N00.getOperand(0)), 7468 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7469 N00.getOperand(1)), 7470 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1)); 7471 } 7472 7473 // fold (fsub x, (fpext (fmul y, z))) 7474 // -> (fma (fneg (fpext y)), (fpext z), x) 7475 // Note: Commutes FSUB operands. 7476 if (N1.getOpcode() == ISD::FP_EXTEND) { 7477 SDValue N10 = N1.getOperand(0); 7478 if (N10.getOpcode() == ISD::FMUL) 7479 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7480 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7481 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), 7482 VT, N10.getOperand(0))), 7483 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7484 N10.getOperand(1)), 7485 N0); 7486 } 7487 7488 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7489 // -> (fma (fneg (fpext x)), (fpext y), (fneg z)) 7490 if (N0.getOpcode() == ISD::FP_EXTEND) { 7491 SDValue N00 = N0.getOperand(0); 7492 if (N00.getOpcode() == ISD::FNEG) { 7493 SDValue N000 = N00.getOperand(0); 7494 if (N000.getOpcode() == ISD::FMUL) { 7495 return DAG.getNode(ISD::FMA, dl, VT, 7496 DAG.getNode(ISD::FNEG, dl, VT, 7497 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), 7498 VT, N000.getOperand(0))), 7499 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7500 N000.getOperand(1)), 7501 DAG.getNode(ISD::FNEG, dl, VT, N1)); 7502 } 7503 } 7504 } 7505 7506 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7507 // -> (fma (fneg (fpext x)), (fpext y), (fneg z)) 7508 if (N0.getOpcode() == ISD::FNEG) { 7509 SDValue N00 = N0.getOperand(0); 7510 if (N00.getOpcode() == ISD::FP_EXTEND) { 7511 SDValue N000 = N00.getOperand(0); 7512 if (N000.getOpcode() == ISD::FMUL) { 7513 return DAG.getNode(ISD::FMA, dl, VT, 7514 DAG.getNode(ISD::FNEG, dl, VT, 7515 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), 7516 VT, N000.getOperand(0))), 7517 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7518 N000.getOperand(1)), 7519 DAG.getNode(ISD::FNEG, dl, VT, N1)); 7520 } 7521 } 7522 } 7523 } 7524 } 7525 7526 return SDValue(); 7527 } 7528 7529 SDValue DAGCombiner::visitFMUL(SDNode *N) { 7530 SDValue N0 = N->getOperand(0); 7531 SDValue N1 = N->getOperand(1); 7532 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7533 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7534 EVT VT = N->getValueType(0); 7535 const TargetOptions &Options = DAG.getTarget().Options; 7536 7537 // fold vector ops 7538 if (VT.isVector()) { 7539 // This just handles C1 * C2 for vectors. Other vector folds are below. 7540 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7541 return FoldedVOp; 7542 } 7543 7544 // fold (fmul c1, c2) -> c1*c2 7545 if (N0CFP && N1CFP) 7546 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 7547 7548 // canonicalize constant to RHS 7549 if (isConstantFPBuildVectorOrConstantFP(N0) && 7550 !isConstantFPBuildVectorOrConstantFP(N1)) 7551 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 7552 7553 // fold (fmul A, 1.0) -> A 7554 if (N1CFP && N1CFP->isExactlyValue(1.0)) 7555 return N0; 7556 7557 if (Options.UnsafeFPMath) { 7558 // fold (fmul A, 0) -> 0 7559 if (N1CFP && N1CFP->getValueAPF().isZero()) 7560 return N1; 7561 7562 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 7563 if (N0.getOpcode() == ISD::FMUL) { 7564 // Fold scalars or any vector constants (not just splats). 7565 // This fold is done in general by InstCombine, but extra fmul insts 7566 // may have been generated during lowering. 7567 SDValue N00 = N0.getOperand(0); 7568 SDValue N01 = N0.getOperand(1); 7569 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 7570 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 7571 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 7572 7573 // Check 1: Make sure that the first operand of the inner multiply is NOT 7574 // a constant. Otherwise, we may induce infinite looping. 7575 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 7576 // Check 2: Make sure that the second operand of the inner multiply and 7577 // the second operand of the outer multiply are constants. 7578 if ((N1CFP && isConstOrConstSplatFP(N01)) || 7579 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 7580 SDLoc SL(N); 7581 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1); 7582 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts); 7583 } 7584 } 7585 } 7586 7587 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 7588 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 7589 // during an early run of DAGCombiner can prevent folding with fmuls 7590 // inserted during lowering. 7591 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) { 7592 SDLoc SL(N); 7593 const SDValue Two = DAG.getConstantFP(2.0, VT); 7594 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1); 7595 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts); 7596 } 7597 } 7598 7599 // fold (fmul X, 2.0) -> (fadd X, X) 7600 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 7601 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 7602 7603 // fold (fmul X, -1.0) -> (fneg X) 7604 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 7605 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7606 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 7607 7608 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 7609 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 7610 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 7611 // Both can be negated for free, check to see if at least one is cheaper 7612 // negated. 7613 if (LHSNeg == 2 || RHSNeg == 2) 7614 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7615 GetNegatedExpression(N0, DAG, LegalOperations), 7616 GetNegatedExpression(N1, DAG, LegalOperations)); 7617 } 7618 } 7619 7620 return SDValue(); 7621 } 7622 7623 SDValue DAGCombiner::visitFMA(SDNode *N) { 7624 SDValue N0 = N->getOperand(0); 7625 SDValue N1 = N->getOperand(1); 7626 SDValue N2 = N->getOperand(2); 7627 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7628 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7629 EVT VT = N->getValueType(0); 7630 SDLoc dl(N); 7631 const TargetOptions &Options = DAG.getTarget().Options; 7632 7633 // Constant fold FMA. 7634 if (isa<ConstantFPSDNode>(N0) && 7635 isa<ConstantFPSDNode>(N1) && 7636 isa<ConstantFPSDNode>(N2)) { 7637 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 7638 } 7639 7640 if (Options.UnsafeFPMath) { 7641 if (N0CFP && N0CFP->isZero()) 7642 return N2; 7643 if (N1CFP && N1CFP->isZero()) 7644 return N2; 7645 } 7646 if (N0CFP && N0CFP->isExactlyValue(1.0)) 7647 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 7648 if (N1CFP && N1CFP->isExactlyValue(1.0)) 7649 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 7650 7651 // Canonicalize (fma c, x, y) -> (fma x, c, y) 7652 if (N0CFP && !N1CFP) 7653 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 7654 7655 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 7656 if (Options.UnsafeFPMath && N1CFP && 7657 N2.getOpcode() == ISD::FMUL && 7658 N0 == N2.getOperand(0) && 7659 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 7660 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7661 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 7662 } 7663 7664 7665 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 7666 if (Options.UnsafeFPMath && 7667 N0.getOpcode() == ISD::FMUL && N1CFP && 7668 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 7669 return DAG.getNode(ISD::FMA, dl, VT, 7670 N0.getOperand(0), 7671 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 7672 N2); 7673 } 7674 7675 // (fma x, 1, y) -> (fadd x, y) 7676 // (fma x, -1, y) -> (fadd (fneg x), y) 7677 if (N1CFP) { 7678 if (N1CFP->isExactlyValue(1.0)) 7679 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 7680 7681 if (N1CFP->isExactlyValue(-1.0) && 7682 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 7683 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 7684 AddToWorklist(RHSNeg.getNode()); 7685 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 7686 } 7687 } 7688 7689 // (fma x, c, x) -> (fmul x, (c+1)) 7690 if (Options.UnsafeFPMath && N1CFP && N0 == N2) 7691 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7692 DAG.getNode(ISD::FADD, dl, VT, 7693 N1, DAG.getConstantFP(1.0, VT))); 7694 7695 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 7696 if (Options.UnsafeFPMath && N1CFP && 7697 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 7698 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7699 DAG.getNode(ISD::FADD, dl, VT, 7700 N1, DAG.getConstantFP(-1.0, VT))); 7701 7702 7703 return SDValue(); 7704 } 7705 7706 SDValue DAGCombiner::visitFDIV(SDNode *N) { 7707 SDValue N0 = N->getOperand(0); 7708 SDValue N1 = N->getOperand(1); 7709 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7710 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7711 EVT VT = N->getValueType(0); 7712 SDLoc DL(N); 7713 const TargetOptions &Options = DAG.getTarget().Options; 7714 7715 // fold vector ops 7716 if (VT.isVector()) 7717 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7718 return FoldedVOp; 7719 7720 // fold (fdiv c1, c2) -> c1/c2 7721 if (N0CFP && N1CFP) 7722 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 7723 7724 if (Options.UnsafeFPMath) { 7725 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 7726 if (N1CFP) { 7727 // Compute the reciprocal 1.0 / c2. 7728 APFloat N1APF = N1CFP->getValueAPF(); 7729 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 7730 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 7731 // Only do the transform if the reciprocal is a legal fp immediate that 7732 // isn't too nasty (eg NaN, denormal, ...). 7733 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 7734 (!LegalOperations || 7735 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 7736 // backend)... we should handle this gracefully after Legalize. 7737 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 7738 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 7739 TLI.isFPImmLegal(Recip, VT))) 7740 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 7741 DAG.getConstantFP(Recip, VT)); 7742 } 7743 7744 // If this FDIV is part of a reciprocal square root, it may be folded 7745 // into a target-specific square root estimate instruction. 7746 if (N1.getOpcode() == ISD::FSQRT) { 7747 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) { 7748 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7749 } 7750 } else if (N1.getOpcode() == ISD::FP_EXTEND && 7751 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7752 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 7753 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 7754 AddToWorklist(RV.getNode()); 7755 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7756 } 7757 } else if (N1.getOpcode() == ISD::FP_ROUND && 7758 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7759 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 7760 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 7761 AddToWorklist(RV.getNode()); 7762 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7763 } 7764 } else if (N1.getOpcode() == ISD::FMUL) { 7765 // Look through an FMUL. Even though this won't remove the FDIV directly, 7766 // it's still worthwhile to get rid of the FSQRT if possible. 7767 SDValue SqrtOp; 7768 SDValue OtherOp; 7769 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7770 SqrtOp = N1.getOperand(0); 7771 OtherOp = N1.getOperand(1); 7772 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 7773 SqrtOp = N1.getOperand(1); 7774 OtherOp = N1.getOperand(0); 7775 } 7776 if (SqrtOp.getNode()) { 7777 // We found a FSQRT, so try to make this fold: 7778 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 7779 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) { 7780 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp); 7781 AddToWorklist(RV.getNode()); 7782 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7783 } 7784 } 7785 } 7786 7787 // Fold into a reciprocal estimate and multiply instead of a real divide. 7788 if (SDValue RV = BuildReciprocalEstimate(N1)) { 7789 AddToWorklist(RV.getNode()); 7790 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7791 } 7792 } 7793 7794 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 7795 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 7796 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 7797 // Both can be negated for free, check to see if at least one is cheaper 7798 // negated. 7799 if (LHSNeg == 2 || RHSNeg == 2) 7800 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 7801 GetNegatedExpression(N0, DAG, LegalOperations), 7802 GetNegatedExpression(N1, DAG, LegalOperations)); 7803 } 7804 } 7805 7806 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 7807 // reciprocal. 7808 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 7809 // Notice that this is not always beneficial. One reason is different target 7810 // may have different costs for FDIV and FMUL, so sometimes the cost of two 7811 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 7812 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 7813 if (Options.UnsafeFPMath) { 7814 // Skip if current node is a reciprocal. 7815 if (N0CFP && N0CFP->isExactlyValue(1.0)) 7816 return SDValue(); 7817 7818 SmallVector<SDNode *, 4> Users; 7819 // Find all FDIV users of the same divisor. 7820 for (SDNode::use_iterator UI = N1.getNode()->use_begin(), 7821 UE = N1.getNode()->use_end(); 7822 UI != UE; ++UI) { 7823 SDNode *User = UI.getUse().getUser(); 7824 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1) 7825 Users.push_back(User); 7826 } 7827 7828 if (TLI.combineRepeatedFPDivisors(Users.size())) { 7829 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0 7830 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1); 7831 7832 // Dividend / Divisor -> Dividend * Reciprocal 7833 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) { 7834 if ((*I)->getOperand(0) != FPOne) { 7835 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT, 7836 (*I)->getOperand(0), Reciprocal); 7837 DAG.ReplaceAllUsesWith(*I, NewNode.getNode()); 7838 } 7839 } 7840 return SDValue(); 7841 } 7842 } 7843 7844 return SDValue(); 7845 } 7846 7847 SDValue DAGCombiner::visitFREM(SDNode *N) { 7848 SDValue N0 = N->getOperand(0); 7849 SDValue N1 = N->getOperand(1); 7850 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7851 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7852 EVT VT = N->getValueType(0); 7853 7854 // fold (frem c1, c2) -> fmod(c1,c2) 7855 if (N0CFP && N1CFP) 7856 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 7857 7858 return SDValue(); 7859 } 7860 7861 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 7862 if (DAG.getTarget().Options.UnsafeFPMath && 7863 !TLI.isFsqrtCheap()) { 7864 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 7865 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) { 7866 EVT VT = RV.getValueType(); 7867 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV); 7868 AddToWorklist(RV.getNode()); 7869 7870 // Unfortunately, RV is now NaN if the input was exactly 0. 7871 // Select out this case and force the answer to 0. 7872 SDValue Zero = DAG.getConstantFP(0.0, VT); 7873 SDValue ZeroCmp = 7874 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT), 7875 N->getOperand(0), Zero, ISD::SETEQ); 7876 AddToWorklist(ZeroCmp.getNode()); 7877 AddToWorklist(RV.getNode()); 7878 7879 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, 7880 SDLoc(N), VT, ZeroCmp, Zero, RV); 7881 return RV; 7882 } 7883 } 7884 return SDValue(); 7885 } 7886 7887 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 7888 SDValue N0 = N->getOperand(0); 7889 SDValue N1 = N->getOperand(1); 7890 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7891 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7892 EVT VT = N->getValueType(0); 7893 7894 if (N0CFP && N1CFP) // Constant fold 7895 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 7896 7897 if (N1CFP) { 7898 const APFloat& V = N1CFP->getValueAPF(); 7899 // copysign(x, c1) -> fabs(x) iff ispos(c1) 7900 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 7901 if (!V.isNegative()) { 7902 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 7903 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7904 } else { 7905 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7906 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7907 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 7908 } 7909 } 7910 7911 // copysign(fabs(x), y) -> copysign(x, y) 7912 // copysign(fneg(x), y) -> copysign(x, y) 7913 // copysign(copysign(x,z), y) -> copysign(x, y) 7914 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 7915 N0.getOpcode() == ISD::FCOPYSIGN) 7916 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7917 N0.getOperand(0), N1); 7918 7919 // copysign(x, abs(y)) -> abs(x) 7920 if (N1.getOpcode() == ISD::FABS) 7921 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7922 7923 // copysign(x, copysign(y,z)) -> copysign(x, z) 7924 if (N1.getOpcode() == ISD::FCOPYSIGN) 7925 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7926 N0, N1.getOperand(1)); 7927 7928 // copysign(x, fp_extend(y)) -> copysign(x, y) 7929 // copysign(x, fp_round(y)) -> copysign(x, y) 7930 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 7931 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7932 N0, N1.getOperand(0)); 7933 7934 return SDValue(); 7935 } 7936 7937 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 7938 SDValue N0 = N->getOperand(0); 7939 EVT VT = N->getValueType(0); 7940 EVT OpVT = N0.getValueType(); 7941 7942 // fold (sint_to_fp c1) -> c1fp 7943 if (isConstantIntBuildVectorOrConstantInt(N0) && 7944 // ...but only if the target supports immediate floating-point values 7945 (!LegalOperations || 7946 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 7947 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 7948 7949 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 7950 // but UINT_TO_FP is legal on this target, try to convert. 7951 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 7952 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 7953 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 7954 if (DAG.SignBitIsZero(N0)) 7955 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 7956 } 7957 7958 // The next optimizations are desirable only if SELECT_CC can be lowered. 7959 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 7960 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 7961 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 7962 !VT.isVector() && 7963 (!LegalOperations || 7964 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7965 SDValue Ops[] = 7966 { N0.getOperand(0), N0.getOperand(1), 7967 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 7968 N0.getOperand(2) }; 7969 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7970 } 7971 7972 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 7973 // (select_cc x, y, 1.0, 0.0,, cc) 7974 if (N0.getOpcode() == ISD::ZERO_EXTEND && 7975 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 7976 (!LegalOperations || 7977 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7978 SDValue Ops[] = 7979 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 7980 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 7981 N0.getOperand(0).getOperand(2) }; 7982 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7983 } 7984 } 7985 7986 return SDValue(); 7987 } 7988 7989 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 7990 SDValue N0 = N->getOperand(0); 7991 EVT VT = N->getValueType(0); 7992 EVT OpVT = N0.getValueType(); 7993 7994 // fold (uint_to_fp c1) -> c1fp 7995 if (isConstantIntBuildVectorOrConstantInt(N0) && 7996 // ...but only if the target supports immediate floating-point values 7997 (!LegalOperations || 7998 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 7999 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8000 8001 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8002 // but SINT_TO_FP is legal on this target, try to convert. 8003 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8004 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8005 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8006 if (DAG.SignBitIsZero(N0)) 8007 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8008 } 8009 8010 // The next optimizations are desirable only if SELECT_CC can be lowered. 8011 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8012 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8013 8014 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8015 (!LegalOperations || 8016 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8017 SDValue Ops[] = 8018 { N0.getOperand(0), N0.getOperand(1), 8019 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 8020 N0.getOperand(2) }; 8021 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 8022 } 8023 } 8024 8025 return SDValue(); 8026 } 8027 8028 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8029 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8030 SDValue N0 = N->getOperand(0); 8031 EVT VT = N->getValueType(0); 8032 8033 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8034 return SDValue(); 8035 8036 SDValue Src = N0.getOperand(0); 8037 EVT SrcVT = Src.getValueType(); 8038 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8039 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8040 8041 // We can safely assume the conversion won't overflow the output range, 8042 // because (for example) (uint8_t)18293.f is undefined behavior. 8043 8044 // Since we can assume the conversion won't overflow, our decision as to 8045 // whether the input will fit in the float should depend on the minimum 8046 // of the input range and output range. 8047 8048 // This means this is also safe for a signed input and unsigned output, since 8049 // a negative input would lead to undefined behavior. 8050 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8051 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8052 unsigned ActualSize = std::min(InputSize, OutputSize); 8053 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8054 8055 // We can only fold away the float conversion if the input range can be 8056 // represented exactly in the float range. 8057 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8058 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8059 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8060 : ISD::ZERO_EXTEND; 8061 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8062 } 8063 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8064 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8065 if (SrcVT == VT) 8066 return Src; 8067 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 8068 } 8069 return SDValue(); 8070 } 8071 8072 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8073 SDValue N0 = N->getOperand(0); 8074 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8075 EVT VT = N->getValueType(0); 8076 8077 // fold (fp_to_sint c1fp) -> c1 8078 if (N0CFP) 8079 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8080 8081 return FoldIntToFPToInt(N, DAG); 8082 } 8083 8084 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 8085 SDValue N0 = N->getOperand(0); 8086 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8087 EVT VT = N->getValueType(0); 8088 8089 // fold (fp_to_uint c1fp) -> c1 8090 if (N0CFP) 8091 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 8092 8093 return FoldIntToFPToInt(N, DAG); 8094 } 8095 8096 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 8097 SDValue N0 = N->getOperand(0); 8098 SDValue N1 = N->getOperand(1); 8099 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8100 EVT VT = N->getValueType(0); 8101 8102 // fold (fp_round c1fp) -> c1fp 8103 if (N0CFP) 8104 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 8105 8106 // fold (fp_round (fp_extend x)) -> x 8107 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 8108 return N0.getOperand(0); 8109 8110 // fold (fp_round (fp_round x)) -> (fp_round x) 8111 if (N0.getOpcode() == ISD::FP_ROUND) { 8112 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 8113 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 8114 // If the first fp_round isn't a value preserving truncation, it might 8115 // introduce a tie in the second fp_round, that wouldn't occur in the 8116 // single-step fp_round we want to fold to. 8117 // In other words, double rounding isn't the same as rounding. 8118 // Also, this is a value preserving truncation iff both fp_round's are. 8119 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) 8120 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 8121 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc)); 8122 } 8123 8124 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 8125 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 8126 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 8127 N0.getOperand(0), N1); 8128 AddToWorklist(Tmp.getNode()); 8129 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8130 Tmp, N0.getOperand(1)); 8131 } 8132 8133 return SDValue(); 8134 } 8135 8136 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 8137 SDValue N0 = N->getOperand(0); 8138 EVT VT = N->getValueType(0); 8139 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8140 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8141 8142 // fold (fp_round_inreg c1fp) -> c1fp 8143 if (N0CFP && isTypeLegal(EVT)) { 8144 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 8145 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 8146 } 8147 8148 return SDValue(); 8149 } 8150 8151 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 8152 SDValue N0 = N->getOperand(0); 8153 EVT VT = N->getValueType(0); 8154 8155 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 8156 if (N->hasOneUse() && 8157 N->use_begin()->getOpcode() == ISD::FP_ROUND) 8158 return SDValue(); 8159 8160 // fold (fp_extend c1fp) -> c1fp 8161 if (isConstantFPBuildVectorOrConstantFP(N0)) 8162 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 8163 8164 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 8165 // value of X. 8166 if (N0.getOpcode() == ISD::FP_ROUND 8167 && N0.getNode()->getConstantOperandVal(1) == 1) { 8168 SDValue In = N0.getOperand(0); 8169 if (In.getValueType() == VT) return In; 8170 if (VT.bitsLT(In.getValueType())) 8171 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 8172 In, N0.getOperand(1)); 8173 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 8174 } 8175 8176 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 8177 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8178 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8179 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8180 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8181 LN0->getChain(), 8182 LN0->getBasePtr(), N0.getValueType(), 8183 LN0->getMemOperand()); 8184 CombineTo(N, ExtLoad); 8185 CombineTo(N0.getNode(), 8186 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 8187 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 8188 ExtLoad.getValue(1)); 8189 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8190 } 8191 8192 return SDValue(); 8193 } 8194 8195 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 8196 SDValue N0 = N->getOperand(0); 8197 EVT VT = N->getValueType(0); 8198 8199 // fold (fceil c1) -> fceil(c1) 8200 if (isConstantFPBuildVectorOrConstantFP(N0)) 8201 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 8202 8203 return SDValue(); 8204 } 8205 8206 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 8207 SDValue N0 = N->getOperand(0); 8208 EVT VT = N->getValueType(0); 8209 8210 // fold (ftrunc c1) -> ftrunc(c1) 8211 if (isConstantFPBuildVectorOrConstantFP(N0)) 8212 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 8213 8214 return SDValue(); 8215 } 8216 8217 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 8218 SDValue N0 = N->getOperand(0); 8219 EVT VT = N->getValueType(0); 8220 8221 // fold (ffloor c1) -> ffloor(c1) 8222 if (isConstantFPBuildVectorOrConstantFP(N0)) 8223 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 8224 8225 return SDValue(); 8226 } 8227 8228 // FIXME: FNEG and FABS have a lot in common; refactor. 8229 SDValue DAGCombiner::visitFNEG(SDNode *N) { 8230 SDValue N0 = N->getOperand(0); 8231 EVT VT = N->getValueType(0); 8232 8233 // Constant fold FNEG. 8234 if (isConstantFPBuildVectorOrConstantFP(N0)) 8235 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 8236 8237 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 8238 &DAG.getTarget().Options)) 8239 return GetNegatedExpression(N0, DAG, LegalOperations); 8240 8241 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 8242 // constant pool values. 8243 if (!TLI.isFNegFree(VT) && 8244 N0.getOpcode() == ISD::BITCAST && 8245 N0.getNode()->hasOneUse()) { 8246 SDValue Int = N0.getOperand(0); 8247 EVT IntVT = Int.getValueType(); 8248 if (IntVT.isInteger() && !IntVT.isVector()) { 8249 APInt SignMask; 8250 if (N0.getValueType().isVector()) { 8251 // For a vector, get a mask such as 0x80... per scalar element 8252 // and splat it. 8253 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8254 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8255 } else { 8256 // For a scalar, just generate 0x80... 8257 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 8258 } 8259 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 8260 DAG.getConstant(SignMask, IntVT)); 8261 AddToWorklist(Int.getNode()); 8262 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 8263 } 8264 } 8265 8266 // (fneg (fmul c, x)) -> (fmul -c, x) 8267 if (N0.getOpcode() == ISD::FMUL) { 8268 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8269 if (CFP1) { 8270 APFloat CVal = CFP1->getValueAPF(); 8271 CVal.changeSign(); 8272 if (Level >= AfterLegalizeDAG && 8273 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 8274 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 8275 return DAG.getNode( 8276 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 8277 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1))); 8278 } 8279 } 8280 8281 return SDValue(); 8282 } 8283 8284 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 8285 SDValue N0 = N->getOperand(0); 8286 SDValue N1 = N->getOperand(1); 8287 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8288 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8289 8290 if (N0CFP && N1CFP) { 8291 const APFloat &C0 = N0CFP->getValueAPF(); 8292 const APFloat &C1 = N1CFP->getValueAPF(); 8293 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0)); 8294 } 8295 8296 if (N0CFP) { 8297 EVT VT = N->getValueType(0); 8298 // Canonicalize to constant on RHS. 8299 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 8300 } 8301 8302 return SDValue(); 8303 } 8304 8305 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 8306 SDValue N0 = N->getOperand(0); 8307 SDValue N1 = N->getOperand(1); 8308 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8309 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8310 8311 if (N0CFP && N1CFP) { 8312 const APFloat &C0 = N0CFP->getValueAPF(); 8313 const APFloat &C1 = N1CFP->getValueAPF(); 8314 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0)); 8315 } 8316 8317 if (N0CFP) { 8318 EVT VT = N->getValueType(0); 8319 // Canonicalize to constant on RHS. 8320 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 8321 } 8322 8323 return SDValue(); 8324 } 8325 8326 SDValue DAGCombiner::visitFABS(SDNode *N) { 8327 SDValue N0 = N->getOperand(0); 8328 EVT VT = N->getValueType(0); 8329 8330 // fold (fabs c1) -> fabs(c1) 8331 if (isConstantFPBuildVectorOrConstantFP(N0)) 8332 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8333 8334 // fold (fabs (fabs x)) -> (fabs x) 8335 if (N0.getOpcode() == ISD::FABS) 8336 return N->getOperand(0); 8337 8338 // fold (fabs (fneg x)) -> (fabs x) 8339 // fold (fabs (fcopysign x, y)) -> (fabs x) 8340 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 8341 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 8342 8343 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 8344 // constant pool values. 8345 if (!TLI.isFAbsFree(VT) && 8346 N0.getOpcode() == ISD::BITCAST && 8347 N0.getNode()->hasOneUse()) { 8348 SDValue Int = N0.getOperand(0); 8349 EVT IntVT = Int.getValueType(); 8350 if (IntVT.isInteger() && !IntVT.isVector()) { 8351 APInt SignMask; 8352 if (N0.getValueType().isVector()) { 8353 // For a vector, get a mask such as 0x7f... per scalar element 8354 // and splat it. 8355 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8356 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8357 } else { 8358 // For a scalar, just generate 0x7f... 8359 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 8360 } 8361 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 8362 DAG.getConstant(SignMask, IntVT)); 8363 AddToWorklist(Int.getNode()); 8364 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 8365 } 8366 } 8367 8368 return SDValue(); 8369 } 8370 8371 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 8372 SDValue Chain = N->getOperand(0); 8373 SDValue N1 = N->getOperand(1); 8374 SDValue N2 = N->getOperand(2); 8375 8376 // If N is a constant we could fold this into a fallthrough or unconditional 8377 // branch. However that doesn't happen very often in normal code, because 8378 // Instcombine/SimplifyCFG should have handled the available opportunities. 8379 // If we did this folding here, it would be necessary to update the 8380 // MachineBasicBlock CFG, which is awkward. 8381 8382 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 8383 // on the target. 8384 if (N1.getOpcode() == ISD::SETCC && 8385 TLI.isOperationLegalOrCustom(ISD::BR_CC, 8386 N1.getOperand(0).getValueType())) { 8387 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8388 Chain, N1.getOperand(2), 8389 N1.getOperand(0), N1.getOperand(1), N2); 8390 } 8391 8392 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 8393 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 8394 (N1.getOperand(0).hasOneUse() && 8395 N1.getOperand(0).getOpcode() == ISD::SRL))) { 8396 SDNode *Trunc = nullptr; 8397 if (N1.getOpcode() == ISD::TRUNCATE) { 8398 // Look pass the truncate. 8399 Trunc = N1.getNode(); 8400 N1 = N1.getOperand(0); 8401 } 8402 8403 // Match this pattern so that we can generate simpler code: 8404 // 8405 // %a = ... 8406 // %b = and i32 %a, 2 8407 // %c = srl i32 %b, 1 8408 // brcond i32 %c ... 8409 // 8410 // into 8411 // 8412 // %a = ... 8413 // %b = and i32 %a, 2 8414 // %c = setcc eq %b, 0 8415 // brcond %c ... 8416 // 8417 // This applies only when the AND constant value has one bit set and the 8418 // SRL constant is equal to the log2 of the AND constant. The back-end is 8419 // smart enough to convert the result into a TEST/JMP sequence. 8420 SDValue Op0 = N1.getOperand(0); 8421 SDValue Op1 = N1.getOperand(1); 8422 8423 if (Op0.getOpcode() == ISD::AND && 8424 Op1.getOpcode() == ISD::Constant) { 8425 SDValue AndOp1 = Op0.getOperand(1); 8426 8427 if (AndOp1.getOpcode() == ISD::Constant) { 8428 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 8429 8430 if (AndConst.isPowerOf2() && 8431 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 8432 SDValue SetCC = 8433 DAG.getSetCC(SDLoc(N), 8434 getSetCCResultType(Op0.getValueType()), 8435 Op0, DAG.getConstant(0, Op0.getValueType()), 8436 ISD::SETNE); 8437 8438 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 8439 MVT::Other, Chain, SetCC, N2); 8440 // Don't add the new BRCond into the worklist or else SimplifySelectCC 8441 // will convert it back to (X & C1) >> C2. 8442 CombineTo(N, NewBRCond, false); 8443 // Truncate is dead. 8444 if (Trunc) 8445 deleteAndRecombine(Trunc); 8446 // Replace the uses of SRL with SETCC 8447 WorklistRemover DeadNodes(*this); 8448 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8449 deleteAndRecombine(N1.getNode()); 8450 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8451 } 8452 } 8453 } 8454 8455 if (Trunc) 8456 // Restore N1 if the above transformation doesn't match. 8457 N1 = N->getOperand(1); 8458 } 8459 8460 // Transform br(xor(x, y)) -> br(x != y) 8461 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 8462 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 8463 SDNode *TheXor = N1.getNode(); 8464 SDValue Op0 = TheXor->getOperand(0); 8465 SDValue Op1 = TheXor->getOperand(1); 8466 if (Op0.getOpcode() == Op1.getOpcode()) { 8467 // Avoid missing important xor optimizations. 8468 SDValue Tmp = visitXOR(TheXor); 8469 if (Tmp.getNode()) { 8470 if (Tmp.getNode() != TheXor) { 8471 DEBUG(dbgs() << "\nReplacing.8 "; 8472 TheXor->dump(&DAG); 8473 dbgs() << "\nWith: "; 8474 Tmp.getNode()->dump(&DAG); 8475 dbgs() << '\n'); 8476 WorklistRemover DeadNodes(*this); 8477 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 8478 deleteAndRecombine(TheXor); 8479 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8480 MVT::Other, Chain, Tmp, N2); 8481 } 8482 8483 // visitXOR has changed XOR's operands or replaced the XOR completely, 8484 // bail out. 8485 return SDValue(N, 0); 8486 } 8487 } 8488 8489 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 8490 bool Equal = false; 8491 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 8492 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 8493 Op0.getOpcode() == ISD::XOR) { 8494 TheXor = Op0.getNode(); 8495 Equal = true; 8496 } 8497 8498 EVT SetCCVT = N1.getValueType(); 8499 if (LegalTypes) 8500 SetCCVT = getSetCCResultType(SetCCVT); 8501 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 8502 SetCCVT, 8503 Op0, Op1, 8504 Equal ? ISD::SETEQ : ISD::SETNE); 8505 // Replace the uses of XOR with SETCC 8506 WorklistRemover DeadNodes(*this); 8507 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8508 deleteAndRecombine(N1.getNode()); 8509 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8510 MVT::Other, Chain, SetCC, N2); 8511 } 8512 } 8513 8514 return SDValue(); 8515 } 8516 8517 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 8518 // 8519 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 8520 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 8521 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 8522 8523 // If N is a constant we could fold this into a fallthrough or unconditional 8524 // branch. However that doesn't happen very often in normal code, because 8525 // Instcombine/SimplifyCFG should have handled the available opportunities. 8526 // If we did this folding here, it would be necessary to update the 8527 // MachineBasicBlock CFG, which is awkward. 8528 8529 // Use SimplifySetCC to simplify SETCC's. 8530 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 8531 CondLHS, CondRHS, CC->get(), SDLoc(N), 8532 false); 8533 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 8534 8535 // fold to a simpler setcc 8536 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 8537 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8538 N->getOperand(0), Simp.getOperand(2), 8539 Simp.getOperand(0), Simp.getOperand(1), 8540 N->getOperand(4)); 8541 8542 return SDValue(); 8543 } 8544 8545 /// Return true if 'Use' is a load or a store that uses N as its base pointer 8546 /// and that N may be folded in the load / store addressing mode. 8547 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 8548 SelectionDAG &DAG, 8549 const TargetLowering &TLI) { 8550 EVT VT; 8551 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 8552 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 8553 return false; 8554 VT = Use->getValueType(0); 8555 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 8556 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 8557 return false; 8558 VT = ST->getValue().getValueType(); 8559 } else 8560 return false; 8561 8562 TargetLowering::AddrMode AM; 8563 if (N->getOpcode() == ISD::ADD) { 8564 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8565 if (Offset) 8566 // [reg +/- imm] 8567 AM.BaseOffs = Offset->getSExtValue(); 8568 else 8569 // [reg +/- reg] 8570 AM.Scale = 1; 8571 } else if (N->getOpcode() == ISD::SUB) { 8572 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8573 if (Offset) 8574 // [reg +/- imm] 8575 AM.BaseOffs = -Offset->getSExtValue(); 8576 else 8577 // [reg +/- reg] 8578 AM.Scale = 1; 8579 } else 8580 return false; 8581 8582 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 8583 } 8584 8585 /// Try turning a load/store into a pre-indexed load/store when the base 8586 /// pointer is an add or subtract and it has other uses besides the load/store. 8587 /// After the transformation, the new indexed load/store has effectively folded 8588 /// the add/subtract in and all of its other uses are redirected to the 8589 /// new load/store. 8590 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 8591 if (Level < AfterLegalizeDAG) 8592 return false; 8593 8594 bool isLoad = true; 8595 SDValue Ptr; 8596 EVT VT; 8597 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8598 if (LD->isIndexed()) 8599 return false; 8600 VT = LD->getMemoryVT(); 8601 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 8602 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 8603 return false; 8604 Ptr = LD->getBasePtr(); 8605 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 8606 if (ST->isIndexed()) 8607 return false; 8608 VT = ST->getMemoryVT(); 8609 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 8610 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 8611 return false; 8612 Ptr = ST->getBasePtr(); 8613 isLoad = false; 8614 } else { 8615 return false; 8616 } 8617 8618 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 8619 // out. There is no reason to make this a preinc/predec. 8620 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 8621 Ptr.getNode()->hasOneUse()) 8622 return false; 8623 8624 // Ask the target to do addressing mode selection. 8625 SDValue BasePtr; 8626 SDValue Offset; 8627 ISD::MemIndexedMode AM = ISD::UNINDEXED; 8628 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 8629 return false; 8630 8631 // Backends without true r+i pre-indexed forms may need to pass a 8632 // constant base with a variable offset so that constant coercion 8633 // will work with the patterns in canonical form. 8634 bool Swapped = false; 8635 if (isa<ConstantSDNode>(BasePtr)) { 8636 std::swap(BasePtr, Offset); 8637 Swapped = true; 8638 } 8639 8640 // Don't create a indexed load / store with zero offset. 8641 if (isa<ConstantSDNode>(Offset) && 8642 cast<ConstantSDNode>(Offset)->isNullValue()) 8643 return false; 8644 8645 // Try turning it into a pre-indexed load / store except when: 8646 // 1) The new base ptr is a frame index. 8647 // 2) If N is a store and the new base ptr is either the same as or is a 8648 // predecessor of the value being stored. 8649 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 8650 // that would create a cycle. 8651 // 4) All uses are load / store ops that use it as old base ptr. 8652 8653 // Check #1. Preinc'ing a frame index would require copying the stack pointer 8654 // (plus the implicit offset) to a register to preinc anyway. 8655 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 8656 return false; 8657 8658 // Check #2. 8659 if (!isLoad) { 8660 SDValue Val = cast<StoreSDNode>(N)->getValue(); 8661 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 8662 return false; 8663 } 8664 8665 // If the offset is a constant, there may be other adds of constants that 8666 // can be folded with this one. We should do this to avoid having to keep 8667 // a copy of the original base pointer. 8668 SmallVector<SDNode *, 16> OtherUses; 8669 if (isa<ConstantSDNode>(Offset)) 8670 for (SDNode *Use : BasePtr.getNode()->uses()) { 8671 if (Use == Ptr.getNode()) 8672 continue; 8673 8674 if (Use->isPredecessorOf(N)) 8675 continue; 8676 8677 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 8678 OtherUses.clear(); 8679 break; 8680 } 8681 8682 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 8683 if (Op1.getNode() == BasePtr.getNode()) 8684 std::swap(Op0, Op1); 8685 assert(Op0.getNode() == BasePtr.getNode() && 8686 "Use of ADD/SUB but not an operand"); 8687 8688 if (!isa<ConstantSDNode>(Op1)) { 8689 OtherUses.clear(); 8690 break; 8691 } 8692 8693 // FIXME: In some cases, we can be smarter about this. 8694 if (Op1.getValueType() != Offset.getValueType()) { 8695 OtherUses.clear(); 8696 break; 8697 } 8698 8699 OtherUses.push_back(Use); 8700 } 8701 8702 if (Swapped) 8703 std::swap(BasePtr, Offset); 8704 8705 // Now check for #3 and #4. 8706 bool RealUse = false; 8707 8708 // Caches for hasPredecessorHelper 8709 SmallPtrSet<const SDNode *, 32> Visited; 8710 SmallVector<const SDNode *, 16> Worklist; 8711 8712 for (SDNode *Use : Ptr.getNode()->uses()) { 8713 if (Use == N) 8714 continue; 8715 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 8716 return false; 8717 8718 // If Ptr may be folded in addressing mode of other use, then it's 8719 // not profitable to do this transformation. 8720 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 8721 RealUse = true; 8722 } 8723 8724 if (!RealUse) 8725 return false; 8726 8727 SDValue Result; 8728 if (isLoad) 8729 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 8730 BasePtr, Offset, AM); 8731 else 8732 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 8733 BasePtr, Offset, AM); 8734 ++PreIndexedNodes; 8735 ++NodesCombined; 8736 DEBUG(dbgs() << "\nReplacing.4 "; 8737 N->dump(&DAG); 8738 dbgs() << "\nWith: "; 8739 Result.getNode()->dump(&DAG); 8740 dbgs() << '\n'); 8741 WorklistRemover DeadNodes(*this); 8742 if (isLoad) { 8743 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 8744 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 8745 } else { 8746 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 8747 } 8748 8749 // Finally, since the node is now dead, remove it from the graph. 8750 deleteAndRecombine(N); 8751 8752 if (Swapped) 8753 std::swap(BasePtr, Offset); 8754 8755 // Replace other uses of BasePtr that can be updated to use Ptr 8756 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 8757 unsigned OffsetIdx = 1; 8758 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 8759 OffsetIdx = 0; 8760 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 8761 BasePtr.getNode() && "Expected BasePtr operand"); 8762 8763 // We need to replace ptr0 in the following expression: 8764 // x0 * offset0 + y0 * ptr0 = t0 8765 // knowing that 8766 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 8767 // 8768 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 8769 // indexed load/store and the expresion that needs to be re-written. 8770 // 8771 // Therefore, we have: 8772 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 8773 8774 ConstantSDNode *CN = 8775 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 8776 int X0, X1, Y0, Y1; 8777 APInt Offset0 = CN->getAPIntValue(); 8778 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 8779 8780 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 8781 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 8782 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 8783 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 8784 8785 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 8786 8787 APInt CNV = Offset0; 8788 if (X0 < 0) CNV = -CNV; 8789 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 8790 else CNV = CNV - Offset1; 8791 8792 // We can now generate the new expression. 8793 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 8794 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 8795 8796 SDValue NewUse = DAG.getNode(Opcode, 8797 SDLoc(OtherUses[i]), 8798 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 8799 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 8800 deleteAndRecombine(OtherUses[i]); 8801 } 8802 8803 // Replace the uses of Ptr with uses of the updated base value. 8804 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 8805 deleteAndRecombine(Ptr.getNode()); 8806 8807 return true; 8808 } 8809 8810 /// Try to combine a load/store with a add/sub of the base pointer node into a 8811 /// post-indexed load/store. The transformation folded the add/subtract into the 8812 /// new indexed load/store effectively and all of its uses are redirected to the 8813 /// new load/store. 8814 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 8815 if (Level < AfterLegalizeDAG) 8816 return false; 8817 8818 bool isLoad = true; 8819 SDValue Ptr; 8820 EVT VT; 8821 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8822 if (LD->isIndexed()) 8823 return false; 8824 VT = LD->getMemoryVT(); 8825 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 8826 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 8827 return false; 8828 Ptr = LD->getBasePtr(); 8829 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 8830 if (ST->isIndexed()) 8831 return false; 8832 VT = ST->getMemoryVT(); 8833 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 8834 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 8835 return false; 8836 Ptr = ST->getBasePtr(); 8837 isLoad = false; 8838 } else { 8839 return false; 8840 } 8841 8842 if (Ptr.getNode()->hasOneUse()) 8843 return false; 8844 8845 for (SDNode *Op : Ptr.getNode()->uses()) { 8846 if (Op == N || 8847 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 8848 continue; 8849 8850 SDValue BasePtr; 8851 SDValue Offset; 8852 ISD::MemIndexedMode AM = ISD::UNINDEXED; 8853 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 8854 // Don't create a indexed load / store with zero offset. 8855 if (isa<ConstantSDNode>(Offset) && 8856 cast<ConstantSDNode>(Offset)->isNullValue()) 8857 continue; 8858 8859 // Try turning it into a post-indexed load / store except when 8860 // 1) All uses are load / store ops that use it as base ptr (and 8861 // it may be folded as addressing mmode). 8862 // 2) Op must be independent of N, i.e. Op is neither a predecessor 8863 // nor a successor of N. Otherwise, if Op is folded that would 8864 // create a cycle. 8865 8866 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 8867 continue; 8868 8869 // Check for #1. 8870 bool TryNext = false; 8871 for (SDNode *Use : BasePtr.getNode()->uses()) { 8872 if (Use == Ptr.getNode()) 8873 continue; 8874 8875 // If all the uses are load / store addresses, then don't do the 8876 // transformation. 8877 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 8878 bool RealUse = false; 8879 for (SDNode *UseUse : Use->uses()) { 8880 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 8881 RealUse = true; 8882 } 8883 8884 if (!RealUse) { 8885 TryNext = true; 8886 break; 8887 } 8888 } 8889 } 8890 8891 if (TryNext) 8892 continue; 8893 8894 // Check for #2 8895 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 8896 SDValue Result = isLoad 8897 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 8898 BasePtr, Offset, AM) 8899 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 8900 BasePtr, Offset, AM); 8901 ++PostIndexedNodes; 8902 ++NodesCombined; 8903 DEBUG(dbgs() << "\nReplacing.5 "; 8904 N->dump(&DAG); 8905 dbgs() << "\nWith: "; 8906 Result.getNode()->dump(&DAG); 8907 dbgs() << '\n'); 8908 WorklistRemover DeadNodes(*this); 8909 if (isLoad) { 8910 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 8911 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 8912 } else { 8913 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 8914 } 8915 8916 // Finally, since the node is now dead, remove it from the graph. 8917 deleteAndRecombine(N); 8918 8919 // Replace the uses of Use with uses of the updated base value. 8920 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 8921 Result.getValue(isLoad ? 1 : 0)); 8922 deleteAndRecombine(Op); 8923 return true; 8924 } 8925 } 8926 } 8927 8928 return false; 8929 } 8930 8931 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 8932 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 8933 ISD::MemIndexedMode AM = LD->getAddressingMode(); 8934 assert(AM != ISD::UNINDEXED); 8935 SDValue BP = LD->getOperand(1); 8936 SDValue Inc = LD->getOperand(2); 8937 8938 // Some backends use TargetConstants for load offsets, but don't expect 8939 // TargetConstants in general ADD nodes. We can convert these constants into 8940 // regular Constants (if the constant is not opaque). 8941 assert((Inc.getOpcode() != ISD::TargetConstant || 8942 !cast<ConstantSDNode>(Inc)->isOpaque()) && 8943 "Cannot split out indexing using opaque target constants"); 8944 if (Inc.getOpcode() == ISD::TargetConstant) { 8945 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 8946 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), 8947 ConstInc->getValueType(0)); 8948 } 8949 8950 unsigned Opc = 8951 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 8952 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 8953 } 8954 8955 SDValue DAGCombiner::visitLOAD(SDNode *N) { 8956 LoadSDNode *LD = cast<LoadSDNode>(N); 8957 SDValue Chain = LD->getChain(); 8958 SDValue Ptr = LD->getBasePtr(); 8959 8960 // If load is not volatile and there are no uses of the loaded value (and 8961 // the updated indexed value in case of indexed loads), change uses of the 8962 // chain value into uses of the chain input (i.e. delete the dead load). 8963 if (!LD->isVolatile()) { 8964 if (N->getValueType(1) == MVT::Other) { 8965 // Unindexed loads. 8966 if (!N->hasAnyUseOfValue(0)) { 8967 // It's not safe to use the two value CombineTo variant here. e.g. 8968 // v1, chain2 = load chain1, loc 8969 // v2, chain3 = load chain2, loc 8970 // v3 = add v2, c 8971 // Now we replace use of chain2 with chain1. This makes the second load 8972 // isomorphic to the one we are deleting, and thus makes this load live. 8973 DEBUG(dbgs() << "\nReplacing.6 "; 8974 N->dump(&DAG); 8975 dbgs() << "\nWith chain: "; 8976 Chain.getNode()->dump(&DAG); 8977 dbgs() << "\n"); 8978 WorklistRemover DeadNodes(*this); 8979 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 8980 8981 if (N->use_empty()) 8982 deleteAndRecombine(N); 8983 8984 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8985 } 8986 } else { 8987 // Indexed loads. 8988 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 8989 8990 // If this load has an opaque TargetConstant offset, then we cannot split 8991 // the indexing into an add/sub directly (that TargetConstant may not be 8992 // valid for a different type of node, and we cannot convert an opaque 8993 // target constant into a regular constant). 8994 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 8995 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 8996 8997 if (!N->hasAnyUseOfValue(0) && 8998 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 8999 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9000 SDValue Index; 9001 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9002 Index = SplitIndexingFromLoad(LD); 9003 // Try to fold the base pointer arithmetic into subsequent loads and 9004 // stores. 9005 AddUsersToWorklist(N); 9006 } else 9007 Index = DAG.getUNDEF(N->getValueType(1)); 9008 DEBUG(dbgs() << "\nReplacing.7 "; 9009 N->dump(&DAG); 9010 dbgs() << "\nWith: "; 9011 Undef.getNode()->dump(&DAG); 9012 dbgs() << " and 2 other values\n"); 9013 WorklistRemover DeadNodes(*this); 9014 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9015 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9016 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9017 deleteAndRecombine(N); 9018 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9019 } 9020 } 9021 } 9022 9023 // If this load is directly stored, replace the load value with the stored 9024 // value. 9025 // TODO: Handle store large -> read small portion. 9026 // TODO: Handle TRUNCSTORE/LOADEXT 9027 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9028 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9029 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9030 if (PrevST->getBasePtr() == Ptr && 9031 PrevST->getValue().getValueType() == N->getValueType(0)) 9032 return CombineTo(N, Chain.getOperand(1), Chain); 9033 } 9034 } 9035 9036 // Try to infer better alignment information than the load already has. 9037 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9038 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9039 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9040 SDValue NewLoad = 9041 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9042 LD->getValueType(0), 9043 Chain, Ptr, LD->getPointerInfo(), 9044 LD->getMemoryVT(), 9045 LD->isVolatile(), LD->isNonTemporal(), 9046 LD->isInvariant(), Align, LD->getAAInfo()); 9047 if (NewLoad.getNode() != N) 9048 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9049 } 9050 } 9051 } 9052 9053 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 9054 : DAG.getSubtarget().useAA(); 9055 #ifndef NDEBUG 9056 if (CombinerAAOnlyFunc.getNumOccurrences() && 9057 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9058 UseAA = false; 9059 #endif 9060 if (UseAA && LD->isUnindexed()) { 9061 // Walk up chain skipping non-aliasing memory nodes. 9062 SDValue BetterChain = FindBetterChain(N, Chain); 9063 9064 // If there is a better chain. 9065 if (Chain != BetterChain) { 9066 SDValue ReplLoad; 9067 9068 // Replace the chain to void dependency. 9069 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 9070 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 9071 BetterChain, Ptr, LD->getMemOperand()); 9072 } else { 9073 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 9074 LD->getValueType(0), 9075 BetterChain, Ptr, LD->getMemoryVT(), 9076 LD->getMemOperand()); 9077 } 9078 9079 // Create token factor to keep old chain connected. 9080 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9081 MVT::Other, Chain, ReplLoad.getValue(1)); 9082 9083 // Make sure the new and old chains are cleaned up. 9084 AddToWorklist(Token.getNode()); 9085 9086 // Replace uses with load result and token factor. Don't add users 9087 // to work list. 9088 return CombineTo(N, ReplLoad.getValue(0), Token, false); 9089 } 9090 } 9091 9092 // Try transforming N to an indexed load. 9093 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9094 return SDValue(N, 0); 9095 9096 // Try to slice up N to more direct loads if the slices are mapped to 9097 // different register banks or pairing can take place. 9098 if (SliceUpLoad(N)) 9099 return SDValue(N, 0); 9100 9101 return SDValue(); 9102 } 9103 9104 namespace { 9105 /// \brief Helper structure used to slice a load in smaller loads. 9106 /// Basically a slice is obtained from the following sequence: 9107 /// Origin = load Ty1, Base 9108 /// Shift = srl Ty1 Origin, CstTy Amount 9109 /// Inst = trunc Shift to Ty2 9110 /// 9111 /// Then, it will be rewriten into: 9112 /// Slice = load SliceTy, Base + SliceOffset 9113 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 9114 /// 9115 /// SliceTy is deduced from the number of bits that are actually used to 9116 /// build Inst. 9117 struct LoadedSlice { 9118 /// \brief Helper structure used to compute the cost of a slice. 9119 struct Cost { 9120 /// Are we optimizing for code size. 9121 bool ForCodeSize; 9122 /// Various cost. 9123 unsigned Loads; 9124 unsigned Truncates; 9125 unsigned CrossRegisterBanksCopies; 9126 unsigned ZExts; 9127 unsigned Shift; 9128 9129 Cost(bool ForCodeSize = false) 9130 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 9131 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 9132 9133 /// \brief Get the cost of one isolated slice. 9134 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 9135 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 9136 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 9137 EVT TruncType = LS.Inst->getValueType(0); 9138 EVT LoadedType = LS.getLoadedType(); 9139 if (TruncType != LoadedType && 9140 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 9141 ZExts = 1; 9142 } 9143 9144 /// \brief Account for slicing gain in the current cost. 9145 /// Slicing provide a few gains like removing a shift or a 9146 /// truncate. This method allows to grow the cost of the original 9147 /// load with the gain from this slice. 9148 void addSliceGain(const LoadedSlice &LS) { 9149 // Each slice saves a truncate. 9150 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 9151 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 9152 LS.Inst->getOperand(0).getValueType())) 9153 ++Truncates; 9154 // If there is a shift amount, this slice gets rid of it. 9155 if (LS.Shift) 9156 ++Shift; 9157 // If this slice can merge a cross register bank copy, account for it. 9158 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 9159 ++CrossRegisterBanksCopies; 9160 } 9161 9162 Cost &operator+=(const Cost &RHS) { 9163 Loads += RHS.Loads; 9164 Truncates += RHS.Truncates; 9165 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 9166 ZExts += RHS.ZExts; 9167 Shift += RHS.Shift; 9168 return *this; 9169 } 9170 9171 bool operator==(const Cost &RHS) const { 9172 return Loads == RHS.Loads && Truncates == RHS.Truncates && 9173 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 9174 ZExts == RHS.ZExts && Shift == RHS.Shift; 9175 } 9176 9177 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 9178 9179 bool operator<(const Cost &RHS) const { 9180 // Assume cross register banks copies are as expensive as loads. 9181 // FIXME: Do we want some more target hooks? 9182 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 9183 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 9184 // Unless we are optimizing for code size, consider the 9185 // expensive operation first. 9186 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 9187 return ExpensiveOpsLHS < ExpensiveOpsRHS; 9188 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 9189 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 9190 } 9191 9192 bool operator>(const Cost &RHS) const { return RHS < *this; } 9193 9194 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 9195 9196 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 9197 }; 9198 // The last instruction that represent the slice. This should be a 9199 // truncate instruction. 9200 SDNode *Inst; 9201 // The original load instruction. 9202 LoadSDNode *Origin; 9203 // The right shift amount in bits from the original load. 9204 unsigned Shift; 9205 // The DAG from which Origin came from. 9206 // This is used to get some contextual information about legal types, etc. 9207 SelectionDAG *DAG; 9208 9209 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 9210 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 9211 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 9212 9213 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 9214 /// \return Result is \p BitWidth and has used bits set to 1 and 9215 /// not used bits set to 0. 9216 APInt getUsedBits() const { 9217 // Reproduce the trunc(lshr) sequence: 9218 // - Start from the truncated value. 9219 // - Zero extend to the desired bit width. 9220 // - Shift left. 9221 assert(Origin && "No original load to compare against."); 9222 unsigned BitWidth = Origin->getValueSizeInBits(0); 9223 assert(Inst && "This slice is not bound to an instruction"); 9224 assert(Inst->getValueSizeInBits(0) <= BitWidth && 9225 "Extracted slice is bigger than the whole type!"); 9226 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 9227 UsedBits.setAllBits(); 9228 UsedBits = UsedBits.zext(BitWidth); 9229 UsedBits <<= Shift; 9230 return UsedBits; 9231 } 9232 9233 /// \brief Get the size of the slice to be loaded in bytes. 9234 unsigned getLoadedSize() const { 9235 unsigned SliceSize = getUsedBits().countPopulation(); 9236 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 9237 return SliceSize / 8; 9238 } 9239 9240 /// \brief Get the type that will be loaded for this slice. 9241 /// Note: This may not be the final type for the slice. 9242 EVT getLoadedType() const { 9243 assert(DAG && "Missing context"); 9244 LLVMContext &Ctxt = *DAG->getContext(); 9245 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 9246 } 9247 9248 /// \brief Get the alignment of the load used for this slice. 9249 unsigned getAlignment() const { 9250 unsigned Alignment = Origin->getAlignment(); 9251 unsigned Offset = getOffsetFromBase(); 9252 if (Offset != 0) 9253 Alignment = MinAlign(Alignment, Alignment + Offset); 9254 return Alignment; 9255 } 9256 9257 /// \brief Check if this slice can be rewritten with legal operations. 9258 bool isLegal() const { 9259 // An invalid slice is not legal. 9260 if (!Origin || !Inst || !DAG) 9261 return false; 9262 9263 // Offsets are for indexed load only, we do not handle that. 9264 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 9265 return false; 9266 9267 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9268 9269 // Check that the type is legal. 9270 EVT SliceType = getLoadedType(); 9271 if (!TLI.isTypeLegal(SliceType)) 9272 return false; 9273 9274 // Check that the load is legal for this type. 9275 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 9276 return false; 9277 9278 // Check that the offset can be computed. 9279 // 1. Check its type. 9280 EVT PtrType = Origin->getBasePtr().getValueType(); 9281 if (PtrType == MVT::Untyped || PtrType.isExtended()) 9282 return false; 9283 9284 // 2. Check that it fits in the immediate. 9285 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 9286 return false; 9287 9288 // 3. Check that the computation is legal. 9289 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 9290 return false; 9291 9292 // Check that the zext is legal if it needs one. 9293 EVT TruncateType = Inst->getValueType(0); 9294 if (TruncateType != SliceType && 9295 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 9296 return false; 9297 9298 return true; 9299 } 9300 9301 /// \brief Get the offset in bytes of this slice in the original chunk of 9302 /// bits. 9303 /// \pre DAG != nullptr. 9304 uint64_t getOffsetFromBase() const { 9305 assert(DAG && "Missing context."); 9306 bool IsBigEndian = 9307 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 9308 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 9309 uint64_t Offset = Shift / 8; 9310 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 9311 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 9312 "The size of the original loaded type is not a multiple of a" 9313 " byte."); 9314 // If Offset is bigger than TySizeInBytes, it means we are loading all 9315 // zeros. This should have been optimized before in the process. 9316 assert(TySizeInBytes > Offset && 9317 "Invalid shift amount for given loaded size"); 9318 if (IsBigEndian) 9319 Offset = TySizeInBytes - Offset - getLoadedSize(); 9320 return Offset; 9321 } 9322 9323 /// \brief Generate the sequence of instructions to load the slice 9324 /// represented by this object and redirect the uses of this slice to 9325 /// this new sequence of instructions. 9326 /// \pre this->Inst && this->Origin are valid Instructions and this 9327 /// object passed the legal check: LoadedSlice::isLegal returned true. 9328 /// \return The last instruction of the sequence used to load the slice. 9329 SDValue loadSlice() const { 9330 assert(Inst && Origin && "Unable to replace a non-existing slice."); 9331 const SDValue &OldBaseAddr = Origin->getBasePtr(); 9332 SDValue BaseAddr = OldBaseAddr; 9333 // Get the offset in that chunk of bytes w.r.t. the endianess. 9334 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 9335 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 9336 if (Offset) { 9337 // BaseAddr = BaseAddr + Offset. 9338 EVT ArithType = BaseAddr.getValueType(); 9339 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr, 9340 DAG->getConstant(Offset, ArithType)); 9341 } 9342 9343 // Create the type of the loaded slice according to its size. 9344 EVT SliceType = getLoadedType(); 9345 9346 // Create the load for the slice. 9347 SDValue LastInst = DAG->getLoad( 9348 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 9349 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 9350 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 9351 // If the final type is not the same as the loaded type, this means that 9352 // we have to pad with zero. Create a zero extend for that. 9353 EVT FinalType = Inst->getValueType(0); 9354 if (SliceType != FinalType) 9355 LastInst = 9356 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 9357 return LastInst; 9358 } 9359 9360 /// \brief Check if this slice can be merged with an expensive cross register 9361 /// bank copy. E.g., 9362 /// i = load i32 9363 /// f = bitcast i32 i to float 9364 bool canMergeExpensiveCrossRegisterBankCopy() const { 9365 if (!Inst || !Inst->hasOneUse()) 9366 return false; 9367 SDNode *Use = *Inst->use_begin(); 9368 if (Use->getOpcode() != ISD::BITCAST) 9369 return false; 9370 assert(DAG && "Missing context"); 9371 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9372 EVT ResVT = Use->getValueType(0); 9373 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 9374 const TargetRegisterClass *ArgRC = 9375 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 9376 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 9377 return false; 9378 9379 // At this point, we know that we perform a cross-register-bank copy. 9380 // Check if it is expensive. 9381 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 9382 // Assume bitcasts are cheap, unless both register classes do not 9383 // explicitly share a common sub class. 9384 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 9385 return false; 9386 9387 // Check if it will be merged with the load. 9388 // 1. Check the alignment constraint. 9389 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 9390 ResVT.getTypeForEVT(*DAG->getContext())); 9391 9392 if (RequiredAlignment > getAlignment()) 9393 return false; 9394 9395 // 2. Check that the load is a legal operation for that type. 9396 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 9397 return false; 9398 9399 // 3. Check that we do not have a zext in the way. 9400 if (Inst->getValueType(0) != getLoadedType()) 9401 return false; 9402 9403 return true; 9404 } 9405 }; 9406 } 9407 9408 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 9409 /// \p UsedBits looks like 0..0 1..1 0..0. 9410 static bool areUsedBitsDense(const APInt &UsedBits) { 9411 // If all the bits are one, this is dense! 9412 if (UsedBits.isAllOnesValue()) 9413 return true; 9414 9415 // Get rid of the unused bits on the right. 9416 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 9417 // Get rid of the unused bits on the left. 9418 if (NarrowedUsedBits.countLeadingZeros()) 9419 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 9420 // Check that the chunk of bits is completely used. 9421 return NarrowedUsedBits.isAllOnesValue(); 9422 } 9423 9424 /// \brief Check whether or not \p First and \p Second are next to each other 9425 /// in memory. This means that there is no hole between the bits loaded 9426 /// by \p First and the bits loaded by \p Second. 9427 static bool areSlicesNextToEachOther(const LoadedSlice &First, 9428 const LoadedSlice &Second) { 9429 assert(First.Origin == Second.Origin && First.Origin && 9430 "Unable to match different memory origins."); 9431 APInt UsedBits = First.getUsedBits(); 9432 assert((UsedBits & Second.getUsedBits()) == 0 && 9433 "Slices are not supposed to overlap."); 9434 UsedBits |= Second.getUsedBits(); 9435 return areUsedBitsDense(UsedBits); 9436 } 9437 9438 /// \brief Adjust the \p GlobalLSCost according to the target 9439 /// paring capabilities and the layout of the slices. 9440 /// \pre \p GlobalLSCost should account for at least as many loads as 9441 /// there is in the slices in \p LoadedSlices. 9442 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9443 LoadedSlice::Cost &GlobalLSCost) { 9444 unsigned NumberOfSlices = LoadedSlices.size(); 9445 // If there is less than 2 elements, no pairing is possible. 9446 if (NumberOfSlices < 2) 9447 return; 9448 9449 // Sort the slices so that elements that are likely to be next to each 9450 // other in memory are next to each other in the list. 9451 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 9452 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 9453 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 9454 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 9455 }); 9456 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 9457 // First (resp. Second) is the first (resp. Second) potentially candidate 9458 // to be placed in a paired load. 9459 const LoadedSlice *First = nullptr; 9460 const LoadedSlice *Second = nullptr; 9461 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 9462 // Set the beginning of the pair. 9463 First = Second) { 9464 9465 Second = &LoadedSlices[CurrSlice]; 9466 9467 // If First is NULL, it means we start a new pair. 9468 // Get to the next slice. 9469 if (!First) 9470 continue; 9471 9472 EVT LoadedType = First->getLoadedType(); 9473 9474 // If the types of the slices are different, we cannot pair them. 9475 if (LoadedType != Second->getLoadedType()) 9476 continue; 9477 9478 // Check if the target supplies paired loads for this type. 9479 unsigned RequiredAlignment = 0; 9480 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 9481 // move to the next pair, this type is hopeless. 9482 Second = nullptr; 9483 continue; 9484 } 9485 // Check if we meet the alignment requirement. 9486 if (RequiredAlignment > First->getAlignment()) 9487 continue; 9488 9489 // Check that both loads are next to each other in memory. 9490 if (!areSlicesNextToEachOther(*First, *Second)) 9491 continue; 9492 9493 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 9494 --GlobalLSCost.Loads; 9495 // Move to the next pair. 9496 Second = nullptr; 9497 } 9498 } 9499 9500 /// \brief Check the profitability of all involved LoadedSlice. 9501 /// Currently, it is considered profitable if there is exactly two 9502 /// involved slices (1) which are (2) next to each other in memory, and 9503 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 9504 /// 9505 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 9506 /// the elements themselves. 9507 /// 9508 /// FIXME: When the cost model will be mature enough, we can relax 9509 /// constraints (1) and (2). 9510 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9511 const APInt &UsedBits, bool ForCodeSize) { 9512 unsigned NumberOfSlices = LoadedSlices.size(); 9513 if (StressLoadSlicing) 9514 return NumberOfSlices > 1; 9515 9516 // Check (1). 9517 if (NumberOfSlices != 2) 9518 return false; 9519 9520 // Check (2). 9521 if (!areUsedBitsDense(UsedBits)) 9522 return false; 9523 9524 // Check (3). 9525 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 9526 // The original code has one big load. 9527 OrigCost.Loads = 1; 9528 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 9529 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 9530 // Accumulate the cost of all the slices. 9531 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 9532 GlobalSlicingCost += SliceCost; 9533 9534 // Account as cost in the original configuration the gain obtained 9535 // with the current slices. 9536 OrigCost.addSliceGain(LS); 9537 } 9538 9539 // If the target supports paired load, adjust the cost accordingly. 9540 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 9541 return OrigCost > GlobalSlicingCost; 9542 } 9543 9544 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 9545 /// operations, split it in the various pieces being extracted. 9546 /// 9547 /// This sort of thing is introduced by SROA. 9548 /// This slicing takes care not to insert overlapping loads. 9549 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 9550 bool DAGCombiner::SliceUpLoad(SDNode *N) { 9551 if (Level < AfterLegalizeDAG) 9552 return false; 9553 9554 LoadSDNode *LD = cast<LoadSDNode>(N); 9555 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 9556 !LD->getValueType(0).isInteger()) 9557 return false; 9558 9559 // Keep track of already used bits to detect overlapping values. 9560 // In that case, we will just abort the transformation. 9561 APInt UsedBits(LD->getValueSizeInBits(0), 0); 9562 9563 SmallVector<LoadedSlice, 4> LoadedSlices; 9564 9565 // Check if this load is used as several smaller chunks of bits. 9566 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 9567 // of computation for each trunc. 9568 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 9569 UI != UIEnd; ++UI) { 9570 // Skip the uses of the chain. 9571 if (UI.getUse().getResNo() != 0) 9572 continue; 9573 9574 SDNode *User = *UI; 9575 unsigned Shift = 0; 9576 9577 // Check if this is a trunc(lshr). 9578 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 9579 isa<ConstantSDNode>(User->getOperand(1))) { 9580 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 9581 User = *User->use_begin(); 9582 } 9583 9584 // At this point, User is a Truncate, iff we encountered, trunc or 9585 // trunc(lshr). 9586 if (User->getOpcode() != ISD::TRUNCATE) 9587 return false; 9588 9589 // The width of the type must be a power of 2 and greater than 8-bits. 9590 // Otherwise the load cannot be represented in LLVM IR. 9591 // Moreover, if we shifted with a non-8-bits multiple, the slice 9592 // will be across several bytes. We do not support that. 9593 unsigned Width = User->getValueSizeInBits(0); 9594 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 9595 return 0; 9596 9597 // Build the slice for this chain of computations. 9598 LoadedSlice LS(User, LD, Shift, &DAG); 9599 APInt CurrentUsedBits = LS.getUsedBits(); 9600 9601 // Check if this slice overlaps with another. 9602 if ((CurrentUsedBits & UsedBits) != 0) 9603 return false; 9604 // Update the bits used globally. 9605 UsedBits |= CurrentUsedBits; 9606 9607 // Check if the new slice would be legal. 9608 if (!LS.isLegal()) 9609 return false; 9610 9611 // Record the slice. 9612 LoadedSlices.push_back(LS); 9613 } 9614 9615 // Abort slicing if it does not seem to be profitable. 9616 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 9617 return false; 9618 9619 ++SlicedLoads; 9620 9621 // Rewrite each chain to use an independent load. 9622 // By construction, each chain can be represented by a unique load. 9623 9624 // Prepare the argument for the new token factor for all the slices. 9625 SmallVector<SDValue, 8> ArgChains; 9626 for (SmallVectorImpl<LoadedSlice>::const_iterator 9627 LSIt = LoadedSlices.begin(), 9628 LSItEnd = LoadedSlices.end(); 9629 LSIt != LSItEnd; ++LSIt) { 9630 SDValue SliceInst = LSIt->loadSlice(); 9631 CombineTo(LSIt->Inst, SliceInst, true); 9632 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 9633 SliceInst = SliceInst.getOperand(0); 9634 assert(SliceInst->getOpcode() == ISD::LOAD && 9635 "It takes more than a zext to get to the loaded slice!!"); 9636 ArgChains.push_back(SliceInst.getValue(1)); 9637 } 9638 9639 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 9640 ArgChains); 9641 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9642 return true; 9643 } 9644 9645 /// Check to see if V is (and load (ptr), imm), where the load is having 9646 /// specific bytes cleared out. If so, return the byte size being masked out 9647 /// and the shift amount. 9648 static std::pair<unsigned, unsigned> 9649 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 9650 std::pair<unsigned, unsigned> Result(0, 0); 9651 9652 // Check for the structure we're looking for. 9653 if (V->getOpcode() != ISD::AND || 9654 !isa<ConstantSDNode>(V->getOperand(1)) || 9655 !ISD::isNormalLoad(V->getOperand(0).getNode())) 9656 return Result; 9657 9658 // Check the chain and pointer. 9659 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 9660 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 9661 9662 // The store should be chained directly to the load or be an operand of a 9663 // tokenfactor. 9664 if (LD == Chain.getNode()) 9665 ; // ok. 9666 else if (Chain->getOpcode() != ISD::TokenFactor) 9667 return Result; // Fail. 9668 else { 9669 bool isOk = false; 9670 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 9671 if (Chain->getOperand(i).getNode() == LD) { 9672 isOk = true; 9673 break; 9674 } 9675 if (!isOk) return Result; 9676 } 9677 9678 // This only handles simple types. 9679 if (V.getValueType() != MVT::i16 && 9680 V.getValueType() != MVT::i32 && 9681 V.getValueType() != MVT::i64) 9682 return Result; 9683 9684 // Check the constant mask. Invert it so that the bits being masked out are 9685 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 9686 // follow the sign bit for uniformity. 9687 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 9688 unsigned NotMaskLZ = countLeadingZeros(NotMask); 9689 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 9690 unsigned NotMaskTZ = countTrailingZeros(NotMask); 9691 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 9692 if (NotMaskLZ == 64) return Result; // All zero mask. 9693 9694 // See if we have a continuous run of bits. If so, we have 0*1+0* 9695 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 9696 return Result; 9697 9698 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 9699 if (V.getValueType() != MVT::i64 && NotMaskLZ) 9700 NotMaskLZ -= 64-V.getValueSizeInBits(); 9701 9702 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 9703 switch (MaskedBytes) { 9704 case 1: 9705 case 2: 9706 case 4: break; 9707 default: return Result; // All one mask, or 5-byte mask. 9708 } 9709 9710 // Verify that the first bit starts at a multiple of mask so that the access 9711 // is aligned the same as the access width. 9712 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 9713 9714 Result.first = MaskedBytes; 9715 Result.second = NotMaskTZ/8; 9716 return Result; 9717 } 9718 9719 9720 /// Check to see if IVal is something that provides a value as specified by 9721 /// MaskInfo. If so, replace the specified store with a narrower store of 9722 /// truncated IVal. 9723 static SDNode * 9724 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 9725 SDValue IVal, StoreSDNode *St, 9726 DAGCombiner *DC) { 9727 unsigned NumBytes = MaskInfo.first; 9728 unsigned ByteShift = MaskInfo.second; 9729 SelectionDAG &DAG = DC->getDAG(); 9730 9731 // Check to see if IVal is all zeros in the part being masked in by the 'or' 9732 // that uses this. If not, this is not a replacement. 9733 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 9734 ByteShift*8, (ByteShift+NumBytes)*8); 9735 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 9736 9737 // Check that it is legal on the target to do this. It is legal if the new 9738 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 9739 // legalization. 9740 MVT VT = MVT::getIntegerVT(NumBytes*8); 9741 if (!DC->isTypeLegal(VT)) 9742 return nullptr; 9743 9744 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 9745 // shifted by ByteShift and truncated down to NumBytes. 9746 if (ByteShift) 9747 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 9748 DAG.getConstant(ByteShift*8, 9749 DC->getShiftAmountTy(IVal.getValueType()))); 9750 9751 // Figure out the offset for the store and the alignment of the access. 9752 unsigned StOffset; 9753 unsigned NewAlign = St->getAlignment(); 9754 9755 if (DAG.getTargetLoweringInfo().isLittleEndian()) 9756 StOffset = ByteShift; 9757 else 9758 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 9759 9760 SDValue Ptr = St->getBasePtr(); 9761 if (StOffset) { 9762 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 9763 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 9764 NewAlign = MinAlign(NewAlign, StOffset); 9765 } 9766 9767 // Truncate down to the new size. 9768 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 9769 9770 ++OpsNarrowed; 9771 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 9772 St->getPointerInfo().getWithOffset(StOffset), 9773 false, false, NewAlign).getNode(); 9774 } 9775 9776 9777 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 9778 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 9779 /// narrowing the load and store if it would end up being a win for performance 9780 /// or code size. 9781 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 9782 StoreSDNode *ST = cast<StoreSDNode>(N); 9783 if (ST->isVolatile()) 9784 return SDValue(); 9785 9786 SDValue Chain = ST->getChain(); 9787 SDValue Value = ST->getValue(); 9788 SDValue Ptr = ST->getBasePtr(); 9789 EVT VT = Value.getValueType(); 9790 9791 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 9792 return SDValue(); 9793 9794 unsigned Opc = Value.getOpcode(); 9795 9796 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 9797 // is a byte mask indicating a consecutive number of bytes, check to see if 9798 // Y is known to provide just those bytes. If so, we try to replace the 9799 // load + replace + store sequence with a single (narrower) store, which makes 9800 // the load dead. 9801 if (Opc == ISD::OR) { 9802 std::pair<unsigned, unsigned> MaskedLoad; 9803 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 9804 if (MaskedLoad.first) 9805 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 9806 Value.getOperand(1), ST,this)) 9807 return SDValue(NewST, 0); 9808 9809 // Or is commutative, so try swapping X and Y. 9810 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 9811 if (MaskedLoad.first) 9812 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 9813 Value.getOperand(0), ST,this)) 9814 return SDValue(NewST, 0); 9815 } 9816 9817 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 9818 Value.getOperand(1).getOpcode() != ISD::Constant) 9819 return SDValue(); 9820 9821 SDValue N0 = Value.getOperand(0); 9822 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9823 Chain == SDValue(N0.getNode(), 1)) { 9824 LoadSDNode *LD = cast<LoadSDNode>(N0); 9825 if (LD->getBasePtr() != Ptr || 9826 LD->getPointerInfo().getAddrSpace() != 9827 ST->getPointerInfo().getAddrSpace()) 9828 return SDValue(); 9829 9830 // Find the type to narrow it the load / op / store to. 9831 SDValue N1 = Value.getOperand(1); 9832 unsigned BitWidth = N1.getValueSizeInBits(); 9833 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 9834 if (Opc == ISD::AND) 9835 Imm ^= APInt::getAllOnesValue(BitWidth); 9836 if (Imm == 0 || Imm.isAllOnesValue()) 9837 return SDValue(); 9838 unsigned ShAmt = Imm.countTrailingZeros(); 9839 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 9840 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 9841 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 9842 // The narrowing should be profitable, the load/store operation should be 9843 // legal (or custom) and the store size should be equal to the NewVT width. 9844 while (NewBW < BitWidth && 9845 (NewVT.getStoreSizeInBits() != NewBW || 9846 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 9847 !TLI.isNarrowingProfitable(VT, NewVT))) { 9848 NewBW = NextPowerOf2(NewBW); 9849 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 9850 } 9851 if (NewBW >= BitWidth) 9852 return SDValue(); 9853 9854 // If the lsb changed does not start at the type bitwidth boundary, 9855 // start at the previous one. 9856 if (ShAmt % NewBW) 9857 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 9858 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 9859 std::min(BitWidth, ShAmt + NewBW)); 9860 if ((Imm & Mask) == Imm) { 9861 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 9862 if (Opc == ISD::AND) 9863 NewImm ^= APInt::getAllOnesValue(NewBW); 9864 uint64_t PtrOff = ShAmt / 8; 9865 // For big endian targets, we need to adjust the offset to the pointer to 9866 // load the correct bytes. 9867 if (TLI.isBigEndian()) 9868 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 9869 9870 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 9871 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 9872 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 9873 return SDValue(); 9874 9875 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 9876 Ptr.getValueType(), Ptr, 9877 DAG.getConstant(PtrOff, Ptr.getValueType())); 9878 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 9879 LD->getChain(), NewPtr, 9880 LD->getPointerInfo().getWithOffset(PtrOff), 9881 LD->isVolatile(), LD->isNonTemporal(), 9882 LD->isInvariant(), NewAlign, 9883 LD->getAAInfo()); 9884 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 9885 DAG.getConstant(NewImm, NewVT)); 9886 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 9887 NewVal, NewPtr, 9888 ST->getPointerInfo().getWithOffset(PtrOff), 9889 false, false, NewAlign); 9890 9891 AddToWorklist(NewPtr.getNode()); 9892 AddToWorklist(NewLD.getNode()); 9893 AddToWorklist(NewVal.getNode()); 9894 WorklistRemover DeadNodes(*this); 9895 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 9896 ++OpsNarrowed; 9897 return NewST; 9898 } 9899 } 9900 9901 return SDValue(); 9902 } 9903 9904 /// For a given floating point load / store pair, if the load value isn't used 9905 /// by any other operations, then consider transforming the pair to integer 9906 /// load / store operations if the target deems the transformation profitable. 9907 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 9908 StoreSDNode *ST = cast<StoreSDNode>(N); 9909 SDValue Chain = ST->getChain(); 9910 SDValue Value = ST->getValue(); 9911 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 9912 Value.hasOneUse() && 9913 Chain == SDValue(Value.getNode(), 1)) { 9914 LoadSDNode *LD = cast<LoadSDNode>(Value); 9915 EVT VT = LD->getMemoryVT(); 9916 if (!VT.isFloatingPoint() || 9917 VT != ST->getMemoryVT() || 9918 LD->isNonTemporal() || 9919 ST->isNonTemporal() || 9920 LD->getPointerInfo().getAddrSpace() != 0 || 9921 ST->getPointerInfo().getAddrSpace() != 0) 9922 return SDValue(); 9923 9924 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 9925 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 9926 !TLI.isOperationLegal(ISD::STORE, IntVT) || 9927 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 9928 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 9929 return SDValue(); 9930 9931 unsigned LDAlign = LD->getAlignment(); 9932 unsigned STAlign = ST->getAlignment(); 9933 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 9934 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 9935 if (LDAlign < ABIAlign || STAlign < ABIAlign) 9936 return SDValue(); 9937 9938 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 9939 LD->getChain(), LD->getBasePtr(), 9940 LD->getPointerInfo(), 9941 false, false, false, LDAlign); 9942 9943 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 9944 NewLD, ST->getBasePtr(), 9945 ST->getPointerInfo(), 9946 false, false, STAlign); 9947 9948 AddToWorklist(NewLD.getNode()); 9949 AddToWorklist(NewST.getNode()); 9950 WorklistRemover DeadNodes(*this); 9951 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 9952 ++LdStFP2Int; 9953 return NewST; 9954 } 9955 9956 return SDValue(); 9957 } 9958 9959 namespace { 9960 /// Helper struct to parse and store a memory address as base + index + offset. 9961 /// We ignore sign extensions when it is safe to do so. 9962 /// The following two expressions are not equivalent. To differentiate we need 9963 /// to store whether there was a sign extension involved in the index 9964 /// computation. 9965 /// (load (i64 add (i64 copyfromreg %c) 9966 /// (i64 signextend (add (i8 load %index) 9967 /// (i8 1)))) 9968 /// vs 9969 /// 9970 /// (load (i64 add (i64 copyfromreg %c) 9971 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 9972 /// (i32 1))))) 9973 struct BaseIndexOffset { 9974 SDValue Base; 9975 SDValue Index; 9976 int64_t Offset; 9977 bool IsIndexSignExt; 9978 9979 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 9980 9981 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 9982 bool IsIndexSignExt) : 9983 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 9984 9985 bool equalBaseIndex(const BaseIndexOffset &Other) { 9986 return Other.Base == Base && Other.Index == Index && 9987 Other.IsIndexSignExt == IsIndexSignExt; 9988 } 9989 9990 /// Parses tree in Ptr for base, index, offset addresses. 9991 static BaseIndexOffset match(SDValue Ptr) { 9992 bool IsIndexSignExt = false; 9993 9994 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 9995 // instruction, then it could be just the BASE or everything else we don't 9996 // know how to handle. Just use Ptr as BASE and give up. 9997 if (Ptr->getOpcode() != ISD::ADD) 9998 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 9999 10000 // We know that we have at least an ADD instruction. Try to pattern match 10001 // the simple case of BASE + OFFSET. 10002 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10003 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10004 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10005 IsIndexSignExt); 10006 } 10007 10008 // Inside a loop the current BASE pointer is calculated using an ADD and a 10009 // MUL instruction. In this case Ptr is the actual BASE pointer. 10010 // (i64 add (i64 %array_ptr) 10011 // (i64 mul (i64 %induction_var) 10012 // (i64 %element_size))) 10013 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10014 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10015 10016 // Look at Base + Index + Offset cases. 10017 SDValue Base = Ptr->getOperand(0); 10018 SDValue IndexOffset = Ptr->getOperand(1); 10019 10020 // Skip signextends. 10021 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10022 IndexOffset = IndexOffset->getOperand(0); 10023 IsIndexSignExt = true; 10024 } 10025 10026 // Either the case of Base + Index (no offset) or something else. 10027 if (IndexOffset->getOpcode() != ISD::ADD) 10028 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10029 10030 // Now we have the case of Base + Index + offset. 10031 SDValue Index = IndexOffset->getOperand(0); 10032 SDValue Offset = IndexOffset->getOperand(1); 10033 10034 if (!isa<ConstantSDNode>(Offset)) 10035 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10036 10037 // Ignore signextends. 10038 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 10039 Index = Index->getOperand(0); 10040 IsIndexSignExt = true; 10041 } else IsIndexSignExt = false; 10042 10043 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 10044 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 10045 } 10046 }; 10047 } // namespace 10048 10049 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 10050 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 10051 unsigned NumElem, bool IsConstantSrc, bool UseVector) { 10052 // Make sure we have something to merge. 10053 if (NumElem < 2) 10054 return false; 10055 10056 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 10057 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10058 unsigned LatestNodeUsed = 0; 10059 10060 for (unsigned i=0; i < NumElem; ++i) { 10061 // Find a chain for the new wide-store operand. Notice that some 10062 // of the store nodes that we found may not be selected for inclusion 10063 // in the wide store. The chain we use needs to be the chain of the 10064 // latest store node which is *used* and replaced by the wide store. 10065 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 10066 LatestNodeUsed = i; 10067 } 10068 10069 // The latest Node in the DAG. 10070 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 10071 SDLoc DL(StoreNodes[0].MemNode); 10072 10073 SDValue StoredVal; 10074 if (UseVector) { 10075 // Find a legal type for the vector store. 10076 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 10077 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 10078 if (IsConstantSrc) { 10079 // A vector store with a constant source implies that the constant is 10080 // zero; we only handle merging stores of constant zeros because the zero 10081 // can be materialized without a load. 10082 // It may be beneficial to loosen this restriction to allow non-zero 10083 // store merging. 10084 StoredVal = DAG.getConstant(0, Ty); 10085 } else { 10086 SmallVector<SDValue, 8> Ops; 10087 for (unsigned i = 0; i < NumElem ; ++i) { 10088 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10089 SDValue Val = St->getValue(); 10090 // All of the operands of a BUILD_VECTOR must have the same type. 10091 if (Val.getValueType() != MemVT) 10092 return false; 10093 Ops.push_back(Val); 10094 } 10095 10096 // Build the extracted vector elements back into a vector. 10097 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops); 10098 } 10099 } else { 10100 // We should always use a vector store when merging extracted vector 10101 // elements, so this path implies a store of constants. 10102 assert(IsConstantSrc && "Merged vector elements should use vector store"); 10103 10104 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 10105 APInt StoreInt(StoreBW, 0); 10106 10107 // Construct a single integer constant which is made of the smaller 10108 // constant inputs. 10109 bool IsLE = TLI.isLittleEndian(); 10110 for (unsigned i = 0; i < NumElem ; ++i) { 10111 unsigned Idx = IsLE ? (NumElem - 1 - i) : i; 10112 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 10113 SDValue Val = St->getValue(); 10114 StoreInt <<= ElementSizeBytes*8; 10115 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 10116 StoreInt |= C->getAPIntValue().zext(StoreBW); 10117 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 10118 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 10119 } else { 10120 llvm_unreachable("Invalid constant element type"); 10121 } 10122 } 10123 10124 // Create the new Load and Store operations. 10125 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10126 StoredVal = DAG.getConstant(StoreInt, StoreTy); 10127 } 10128 10129 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal, 10130 FirstInChain->getBasePtr(), 10131 FirstInChain->getPointerInfo(), 10132 false, false, 10133 FirstInChain->getAlignment()); 10134 10135 // Replace the last store with the new store 10136 CombineTo(LatestOp, NewStore); 10137 // Erase all other stores. 10138 for (unsigned i = 0; i < NumElem ; ++i) { 10139 if (StoreNodes[i].MemNode == LatestOp) 10140 continue; 10141 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10142 // ReplaceAllUsesWith will replace all uses that existed when it was 10143 // called, but graph optimizations may cause new ones to appear. For 10144 // example, the case in pr14333 looks like 10145 // 10146 // St's chain -> St -> another store -> X 10147 // 10148 // And the only difference from St to the other store is the chain. 10149 // When we change it's chain to be St's chain they become identical, 10150 // get CSEed and the net result is that X is now a use of St. 10151 // Since we know that St is redundant, just iterate. 10152 while (!St->use_empty()) 10153 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 10154 deleteAndRecombine(St); 10155 } 10156 10157 return true; 10158 } 10159 10160 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 10161 if (OptLevel == CodeGenOpt::None) 10162 return false; 10163 10164 EVT MemVT = St->getMemoryVT(); 10165 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 10166 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 10167 Attribute::NoImplicitFloat); 10168 10169 // Don't merge vectors into wider inputs. 10170 if (MemVT.isVector() || !MemVT.isSimple()) 10171 return false; 10172 10173 // Perform an early exit check. Do not bother looking at stored values that 10174 // are not constants, loads, or extracted vector elements. 10175 SDValue StoredVal = St->getValue(); 10176 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 10177 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 10178 isa<ConstantFPSDNode>(StoredVal); 10179 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT); 10180 10181 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc) 10182 return false; 10183 10184 // Only look at ends of store sequences. 10185 SDValue Chain = SDValue(St, 0); 10186 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 10187 return false; 10188 10189 // This holds the base pointer, index, and the offset in bytes from the base 10190 // pointer. 10191 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 10192 10193 // We must have a base and an offset. 10194 if (!BasePtr.Base.getNode()) 10195 return false; 10196 10197 // Do not handle stores to undef base pointers. 10198 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 10199 return false; 10200 10201 // Save the LoadSDNodes that we find in the chain. 10202 // We need to make sure that these nodes do not interfere with 10203 // any of the store nodes. 10204 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 10205 10206 // Save the StoreSDNodes that we find in the chain. 10207 SmallVector<MemOpLink, 8> StoreNodes; 10208 10209 // Walk up the chain and look for nodes with offsets from the same 10210 // base pointer. Stop when reaching an instruction with a different kind 10211 // or instruction which has a different base pointer. 10212 unsigned Seq = 0; 10213 StoreSDNode *Index = St; 10214 while (Index) { 10215 // If the chain has more than one use, then we can't reorder the mem ops. 10216 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 10217 break; 10218 10219 // Find the base pointer and offset for this memory node. 10220 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 10221 10222 // Check that the base pointer is the same as the original one. 10223 if (!Ptr.equalBaseIndex(BasePtr)) 10224 break; 10225 10226 // Check that the alignment is the same. 10227 if (Index->getAlignment() != St->getAlignment()) 10228 break; 10229 10230 // The memory operands must not be volatile. 10231 if (Index->isVolatile() || Index->isIndexed()) 10232 break; 10233 10234 // No truncation. 10235 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 10236 if (St->isTruncatingStore()) 10237 break; 10238 10239 // The stored memory type must be the same. 10240 if (Index->getMemoryVT() != MemVT) 10241 break; 10242 10243 // We do not allow unaligned stores because we want to prevent overriding 10244 // stores. 10245 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 10246 break; 10247 10248 // We found a potential memory operand to merge. 10249 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 10250 10251 // Find the next memory operand in the chain. If the next operand in the 10252 // chain is a store then move up and continue the scan with the next 10253 // memory operand. If the next operand is a load save it and use alias 10254 // information to check if it interferes with anything. 10255 SDNode *NextInChain = Index->getChain().getNode(); 10256 while (1) { 10257 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 10258 // We found a store node. Use it for the next iteration. 10259 Index = STn; 10260 break; 10261 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 10262 if (Ldn->isVolatile()) { 10263 Index = nullptr; 10264 break; 10265 } 10266 10267 // Save the load node for later. Continue the scan. 10268 AliasLoadNodes.push_back(Ldn); 10269 NextInChain = Ldn->getChain().getNode(); 10270 continue; 10271 } else { 10272 Index = nullptr; 10273 break; 10274 } 10275 } 10276 } 10277 10278 // Check if there is anything to merge. 10279 if (StoreNodes.size() < 2) 10280 return false; 10281 10282 // Sort the memory operands according to their distance from the base pointer. 10283 std::sort(StoreNodes.begin(), StoreNodes.end(), 10284 [](MemOpLink LHS, MemOpLink RHS) { 10285 return LHS.OffsetFromBase < RHS.OffsetFromBase || 10286 (LHS.OffsetFromBase == RHS.OffsetFromBase && 10287 LHS.SequenceNum > RHS.SequenceNum); 10288 }); 10289 10290 // Scan the memory operations on the chain and find the first non-consecutive 10291 // store memory address. 10292 unsigned LastConsecutiveStore = 0; 10293 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 10294 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 10295 10296 // Check that the addresses are consecutive starting from the second 10297 // element in the list of stores. 10298 if (i > 0) { 10299 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 10300 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10301 break; 10302 } 10303 10304 bool Alias = false; 10305 // Check if this store interferes with any of the loads that we found. 10306 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 10307 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 10308 Alias = true; 10309 break; 10310 } 10311 // We found a load that alias with this store. Stop the sequence. 10312 if (Alias) 10313 break; 10314 10315 // Mark this node as useful. 10316 LastConsecutiveStore = i; 10317 } 10318 10319 // The node with the lowest store address. 10320 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10321 10322 // Store the constants into memory as one consecutive store. 10323 if (IsConstantSrc) { 10324 unsigned LastLegalType = 0; 10325 unsigned LastLegalVectorType = 0; 10326 bool NonZero = false; 10327 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10328 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10329 SDValue StoredVal = St->getValue(); 10330 10331 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 10332 NonZero |= !C->isNullValue(); 10333 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 10334 NonZero |= !C->getConstantFPValue()->isNullValue(); 10335 } else { 10336 // Non-constant. 10337 break; 10338 } 10339 10340 // Find a legal type for the constant store. 10341 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10342 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10343 if (TLI.isTypeLegal(StoreTy)) 10344 LastLegalType = i+1; 10345 // Or check whether a truncstore is legal. 10346 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10347 TargetLowering::TypePromoteInteger) { 10348 EVT LegalizedStoredValueTy = 10349 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 10350 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 10351 LastLegalType = i+1; 10352 } 10353 10354 // Find a legal type for the vector store. 10355 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10356 if (TLI.isTypeLegal(Ty)) 10357 LastLegalVectorType = i + 1; 10358 } 10359 10360 // We only use vectors if the constant is known to be zero and the 10361 // function is not marked with the noimplicitfloat attribute. 10362 if (NonZero || NoVectors) 10363 LastLegalVectorType = 0; 10364 10365 // Check if we found a legal integer type to store. 10366 if (LastLegalType == 0 && LastLegalVectorType == 0) 10367 return false; 10368 10369 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 10370 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 10371 10372 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10373 true, UseVector); 10374 } 10375 10376 // When extracting multiple vector elements, try to store them 10377 // in one vector store rather than a sequence of scalar stores. 10378 if (IsExtractVecEltSrc) { 10379 unsigned NumElem = 0; 10380 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 10381 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10382 SDValue StoredVal = St->getValue(); 10383 // This restriction could be loosened. 10384 // Bail out if any stored values are not elements extracted from a vector. 10385 // It should be possible to handle mixed sources, but load sources need 10386 // more careful handling (see the block of code below that handles 10387 // consecutive loads). 10388 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10389 return false; 10390 10391 // Find a legal type for the vector store. 10392 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10393 if (TLI.isTypeLegal(Ty)) 10394 NumElem = i + 1; 10395 } 10396 10397 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10398 false, true); 10399 } 10400 10401 // Below we handle the case of multiple consecutive stores that 10402 // come from multiple consecutive loads. We merge them into a single 10403 // wide load and a single wide store. 10404 10405 // Look for load nodes which are used by the stored values. 10406 SmallVector<MemOpLink, 8> LoadNodes; 10407 10408 // Find acceptable loads. Loads need to have the same chain (token factor), 10409 // must not be zext, volatile, indexed, and they must be consecutive. 10410 BaseIndexOffset LdBasePtr; 10411 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10412 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10413 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 10414 if (!Ld) break; 10415 10416 // Loads must only have one use. 10417 if (!Ld->hasNUsesOfValue(1, 0)) 10418 break; 10419 10420 // Check that the alignment is the same as the stores. 10421 if (Ld->getAlignment() != St->getAlignment()) 10422 break; 10423 10424 // The memory operands must not be volatile. 10425 if (Ld->isVolatile() || Ld->isIndexed()) 10426 break; 10427 10428 // We do not accept ext loads. 10429 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 10430 break; 10431 10432 // The stored memory type must be the same. 10433 if (Ld->getMemoryVT() != MemVT) 10434 break; 10435 10436 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 10437 // If this is not the first ptr that we check. 10438 if (LdBasePtr.Base.getNode()) { 10439 // The base ptr must be the same. 10440 if (!LdPtr.equalBaseIndex(LdBasePtr)) 10441 break; 10442 } else { 10443 // Check that all other base pointers are the same as this one. 10444 LdBasePtr = LdPtr; 10445 } 10446 10447 // We found a potential memory operand to merge. 10448 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 10449 } 10450 10451 if (LoadNodes.size() < 2) 10452 return false; 10453 10454 // If we have load/store pair instructions and we only have two values, 10455 // don't bother. 10456 unsigned RequiredAlignment; 10457 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 10458 St->getAlignment() >= RequiredAlignment) 10459 return false; 10460 10461 // Scan the memory operations on the chain and find the first non-consecutive 10462 // load memory address. These variables hold the index in the store node 10463 // array. 10464 unsigned LastConsecutiveLoad = 0; 10465 // This variable refers to the size and not index in the array. 10466 unsigned LastLegalVectorType = 0; 10467 unsigned LastLegalIntegerType = 0; 10468 StartAddress = LoadNodes[0].OffsetFromBase; 10469 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 10470 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 10471 // All loads much share the same chain. 10472 if (LoadNodes[i].MemNode->getChain() != FirstChain) 10473 break; 10474 10475 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 10476 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10477 break; 10478 LastConsecutiveLoad = i; 10479 10480 // Find a legal type for the vector store. 10481 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10482 if (TLI.isTypeLegal(StoreTy)) 10483 LastLegalVectorType = i + 1; 10484 10485 // Find a legal type for the integer store. 10486 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10487 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10488 if (TLI.isTypeLegal(StoreTy)) 10489 LastLegalIntegerType = i + 1; 10490 // Or check whether a truncstore and extload is legal. 10491 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10492 TargetLowering::TypePromoteInteger) { 10493 EVT LegalizedStoredValueTy = 10494 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 10495 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 10496 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10497 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10498 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy)) 10499 LastLegalIntegerType = i+1; 10500 } 10501 } 10502 10503 // Only use vector types if the vector type is larger than the integer type. 10504 // If they are the same, use integers. 10505 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 10506 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 10507 10508 // We add +1 here because the LastXXX variables refer to location while 10509 // the NumElem refers to array/index size. 10510 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 10511 NumElem = std::min(LastLegalType, NumElem); 10512 10513 if (NumElem < 2) 10514 return false; 10515 10516 // The latest Node in the DAG. 10517 unsigned LatestNodeUsed = 0; 10518 for (unsigned i=1; i<NumElem; ++i) { 10519 // Find a chain for the new wide-store operand. Notice that some 10520 // of the store nodes that we found may not be selected for inclusion 10521 // in the wide store. The chain we use needs to be the chain of the 10522 // latest store node which is *used* and replaced by the wide store. 10523 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 10524 LatestNodeUsed = i; 10525 } 10526 10527 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 10528 10529 // Find if it is better to use vectors or integers to load and store 10530 // to memory. 10531 EVT JointMemOpVT; 10532 if (UseVectorTy) { 10533 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 10534 } else { 10535 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 10536 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10537 } 10538 10539 SDLoc LoadDL(LoadNodes[0].MemNode); 10540 SDLoc StoreDL(StoreNodes[0].MemNode); 10541 10542 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 10543 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 10544 FirstLoad->getChain(), 10545 FirstLoad->getBasePtr(), 10546 FirstLoad->getPointerInfo(), 10547 false, false, false, 10548 FirstLoad->getAlignment()); 10549 10550 SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad, 10551 FirstInChain->getBasePtr(), 10552 FirstInChain->getPointerInfo(), false, false, 10553 FirstInChain->getAlignment()); 10554 10555 // Replace one of the loads with the new load. 10556 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 10557 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 10558 SDValue(NewLoad.getNode(), 1)); 10559 10560 // Remove the rest of the load chains. 10561 for (unsigned i = 1; i < NumElem ; ++i) { 10562 // Replace all chain users of the old load nodes with the chain of the new 10563 // load node. 10564 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 10565 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 10566 } 10567 10568 // Replace the last store with the new store. 10569 CombineTo(LatestOp, NewStore); 10570 // Erase all other stores. 10571 for (unsigned i = 0; i < NumElem ; ++i) { 10572 // Remove all Store nodes. 10573 if (StoreNodes[i].MemNode == LatestOp) 10574 continue; 10575 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10576 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 10577 deleteAndRecombine(St); 10578 } 10579 10580 return true; 10581 } 10582 10583 SDValue DAGCombiner::visitSTORE(SDNode *N) { 10584 StoreSDNode *ST = cast<StoreSDNode>(N); 10585 SDValue Chain = ST->getChain(); 10586 SDValue Value = ST->getValue(); 10587 SDValue Ptr = ST->getBasePtr(); 10588 10589 // If this is a store of a bit convert, store the input value if the 10590 // resultant store does not need a higher alignment than the original. 10591 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 10592 ST->isUnindexed()) { 10593 unsigned OrigAlign = ST->getAlignment(); 10594 EVT SVT = Value.getOperand(0).getValueType(); 10595 unsigned Align = TLI.getDataLayout()-> 10596 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 10597 if (Align <= OrigAlign && 10598 ((!LegalOperations && !ST->isVolatile()) || 10599 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 10600 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 10601 Ptr, ST->getPointerInfo(), ST->isVolatile(), 10602 ST->isNonTemporal(), OrigAlign, 10603 ST->getAAInfo()); 10604 } 10605 10606 // Turn 'store undef, Ptr' -> nothing. 10607 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 10608 return Chain; 10609 10610 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 10611 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 10612 // NOTE: If the original store is volatile, this transform must not increase 10613 // the number of stores. For example, on x86-32 an f64 can be stored in one 10614 // processor operation but an i64 (which is not legal) requires two. So the 10615 // transform should not be done in this case. 10616 if (Value.getOpcode() != ISD::TargetConstantFP) { 10617 SDValue Tmp; 10618 switch (CFP->getSimpleValueType(0).SimpleTy) { 10619 default: llvm_unreachable("Unknown FP type"); 10620 case MVT::f16: // We don't do this for these yet. 10621 case MVT::f80: 10622 case MVT::f128: 10623 case MVT::ppcf128: 10624 break; 10625 case MVT::f32: 10626 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 10627 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 10628 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 10629 bitcastToAPInt().getZExtValue(), MVT::i32); 10630 return DAG.getStore(Chain, SDLoc(N), Tmp, 10631 Ptr, ST->getMemOperand()); 10632 } 10633 break; 10634 case MVT::f64: 10635 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 10636 !ST->isVolatile()) || 10637 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 10638 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 10639 getZExtValue(), MVT::i64); 10640 return DAG.getStore(Chain, SDLoc(N), Tmp, 10641 Ptr, ST->getMemOperand()); 10642 } 10643 10644 if (!ST->isVolatile() && 10645 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 10646 // Many FP stores are not made apparent until after legalize, e.g. for 10647 // argument passing. Since this is so common, custom legalize the 10648 // 64-bit integer store into two 32-bit stores. 10649 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 10650 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 10651 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 10652 if (TLI.isBigEndian()) std::swap(Lo, Hi); 10653 10654 unsigned Alignment = ST->getAlignment(); 10655 bool isVolatile = ST->isVolatile(); 10656 bool isNonTemporal = ST->isNonTemporal(); 10657 AAMDNodes AAInfo = ST->getAAInfo(); 10658 10659 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 10660 Ptr, ST->getPointerInfo(), 10661 isVolatile, isNonTemporal, 10662 ST->getAlignment(), AAInfo); 10663 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 10664 DAG.getConstant(4, Ptr.getValueType())); 10665 Alignment = MinAlign(Alignment, 4U); 10666 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 10667 Ptr, ST->getPointerInfo().getWithOffset(4), 10668 isVolatile, isNonTemporal, 10669 Alignment, AAInfo); 10670 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 10671 St0, St1); 10672 } 10673 10674 break; 10675 } 10676 } 10677 } 10678 10679 // Try to infer better alignment information than the store already has. 10680 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 10681 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10682 if (Align > ST->getAlignment()) { 10683 SDValue NewStore = 10684 DAG.getTruncStore(Chain, SDLoc(N), Value, 10685 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 10686 ST->isVolatile(), ST->isNonTemporal(), Align, 10687 ST->getAAInfo()); 10688 if (NewStore.getNode() != N) 10689 return CombineTo(ST, NewStore, true); 10690 } 10691 } 10692 } 10693 10694 // Try transforming a pair floating point load / store ops to integer 10695 // load / store ops. 10696 SDValue NewST = TransformFPLoadStorePair(N); 10697 if (NewST.getNode()) 10698 return NewST; 10699 10700 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10701 : DAG.getSubtarget().useAA(); 10702 #ifndef NDEBUG 10703 if (CombinerAAOnlyFunc.getNumOccurrences() && 10704 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10705 UseAA = false; 10706 #endif 10707 if (UseAA && ST->isUnindexed()) { 10708 // Walk up chain skipping non-aliasing memory nodes. 10709 SDValue BetterChain = FindBetterChain(N, Chain); 10710 10711 // If there is a better chain. 10712 if (Chain != BetterChain) { 10713 SDValue ReplStore; 10714 10715 // Replace the chain to avoid dependency. 10716 if (ST->isTruncatingStore()) { 10717 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 10718 ST->getMemoryVT(), ST->getMemOperand()); 10719 } else { 10720 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 10721 ST->getMemOperand()); 10722 } 10723 10724 // Create token to keep both nodes around. 10725 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10726 MVT::Other, Chain, ReplStore); 10727 10728 // Make sure the new and old chains are cleaned up. 10729 AddToWorklist(Token.getNode()); 10730 10731 // Don't add users to work list. 10732 return CombineTo(N, Token, false); 10733 } 10734 } 10735 10736 // Try transforming N to an indexed store. 10737 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10738 return SDValue(N, 0); 10739 10740 // FIXME: is there such a thing as a truncating indexed store? 10741 if (ST->isTruncatingStore() && ST->isUnindexed() && 10742 Value.getValueType().isInteger()) { 10743 // See if we can simplify the input to this truncstore with knowledge that 10744 // only the low bits are being used. For example: 10745 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 10746 SDValue Shorter = 10747 GetDemandedBits(Value, 10748 APInt::getLowBitsSet( 10749 Value.getValueType().getScalarType().getSizeInBits(), 10750 ST->getMemoryVT().getScalarType().getSizeInBits())); 10751 AddToWorklist(Value.getNode()); 10752 if (Shorter.getNode()) 10753 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 10754 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 10755 10756 // Otherwise, see if we can simplify the operation with 10757 // SimplifyDemandedBits, which only works if the value has a single use. 10758 if (SimplifyDemandedBits(Value, 10759 APInt::getLowBitsSet( 10760 Value.getValueType().getScalarType().getSizeInBits(), 10761 ST->getMemoryVT().getScalarType().getSizeInBits()))) 10762 return SDValue(N, 0); 10763 } 10764 10765 // If this is a load followed by a store to the same location, then the store 10766 // is dead/noop. 10767 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 10768 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 10769 ST->isUnindexed() && !ST->isVolatile() && 10770 // There can't be any side effects between the load and store, such as 10771 // a call or store. 10772 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 10773 // The store is dead, remove it. 10774 return Chain; 10775 } 10776 } 10777 10778 // If this is a store followed by a store with the same value to the same 10779 // location, then the store is dead/noop. 10780 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 10781 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 10782 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 10783 ST1->isUnindexed() && !ST1->isVolatile()) { 10784 // The store is dead, remove it. 10785 return Chain; 10786 } 10787 } 10788 10789 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 10790 // truncating store. We can do this even if this is already a truncstore. 10791 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 10792 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 10793 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 10794 ST->getMemoryVT())) { 10795 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 10796 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 10797 } 10798 10799 // Only perform this optimization before the types are legal, because we 10800 // don't want to perform this optimization on every DAGCombine invocation. 10801 if (!LegalTypes) { 10802 bool EverChanged = false; 10803 10804 do { 10805 // There can be multiple store sequences on the same chain. 10806 // Keep trying to merge store sequences until we are unable to do so 10807 // or until we merge the last store on the chain. 10808 bool Changed = MergeConsecutiveStores(ST); 10809 EverChanged |= Changed; 10810 if (!Changed) break; 10811 } while (ST->getOpcode() != ISD::DELETED_NODE); 10812 10813 if (EverChanged) 10814 return SDValue(N, 0); 10815 } 10816 10817 return ReduceLoadOpStoreWidth(N); 10818 } 10819 10820 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 10821 SDValue InVec = N->getOperand(0); 10822 SDValue InVal = N->getOperand(1); 10823 SDValue EltNo = N->getOperand(2); 10824 SDLoc dl(N); 10825 10826 // If the inserted element is an UNDEF, just use the input vector. 10827 if (InVal.getOpcode() == ISD::UNDEF) 10828 return InVec; 10829 10830 EVT VT = InVec.getValueType(); 10831 10832 // If we can't generate a legal BUILD_VECTOR, exit 10833 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 10834 return SDValue(); 10835 10836 // Check that we know which element is being inserted 10837 if (!isa<ConstantSDNode>(EltNo)) 10838 return SDValue(); 10839 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 10840 10841 // Canonicalize insert_vector_elt dag nodes. 10842 // Example: 10843 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 10844 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 10845 // 10846 // Do this only if the child insert_vector node has one use; also 10847 // do this only if indices are both constants and Idx1 < Idx0. 10848 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 10849 && isa<ConstantSDNode>(InVec.getOperand(2))) { 10850 unsigned OtherElt = 10851 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 10852 if (Elt < OtherElt) { 10853 // Swap nodes. 10854 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 10855 InVec.getOperand(0), InVal, EltNo); 10856 AddToWorklist(NewOp.getNode()); 10857 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 10858 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 10859 } 10860 } 10861 10862 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 10863 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 10864 // vector elements. 10865 SmallVector<SDValue, 8> Ops; 10866 // Do not combine these two vectors if the output vector will not replace 10867 // the input vector. 10868 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 10869 Ops.append(InVec.getNode()->op_begin(), 10870 InVec.getNode()->op_end()); 10871 } else if (InVec.getOpcode() == ISD::UNDEF) { 10872 unsigned NElts = VT.getVectorNumElements(); 10873 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 10874 } else { 10875 return SDValue(); 10876 } 10877 10878 // Insert the element 10879 if (Elt < Ops.size()) { 10880 // All the operands of BUILD_VECTOR must have the same type; 10881 // we enforce that here. 10882 EVT OpVT = Ops[0].getValueType(); 10883 if (InVal.getValueType() != OpVT) 10884 InVal = OpVT.bitsGT(InVal.getValueType()) ? 10885 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 10886 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 10887 Ops[Elt] = InVal; 10888 } 10889 10890 // Return the new vector 10891 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 10892 } 10893 10894 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 10895 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 10896 EVT ResultVT = EVE->getValueType(0); 10897 EVT VecEltVT = InVecVT.getVectorElementType(); 10898 unsigned Align = OriginalLoad->getAlignment(); 10899 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment( 10900 VecEltVT.getTypeForEVT(*DAG.getContext())); 10901 10902 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 10903 return SDValue(); 10904 10905 Align = NewAlign; 10906 10907 SDValue NewPtr = OriginalLoad->getBasePtr(); 10908 SDValue Offset; 10909 EVT PtrType = NewPtr.getValueType(); 10910 MachinePointerInfo MPI; 10911 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 10912 int Elt = ConstEltNo->getZExtValue(); 10913 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 10914 if (TLI.isBigEndian()) 10915 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff; 10916 Offset = DAG.getConstant(PtrOff, PtrType); 10917 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 10918 } else { 10919 Offset = DAG.getNode( 10920 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo, 10921 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType())); 10922 if (TLI.isBigEndian()) 10923 Offset = DAG.getNode( 10924 ISD::SUB, SDLoc(EVE), EltNo.getValueType(), 10925 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset); 10926 MPI = OriginalLoad->getPointerInfo(); 10927 } 10928 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset); 10929 10930 // The replacement we need to do here is a little tricky: we need to 10931 // replace an extractelement of a load with a load. 10932 // Use ReplaceAllUsesOfValuesWith to do the replacement. 10933 // Note that this replacement assumes that the extractvalue is the only 10934 // use of the load; that's okay because we don't want to perform this 10935 // transformation in other cases anyway. 10936 SDValue Load; 10937 SDValue Chain; 10938 if (ResultVT.bitsGT(VecEltVT)) { 10939 // If the result type of vextract is wider than the load, then issue an 10940 // extending load instead. 10941 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 10942 VecEltVT) 10943 ? ISD::ZEXTLOAD 10944 : ISD::EXTLOAD; 10945 Load = DAG.getExtLoad( 10946 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 10947 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 10948 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 10949 Chain = Load.getValue(1); 10950 } else { 10951 Load = DAG.getLoad( 10952 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 10953 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 10954 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 10955 Chain = Load.getValue(1); 10956 if (ResultVT.bitsLT(VecEltVT)) 10957 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 10958 else 10959 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 10960 } 10961 WorklistRemover DeadNodes(*this); 10962 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 10963 SDValue To[] = { Load, Chain }; 10964 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10965 // Since we're explicitly calling ReplaceAllUses, add the new node to the 10966 // worklist explicitly as well. 10967 AddToWorklist(Load.getNode()); 10968 AddUsersToWorklist(Load.getNode()); // Add users too 10969 // Make sure to revisit this node to clean it up; it will usually be dead. 10970 AddToWorklist(EVE); 10971 ++OpsNarrowed; 10972 return SDValue(EVE, 0); 10973 } 10974 10975 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 10976 // (vextract (scalar_to_vector val, 0) -> val 10977 SDValue InVec = N->getOperand(0); 10978 EVT VT = InVec.getValueType(); 10979 EVT NVT = N->getValueType(0); 10980 10981 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 10982 // Check if the result type doesn't match the inserted element type. A 10983 // SCALAR_TO_VECTOR may truncate the inserted element and the 10984 // EXTRACT_VECTOR_ELT may widen the extracted vector. 10985 SDValue InOp = InVec.getOperand(0); 10986 if (InOp.getValueType() != NVT) { 10987 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 10988 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 10989 } 10990 return InOp; 10991 } 10992 10993 SDValue EltNo = N->getOperand(1); 10994 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 10995 10996 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 10997 // We only perform this optimization before the op legalization phase because 10998 // we may introduce new vector instructions which are not backed by TD 10999 // patterns. For example on AVX, extracting elements from a wide vector 11000 // without using extract_subvector. However, if we can find an underlying 11001 // scalar value, then we can always use that. 11002 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 11003 && ConstEltNo) { 11004 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11005 int NumElem = VT.getVectorNumElements(); 11006 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 11007 // Find the new index to extract from. 11008 int OrigElt = SVOp->getMaskElt(Elt); 11009 11010 // Extracting an undef index is undef. 11011 if (OrigElt == -1) 11012 return DAG.getUNDEF(NVT); 11013 11014 // Select the right vector half to extract from. 11015 SDValue SVInVec; 11016 if (OrigElt < NumElem) { 11017 SVInVec = InVec->getOperand(0); 11018 } else { 11019 SVInVec = InVec->getOperand(1); 11020 OrigElt -= NumElem; 11021 } 11022 11023 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 11024 SDValue InOp = SVInVec.getOperand(OrigElt); 11025 if (InOp.getValueType() != NVT) { 11026 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11027 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 11028 } 11029 11030 return InOp; 11031 } 11032 11033 // FIXME: We should handle recursing on other vector shuffles and 11034 // scalar_to_vector here as well. 11035 11036 if (!LegalOperations) { 11037 EVT IndexTy = TLI.getVectorIdxTy(); 11038 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 11039 SVInVec, DAG.getConstant(OrigElt, IndexTy)); 11040 } 11041 } 11042 11043 bool BCNumEltsChanged = false; 11044 EVT ExtVT = VT.getVectorElementType(); 11045 EVT LVT = ExtVT; 11046 11047 // If the result of load has to be truncated, then it's not necessarily 11048 // profitable. 11049 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 11050 return SDValue(); 11051 11052 if (InVec.getOpcode() == ISD::BITCAST) { 11053 // Don't duplicate a load with other uses. 11054 if (!InVec.hasOneUse()) 11055 return SDValue(); 11056 11057 EVT BCVT = InVec.getOperand(0).getValueType(); 11058 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 11059 return SDValue(); 11060 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 11061 BCNumEltsChanged = true; 11062 InVec = InVec.getOperand(0); 11063 ExtVT = BCVT.getVectorElementType(); 11064 } 11065 11066 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 11067 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 11068 ISD::isNormalLoad(InVec.getNode()) && 11069 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 11070 SDValue Index = N->getOperand(1); 11071 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 11072 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 11073 OrigLoad); 11074 } 11075 11076 // Perform only after legalization to ensure build_vector / vector_shuffle 11077 // optimizations have already been done. 11078 if (!LegalOperations) return SDValue(); 11079 11080 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 11081 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 11082 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 11083 11084 if (ConstEltNo) { 11085 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11086 11087 LoadSDNode *LN0 = nullptr; 11088 const ShuffleVectorSDNode *SVN = nullptr; 11089 if (ISD::isNormalLoad(InVec.getNode())) { 11090 LN0 = cast<LoadSDNode>(InVec); 11091 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 11092 InVec.getOperand(0).getValueType() == ExtVT && 11093 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 11094 // Don't duplicate a load with other uses. 11095 if (!InVec.hasOneUse()) 11096 return SDValue(); 11097 11098 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 11099 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 11100 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 11101 // => 11102 // (load $addr+1*size) 11103 11104 // Don't duplicate a load with other uses. 11105 if (!InVec.hasOneUse()) 11106 return SDValue(); 11107 11108 // If the bit convert changed the number of elements, it is unsafe 11109 // to examine the mask. 11110 if (BCNumEltsChanged) 11111 return SDValue(); 11112 11113 // Select the input vector, guarding against out of range extract vector. 11114 unsigned NumElems = VT.getVectorNumElements(); 11115 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 11116 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 11117 11118 if (InVec.getOpcode() == ISD::BITCAST) { 11119 // Don't duplicate a load with other uses. 11120 if (!InVec.hasOneUse()) 11121 return SDValue(); 11122 11123 InVec = InVec.getOperand(0); 11124 } 11125 if (ISD::isNormalLoad(InVec.getNode())) { 11126 LN0 = cast<LoadSDNode>(InVec); 11127 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 11128 EltNo = DAG.getConstant(Elt, EltNo.getValueType()); 11129 } 11130 } 11131 11132 // Make sure we found a non-volatile load and the extractelement is 11133 // the only use. 11134 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 11135 return SDValue(); 11136 11137 // If Idx was -1 above, Elt is going to be -1, so just return undef. 11138 if (Elt == -1) 11139 return DAG.getUNDEF(LVT); 11140 11141 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 11142 } 11143 11144 return SDValue(); 11145 } 11146 11147 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 11148 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 11149 // We perform this optimization post type-legalization because 11150 // the type-legalizer often scalarizes integer-promoted vectors. 11151 // Performing this optimization before may create bit-casts which 11152 // will be type-legalized to complex code sequences. 11153 // We perform this optimization only before the operation legalizer because we 11154 // may introduce illegal operations. 11155 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 11156 return SDValue(); 11157 11158 unsigned NumInScalars = N->getNumOperands(); 11159 SDLoc dl(N); 11160 EVT VT = N->getValueType(0); 11161 11162 // Check to see if this is a BUILD_VECTOR of a bunch of values 11163 // which come from any_extend or zero_extend nodes. If so, we can create 11164 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 11165 // optimizations. We do not handle sign-extend because we can't fill the sign 11166 // using shuffles. 11167 EVT SourceType = MVT::Other; 11168 bool AllAnyExt = true; 11169 11170 for (unsigned i = 0; i != NumInScalars; ++i) { 11171 SDValue In = N->getOperand(i); 11172 // Ignore undef inputs. 11173 if (In.getOpcode() == ISD::UNDEF) continue; 11174 11175 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 11176 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 11177 11178 // Abort if the element is not an extension. 11179 if (!ZeroExt && !AnyExt) { 11180 SourceType = MVT::Other; 11181 break; 11182 } 11183 11184 // The input is a ZeroExt or AnyExt. Check the original type. 11185 EVT InTy = In.getOperand(0).getValueType(); 11186 11187 // Check that all of the widened source types are the same. 11188 if (SourceType == MVT::Other) 11189 // First time. 11190 SourceType = InTy; 11191 else if (InTy != SourceType) { 11192 // Multiple income types. Abort. 11193 SourceType = MVT::Other; 11194 break; 11195 } 11196 11197 // Check if all of the extends are ANY_EXTENDs. 11198 AllAnyExt &= AnyExt; 11199 } 11200 11201 // In order to have valid types, all of the inputs must be extended from the 11202 // same source type and all of the inputs must be any or zero extend. 11203 // Scalar sizes must be a power of two. 11204 EVT OutScalarTy = VT.getScalarType(); 11205 bool ValidTypes = SourceType != MVT::Other && 11206 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 11207 isPowerOf2_32(SourceType.getSizeInBits()); 11208 11209 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 11210 // turn into a single shuffle instruction. 11211 if (!ValidTypes) 11212 return SDValue(); 11213 11214 bool isLE = TLI.isLittleEndian(); 11215 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 11216 assert(ElemRatio > 1 && "Invalid element size ratio"); 11217 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 11218 DAG.getConstant(0, SourceType); 11219 11220 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 11221 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 11222 11223 // Populate the new build_vector 11224 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11225 SDValue Cast = N->getOperand(i); 11226 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 11227 Cast.getOpcode() == ISD::ZERO_EXTEND || 11228 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 11229 SDValue In; 11230 if (Cast.getOpcode() == ISD::UNDEF) 11231 In = DAG.getUNDEF(SourceType); 11232 else 11233 In = Cast->getOperand(0); 11234 unsigned Index = isLE ? (i * ElemRatio) : 11235 (i * ElemRatio + (ElemRatio - 1)); 11236 11237 assert(Index < Ops.size() && "Invalid index"); 11238 Ops[Index] = In; 11239 } 11240 11241 // The type of the new BUILD_VECTOR node. 11242 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 11243 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 11244 "Invalid vector size"); 11245 // Check if the new vector type is legal. 11246 if (!isTypeLegal(VecVT)) return SDValue(); 11247 11248 // Make the new BUILD_VECTOR. 11249 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 11250 11251 // The new BUILD_VECTOR node has the potential to be further optimized. 11252 AddToWorklist(BV.getNode()); 11253 // Bitcast to the desired type. 11254 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11255 } 11256 11257 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 11258 EVT VT = N->getValueType(0); 11259 11260 unsigned NumInScalars = N->getNumOperands(); 11261 SDLoc dl(N); 11262 11263 EVT SrcVT = MVT::Other; 11264 unsigned Opcode = ISD::DELETED_NODE; 11265 unsigned NumDefs = 0; 11266 11267 for (unsigned i = 0; i != NumInScalars; ++i) { 11268 SDValue In = N->getOperand(i); 11269 unsigned Opc = In.getOpcode(); 11270 11271 if (Opc == ISD::UNDEF) 11272 continue; 11273 11274 // If all scalar values are floats and converted from integers. 11275 if (Opcode == ISD::DELETED_NODE && 11276 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 11277 Opcode = Opc; 11278 } 11279 11280 if (Opc != Opcode) 11281 return SDValue(); 11282 11283 EVT InVT = In.getOperand(0).getValueType(); 11284 11285 // If all scalar values are typed differently, bail out. It's chosen to 11286 // simplify BUILD_VECTOR of integer types. 11287 if (SrcVT == MVT::Other) 11288 SrcVT = InVT; 11289 if (SrcVT != InVT) 11290 return SDValue(); 11291 NumDefs++; 11292 } 11293 11294 // If the vector has just one element defined, it's not worth to fold it into 11295 // a vectorized one. 11296 if (NumDefs < 2) 11297 return SDValue(); 11298 11299 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 11300 && "Should only handle conversion from integer to float."); 11301 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 11302 11303 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 11304 11305 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 11306 return SDValue(); 11307 11308 // Just because the floating-point vector type is legal does not necessarily 11309 // mean that the corresponding integer vector type is. 11310 if (!isTypeLegal(NVT)) 11311 return SDValue(); 11312 11313 SmallVector<SDValue, 8> Opnds; 11314 for (unsigned i = 0; i != NumInScalars; ++i) { 11315 SDValue In = N->getOperand(i); 11316 11317 if (In.getOpcode() == ISD::UNDEF) 11318 Opnds.push_back(DAG.getUNDEF(SrcVT)); 11319 else 11320 Opnds.push_back(In.getOperand(0)); 11321 } 11322 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 11323 AddToWorklist(BV.getNode()); 11324 11325 return DAG.getNode(Opcode, dl, VT, BV); 11326 } 11327 11328 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 11329 unsigned NumInScalars = N->getNumOperands(); 11330 SDLoc dl(N); 11331 EVT VT = N->getValueType(0); 11332 11333 // A vector built entirely of undefs is undef. 11334 if (ISD::allOperandsUndef(N)) 11335 return DAG.getUNDEF(VT); 11336 11337 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 11338 return V; 11339 11340 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 11341 return V; 11342 11343 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 11344 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 11345 // at most two distinct vectors, turn this into a shuffle node. 11346 11347 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 11348 if (!isTypeLegal(VT)) 11349 return SDValue(); 11350 11351 // May only combine to shuffle after legalize if shuffle is legal. 11352 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 11353 return SDValue(); 11354 11355 SDValue VecIn1, VecIn2; 11356 bool UsesZeroVector = false; 11357 for (unsigned i = 0; i != NumInScalars; ++i) { 11358 SDValue Op = N->getOperand(i); 11359 // Ignore undef inputs. 11360 if (Op.getOpcode() == ISD::UNDEF) continue; 11361 11362 // See if we can combine this build_vector into a blend with a zero vector. 11363 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant && 11364 cast<ConstantSDNode>(Op.getNode())->isNullValue()) || 11365 (Op.getOpcode() == ISD::ConstantFP && 11366 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) { 11367 UsesZeroVector = true; 11368 continue; 11369 } 11370 11371 // If this input is something other than a EXTRACT_VECTOR_ELT with a 11372 // constant index, bail out. 11373 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11374 !isa<ConstantSDNode>(Op.getOperand(1))) { 11375 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11376 break; 11377 } 11378 11379 // We allow up to two distinct input vectors. 11380 SDValue ExtractedFromVec = Op.getOperand(0); 11381 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 11382 continue; 11383 11384 if (!VecIn1.getNode()) { 11385 VecIn1 = ExtractedFromVec; 11386 } else if (!VecIn2.getNode() && !UsesZeroVector) { 11387 VecIn2 = ExtractedFromVec; 11388 } else { 11389 // Too many inputs. 11390 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11391 break; 11392 } 11393 } 11394 11395 // If everything is good, we can make a shuffle operation. 11396 if (VecIn1.getNode()) { 11397 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 11398 SmallVector<int, 8> Mask; 11399 for (unsigned i = 0; i != NumInScalars; ++i) { 11400 unsigned Opcode = N->getOperand(i).getOpcode(); 11401 if (Opcode == ISD::UNDEF) { 11402 Mask.push_back(-1); 11403 continue; 11404 } 11405 11406 // Operands can also be zero. 11407 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 11408 assert(UsesZeroVector && 11409 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 11410 "Unexpected node found!"); 11411 Mask.push_back(NumInScalars+i); 11412 continue; 11413 } 11414 11415 // If extracting from the first vector, just use the index directly. 11416 SDValue Extract = N->getOperand(i); 11417 SDValue ExtVal = Extract.getOperand(1); 11418 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 11419 if (Extract.getOperand(0) == VecIn1) { 11420 Mask.push_back(ExtIndex); 11421 continue; 11422 } 11423 11424 // Otherwise, use InIdx + InputVecSize 11425 Mask.push_back(InNumElements + ExtIndex); 11426 } 11427 11428 // Avoid introducing illegal shuffles with zero. 11429 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 11430 return SDValue(); 11431 11432 // We can't generate a shuffle node with mismatched input and output types. 11433 // Attempt to transform a single input vector to the correct type. 11434 if ((VT != VecIn1.getValueType())) { 11435 // If the input vector type has a different base type to the output 11436 // vector type, bail out. 11437 EVT VTElemType = VT.getVectorElementType(); 11438 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 11439 (VecIn2.getNode() && 11440 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 11441 return SDValue(); 11442 11443 // If the input vector is too small, widen it. 11444 // We only support widening of vectors which are half the size of the 11445 // output registers. For example XMM->YMM widening on X86 with AVX. 11446 EVT VecInT = VecIn1.getValueType(); 11447 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 11448 // If we only have one small input, widen it by adding undef values. 11449 if (!VecIn2.getNode()) 11450 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 11451 DAG.getUNDEF(VecIn1.getValueType())); 11452 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 11453 // If we have two small inputs of the same type, try to concat them. 11454 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 11455 VecIn2 = SDValue(nullptr, 0); 11456 } else 11457 return SDValue(); 11458 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 11459 // If the input vector is too large, try to split it. 11460 // We don't support having two input vectors that are too large. 11461 // If the zero vector was used, we can not split the vector, 11462 // since we'd need 3 inputs. 11463 if (UsesZeroVector || VecIn2.getNode()) 11464 return SDValue(); 11465 11466 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 11467 return SDValue(); 11468 11469 // Try to replace VecIn1 with two extract_subvectors 11470 // No need to update the masks, they should still be correct. 11471 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11472 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy())); 11473 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11474 DAG.getConstant(0, TLI.getVectorIdxTy())); 11475 } else 11476 return SDValue(); 11477 } 11478 11479 if (UsesZeroVector) 11480 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) : 11481 DAG.getConstantFP(0.0, VT); 11482 else 11483 // If VecIn2 is unused then change it to undef. 11484 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 11485 11486 // Check that we were able to transform all incoming values to the same 11487 // type. 11488 if (VecIn2.getValueType() != VecIn1.getValueType() || 11489 VecIn1.getValueType() != VT) 11490 return SDValue(); 11491 11492 // Return the new VECTOR_SHUFFLE node. 11493 SDValue Ops[2]; 11494 Ops[0] = VecIn1; 11495 Ops[1] = VecIn2; 11496 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 11497 } 11498 11499 return SDValue(); 11500 } 11501 11502 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 11503 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 11504 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 11505 // inputs come from at most two distinct vectors, turn this into a shuffle 11506 // node. 11507 11508 // If we only have one input vector, we don't need to do any concatenation. 11509 if (N->getNumOperands() == 1) 11510 return N->getOperand(0); 11511 11512 // Check if all of the operands are undefs. 11513 EVT VT = N->getValueType(0); 11514 if (ISD::allOperandsUndef(N)) 11515 return DAG.getUNDEF(VT); 11516 11517 // Optimize concat_vectors where all but the first of the vectors are undef. 11518 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 11519 return Op.getOpcode() == ISD::UNDEF; 11520 })) { 11521 SDValue In = N->getOperand(0); 11522 assert(In.getValueType().isVector() && "Must concat vectors"); 11523 11524 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 11525 if (In->getOpcode() == ISD::BITCAST && 11526 !In->getOperand(0)->getValueType(0).isVector()) { 11527 SDValue Scalar = In->getOperand(0); 11528 11529 // If the bitcast type isn't legal, it might be a trunc of a legal type; 11530 // look through the trunc so we can still do the transform: 11531 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 11532 if (Scalar->getOpcode() == ISD::TRUNCATE && 11533 !TLI.isTypeLegal(Scalar.getValueType()) && 11534 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 11535 Scalar = Scalar->getOperand(0); 11536 11537 EVT SclTy = Scalar->getValueType(0); 11538 11539 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 11540 return SDValue(); 11541 11542 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 11543 VT.getSizeInBits() / SclTy.getSizeInBits()); 11544 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 11545 return SDValue(); 11546 11547 SDLoc dl = SDLoc(N); 11548 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 11549 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 11550 } 11551 } 11552 11553 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 11554 // We have already tested above for an UNDEF only concatenation. 11555 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 11556 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 11557 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 11558 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 11559 }; 11560 bool AllBuildVectorsOrUndefs = 11561 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 11562 if (AllBuildVectorsOrUndefs) { 11563 SmallVector<SDValue, 8> Opnds; 11564 EVT SVT = VT.getScalarType(); 11565 11566 EVT MinVT = SVT; 11567 if (!SVT.isFloatingPoint()) { 11568 // If BUILD_VECTOR are from built from integer, they may have different 11569 // operand types. Get the smallest type and truncate all operands to it. 11570 bool FoundMinVT = false; 11571 for (const SDValue &Op : N->ops()) 11572 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 11573 EVT OpSVT = Op.getOperand(0)->getValueType(0); 11574 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 11575 FoundMinVT = true; 11576 } 11577 assert(FoundMinVT && "Concat vector type mismatch"); 11578 } 11579 11580 for (const SDValue &Op : N->ops()) { 11581 EVT OpVT = Op.getValueType(); 11582 unsigned NumElts = OpVT.getVectorNumElements(); 11583 11584 if (ISD::UNDEF == Op.getOpcode()) 11585 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 11586 11587 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 11588 if (SVT.isFloatingPoint()) { 11589 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 11590 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 11591 } else { 11592 for (unsigned i = 0; i != NumElts; ++i) 11593 Opnds.push_back( 11594 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 11595 } 11596 } 11597 } 11598 11599 assert(VT.getVectorNumElements() == Opnds.size() && 11600 "Concat vector type mismatch"); 11601 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 11602 } 11603 11604 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 11605 // nodes often generate nop CONCAT_VECTOR nodes. 11606 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 11607 // place the incoming vectors at the exact same location. 11608 SDValue SingleSource = SDValue(); 11609 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 11610 11611 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11612 SDValue Op = N->getOperand(i); 11613 11614 if (Op.getOpcode() == ISD::UNDEF) 11615 continue; 11616 11617 // Check if this is the identity extract: 11618 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 11619 return SDValue(); 11620 11621 // Find the single incoming vector for the extract_subvector. 11622 if (SingleSource.getNode()) { 11623 if (Op.getOperand(0) != SingleSource) 11624 return SDValue(); 11625 } else { 11626 SingleSource = Op.getOperand(0); 11627 11628 // Check the source type is the same as the type of the result. 11629 // If not, this concat may extend the vector, so we can not 11630 // optimize it away. 11631 if (SingleSource.getValueType() != N->getValueType(0)) 11632 return SDValue(); 11633 } 11634 11635 unsigned IdentityIndex = i * PartNumElem; 11636 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 11637 // The extract index must be constant. 11638 if (!CS) 11639 return SDValue(); 11640 11641 // Check that we are reading from the identity index. 11642 if (CS->getZExtValue() != IdentityIndex) 11643 return SDValue(); 11644 } 11645 11646 if (SingleSource.getNode()) 11647 return SingleSource; 11648 11649 return SDValue(); 11650 } 11651 11652 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 11653 EVT NVT = N->getValueType(0); 11654 SDValue V = N->getOperand(0); 11655 11656 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 11657 // Combine: 11658 // (extract_subvec (concat V1, V2, ...), i) 11659 // Into: 11660 // Vi if possible 11661 // Only operand 0 is checked as 'concat' assumes all inputs of the same 11662 // type. 11663 if (V->getOperand(0).getValueType() != NVT) 11664 return SDValue(); 11665 unsigned Idx = N->getConstantOperandVal(1); 11666 unsigned NumElems = NVT.getVectorNumElements(); 11667 assert((Idx % NumElems) == 0 && 11668 "IDX in concat is not a multiple of the result vector length."); 11669 return V->getOperand(Idx / NumElems); 11670 } 11671 11672 // Skip bitcasting 11673 if (V->getOpcode() == ISD::BITCAST) 11674 V = V.getOperand(0); 11675 11676 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 11677 SDLoc dl(N); 11678 // Handle only simple case where vector being inserted and vector 11679 // being extracted are of same type, and are half size of larger vectors. 11680 EVT BigVT = V->getOperand(0).getValueType(); 11681 EVT SmallVT = V->getOperand(1).getValueType(); 11682 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 11683 return SDValue(); 11684 11685 // Only handle cases where both indexes are constants with the same type. 11686 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11687 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 11688 11689 if (InsIdx && ExtIdx && 11690 InsIdx->getValueType(0).getSizeInBits() <= 64 && 11691 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 11692 // Combine: 11693 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 11694 // Into: 11695 // indices are equal or bit offsets are equal => V1 11696 // otherwise => (extract_subvec V1, ExtIdx) 11697 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 11698 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 11699 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 11700 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 11701 DAG.getNode(ISD::BITCAST, dl, 11702 N->getOperand(0).getValueType(), 11703 V->getOperand(0)), N->getOperand(1)); 11704 } 11705 } 11706 11707 return SDValue(); 11708 } 11709 11710 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 11711 SDValue V, SelectionDAG &DAG) { 11712 SDLoc DL(V); 11713 EVT VT = V.getValueType(); 11714 11715 switch (V.getOpcode()) { 11716 default: 11717 return V; 11718 11719 case ISD::CONCAT_VECTORS: { 11720 EVT OpVT = V->getOperand(0).getValueType(); 11721 int OpSize = OpVT.getVectorNumElements(); 11722 SmallBitVector OpUsedElements(OpSize, false); 11723 bool FoundSimplification = false; 11724 SmallVector<SDValue, 4> NewOps; 11725 NewOps.reserve(V->getNumOperands()); 11726 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 11727 SDValue Op = V->getOperand(i); 11728 bool OpUsed = false; 11729 for (int j = 0; j < OpSize; ++j) 11730 if (UsedElements[i * OpSize + j]) { 11731 OpUsedElements[j] = true; 11732 OpUsed = true; 11733 } 11734 NewOps.push_back( 11735 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 11736 : DAG.getUNDEF(OpVT)); 11737 FoundSimplification |= Op == NewOps.back(); 11738 OpUsedElements.reset(); 11739 } 11740 if (FoundSimplification) 11741 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 11742 return V; 11743 } 11744 11745 case ISD::INSERT_SUBVECTOR: { 11746 SDValue BaseV = V->getOperand(0); 11747 SDValue SubV = V->getOperand(1); 11748 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 11749 if (!IdxN) 11750 return V; 11751 11752 int SubSize = SubV.getValueType().getVectorNumElements(); 11753 int Idx = IdxN->getZExtValue(); 11754 bool SubVectorUsed = false; 11755 SmallBitVector SubUsedElements(SubSize, false); 11756 for (int i = 0; i < SubSize; ++i) 11757 if (UsedElements[i + Idx]) { 11758 SubVectorUsed = true; 11759 SubUsedElements[i] = true; 11760 UsedElements[i + Idx] = false; 11761 } 11762 11763 // Now recurse on both the base and sub vectors. 11764 SDValue SimplifiedSubV = 11765 SubVectorUsed 11766 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 11767 : DAG.getUNDEF(SubV.getValueType()); 11768 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 11769 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 11770 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 11771 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 11772 return V; 11773 } 11774 } 11775 } 11776 11777 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 11778 SDValue N1, SelectionDAG &DAG) { 11779 EVT VT = SVN->getValueType(0); 11780 int NumElts = VT.getVectorNumElements(); 11781 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 11782 for (int M : SVN->getMask()) 11783 if (M >= 0 && M < NumElts) 11784 N0UsedElements[M] = true; 11785 else if (M >= NumElts) 11786 N1UsedElements[M - NumElts] = true; 11787 11788 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 11789 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 11790 if (S0 == N0 && S1 == N1) 11791 return SDValue(); 11792 11793 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 11794 } 11795 11796 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 11797 // or turn a shuffle of a single concat into simpler shuffle then concat. 11798 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 11799 EVT VT = N->getValueType(0); 11800 unsigned NumElts = VT.getVectorNumElements(); 11801 11802 SDValue N0 = N->getOperand(0); 11803 SDValue N1 = N->getOperand(1); 11804 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11805 11806 SmallVector<SDValue, 4> Ops; 11807 EVT ConcatVT = N0.getOperand(0).getValueType(); 11808 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 11809 unsigned NumConcats = NumElts / NumElemsPerConcat; 11810 11811 // Special case: shuffle(concat(A,B)) can be more efficiently represented 11812 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 11813 // half vector elements. 11814 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 11815 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 11816 SVN->getMask().end(), [](int i) { return i == -1; })) { 11817 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 11818 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat)); 11819 N1 = DAG.getUNDEF(ConcatVT); 11820 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 11821 } 11822 11823 // Look at every vector that's inserted. We're looking for exact 11824 // subvector-sized copies from a concatenated vector 11825 for (unsigned I = 0; I != NumConcats; ++I) { 11826 // Make sure we're dealing with a copy. 11827 unsigned Begin = I * NumElemsPerConcat; 11828 bool AllUndef = true, NoUndef = true; 11829 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 11830 if (SVN->getMaskElt(J) >= 0) 11831 AllUndef = false; 11832 else 11833 NoUndef = false; 11834 } 11835 11836 if (NoUndef) { 11837 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 11838 return SDValue(); 11839 11840 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 11841 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 11842 return SDValue(); 11843 11844 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 11845 if (FirstElt < N0.getNumOperands()) 11846 Ops.push_back(N0.getOperand(FirstElt)); 11847 else 11848 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 11849 11850 } else if (AllUndef) { 11851 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 11852 } else { // Mixed with general masks and undefs, can't do optimization. 11853 return SDValue(); 11854 } 11855 } 11856 11857 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 11858 } 11859 11860 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 11861 EVT VT = N->getValueType(0); 11862 unsigned NumElts = VT.getVectorNumElements(); 11863 11864 SDValue N0 = N->getOperand(0); 11865 SDValue N1 = N->getOperand(1); 11866 11867 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 11868 11869 // Canonicalize shuffle undef, undef -> undef 11870 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 11871 return DAG.getUNDEF(VT); 11872 11873 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11874 11875 // Canonicalize shuffle v, v -> v, undef 11876 if (N0 == N1) { 11877 SmallVector<int, 8> NewMask; 11878 for (unsigned i = 0; i != NumElts; ++i) { 11879 int Idx = SVN->getMaskElt(i); 11880 if (Idx >= (int)NumElts) Idx -= NumElts; 11881 NewMask.push_back(Idx); 11882 } 11883 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 11884 &NewMask[0]); 11885 } 11886 11887 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 11888 if (N0.getOpcode() == ISD::UNDEF) { 11889 SmallVector<int, 8> NewMask; 11890 for (unsigned i = 0; i != NumElts; ++i) { 11891 int Idx = SVN->getMaskElt(i); 11892 if (Idx >= 0) { 11893 if (Idx >= (int)NumElts) 11894 Idx -= NumElts; 11895 else 11896 Idx = -1; // remove reference to lhs 11897 } 11898 NewMask.push_back(Idx); 11899 } 11900 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 11901 &NewMask[0]); 11902 } 11903 11904 // Remove references to rhs if it is undef 11905 if (N1.getOpcode() == ISD::UNDEF) { 11906 bool Changed = false; 11907 SmallVector<int, 8> NewMask; 11908 for (unsigned i = 0; i != NumElts; ++i) { 11909 int Idx = SVN->getMaskElt(i); 11910 if (Idx >= (int)NumElts) { 11911 Idx = -1; 11912 Changed = true; 11913 } 11914 NewMask.push_back(Idx); 11915 } 11916 if (Changed) 11917 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 11918 } 11919 11920 // If it is a splat, check if the argument vector is another splat or a 11921 // build_vector. 11922 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 11923 SDNode *V = N0.getNode(); 11924 11925 // If this is a bit convert that changes the element type of the vector but 11926 // not the number of vector elements, look through it. Be careful not to 11927 // look though conversions that change things like v4f32 to v2f64. 11928 if (V->getOpcode() == ISD::BITCAST) { 11929 SDValue ConvInput = V->getOperand(0); 11930 if (ConvInput.getValueType().isVector() && 11931 ConvInput.getValueType().getVectorNumElements() == NumElts) 11932 V = ConvInput.getNode(); 11933 } 11934 11935 if (V->getOpcode() == ISD::BUILD_VECTOR) { 11936 assert(V->getNumOperands() == NumElts && 11937 "BUILD_VECTOR has wrong number of operands"); 11938 SDValue Base; 11939 bool AllSame = true; 11940 for (unsigned i = 0; i != NumElts; ++i) { 11941 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 11942 Base = V->getOperand(i); 11943 break; 11944 } 11945 } 11946 // Splat of <u, u, u, u>, return <u, u, u, u> 11947 if (!Base.getNode()) 11948 return N0; 11949 for (unsigned i = 0; i != NumElts; ++i) { 11950 if (V->getOperand(i) != Base) { 11951 AllSame = false; 11952 break; 11953 } 11954 } 11955 // Splat of <x, x, x, x>, return <x, x, x, x> 11956 if (AllSame) 11957 return N0; 11958 11959 // Canonicalize any other splat as a build_vector. 11960 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 11961 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 11962 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 11963 V->getValueType(0), Ops); 11964 11965 // We may have jumped through bitcasts, so the type of the 11966 // BUILD_VECTOR may not match the type of the shuffle. 11967 if (V->getValueType(0) != VT) 11968 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 11969 return NewBV; 11970 } 11971 } 11972 11973 // There are various patterns used to build up a vector from smaller vectors, 11974 // subvectors, or elements. Scan chains of these and replace unused insertions 11975 // or components with undef. 11976 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 11977 return S; 11978 11979 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 11980 Level < AfterLegalizeVectorOps && 11981 (N1.getOpcode() == ISD::UNDEF || 11982 (N1.getOpcode() == ISD::CONCAT_VECTORS && 11983 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 11984 SDValue V = partitionShuffleOfConcats(N, DAG); 11985 11986 if (V.getNode()) 11987 return V; 11988 } 11989 11990 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 11991 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 11992 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 11993 SmallVector<SDValue, 8> Ops; 11994 for (int M : SVN->getMask()) { 11995 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 11996 if (M >= 0) { 11997 int Idx = M % NumElts; 11998 SDValue &S = (M < (int)NumElts ? N0 : N1); 11999 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 12000 Op = S.getOperand(Idx); 12001 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 12002 if (Idx == 0) 12003 Op = S.getOperand(0); 12004 } else { 12005 // Operand can't be combined - bail out. 12006 break; 12007 } 12008 } 12009 Ops.push_back(Op); 12010 } 12011 if (Ops.size() == VT.getVectorNumElements()) { 12012 // BUILD_VECTOR requires all inputs to be of the same type, find the 12013 // maximum type and extend them all. 12014 EVT SVT = VT.getScalarType(); 12015 if (SVT.isInteger()) 12016 for (SDValue &Op : Ops) 12017 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 12018 if (SVT != VT.getScalarType()) 12019 for (SDValue &Op : Ops) 12020 Op = TLI.isZExtFree(Op.getValueType(), SVT) 12021 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 12022 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 12023 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 12024 } 12025 } 12026 12027 // If this shuffle only has a single input that is a bitcasted shuffle, 12028 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 12029 // back to their original types. 12030 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 12031 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 12032 TLI.isTypeLegal(VT)) { 12033 12034 // Peek through the bitcast only if there is one user. 12035 SDValue BC0 = N0; 12036 while (BC0.getOpcode() == ISD::BITCAST) { 12037 if (!BC0.hasOneUse()) 12038 break; 12039 BC0 = BC0.getOperand(0); 12040 } 12041 12042 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 12043 if (Scale == 1) 12044 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 12045 12046 SmallVector<int, 8> NewMask; 12047 for (int M : Mask) 12048 for (int s = 0; s != Scale; ++s) 12049 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 12050 return NewMask; 12051 }; 12052 12053 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 12054 EVT SVT = VT.getScalarType(); 12055 EVT InnerVT = BC0->getValueType(0); 12056 EVT InnerSVT = InnerVT.getScalarType(); 12057 12058 // Determine which shuffle works with the smaller scalar type. 12059 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 12060 EVT ScaleSVT = ScaleVT.getScalarType(); 12061 12062 if (TLI.isTypeLegal(ScaleVT) && 12063 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 12064 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 12065 12066 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 12067 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 12068 12069 // Scale the shuffle masks to the smaller scalar type. 12070 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 12071 SmallVector<int, 8> InnerMask = 12072 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 12073 SmallVector<int, 8> OuterMask = 12074 ScaleShuffleMask(SVN->getMask(), OuterScale); 12075 12076 // Merge the shuffle masks. 12077 SmallVector<int, 8> NewMask; 12078 for (int M : OuterMask) 12079 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 12080 12081 // Test for shuffle mask legality over both commutations. 12082 SDValue SV0 = BC0->getOperand(0); 12083 SDValue SV1 = BC0->getOperand(1); 12084 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 12085 if (!LegalMask) { 12086 std::swap(SV0, SV1); 12087 ShuffleVectorSDNode::commuteMask(NewMask); 12088 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 12089 } 12090 12091 if (LegalMask) { 12092 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 12093 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 12094 return DAG.getNode( 12095 ISD::BITCAST, SDLoc(N), VT, 12096 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 12097 } 12098 } 12099 } 12100 } 12101 12102 // Canonicalize shuffles according to rules: 12103 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 12104 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 12105 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 12106 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 12107 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 12108 TLI.isTypeLegal(VT)) { 12109 // The incoming shuffle must be of the same type as the result of the 12110 // current shuffle. 12111 assert(N1->getOperand(0).getValueType() == VT && 12112 "Shuffle types don't match"); 12113 12114 SDValue SV0 = N1->getOperand(0); 12115 SDValue SV1 = N1->getOperand(1); 12116 bool HasSameOp0 = N0 == SV0; 12117 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 12118 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 12119 // Commute the operands of this shuffle so that next rule 12120 // will trigger. 12121 return DAG.getCommutedVectorShuffle(*SVN); 12122 } 12123 12124 // Try to fold according to rules: 12125 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12126 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12127 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12128 // Don't try to fold shuffles with illegal type. 12129 // Only fold if this shuffle is the only user of the other shuffle. 12130 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 12131 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 12132 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 12133 12134 // The incoming shuffle must be of the same type as the result of the 12135 // current shuffle. 12136 assert(OtherSV->getOperand(0).getValueType() == VT && 12137 "Shuffle types don't match"); 12138 12139 SDValue SV0, SV1; 12140 SmallVector<int, 4> Mask; 12141 // Compute the combined shuffle mask for a shuffle with SV0 as the first 12142 // operand, and SV1 as the second operand. 12143 for (unsigned i = 0; i != NumElts; ++i) { 12144 int Idx = SVN->getMaskElt(i); 12145 if (Idx < 0) { 12146 // Propagate Undef. 12147 Mask.push_back(Idx); 12148 continue; 12149 } 12150 12151 SDValue CurrentVec; 12152 if (Idx < (int)NumElts) { 12153 // This shuffle index refers to the inner shuffle N0. Lookup the inner 12154 // shuffle mask to identify which vector is actually referenced. 12155 Idx = OtherSV->getMaskElt(Idx); 12156 if (Idx < 0) { 12157 // Propagate Undef. 12158 Mask.push_back(Idx); 12159 continue; 12160 } 12161 12162 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 12163 : OtherSV->getOperand(1); 12164 } else { 12165 // This shuffle index references an element within N1. 12166 CurrentVec = N1; 12167 } 12168 12169 // Simple case where 'CurrentVec' is UNDEF. 12170 if (CurrentVec.getOpcode() == ISD::UNDEF) { 12171 Mask.push_back(-1); 12172 continue; 12173 } 12174 12175 // Canonicalize the shuffle index. We don't know yet if CurrentVec 12176 // will be the first or second operand of the combined shuffle. 12177 Idx = Idx % NumElts; 12178 if (!SV0.getNode() || SV0 == CurrentVec) { 12179 // Ok. CurrentVec is the left hand side. 12180 // Update the mask accordingly. 12181 SV0 = CurrentVec; 12182 Mask.push_back(Idx); 12183 continue; 12184 } 12185 12186 // Bail out if we cannot convert the shuffle pair into a single shuffle. 12187 if (SV1.getNode() && SV1 != CurrentVec) 12188 return SDValue(); 12189 12190 // Ok. CurrentVec is the right hand side. 12191 // Update the mask accordingly. 12192 SV1 = CurrentVec; 12193 Mask.push_back(Idx + NumElts); 12194 } 12195 12196 // Check if all indices in Mask are Undef. In case, propagate Undef. 12197 bool isUndefMask = true; 12198 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 12199 isUndefMask &= Mask[i] < 0; 12200 12201 if (isUndefMask) 12202 return DAG.getUNDEF(VT); 12203 12204 if (!SV0.getNode()) 12205 SV0 = DAG.getUNDEF(VT); 12206 if (!SV1.getNode()) 12207 SV1 = DAG.getUNDEF(VT); 12208 12209 // Avoid introducing shuffles with illegal mask. 12210 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 12211 ShuffleVectorSDNode::commuteMask(Mask); 12212 12213 if (!TLI.isShuffleMaskLegal(Mask, VT)) 12214 return SDValue(); 12215 12216 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 12217 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 12218 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 12219 std::swap(SV0, SV1); 12220 } 12221 12222 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12223 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12224 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12225 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 12226 } 12227 12228 return SDValue(); 12229 } 12230 12231 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 12232 SDValue InVal = N->getOperand(0); 12233 EVT VT = N->getValueType(0); 12234 12235 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 12236 // with a VECTOR_SHUFFLE. 12237 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12238 SDValue InVec = InVal->getOperand(0); 12239 SDValue EltNo = InVal->getOperand(1); 12240 12241 // FIXME: We could support implicit truncation if the shuffle can be 12242 // scaled to a smaller vector scalar type. 12243 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 12244 if (C0 && VT == InVec.getValueType() && 12245 VT.getScalarType() == InVal.getValueType()) { 12246 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 12247 int Elt = C0->getZExtValue(); 12248 NewMask[0] = Elt; 12249 12250 if (TLI.isShuffleMaskLegal(NewMask, VT)) 12251 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 12252 NewMask); 12253 } 12254 } 12255 12256 return SDValue(); 12257 } 12258 12259 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 12260 SDValue N0 = N->getOperand(0); 12261 SDValue N2 = N->getOperand(2); 12262 12263 // If the input vector is a concatenation, and the insert replaces 12264 // one of the halves, we can optimize into a single concat_vectors. 12265 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 12266 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 12267 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 12268 EVT VT = N->getValueType(0); 12269 12270 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12271 // (concat_vectors Z, Y) 12272 if (InsIdx == 0) 12273 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12274 N->getOperand(1), N0.getOperand(1)); 12275 12276 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12277 // (concat_vectors X, Z) 12278 if (InsIdx == VT.getVectorNumElements()/2) 12279 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12280 N0.getOperand(0), N->getOperand(1)); 12281 } 12282 12283 return SDValue(); 12284 } 12285 12286 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 12287 /// with the destination vector and a zero vector. 12288 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 12289 /// vector_shuffle V, Zero, <0, 4, 2, 4> 12290 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 12291 EVT VT = N->getValueType(0); 12292 SDValue LHS = N->getOperand(0); 12293 SDValue RHS = N->getOperand(1); 12294 SDLoc dl(N); 12295 12296 // Make sure we're not running after operation legalization where it 12297 // may have custom lowered the vector shuffles. 12298 if (LegalOperations) 12299 return SDValue(); 12300 12301 if (N->getOpcode() != ISD::AND) 12302 return SDValue(); 12303 12304 if (RHS.getOpcode() == ISD::BITCAST) 12305 RHS = RHS.getOperand(0); 12306 12307 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 12308 SmallVector<int, 8> Indices; 12309 unsigned NumElts = RHS.getNumOperands(); 12310 12311 for (unsigned i = 0; i != NumElts; ++i) { 12312 SDValue Elt = RHS.getOperand(i); 12313 if (!isa<ConstantSDNode>(Elt)) 12314 return SDValue(); 12315 12316 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 12317 Indices.push_back(i); 12318 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 12319 Indices.push_back(NumElts+i); 12320 else 12321 return SDValue(); 12322 } 12323 12324 // Let's see if the target supports this vector_shuffle. 12325 EVT RVT = RHS.getValueType(); 12326 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 12327 return SDValue(); 12328 12329 // Return the new VECTOR_SHUFFLE node. 12330 EVT EltVT = RVT.getVectorElementType(); 12331 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 12332 DAG.getConstant(0, EltVT)); 12333 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps); 12334 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 12335 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 12336 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 12337 } 12338 12339 return SDValue(); 12340 } 12341 12342 /// Visit a binary vector operation, like ADD. 12343 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 12344 assert(N->getValueType(0).isVector() && 12345 "SimplifyVBinOp only works on vectors!"); 12346 12347 SDValue LHS = N->getOperand(0); 12348 SDValue RHS = N->getOperand(1); 12349 12350 if (SDValue Shuffle = XformToShuffleWithZero(N)) 12351 return Shuffle; 12352 12353 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 12354 // this operation. 12355 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 12356 RHS.getOpcode() == ISD::BUILD_VECTOR) { 12357 // Check if both vectors are constants. If not bail out. 12358 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 12359 cast<BuildVectorSDNode>(RHS)->isConstant())) 12360 return SDValue(); 12361 12362 SmallVector<SDValue, 8> Ops; 12363 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 12364 SDValue LHSOp = LHS.getOperand(i); 12365 SDValue RHSOp = RHS.getOperand(i); 12366 12367 // Can't fold divide by zero. 12368 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 12369 N->getOpcode() == ISD::FDIV) { 12370 if ((RHSOp.getOpcode() == ISD::Constant && 12371 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 12372 (RHSOp.getOpcode() == ISD::ConstantFP && 12373 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 12374 break; 12375 } 12376 12377 EVT VT = LHSOp.getValueType(); 12378 EVT RVT = RHSOp.getValueType(); 12379 if (RVT != VT) { 12380 // Integer BUILD_VECTOR operands may have types larger than the element 12381 // size (e.g., when the element type is not legal). Prior to type 12382 // legalization, the types may not match between the two BUILD_VECTORS. 12383 // Truncate one of the operands to make them match. 12384 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 12385 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 12386 } else { 12387 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 12388 VT = RVT; 12389 } 12390 } 12391 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 12392 LHSOp, RHSOp); 12393 if (FoldOp.getOpcode() != ISD::UNDEF && 12394 FoldOp.getOpcode() != ISD::Constant && 12395 FoldOp.getOpcode() != ISD::ConstantFP) 12396 break; 12397 Ops.push_back(FoldOp); 12398 AddToWorklist(FoldOp.getNode()); 12399 } 12400 12401 if (Ops.size() == LHS.getNumOperands()) 12402 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 12403 } 12404 12405 // Type legalization might introduce new shuffles in the DAG. 12406 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 12407 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 12408 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 12409 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 12410 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 12411 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 12412 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 12413 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 12414 12415 if (SVN0->getMask().equals(SVN1->getMask())) { 12416 EVT VT = N->getValueType(0); 12417 SDValue UndefVector = LHS.getOperand(1); 12418 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 12419 LHS.getOperand(0), RHS.getOperand(0)); 12420 AddUsersToWorklist(N); 12421 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 12422 &SVN0->getMask()[0]); 12423 } 12424 } 12425 12426 return SDValue(); 12427 } 12428 12429 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 12430 SDValue N1, SDValue N2){ 12431 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 12432 12433 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 12434 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 12435 12436 // If we got a simplified select_cc node back from SimplifySelectCC, then 12437 // break it down into a new SETCC node, and a new SELECT node, and then return 12438 // the SELECT node, since we were called with a SELECT node. 12439 if (SCC.getNode()) { 12440 // Check to see if we got a select_cc back (to turn into setcc/select). 12441 // Otherwise, just return whatever node we got back, like fabs. 12442 if (SCC.getOpcode() == ISD::SELECT_CC) { 12443 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 12444 N0.getValueType(), 12445 SCC.getOperand(0), SCC.getOperand(1), 12446 SCC.getOperand(4)); 12447 AddToWorklist(SETCC.getNode()); 12448 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 12449 SCC.getOperand(2), SCC.getOperand(3)); 12450 } 12451 12452 return SCC; 12453 } 12454 return SDValue(); 12455 } 12456 12457 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 12458 /// being selected between, see if we can simplify the select. Callers of this 12459 /// should assume that TheSelect is deleted if this returns true. As such, they 12460 /// should return the appropriate thing (e.g. the node) back to the top-level of 12461 /// the DAG combiner loop to avoid it being looked at. 12462 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 12463 SDValue RHS) { 12464 12465 // Cannot simplify select with vector condition 12466 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 12467 12468 // If this is a select from two identical things, try to pull the operation 12469 // through the select. 12470 if (LHS.getOpcode() != RHS.getOpcode() || 12471 !LHS.hasOneUse() || !RHS.hasOneUse()) 12472 return false; 12473 12474 // If this is a load and the token chain is identical, replace the select 12475 // of two loads with a load through a select of the address to load from. 12476 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 12477 // constants have been dropped into the constant pool. 12478 if (LHS.getOpcode() == ISD::LOAD) { 12479 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 12480 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 12481 12482 // Token chains must be identical. 12483 if (LHS.getOperand(0) != RHS.getOperand(0) || 12484 // Do not let this transformation reduce the number of volatile loads. 12485 LLD->isVolatile() || RLD->isVolatile() || 12486 // If this is an EXTLOAD, the VT's must match. 12487 LLD->getMemoryVT() != RLD->getMemoryVT() || 12488 // If this is an EXTLOAD, the kind of extension must match. 12489 (LLD->getExtensionType() != RLD->getExtensionType() && 12490 // The only exception is if one of the extensions is anyext. 12491 LLD->getExtensionType() != ISD::EXTLOAD && 12492 RLD->getExtensionType() != ISD::EXTLOAD) || 12493 // FIXME: this discards src value information. This is 12494 // over-conservative. It would be beneficial to be able to remember 12495 // both potential memory locations. Since we are discarding 12496 // src value info, don't do the transformation if the memory 12497 // locations are not in the default address space. 12498 LLD->getPointerInfo().getAddrSpace() != 0 || 12499 RLD->getPointerInfo().getAddrSpace() != 0 || 12500 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 12501 LLD->getBasePtr().getValueType())) 12502 return false; 12503 12504 // Check that the select condition doesn't reach either load. If so, 12505 // folding this will induce a cycle into the DAG. If not, this is safe to 12506 // xform, so create a select of the addresses. 12507 SDValue Addr; 12508 if (TheSelect->getOpcode() == ISD::SELECT) { 12509 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 12510 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 12511 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 12512 return false; 12513 // The loads must not depend on one another. 12514 if (LLD->isPredecessorOf(RLD) || 12515 RLD->isPredecessorOf(LLD)) 12516 return false; 12517 Addr = DAG.getSelect(SDLoc(TheSelect), 12518 LLD->getBasePtr().getValueType(), 12519 TheSelect->getOperand(0), LLD->getBasePtr(), 12520 RLD->getBasePtr()); 12521 } else { // Otherwise SELECT_CC 12522 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 12523 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 12524 12525 if ((LLD->hasAnyUseOfValue(1) && 12526 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 12527 (RLD->hasAnyUseOfValue(1) && 12528 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 12529 return false; 12530 12531 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 12532 LLD->getBasePtr().getValueType(), 12533 TheSelect->getOperand(0), 12534 TheSelect->getOperand(1), 12535 LLD->getBasePtr(), RLD->getBasePtr(), 12536 TheSelect->getOperand(4)); 12537 } 12538 12539 SDValue Load; 12540 // It is safe to replace the two loads if they have different alignments, 12541 // but the new load must be the minimum (most restrictive) alignment of the 12542 // inputs. 12543 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 12544 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 12545 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 12546 Load = DAG.getLoad(TheSelect->getValueType(0), 12547 SDLoc(TheSelect), 12548 // FIXME: Discards pointer and AA info. 12549 LLD->getChain(), Addr, MachinePointerInfo(), 12550 LLD->isVolatile(), LLD->isNonTemporal(), 12551 isInvariant, Alignment); 12552 } else { 12553 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 12554 RLD->getExtensionType() : LLD->getExtensionType(), 12555 SDLoc(TheSelect), 12556 TheSelect->getValueType(0), 12557 // FIXME: Discards pointer and AA info. 12558 LLD->getChain(), Addr, MachinePointerInfo(), 12559 LLD->getMemoryVT(), LLD->isVolatile(), 12560 LLD->isNonTemporal(), isInvariant, Alignment); 12561 } 12562 12563 // Users of the select now use the result of the load. 12564 CombineTo(TheSelect, Load); 12565 12566 // Users of the old loads now use the new load's chain. We know the 12567 // old-load value is dead now. 12568 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 12569 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 12570 return true; 12571 } 12572 12573 return false; 12574 } 12575 12576 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 12577 /// where 'cond' is the comparison specified by CC. 12578 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 12579 SDValue N2, SDValue N3, 12580 ISD::CondCode CC, bool NotExtCompare) { 12581 // (x ? y : y) -> y. 12582 if (N2 == N3) return N2; 12583 12584 EVT VT = N2.getValueType(); 12585 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 12586 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 12587 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 12588 12589 // Determine if the condition we're dealing with is constant 12590 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 12591 N0, N1, CC, DL, false); 12592 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 12593 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 12594 12595 // fold select_cc true, x, y -> x 12596 if (SCCC && !SCCC->isNullValue()) 12597 return N2; 12598 // fold select_cc false, x, y -> y 12599 if (SCCC && SCCC->isNullValue()) 12600 return N3; 12601 12602 // Check to see if we can simplify the select into an fabs node 12603 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 12604 // Allow either -0.0 or 0.0 12605 if (CFP->getValueAPF().isZero()) { 12606 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 12607 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 12608 N0 == N2 && N3.getOpcode() == ISD::FNEG && 12609 N2 == N3.getOperand(0)) 12610 return DAG.getNode(ISD::FABS, DL, VT, N0); 12611 12612 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 12613 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 12614 N0 == N3 && N2.getOpcode() == ISD::FNEG && 12615 N2.getOperand(0) == N3) 12616 return DAG.getNode(ISD::FABS, DL, VT, N3); 12617 } 12618 } 12619 12620 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 12621 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 12622 // in it. This is a win when the constant is not otherwise available because 12623 // it replaces two constant pool loads with one. We only do this if the FP 12624 // type is known to be legal, because if it isn't, then we are before legalize 12625 // types an we want the other legalization to happen first (e.g. to avoid 12626 // messing with soft float) and if the ConstantFP is not legal, because if 12627 // it is legal, we may not need to store the FP constant in a constant pool. 12628 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 12629 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 12630 if (TLI.isTypeLegal(N2.getValueType()) && 12631 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 12632 TargetLowering::Legal && 12633 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 12634 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 12635 // If both constants have multiple uses, then we won't need to do an 12636 // extra load, they are likely around in registers for other users. 12637 (TV->hasOneUse() || FV->hasOneUse())) { 12638 Constant *Elts[] = { 12639 const_cast<ConstantFP*>(FV->getConstantFPValue()), 12640 const_cast<ConstantFP*>(TV->getConstantFPValue()) 12641 }; 12642 Type *FPTy = Elts[0]->getType(); 12643 const DataLayout &TD = *TLI.getDataLayout(); 12644 12645 // Create a ConstantArray of the two constants. 12646 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 12647 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 12648 TD.getPrefTypeAlignment(FPTy)); 12649 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 12650 12651 // Get the offsets to the 0 and 1 element of the array so that we can 12652 // select between them. 12653 SDValue Zero = DAG.getIntPtrConstant(0); 12654 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 12655 SDValue One = DAG.getIntPtrConstant(EltSize); 12656 12657 SDValue Cond = DAG.getSetCC(DL, 12658 getSetCCResultType(N0.getValueType()), 12659 N0, N1, CC); 12660 AddToWorklist(Cond.getNode()); 12661 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 12662 Cond, One, Zero); 12663 AddToWorklist(CstOffset.getNode()); 12664 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 12665 CstOffset); 12666 AddToWorklist(CPIdx.getNode()); 12667 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 12668 MachinePointerInfo::getConstantPool(), false, 12669 false, false, Alignment); 12670 12671 } 12672 } 12673 12674 // Check to see if we can perform the "gzip trick", transforming 12675 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 12676 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 12677 (N1C->isNullValue() || // (a < 0) ? b : 0 12678 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 12679 EVT XType = N0.getValueType(); 12680 EVT AType = N2.getValueType(); 12681 if (XType.bitsGE(AType)) { 12682 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 12683 // single-bit constant. 12684 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 12685 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 12686 ShCtV = XType.getSizeInBits()-ShCtV-1; 12687 SDValue ShCt = DAG.getConstant(ShCtV, 12688 getShiftAmountTy(N0.getValueType())); 12689 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 12690 XType, N0, ShCt); 12691 AddToWorklist(Shift.getNode()); 12692 12693 if (XType.bitsGT(AType)) { 12694 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 12695 AddToWorklist(Shift.getNode()); 12696 } 12697 12698 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 12699 } 12700 12701 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 12702 XType, N0, 12703 DAG.getConstant(XType.getSizeInBits()-1, 12704 getShiftAmountTy(N0.getValueType()))); 12705 AddToWorklist(Shift.getNode()); 12706 12707 if (XType.bitsGT(AType)) { 12708 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 12709 AddToWorklist(Shift.getNode()); 12710 } 12711 12712 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 12713 } 12714 } 12715 12716 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 12717 // where y is has a single bit set. 12718 // A plaintext description would be, we can turn the SELECT_CC into an AND 12719 // when the condition can be materialized as an all-ones register. Any 12720 // single bit-test can be materialized as an all-ones register with 12721 // shift-left and shift-right-arith. 12722 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 12723 N0->getValueType(0) == VT && 12724 N1C && N1C->isNullValue() && 12725 N2C && N2C->isNullValue()) { 12726 SDValue AndLHS = N0->getOperand(0); 12727 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12728 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 12729 // Shift the tested bit over the sign bit. 12730 APInt AndMask = ConstAndRHS->getAPIntValue(); 12731 SDValue ShlAmt = 12732 DAG.getConstant(AndMask.countLeadingZeros(), 12733 getShiftAmountTy(AndLHS.getValueType())); 12734 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 12735 12736 // Now arithmetic right shift it all the way over, so the result is either 12737 // all-ones, or zero. 12738 SDValue ShrAmt = 12739 DAG.getConstant(AndMask.getBitWidth()-1, 12740 getShiftAmountTy(Shl.getValueType())); 12741 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 12742 12743 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 12744 } 12745 } 12746 12747 // fold select C, 16, 0 -> shl C, 4 12748 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 12749 TLI.getBooleanContents(N0.getValueType()) == 12750 TargetLowering::ZeroOrOneBooleanContent) { 12751 12752 // If the caller doesn't want us to simplify this into a zext of a compare, 12753 // don't do it. 12754 if (NotExtCompare && N2C->getAPIntValue() == 1) 12755 return SDValue(); 12756 12757 // Get a SetCC of the condition 12758 // NOTE: Don't create a SETCC if it's not legal on this target. 12759 if (!LegalOperations || 12760 TLI.isOperationLegal(ISD::SETCC, 12761 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 12762 SDValue Temp, SCC; 12763 // cast from setcc result type to select result type 12764 if (LegalTypes) { 12765 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 12766 N0, N1, CC); 12767 if (N2.getValueType().bitsLT(SCC.getValueType())) 12768 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 12769 N2.getValueType()); 12770 else 12771 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 12772 N2.getValueType(), SCC); 12773 } else { 12774 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 12775 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 12776 N2.getValueType(), SCC); 12777 } 12778 12779 AddToWorklist(SCC.getNode()); 12780 AddToWorklist(Temp.getNode()); 12781 12782 if (N2C->getAPIntValue() == 1) 12783 return Temp; 12784 12785 // shl setcc result by log2 n2c 12786 return DAG.getNode( 12787 ISD::SHL, DL, N2.getValueType(), Temp, 12788 DAG.getConstant(N2C->getAPIntValue().logBase2(), 12789 getShiftAmountTy(Temp.getValueType()))); 12790 } 12791 } 12792 12793 // Check to see if this is the equivalent of setcc 12794 // FIXME: Turn all of these into setcc if setcc if setcc is legal 12795 // otherwise, go ahead with the folds. 12796 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 12797 EVT XType = N0.getValueType(); 12798 if (!LegalOperations || 12799 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 12800 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 12801 if (Res.getValueType() != VT) 12802 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 12803 return Res; 12804 } 12805 12806 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 12807 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 12808 (!LegalOperations || 12809 TLI.isOperationLegal(ISD::CTLZ, XType))) { 12810 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 12811 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 12812 DAG.getConstant(Log2_32(XType.getSizeInBits()), 12813 getShiftAmountTy(Ctlz.getValueType()))); 12814 } 12815 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 12816 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 12817 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 12818 XType, DAG.getConstant(0, XType), N0); 12819 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 12820 return DAG.getNode(ISD::SRL, DL, XType, 12821 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 12822 DAG.getConstant(XType.getSizeInBits()-1, 12823 getShiftAmountTy(XType))); 12824 } 12825 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 12826 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 12827 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 12828 DAG.getConstant(XType.getSizeInBits()-1, 12829 getShiftAmountTy(N0.getValueType()))); 12830 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 12831 } 12832 } 12833 12834 // Check to see if this is an integer abs. 12835 // select_cc setg[te] X, 0, X, -X -> 12836 // select_cc setgt X, -1, X, -X -> 12837 // select_cc setl[te] X, 0, -X, X -> 12838 // select_cc setlt X, 1, -X, X -> 12839 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 12840 if (N1C) { 12841 ConstantSDNode *SubC = nullptr; 12842 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 12843 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 12844 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 12845 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 12846 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 12847 (N1C->isOne() && CC == ISD::SETLT)) && 12848 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 12849 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 12850 12851 EVT XType = N0.getValueType(); 12852 if (SubC && SubC->isNullValue() && XType.isInteger()) { 12853 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 12854 N0, 12855 DAG.getConstant(XType.getSizeInBits()-1, 12856 getShiftAmountTy(N0.getValueType()))); 12857 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 12858 XType, N0, Shift); 12859 AddToWorklist(Shift.getNode()); 12860 AddToWorklist(Add.getNode()); 12861 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 12862 } 12863 } 12864 12865 return SDValue(); 12866 } 12867 12868 /// This is a stub for TargetLowering::SimplifySetCC. 12869 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 12870 SDValue N1, ISD::CondCode Cond, 12871 SDLoc DL, bool foldBooleans) { 12872 TargetLowering::DAGCombinerInfo 12873 DagCombineInfo(DAG, Level, false, this); 12874 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 12875 } 12876 12877 /// Given an ISD::SDIV node expressing a divide by constant, return 12878 /// a DAG expression to select that will generate the same value by multiplying 12879 /// by a magic number. 12880 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 12881 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 12882 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 12883 if (!C) 12884 return SDValue(); 12885 12886 // Avoid division by zero. 12887 if (!C->getAPIntValue()) 12888 return SDValue(); 12889 12890 std::vector<SDNode*> Built; 12891 SDValue S = 12892 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 12893 12894 for (SDNode *N : Built) 12895 AddToWorklist(N); 12896 return S; 12897 } 12898 12899 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 12900 /// DAG expression that will generate the same value by right shifting. 12901 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 12902 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 12903 if (!C) 12904 return SDValue(); 12905 12906 // Avoid division by zero. 12907 if (!C->getAPIntValue()) 12908 return SDValue(); 12909 12910 std::vector<SDNode *> Built; 12911 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 12912 12913 for (SDNode *N : Built) 12914 AddToWorklist(N); 12915 return S; 12916 } 12917 12918 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 12919 /// expression that will generate the same value by multiplying by a magic 12920 /// number. 12921 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 12922 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 12923 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 12924 if (!C) 12925 return SDValue(); 12926 12927 // Avoid division by zero. 12928 if (!C->getAPIntValue()) 12929 return SDValue(); 12930 12931 std::vector<SDNode*> Built; 12932 SDValue S = 12933 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 12934 12935 for (SDNode *N : Built) 12936 AddToWorklist(N); 12937 return S; 12938 } 12939 12940 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) { 12941 if (Level >= AfterLegalizeDAG) 12942 return SDValue(); 12943 12944 // Expose the DAG combiner to the target combiner implementations. 12945 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 12946 12947 unsigned Iterations = 0; 12948 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 12949 if (Iterations) { 12950 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 12951 // For the reciprocal, we need to find the zero of the function: 12952 // F(X) = A X - 1 [which has a zero at X = 1/A] 12953 // => 12954 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 12955 // does not require additional intermediate precision] 12956 EVT VT = Op.getValueType(); 12957 SDLoc DL(Op); 12958 SDValue FPOne = DAG.getConstantFP(1.0, VT); 12959 12960 AddToWorklist(Est.getNode()); 12961 12962 // Newton iterations: Est = Est + Est (1 - Arg * Est) 12963 for (unsigned i = 0; i < Iterations; ++i) { 12964 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est); 12965 AddToWorklist(NewEst.getNode()); 12966 12967 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst); 12968 AddToWorklist(NewEst.getNode()); 12969 12970 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 12971 AddToWorklist(NewEst.getNode()); 12972 12973 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst); 12974 AddToWorklist(Est.getNode()); 12975 } 12976 } 12977 return Est; 12978 } 12979 12980 return SDValue(); 12981 } 12982 12983 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 12984 /// For the reciprocal sqrt, we need to find the zero of the function: 12985 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 12986 /// => 12987 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 12988 /// As a result, we precompute A/2 prior to the iteration loop. 12989 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 12990 unsigned Iterations) { 12991 EVT VT = Arg.getValueType(); 12992 SDLoc DL(Arg); 12993 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT); 12994 12995 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 12996 // this entire sequence requires only one FP constant. 12997 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg); 12998 AddToWorklist(HalfArg.getNode()); 12999 13000 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg); 13001 AddToWorklist(HalfArg.getNode()); 13002 13003 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 13004 for (unsigned i = 0; i < Iterations; ++i) { 13005 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 13006 AddToWorklist(NewEst.getNode()); 13007 13008 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst); 13009 AddToWorklist(NewEst.getNode()); 13010 13011 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst); 13012 AddToWorklist(NewEst.getNode()); 13013 13014 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 13015 AddToWorklist(Est.getNode()); 13016 } 13017 return Est; 13018 } 13019 13020 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13021 /// For the reciprocal sqrt, we need to find the zero of the function: 13022 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 13023 /// => 13024 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 13025 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 13026 unsigned Iterations) { 13027 EVT VT = Arg.getValueType(); 13028 SDLoc DL(Arg); 13029 SDValue MinusThree = DAG.getConstantFP(-3.0, VT); 13030 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT); 13031 13032 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 13033 for (unsigned i = 0; i < Iterations; ++i) { 13034 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf); 13035 AddToWorklist(HalfEst.getNode()); 13036 13037 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 13038 AddToWorklist(Est.getNode()); 13039 13040 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg); 13041 AddToWorklist(Est.getNode()); 13042 13043 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree); 13044 AddToWorklist(Est.getNode()); 13045 13046 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst); 13047 AddToWorklist(Est.getNode()); 13048 } 13049 return Est; 13050 } 13051 13052 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) { 13053 if (Level >= AfterLegalizeDAG) 13054 return SDValue(); 13055 13056 // Expose the DAG combiner to the target combiner implementations. 13057 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 13058 unsigned Iterations = 0; 13059 bool UseOneConstNR = false; 13060 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 13061 AddToWorklist(Est.getNode()); 13062 if (Iterations) { 13063 Est = UseOneConstNR ? 13064 BuildRsqrtNROneConst(Op, Est, Iterations) : 13065 BuildRsqrtNRTwoConst(Op, Est, Iterations); 13066 } 13067 return Est; 13068 } 13069 13070 return SDValue(); 13071 } 13072 13073 /// Return true if base is a frame index, which is known not to alias with 13074 /// anything but itself. Provides base object and offset as results. 13075 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 13076 const GlobalValue *&GV, const void *&CV) { 13077 // Assume it is a primitive operation. 13078 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 13079 13080 // If it's an adding a simple constant then integrate the offset. 13081 if (Base.getOpcode() == ISD::ADD) { 13082 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 13083 Base = Base.getOperand(0); 13084 Offset += C->getZExtValue(); 13085 } 13086 } 13087 13088 // Return the underlying GlobalValue, and update the Offset. Return false 13089 // for GlobalAddressSDNode since the same GlobalAddress may be represented 13090 // by multiple nodes with different offsets. 13091 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 13092 GV = G->getGlobal(); 13093 Offset += G->getOffset(); 13094 return false; 13095 } 13096 13097 // Return the underlying Constant value, and update the Offset. Return false 13098 // for ConstantSDNodes since the same constant pool entry may be represented 13099 // by multiple nodes with different offsets. 13100 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 13101 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 13102 : (const void *)C->getConstVal(); 13103 Offset += C->getOffset(); 13104 return false; 13105 } 13106 // If it's any of the following then it can't alias with anything but itself. 13107 return isa<FrameIndexSDNode>(Base); 13108 } 13109 13110 /// Return true if there is any possibility that the two addresses overlap. 13111 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 13112 // If they are the same then they must be aliases. 13113 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 13114 13115 // If they are both volatile then they cannot be reordered. 13116 if (Op0->isVolatile() && Op1->isVolatile()) return true; 13117 13118 // Gather base node and offset information. 13119 SDValue Base1, Base2; 13120 int64_t Offset1, Offset2; 13121 const GlobalValue *GV1, *GV2; 13122 const void *CV1, *CV2; 13123 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 13124 Base1, Offset1, GV1, CV1); 13125 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 13126 Base2, Offset2, GV2, CV2); 13127 13128 // If they have a same base address then check to see if they overlap. 13129 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 13130 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 13131 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 13132 13133 // It is possible for different frame indices to alias each other, mostly 13134 // when tail call optimization reuses return address slots for arguments. 13135 // To catch this case, look up the actual index of frame indices to compute 13136 // the real alias relationship. 13137 if (isFrameIndex1 && isFrameIndex2) { 13138 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 13139 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 13140 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 13141 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 13142 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 13143 } 13144 13145 // Otherwise, if we know what the bases are, and they aren't identical, then 13146 // we know they cannot alias. 13147 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 13148 return false; 13149 13150 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 13151 // compared to the size and offset of the access, we may be able to prove they 13152 // do not alias. This check is conservative for now to catch cases created by 13153 // splitting vector types. 13154 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 13155 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 13156 (Op0->getMemoryVT().getSizeInBits() >> 3 == 13157 Op1->getMemoryVT().getSizeInBits() >> 3) && 13158 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 13159 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 13160 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 13161 13162 // There is no overlap between these relatively aligned accesses of similar 13163 // size, return no alias. 13164 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 13165 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 13166 return false; 13167 } 13168 13169 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 13170 ? CombinerGlobalAA 13171 : DAG.getSubtarget().useAA(); 13172 #ifndef NDEBUG 13173 if (CombinerAAOnlyFunc.getNumOccurrences() && 13174 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 13175 UseAA = false; 13176 #endif 13177 if (UseAA && 13178 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 13179 // Use alias analysis information. 13180 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 13181 Op1->getSrcValueOffset()); 13182 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 13183 Op0->getSrcValueOffset() - MinOffset; 13184 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 13185 Op1->getSrcValueOffset() - MinOffset; 13186 AliasAnalysis::AliasResult AAResult = 13187 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(), 13188 Overlap1, 13189 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 13190 AliasAnalysis::Location(Op1->getMemOperand()->getValue(), 13191 Overlap2, 13192 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 13193 if (AAResult == AliasAnalysis::NoAlias) 13194 return false; 13195 } 13196 13197 // Otherwise we have to assume they alias. 13198 return true; 13199 } 13200 13201 /// Walk up chain skipping non-aliasing memory nodes, 13202 /// looking for aliasing nodes and adding them to the Aliases vector. 13203 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 13204 SmallVectorImpl<SDValue> &Aliases) { 13205 SmallVector<SDValue, 8> Chains; // List of chains to visit. 13206 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 13207 13208 // Get alias information for node. 13209 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 13210 13211 // Starting off. 13212 Chains.push_back(OriginalChain); 13213 unsigned Depth = 0; 13214 13215 // Look at each chain and determine if it is an alias. If so, add it to the 13216 // aliases list. If not, then continue up the chain looking for the next 13217 // candidate. 13218 while (!Chains.empty()) { 13219 SDValue Chain = Chains.back(); 13220 Chains.pop_back(); 13221 13222 // For TokenFactor nodes, look at each operand and only continue up the 13223 // chain until we find two aliases. If we've seen two aliases, assume we'll 13224 // find more and revert to original chain since the xform is unlikely to be 13225 // profitable. 13226 // 13227 // FIXME: The depth check could be made to return the last non-aliasing 13228 // chain we found before we hit a tokenfactor rather than the original 13229 // chain. 13230 if (Depth > 6 || Aliases.size() == 2) { 13231 Aliases.clear(); 13232 Aliases.push_back(OriginalChain); 13233 return; 13234 } 13235 13236 // Don't bother if we've been before. 13237 if (!Visited.insert(Chain.getNode()).second) 13238 continue; 13239 13240 switch (Chain.getOpcode()) { 13241 case ISD::EntryToken: 13242 // Entry token is ideal chain operand, but handled in FindBetterChain. 13243 break; 13244 13245 case ISD::LOAD: 13246 case ISD::STORE: { 13247 // Get alias information for Chain. 13248 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 13249 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 13250 13251 // If chain is alias then stop here. 13252 if (!(IsLoad && IsOpLoad) && 13253 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 13254 Aliases.push_back(Chain); 13255 } else { 13256 // Look further up the chain. 13257 Chains.push_back(Chain.getOperand(0)); 13258 ++Depth; 13259 } 13260 break; 13261 } 13262 13263 case ISD::TokenFactor: 13264 // We have to check each of the operands of the token factor for "small" 13265 // token factors, so we queue them up. Adding the operands to the queue 13266 // (stack) in reverse order maintains the original order and increases the 13267 // likelihood that getNode will find a matching token factor (CSE.) 13268 if (Chain.getNumOperands() > 16) { 13269 Aliases.push_back(Chain); 13270 break; 13271 } 13272 for (unsigned n = Chain.getNumOperands(); n;) 13273 Chains.push_back(Chain.getOperand(--n)); 13274 ++Depth; 13275 break; 13276 13277 default: 13278 // For all other instructions we will just have to take what we can get. 13279 Aliases.push_back(Chain); 13280 break; 13281 } 13282 } 13283 13284 // We need to be careful here to also search for aliases through the 13285 // value operand of a store, etc. Consider the following situation: 13286 // Token1 = ... 13287 // L1 = load Token1, %52 13288 // S1 = store Token1, L1, %51 13289 // L2 = load Token1, %52+8 13290 // S2 = store Token1, L2, %51+8 13291 // Token2 = Token(S1, S2) 13292 // L3 = load Token2, %53 13293 // S3 = store Token2, L3, %52 13294 // L4 = load Token2, %53+8 13295 // S4 = store Token2, L4, %52+8 13296 // If we search for aliases of S3 (which loads address %52), and we look 13297 // only through the chain, then we'll miss the trivial dependence on L1 13298 // (which also loads from %52). We then might change all loads and 13299 // stores to use Token1 as their chain operand, which could result in 13300 // copying %53 into %52 before copying %52 into %51 (which should 13301 // happen first). 13302 // 13303 // The problem is, however, that searching for such data dependencies 13304 // can become expensive, and the cost is not directly related to the 13305 // chain depth. Instead, we'll rule out such configurations here by 13306 // insisting that we've visited all chain users (except for users 13307 // of the original chain, which is not necessary). When doing this, 13308 // we need to look through nodes we don't care about (otherwise, things 13309 // like register copies will interfere with trivial cases). 13310 13311 SmallVector<const SDNode *, 16> Worklist; 13312 for (const SDNode *N : Visited) 13313 if (N != OriginalChain.getNode()) 13314 Worklist.push_back(N); 13315 13316 while (!Worklist.empty()) { 13317 const SDNode *M = Worklist.pop_back_val(); 13318 13319 // We have already visited M, and want to make sure we've visited any uses 13320 // of M that we care about. For uses that we've not visisted, and don't 13321 // care about, queue them to the worklist. 13322 13323 for (SDNode::use_iterator UI = M->use_begin(), 13324 UIE = M->use_end(); UI != UIE; ++UI) 13325 if (UI.getUse().getValueType() == MVT::Other && 13326 Visited.insert(*UI).second) { 13327 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 13328 // We've not visited this use, and we care about it (it could have an 13329 // ordering dependency with the original node). 13330 Aliases.clear(); 13331 Aliases.push_back(OriginalChain); 13332 return; 13333 } 13334 13335 // We've not visited this use, but we don't care about it. Mark it as 13336 // visited and enqueue it to the worklist. 13337 Worklist.push_back(*UI); 13338 } 13339 } 13340 } 13341 13342 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 13343 /// (aliasing node.) 13344 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 13345 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 13346 13347 // Accumulate all the aliases to this node. 13348 GatherAllAliases(N, OldChain, Aliases); 13349 13350 // If no operands then chain to entry token. 13351 if (Aliases.size() == 0) 13352 return DAG.getEntryNode(); 13353 13354 // If a single operand then chain to it. We don't need to revisit it. 13355 if (Aliases.size() == 1) 13356 return Aliases[0]; 13357 13358 // Construct a custom tailored token factor. 13359 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 13360 } 13361 13362 /// This is the entry point for the file. 13363 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 13364 CodeGenOpt::Level OptLevel) { 13365 /// This is the main entry point to this class. 13366 DAGCombiner(*this, AA, OptLevel).Run(Level); 13367 } 13368