1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 11 // both before and after the DAG is legalized. 12 // 13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 14 // primarily intended to handle simplification opportunities that are implicit 15 // in the LLVM IR and exposed by the various codegen lowering phases. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/CodeGen/SelectionDAG.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallBitVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/AliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetLowering.h" 37 #include "llvm/Target/TargetOptions.h" 38 #include "llvm/Target/TargetRegisterInfo.h" 39 #include "llvm/Target/TargetSubtargetInfo.h" 40 #include <algorithm> 41 using namespace llvm; 42 43 #define DEBUG_TYPE "dagcombine" 44 45 STATISTIC(NodesCombined , "Number of dag nodes combined"); 46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 50 STATISTIC(SlicedLoads, "Number of load sliced"); 51 52 namespace { 53 static cl::opt<bool> 54 CombinerAA("combiner-alias-analysis", cl::Hidden, 55 cl::desc("Enable DAG combiner alias-analysis heuristics")); 56 57 static cl::opt<bool> 58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 59 cl::desc("Enable DAG combiner's use of IR alias analysis")); 60 61 static cl::opt<bool> 62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 63 cl::desc("Enable DAG combiner's use of TBAA")); 64 65 #ifndef NDEBUG 66 static cl::opt<std::string> 67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 68 cl::desc("Only use DAG-combiner alias analysis in this" 69 " function")); 70 #endif 71 72 /// Hidden option to stress test load slicing, i.e., when this option 73 /// is enabled, load slicing bypasses most of its profitability guards. 74 static cl::opt<bool> 75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 76 cl::desc("Bypass the profitability model of load " 77 "slicing"), 78 cl::init(false)); 79 80 static cl::opt<bool> 81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 82 cl::desc("DAG combiner may split indexing from loads")); 83 84 //------------------------------ DAGCombiner ---------------------------------// 85 86 class DAGCombiner { 87 SelectionDAG &DAG; 88 const TargetLowering &TLI; 89 CombineLevel Level; 90 CodeGenOpt::Level OptLevel; 91 bool LegalOperations; 92 bool LegalTypes; 93 bool ForCodeSize; 94 95 /// \brief Worklist of all of the nodes that need to be simplified. 96 /// 97 /// This must behave as a stack -- new nodes to process are pushed onto the 98 /// back and when processing we pop off of the back. 99 /// 100 /// The worklist will not contain duplicates but may contain null entries 101 /// due to nodes being deleted from the underlying DAG. 102 SmallVector<SDNode *, 64> Worklist; 103 104 /// \brief Mapping from an SDNode to its position on the worklist. 105 /// 106 /// This is used to find and remove nodes from the worklist (by nulling 107 /// them) when they are deleted from the underlying DAG. It relies on 108 /// stable indices of nodes within the worklist. 109 DenseMap<SDNode *, unsigned> WorklistMap; 110 111 /// \brief Set of nodes which have been combined (at least once). 112 /// 113 /// This is used to allow us to reliably add any operands of a DAG node 114 /// which have not yet been combined to the worklist. 115 SmallPtrSet<SDNode *, 64> CombinedNodes; 116 117 // AA - Used for DAG load/store alias analysis. 118 AliasAnalysis &AA; 119 120 /// When an instruction is simplified, add all users of the instruction to 121 /// the work lists because they might get more simplified now. 122 void AddUsersToWorklist(SDNode *N) { 123 for (SDNode *Node : N->uses()) 124 AddToWorklist(Node); 125 } 126 127 /// Call the node-specific routine that folds each particular type of node. 128 SDValue visit(SDNode *N); 129 130 public: 131 /// Add to the worklist making sure its instance is at the back (next to be 132 /// processed.) 133 void AddToWorklist(SDNode *N) { 134 // Skip handle nodes as they can't usefully be combined and confuse the 135 // zero-use deletion strategy. 136 if (N->getOpcode() == ISD::HANDLENODE) 137 return; 138 139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 140 Worklist.push_back(N); 141 } 142 143 /// Remove all instances of N from the worklist. 144 void removeFromWorklist(SDNode *N) { 145 CombinedNodes.erase(N); 146 147 auto It = WorklistMap.find(N); 148 if (It == WorklistMap.end()) 149 return; // Not in the worklist. 150 151 // Null out the entry rather than erasing it to avoid a linear operation. 152 Worklist[It->second] = nullptr; 153 WorklistMap.erase(It); 154 } 155 156 void deleteAndRecombine(SDNode *N); 157 bool recursivelyDeleteUnusedNodes(SDNode *N); 158 159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 160 bool AddTo = true); 161 162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 163 return CombineTo(N, &Res, 1, AddTo); 164 } 165 166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 167 bool AddTo = true) { 168 SDValue To[] = { Res0, Res1 }; 169 return CombineTo(N, To, 2, AddTo); 170 } 171 172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 173 174 private: 175 176 /// Check the specified integer node value to see if it can be simplified or 177 /// if things it uses can be simplified by bit propagation. 178 /// If so, return true. 179 bool SimplifyDemandedBits(SDValue Op) { 180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 181 APInt Demanded = APInt::getAllOnesValue(BitWidth); 182 return SimplifyDemandedBits(Op, Demanded); 183 } 184 185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded); 186 187 bool CombineToPreIndexedLoadStore(SDNode *N); 188 bool CombineToPostIndexedLoadStore(SDNode *N); 189 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 190 bool SliceUpLoad(SDNode *N); 191 192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 193 /// load. 194 /// 195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 197 /// \param EltNo index of the vector element to load. 198 /// \param OriginalLoad load that EVE came from to be replaced. 199 /// \returns EVE on success SDValue() on failure. 200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad); 202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 206 SDValue PromoteIntBinOp(SDValue Op); 207 SDValue PromoteIntShiftOp(SDValue Op); 208 SDValue PromoteExtend(SDValue Op); 209 bool PromoteLoad(SDValue Op); 210 211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 212 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 213 ISD::NodeType ExtType); 214 215 /// Call the node-specific routine that knows how to fold each 216 /// particular type of node. If that doesn't do anything, try the 217 /// target-specific DAG combines. 218 SDValue combine(SDNode *N); 219 220 // Visitation implementation - Implement dag node combining for different 221 // node types. The semantics are as follows: 222 // Return Value: 223 // SDValue.getNode() == 0 - No change was made 224 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 225 // otherwise - N should be replaced by the returned Operand. 226 // 227 SDValue visitTokenFactor(SDNode *N); 228 SDValue visitMERGE_VALUES(SDNode *N); 229 SDValue visitADD(SDNode *N); 230 SDValue visitSUB(SDNode *N); 231 SDValue visitADDC(SDNode *N); 232 SDValue visitSUBC(SDNode *N); 233 SDValue visitADDE(SDNode *N); 234 SDValue visitSUBE(SDNode *N); 235 SDValue visitMUL(SDNode *N); 236 SDValue visitSDIV(SDNode *N); 237 SDValue visitUDIV(SDNode *N); 238 SDValue visitSREM(SDNode *N); 239 SDValue visitUREM(SDNode *N); 240 SDValue visitMULHU(SDNode *N); 241 SDValue visitMULHS(SDNode *N); 242 SDValue visitSMUL_LOHI(SDNode *N); 243 SDValue visitUMUL_LOHI(SDNode *N); 244 SDValue visitSMULO(SDNode *N); 245 SDValue visitUMULO(SDNode *N); 246 SDValue visitSDIVREM(SDNode *N); 247 SDValue visitUDIVREM(SDNode *N); 248 SDValue visitAND(SDNode *N); 249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference); 250 SDValue visitOR(SDNode *N); 251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference); 252 SDValue visitXOR(SDNode *N); 253 SDValue SimplifyVBinOp(SDNode *N); 254 SDValue visitSHL(SDNode *N); 255 SDValue visitSRA(SDNode *N); 256 SDValue visitSRL(SDNode *N); 257 SDValue visitRotate(SDNode *N); 258 SDValue visitCTLZ(SDNode *N); 259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 260 SDValue visitCTTZ(SDNode *N); 261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 262 SDValue visitCTPOP(SDNode *N); 263 SDValue visitSELECT(SDNode *N); 264 SDValue visitVSELECT(SDNode *N); 265 SDValue visitSELECT_CC(SDNode *N); 266 SDValue visitSETCC(SDNode *N); 267 SDValue visitSIGN_EXTEND(SDNode *N); 268 SDValue visitZERO_EXTEND(SDNode *N); 269 SDValue visitANY_EXTEND(SDNode *N); 270 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 271 SDValue visitTRUNCATE(SDNode *N); 272 SDValue visitBITCAST(SDNode *N); 273 SDValue visitBUILD_PAIR(SDNode *N); 274 SDValue visitFADD(SDNode *N); 275 SDValue visitFSUB(SDNode *N); 276 SDValue visitFMUL(SDNode *N); 277 SDValue visitFMA(SDNode *N); 278 SDValue visitFDIV(SDNode *N); 279 SDValue visitFREM(SDNode *N); 280 SDValue visitFSQRT(SDNode *N); 281 SDValue visitFCOPYSIGN(SDNode *N); 282 SDValue visitSINT_TO_FP(SDNode *N); 283 SDValue visitUINT_TO_FP(SDNode *N); 284 SDValue visitFP_TO_SINT(SDNode *N); 285 SDValue visitFP_TO_UINT(SDNode *N); 286 SDValue visitFP_ROUND(SDNode *N); 287 SDValue visitFP_ROUND_INREG(SDNode *N); 288 SDValue visitFP_EXTEND(SDNode *N); 289 SDValue visitFNEG(SDNode *N); 290 SDValue visitFABS(SDNode *N); 291 SDValue visitFCEIL(SDNode *N); 292 SDValue visitFTRUNC(SDNode *N); 293 SDValue visitFFLOOR(SDNode *N); 294 SDValue visitFMINNUM(SDNode *N); 295 SDValue visitFMAXNUM(SDNode *N); 296 SDValue visitBRCOND(SDNode *N); 297 SDValue visitBR_CC(SDNode *N); 298 SDValue visitLOAD(SDNode *N); 299 SDValue visitSTORE(SDNode *N); 300 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 301 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 302 SDValue visitBUILD_VECTOR(SDNode *N); 303 SDValue visitCONCAT_VECTORS(SDNode *N); 304 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 305 SDValue visitVECTOR_SHUFFLE(SDNode *N); 306 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 307 SDValue visitINSERT_SUBVECTOR(SDNode *N); 308 SDValue visitMLOAD(SDNode *N); 309 SDValue visitMSTORE(SDNode *N); 310 SDValue visitMGATHER(SDNode *N); 311 SDValue visitMSCATTER(SDNode *N); 312 SDValue visitFP_TO_FP16(SDNode *N); 313 314 SDValue visitFADDForFMACombine(SDNode *N); 315 SDValue visitFSUBForFMACombine(SDNode *N); 316 317 SDValue XformToShuffleWithZero(SDNode *N); 318 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 319 320 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 321 322 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 323 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 324 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 325 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 326 SDValue N3, ISD::CondCode CC, 327 bool NotExtCompare = false); 328 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 329 SDLoc DL, bool foldBooleans = true); 330 331 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 332 SDValue &CC) const; 333 bool isOneUseSetCC(SDValue N) const; 334 335 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 336 unsigned HiOp); 337 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 338 SDValue CombineExtLoad(SDNode *N); 339 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 340 SDValue BuildSDIV(SDNode *N); 341 SDValue BuildSDIVPow2(SDNode *N); 342 SDValue BuildUDIV(SDNode *N); 343 SDValue BuildReciprocalEstimate(SDValue Op); 344 SDValue BuildRsqrtEstimate(SDValue Op); 345 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations); 346 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations); 347 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 348 bool DemandHighBits = true); 349 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 350 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 351 SDValue InnerPos, SDValue InnerNeg, 352 unsigned PosOpcode, unsigned NegOpcode, 353 SDLoc DL); 354 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 355 SDValue ReduceLoadWidth(SDNode *N); 356 SDValue ReduceLoadOpStoreWidth(SDNode *N); 357 SDValue TransformFPLoadStorePair(SDNode *N); 358 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 359 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 360 361 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 362 363 /// Walk up chain skipping non-aliasing memory nodes, 364 /// looking for aliasing nodes and adding them to the Aliases vector. 365 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 366 SmallVectorImpl<SDValue> &Aliases); 367 368 /// Return true if there is any possibility that the two addresses overlap. 369 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 370 371 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 372 /// chain (aliasing node.) 373 SDValue FindBetterChain(SDNode *N, SDValue Chain); 374 375 /// Holds a pointer to an LSBaseSDNode as well as information on where it 376 /// is located in a sequence of memory operations connected by a chain. 377 struct MemOpLink { 378 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 379 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 380 // Ptr to the mem node. 381 LSBaseSDNode *MemNode; 382 // Offset from the base ptr. 383 int64_t OffsetFromBase; 384 // What is the sequence number of this mem node. 385 // Lowest mem operand in the DAG starts at zero. 386 unsigned SequenceNum; 387 }; 388 389 /// This is a helper function for MergeConsecutiveStores. When the source 390 /// elements of the consecutive stores are all constants or all extracted 391 /// vector elements, try to merge them into one larger store. 392 /// \return True if a merged store was created. 393 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 394 EVT MemVT, unsigned NumElem, 395 bool IsConstantSrc, bool UseVector); 396 397 /// Merge consecutive store operations into a wide store. 398 /// This optimization uses wide integers or vectors when possible. 399 /// \return True if some memory operations were changed. 400 bool MergeConsecutiveStores(StoreSDNode *N); 401 402 /// \brief Try to transform a truncation where C is a constant: 403 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 404 /// 405 /// \p N needs to be a truncation and its first operand an AND. Other 406 /// requirements are checked by the function (e.g. that trunc is 407 /// single-use) and if missed an empty SDValue is returned. 408 SDValue distributeTruncateThroughAnd(SDNode *N); 409 410 public: 411 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 412 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 413 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 414 auto *F = DAG.getMachineFunction().getFunction(); 415 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) || 416 F->hasFnAttribute(Attribute::MinSize); 417 } 418 419 /// Runs the dag combiner on all nodes in the work list 420 void Run(CombineLevel AtLevel); 421 422 SelectionDAG &getDAG() const { return DAG; } 423 424 /// Returns a type large enough to hold any valid shift amount - before type 425 /// legalization these can be huge. 426 EVT getShiftAmountTy(EVT LHSTy) { 427 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 428 if (LHSTy.isVector()) 429 return LHSTy; 430 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 431 : TLI.getPointerTy(); 432 } 433 434 /// This method returns true if we are running before type legalization or 435 /// if the specified VT is legal. 436 bool isTypeLegal(const EVT &VT) { 437 if (!LegalTypes) return true; 438 return TLI.isTypeLegal(VT); 439 } 440 441 /// Convenience wrapper around TargetLowering::getSetCCResultType 442 EVT getSetCCResultType(EVT VT) const { 443 return TLI.getSetCCResultType(*DAG.getContext(), VT); 444 } 445 }; 446 } 447 448 449 namespace { 450 /// This class is a DAGUpdateListener that removes any deleted 451 /// nodes from the worklist. 452 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 453 DAGCombiner &DC; 454 public: 455 explicit WorklistRemover(DAGCombiner &dc) 456 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 457 458 void NodeDeleted(SDNode *N, SDNode *E) override { 459 DC.removeFromWorklist(N); 460 } 461 }; 462 } 463 464 //===----------------------------------------------------------------------===// 465 // TargetLowering::DAGCombinerInfo implementation 466 //===----------------------------------------------------------------------===// 467 468 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 469 ((DAGCombiner*)DC)->AddToWorklist(N); 470 } 471 472 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 473 ((DAGCombiner*)DC)->removeFromWorklist(N); 474 } 475 476 SDValue TargetLowering::DAGCombinerInfo:: 477 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 478 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 479 } 480 481 SDValue TargetLowering::DAGCombinerInfo:: 482 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 483 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 484 } 485 486 487 SDValue TargetLowering::DAGCombinerInfo:: 488 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 489 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 490 } 491 492 void TargetLowering::DAGCombinerInfo:: 493 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 494 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 495 } 496 497 //===----------------------------------------------------------------------===// 498 // Helper Functions 499 //===----------------------------------------------------------------------===// 500 501 void DAGCombiner::deleteAndRecombine(SDNode *N) { 502 removeFromWorklist(N); 503 504 // If the operands of this node are only used by the node, they will now be 505 // dead. Make sure to re-visit them and recursively delete dead nodes. 506 for (const SDValue &Op : N->ops()) 507 // For an operand generating multiple values, one of the values may 508 // become dead allowing further simplification (e.g. split index 509 // arithmetic from an indexed load). 510 if (Op->hasOneUse() || Op->getNumValues() > 1) 511 AddToWorklist(Op.getNode()); 512 513 DAG.DeleteNode(N); 514 } 515 516 /// Return 1 if we can compute the negated form of the specified expression for 517 /// the same cost as the expression itself, or 2 if we can compute the negated 518 /// form more cheaply than the expression itself. 519 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 520 const TargetLowering &TLI, 521 const TargetOptions *Options, 522 unsigned Depth = 0) { 523 // fneg is removable even if it has multiple uses. 524 if (Op.getOpcode() == ISD::FNEG) return 2; 525 526 // Don't allow anything with multiple uses. 527 if (!Op.hasOneUse()) return 0; 528 529 // Don't recurse exponentially. 530 if (Depth > 6) return 0; 531 532 switch (Op.getOpcode()) { 533 default: return false; 534 case ISD::ConstantFP: 535 // Don't invert constant FP values after legalize. The negated constant 536 // isn't necessarily legal. 537 return LegalOperations ? 0 : 1; 538 case ISD::FADD: 539 // FIXME: determine better conditions for this xform. 540 if (!Options->UnsafeFPMath) return 0; 541 542 // After operation legalization, it might not be legal to create new FSUBs. 543 if (LegalOperations && 544 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 545 return 0; 546 547 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 548 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 549 Options, Depth + 1)) 550 return V; 551 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 552 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 553 Depth + 1); 554 case ISD::FSUB: 555 // We can't turn -(A-B) into B-A when we honor signed zeros. 556 if (!Options->UnsafeFPMath) return 0; 557 558 // fold (fneg (fsub A, B)) -> (fsub B, A) 559 return 1; 560 561 case ISD::FMUL: 562 case ISD::FDIV: 563 if (Options->HonorSignDependentRoundingFPMath()) return 0; 564 565 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 566 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 567 Options, Depth + 1)) 568 return V; 569 570 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 571 Depth + 1); 572 573 case ISD::FP_EXTEND: 574 case ISD::FP_ROUND: 575 case ISD::FSIN: 576 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 577 Depth + 1); 578 } 579 } 580 581 /// If isNegatibleForFree returns true, return the newly negated expression. 582 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 583 bool LegalOperations, unsigned Depth = 0) { 584 const TargetOptions &Options = DAG.getTarget().Options; 585 // fneg is removable even if it has multiple uses. 586 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 587 588 // Don't allow anything with multiple uses. 589 assert(Op.hasOneUse() && "Unknown reuse!"); 590 591 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 592 switch (Op.getOpcode()) { 593 default: llvm_unreachable("Unknown code"); 594 case ISD::ConstantFP: { 595 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 596 V.changeSign(); 597 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 598 } 599 case ISD::FADD: 600 // FIXME: determine better conditions for this xform. 601 assert(Options.UnsafeFPMath); 602 603 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 604 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 605 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 606 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 607 GetNegatedExpression(Op.getOperand(0), DAG, 608 LegalOperations, Depth+1), 609 Op.getOperand(1)); 610 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 611 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 612 GetNegatedExpression(Op.getOperand(1), DAG, 613 LegalOperations, Depth+1), 614 Op.getOperand(0)); 615 case ISD::FSUB: 616 // We can't turn -(A-B) into B-A when we honor signed zeros. 617 assert(Options.UnsafeFPMath); 618 619 // fold (fneg (fsub 0, B)) -> B 620 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 621 if (N0CFP->getValueAPF().isZero()) 622 return Op.getOperand(1); 623 624 // fold (fneg (fsub A, B)) -> (fsub B, A) 625 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 626 Op.getOperand(1), Op.getOperand(0)); 627 628 case ISD::FMUL: 629 case ISD::FDIV: 630 assert(!Options.HonorSignDependentRoundingFPMath()); 631 632 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 633 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 634 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 636 GetNegatedExpression(Op.getOperand(0), DAG, 637 LegalOperations, Depth+1), 638 Op.getOperand(1)); 639 640 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 641 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 642 Op.getOperand(0), 643 GetNegatedExpression(Op.getOperand(1), DAG, 644 LegalOperations, Depth+1)); 645 646 case ISD::FP_EXTEND: 647 case ISD::FSIN: 648 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 649 GetNegatedExpression(Op.getOperand(0), DAG, 650 LegalOperations, Depth+1)); 651 case ISD::FP_ROUND: 652 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 653 GetNegatedExpression(Op.getOperand(0), DAG, 654 LegalOperations, Depth+1), 655 Op.getOperand(1)); 656 } 657 } 658 659 // Return true if this node is a setcc, or is a select_cc 660 // that selects between the target values used for true and false, making it 661 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 662 // the appropriate nodes based on the type of node we are checking. This 663 // simplifies life a bit for the callers. 664 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 665 SDValue &CC) const { 666 if (N.getOpcode() == ISD::SETCC) { 667 LHS = N.getOperand(0); 668 RHS = N.getOperand(1); 669 CC = N.getOperand(2); 670 return true; 671 } 672 673 if (N.getOpcode() != ISD::SELECT_CC || 674 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 675 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 676 return false; 677 678 if (TLI.getBooleanContents(N.getValueType()) == 679 TargetLowering::UndefinedBooleanContent) 680 return false; 681 682 LHS = N.getOperand(0); 683 RHS = N.getOperand(1); 684 CC = N.getOperand(4); 685 return true; 686 } 687 688 /// Return true if this is a SetCC-equivalent operation with only one use. 689 /// If this is true, it allows the users to invert the operation for free when 690 /// it is profitable to do so. 691 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 692 SDValue N0, N1, N2; 693 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 694 return true; 695 return false; 696 } 697 698 /// Returns true if N is a BUILD_VECTOR node whose 699 /// elements are all the same constant or undefined. 700 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 701 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 702 if (!C) 703 return false; 704 705 APInt SplatUndef; 706 unsigned SplatBitSize; 707 bool HasAnyUndefs; 708 EVT EltVT = N->getValueType(0).getVectorElementType(); 709 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 710 HasAnyUndefs) && 711 EltVT.getSizeInBits() >= SplatBitSize); 712 } 713 714 // \brief Returns the SDNode if it is a constant integer BuildVector 715 // or constant integer. 716 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) { 717 if (isa<ConstantSDNode>(N)) 718 return N.getNode(); 719 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 720 return N.getNode(); 721 return nullptr; 722 } 723 724 // \brief Returns the SDNode if it is a constant float BuildVector 725 // or constant float. 726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 727 if (isa<ConstantFPSDNode>(N)) 728 return N.getNode(); 729 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 730 return N.getNode(); 731 return nullptr; 732 } 733 734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 735 // int. 736 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 737 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 738 return CN; 739 740 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 741 BitVector UndefElements; 742 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 743 744 // BuildVectors can truncate their operands. Ignore that case here. 745 // FIXME: We blindly ignore splats which include undef which is overly 746 // pessimistic. 747 if (CN && UndefElements.none() && 748 CN->getValueType(0) == N.getValueType().getScalarType()) 749 return CN; 750 } 751 752 return nullptr; 753 } 754 755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 756 // float. 757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 758 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 759 return CN; 760 761 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 762 BitVector UndefElements; 763 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 764 765 if (CN && UndefElements.none()) 766 return CN; 767 } 768 769 return nullptr; 770 } 771 772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 773 SDValue N0, SDValue N1) { 774 EVT VT = N0.getValueType(); 775 if (N0.getOpcode() == Opc) { 776 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 777 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) { 778 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 779 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 780 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 781 return SDValue(); 782 } 783 if (N0.hasOneUse()) { 784 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 785 // use 786 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 787 if (!OpNode.getNode()) 788 return SDValue(); 789 AddToWorklist(OpNode.getNode()); 790 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 791 } 792 } 793 } 794 795 if (N1.getOpcode() == Opc) { 796 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 797 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) { 798 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 799 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 800 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 801 return SDValue(); 802 } 803 if (N1.hasOneUse()) { 804 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 805 // use 806 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 807 if (!OpNode.getNode()) 808 return SDValue(); 809 AddToWorklist(OpNode.getNode()); 810 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 811 } 812 } 813 } 814 815 return SDValue(); 816 } 817 818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 819 bool AddTo) { 820 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 821 ++NodesCombined; 822 DEBUG(dbgs() << "\nReplacing.1 "; 823 N->dump(&DAG); 824 dbgs() << "\nWith: "; 825 To[0].getNode()->dump(&DAG); 826 dbgs() << " and " << NumTo-1 << " other values\n"); 827 for (unsigned i = 0, e = NumTo; i != e; ++i) 828 assert((!To[i].getNode() || 829 N->getValueType(i) == To[i].getValueType()) && 830 "Cannot combine value to value of different type!"); 831 832 WorklistRemover DeadNodes(*this); 833 DAG.ReplaceAllUsesWith(N, To); 834 if (AddTo) { 835 // Push the new nodes and any users onto the worklist 836 for (unsigned i = 0, e = NumTo; i != e; ++i) { 837 if (To[i].getNode()) { 838 AddToWorklist(To[i].getNode()); 839 AddUsersToWorklist(To[i].getNode()); 840 } 841 } 842 } 843 844 // Finally, if the node is now dead, remove it from the graph. The node 845 // may not be dead if the replacement process recursively simplified to 846 // something else needing this node. 847 if (N->use_empty()) 848 deleteAndRecombine(N); 849 return SDValue(N, 0); 850 } 851 852 void DAGCombiner:: 853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 854 // Replace all uses. If any nodes become isomorphic to other nodes and 855 // are deleted, make sure to remove them from our worklist. 856 WorklistRemover DeadNodes(*this); 857 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 858 859 // Push the new node and any (possibly new) users onto the worklist. 860 AddToWorklist(TLO.New.getNode()); 861 AddUsersToWorklist(TLO.New.getNode()); 862 863 // Finally, if the node is now dead, remove it from the graph. The node 864 // may not be dead if the replacement process recursively simplified to 865 // something else needing this node. 866 if (TLO.Old.getNode()->use_empty()) 867 deleteAndRecombine(TLO.Old.getNode()); 868 } 869 870 /// Check the specified integer node value to see if it can be simplified or if 871 /// things it uses can be simplified by bit propagation. If so, return true. 872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 873 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 874 APInt KnownZero, KnownOne; 875 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 876 return false; 877 878 // Revisit the node. 879 AddToWorklist(Op.getNode()); 880 881 // Replace the old value with the new one. 882 ++NodesCombined; 883 DEBUG(dbgs() << "\nReplacing.2 "; 884 TLO.Old.getNode()->dump(&DAG); 885 dbgs() << "\nWith: "; 886 TLO.New.getNode()->dump(&DAG); 887 dbgs() << '\n'); 888 889 CommitTargetLoweringOpt(TLO); 890 return true; 891 } 892 893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 894 SDLoc dl(Load); 895 EVT VT = Load->getValueType(0); 896 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 897 898 DEBUG(dbgs() << "\nReplacing.9 "; 899 Load->dump(&DAG); 900 dbgs() << "\nWith: "; 901 Trunc.getNode()->dump(&DAG); 902 dbgs() << '\n'); 903 WorklistRemover DeadNodes(*this); 904 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 905 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 906 deleteAndRecombine(Load); 907 AddToWorklist(Trunc.getNode()); 908 } 909 910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 911 Replace = false; 912 SDLoc dl(Op); 913 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 914 EVT MemVT = LD->getMemoryVT(); 915 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 916 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 917 : ISD::EXTLOAD) 918 : LD->getExtensionType(); 919 Replace = true; 920 return DAG.getExtLoad(ExtType, dl, PVT, 921 LD->getChain(), LD->getBasePtr(), 922 MemVT, LD->getMemOperand()); 923 } 924 925 unsigned Opc = Op.getOpcode(); 926 switch (Opc) { 927 default: break; 928 case ISD::AssertSext: 929 return DAG.getNode(ISD::AssertSext, dl, PVT, 930 SExtPromoteOperand(Op.getOperand(0), PVT), 931 Op.getOperand(1)); 932 case ISD::AssertZext: 933 return DAG.getNode(ISD::AssertZext, dl, PVT, 934 ZExtPromoteOperand(Op.getOperand(0), PVT), 935 Op.getOperand(1)); 936 case ISD::Constant: { 937 unsigned ExtOpc = 938 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 939 return DAG.getNode(ExtOpc, dl, PVT, Op); 940 } 941 } 942 943 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 944 return SDValue(); 945 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 946 } 947 948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 949 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 950 return SDValue(); 951 EVT OldVT = Op.getValueType(); 952 SDLoc dl(Op); 953 bool Replace = false; 954 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 955 if (!NewOp.getNode()) 956 return SDValue(); 957 AddToWorklist(NewOp.getNode()); 958 959 if (Replace) 960 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 961 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 962 DAG.getValueType(OldVT)); 963 } 964 965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 966 EVT OldVT = Op.getValueType(); 967 SDLoc dl(Op); 968 bool Replace = false; 969 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 970 if (!NewOp.getNode()) 971 return SDValue(); 972 AddToWorklist(NewOp.getNode()); 973 974 if (Replace) 975 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 976 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 977 } 978 979 /// Promote the specified integer binary operation if the target indicates it is 980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 981 /// i32 since i16 instructions are longer. 982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 983 if (!LegalOperations) 984 return SDValue(); 985 986 EVT VT = Op.getValueType(); 987 if (VT.isVector() || !VT.isInteger()) 988 return SDValue(); 989 990 // If operation type is 'undesirable', e.g. i16 on x86, consider 991 // promoting it. 992 unsigned Opc = Op.getOpcode(); 993 if (TLI.isTypeDesirableForOp(Opc, VT)) 994 return SDValue(); 995 996 EVT PVT = VT; 997 // Consult target whether it is a good idea to promote this operation and 998 // what's the right type to promote it to. 999 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1000 assert(PVT != VT && "Don't know what type to promote to!"); 1001 1002 bool Replace0 = false; 1003 SDValue N0 = Op.getOperand(0); 1004 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1005 if (!NN0.getNode()) 1006 return SDValue(); 1007 1008 bool Replace1 = false; 1009 SDValue N1 = Op.getOperand(1); 1010 SDValue NN1; 1011 if (N0 == N1) 1012 NN1 = NN0; 1013 else { 1014 NN1 = PromoteOperand(N1, PVT, Replace1); 1015 if (!NN1.getNode()) 1016 return SDValue(); 1017 } 1018 1019 AddToWorklist(NN0.getNode()); 1020 if (NN1.getNode()) 1021 AddToWorklist(NN1.getNode()); 1022 1023 if (Replace0) 1024 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1025 if (Replace1) 1026 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1027 1028 DEBUG(dbgs() << "\nPromoting "; 1029 Op.getNode()->dump(&DAG)); 1030 SDLoc dl(Op); 1031 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1032 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1033 } 1034 return SDValue(); 1035 } 1036 1037 /// Promote the specified integer shift operation if the target indicates it is 1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1039 /// i32 since i16 instructions are longer. 1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1041 if (!LegalOperations) 1042 return SDValue(); 1043 1044 EVT VT = Op.getValueType(); 1045 if (VT.isVector() || !VT.isInteger()) 1046 return SDValue(); 1047 1048 // If operation type is 'undesirable', e.g. i16 on x86, consider 1049 // promoting it. 1050 unsigned Opc = Op.getOpcode(); 1051 if (TLI.isTypeDesirableForOp(Opc, VT)) 1052 return SDValue(); 1053 1054 EVT PVT = VT; 1055 // Consult target whether it is a good idea to promote this operation and 1056 // what's the right type to promote it to. 1057 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1058 assert(PVT != VT && "Don't know what type to promote to!"); 1059 1060 bool Replace = false; 1061 SDValue N0 = Op.getOperand(0); 1062 if (Opc == ISD::SRA) 1063 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1064 else if (Opc == ISD::SRL) 1065 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1066 else 1067 N0 = PromoteOperand(N0, PVT, Replace); 1068 if (!N0.getNode()) 1069 return SDValue(); 1070 1071 AddToWorklist(N0.getNode()); 1072 if (Replace) 1073 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1074 1075 DEBUG(dbgs() << "\nPromoting "; 1076 Op.getNode()->dump(&DAG)); 1077 SDLoc dl(Op); 1078 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1079 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1080 } 1081 return SDValue(); 1082 } 1083 1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1085 if (!LegalOperations) 1086 return SDValue(); 1087 1088 EVT VT = Op.getValueType(); 1089 if (VT.isVector() || !VT.isInteger()) 1090 return SDValue(); 1091 1092 // If operation type is 'undesirable', e.g. i16 on x86, consider 1093 // promoting it. 1094 unsigned Opc = Op.getOpcode(); 1095 if (TLI.isTypeDesirableForOp(Opc, VT)) 1096 return SDValue(); 1097 1098 EVT PVT = VT; 1099 // Consult target whether it is a good idea to promote this operation and 1100 // what's the right type to promote it to. 1101 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1102 assert(PVT != VT && "Don't know what type to promote to!"); 1103 // fold (aext (aext x)) -> (aext x) 1104 // fold (aext (zext x)) -> (zext x) 1105 // fold (aext (sext x)) -> (sext x) 1106 DEBUG(dbgs() << "\nPromoting "; 1107 Op.getNode()->dump(&DAG)); 1108 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1109 } 1110 return SDValue(); 1111 } 1112 1113 bool DAGCombiner::PromoteLoad(SDValue Op) { 1114 if (!LegalOperations) 1115 return false; 1116 1117 EVT VT = Op.getValueType(); 1118 if (VT.isVector() || !VT.isInteger()) 1119 return false; 1120 1121 // If operation type is 'undesirable', e.g. i16 on x86, consider 1122 // promoting it. 1123 unsigned Opc = Op.getOpcode(); 1124 if (TLI.isTypeDesirableForOp(Opc, VT)) 1125 return false; 1126 1127 EVT PVT = VT; 1128 // Consult target whether it is a good idea to promote this operation and 1129 // what's the right type to promote it to. 1130 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1131 assert(PVT != VT && "Don't know what type to promote to!"); 1132 1133 SDLoc dl(Op); 1134 SDNode *N = Op.getNode(); 1135 LoadSDNode *LD = cast<LoadSDNode>(N); 1136 EVT MemVT = LD->getMemoryVT(); 1137 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1138 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1139 : ISD::EXTLOAD) 1140 : LD->getExtensionType(); 1141 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1142 LD->getChain(), LD->getBasePtr(), 1143 MemVT, LD->getMemOperand()); 1144 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1145 1146 DEBUG(dbgs() << "\nPromoting "; 1147 N->dump(&DAG); 1148 dbgs() << "\nTo: "; 1149 Result.getNode()->dump(&DAG); 1150 dbgs() << '\n'); 1151 WorklistRemover DeadNodes(*this); 1152 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1153 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1154 deleteAndRecombine(N); 1155 AddToWorklist(Result.getNode()); 1156 return true; 1157 } 1158 return false; 1159 } 1160 1161 /// \brief Recursively delete a node which has no uses and any operands for 1162 /// which it is the only use. 1163 /// 1164 /// Note that this both deletes the nodes and removes them from the worklist. 1165 /// It also adds any nodes who have had a user deleted to the worklist as they 1166 /// may now have only one use and subject to other combines. 1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1168 if (!N->use_empty()) 1169 return false; 1170 1171 SmallSetVector<SDNode *, 16> Nodes; 1172 Nodes.insert(N); 1173 do { 1174 N = Nodes.pop_back_val(); 1175 if (!N) 1176 continue; 1177 1178 if (N->use_empty()) { 1179 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1180 Nodes.insert(N->getOperand(i).getNode()); 1181 1182 removeFromWorklist(N); 1183 DAG.DeleteNode(N); 1184 } else { 1185 AddToWorklist(N); 1186 } 1187 } while (!Nodes.empty()); 1188 return true; 1189 } 1190 1191 //===----------------------------------------------------------------------===// 1192 // Main DAG Combiner implementation 1193 //===----------------------------------------------------------------------===// 1194 1195 void DAGCombiner::Run(CombineLevel AtLevel) { 1196 // set the instance variables, so that the various visit routines may use it. 1197 Level = AtLevel; 1198 LegalOperations = Level >= AfterLegalizeVectorOps; 1199 LegalTypes = Level >= AfterLegalizeTypes; 1200 1201 // Add all the dag nodes to the worklist. 1202 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1203 E = DAG.allnodes_end(); I != E; ++I) 1204 AddToWorklist(I); 1205 1206 // Create a dummy node (which is not added to allnodes), that adds a reference 1207 // to the root node, preventing it from being deleted, and tracking any 1208 // changes of the root. 1209 HandleSDNode Dummy(DAG.getRoot()); 1210 1211 // while the worklist isn't empty, find a node and 1212 // try and combine it. 1213 while (!WorklistMap.empty()) { 1214 SDNode *N; 1215 // The Worklist holds the SDNodes in order, but it may contain null entries. 1216 do { 1217 N = Worklist.pop_back_val(); 1218 } while (!N); 1219 1220 bool GoodWorklistEntry = WorklistMap.erase(N); 1221 (void)GoodWorklistEntry; 1222 assert(GoodWorklistEntry && 1223 "Found a worklist entry without a corresponding map entry!"); 1224 1225 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1226 // N is deleted from the DAG, since they too may now be dead or may have a 1227 // reduced number of uses, allowing other xforms. 1228 if (recursivelyDeleteUnusedNodes(N)) 1229 continue; 1230 1231 WorklistRemover DeadNodes(*this); 1232 1233 // If this combine is running after legalizing the DAG, re-legalize any 1234 // nodes pulled off the worklist. 1235 if (Level == AfterLegalizeDAG) { 1236 SmallSetVector<SDNode *, 16> UpdatedNodes; 1237 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1238 1239 for (SDNode *LN : UpdatedNodes) { 1240 AddToWorklist(LN); 1241 AddUsersToWorklist(LN); 1242 } 1243 if (!NIsValid) 1244 continue; 1245 } 1246 1247 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1248 1249 // Add any operands of the new node which have not yet been combined to the 1250 // worklist as well. Because the worklist uniques things already, this 1251 // won't repeatedly process the same operand. 1252 CombinedNodes.insert(N); 1253 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1254 if (!CombinedNodes.count(N->getOperand(i).getNode())) 1255 AddToWorklist(N->getOperand(i).getNode()); 1256 1257 SDValue RV = combine(N); 1258 1259 if (!RV.getNode()) 1260 continue; 1261 1262 ++NodesCombined; 1263 1264 // If we get back the same node we passed in, rather than a new node or 1265 // zero, we know that the node must have defined multiple values and 1266 // CombineTo was used. Since CombineTo takes care of the worklist 1267 // mechanics for us, we have no work to do in this case. 1268 if (RV.getNode() == N) 1269 continue; 1270 1271 assert(N->getOpcode() != ISD::DELETED_NODE && 1272 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1273 "Node was deleted but visit returned new node!"); 1274 1275 DEBUG(dbgs() << " ... into: "; 1276 RV.getNode()->dump(&DAG)); 1277 1278 // Transfer debug value. 1279 DAG.TransferDbgValues(SDValue(N, 0), RV); 1280 if (N->getNumValues() == RV.getNode()->getNumValues()) 1281 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1282 else { 1283 assert(N->getValueType(0) == RV.getValueType() && 1284 N->getNumValues() == 1 && "Type mismatch"); 1285 SDValue OpV = RV; 1286 DAG.ReplaceAllUsesWith(N, &OpV); 1287 } 1288 1289 // Push the new node and any users onto the worklist 1290 AddToWorklist(RV.getNode()); 1291 AddUsersToWorklist(RV.getNode()); 1292 1293 // Finally, if the node is now dead, remove it from the graph. The node 1294 // may not be dead if the replacement process recursively simplified to 1295 // something else needing this node. This will also take care of adding any 1296 // operands which have lost a user to the worklist. 1297 recursivelyDeleteUnusedNodes(N); 1298 } 1299 1300 // If the root changed (e.g. it was a dead load, update the root). 1301 DAG.setRoot(Dummy.getValue()); 1302 DAG.RemoveDeadNodes(); 1303 } 1304 1305 SDValue DAGCombiner::visit(SDNode *N) { 1306 switch (N->getOpcode()) { 1307 default: break; 1308 case ISD::TokenFactor: return visitTokenFactor(N); 1309 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1310 case ISD::ADD: return visitADD(N); 1311 case ISD::SUB: return visitSUB(N); 1312 case ISD::ADDC: return visitADDC(N); 1313 case ISD::SUBC: return visitSUBC(N); 1314 case ISD::ADDE: return visitADDE(N); 1315 case ISD::SUBE: return visitSUBE(N); 1316 case ISD::MUL: return visitMUL(N); 1317 case ISD::SDIV: return visitSDIV(N); 1318 case ISD::UDIV: return visitUDIV(N); 1319 case ISD::SREM: return visitSREM(N); 1320 case ISD::UREM: return visitUREM(N); 1321 case ISD::MULHU: return visitMULHU(N); 1322 case ISD::MULHS: return visitMULHS(N); 1323 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1324 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1325 case ISD::SMULO: return visitSMULO(N); 1326 case ISD::UMULO: return visitUMULO(N); 1327 case ISD::SDIVREM: return visitSDIVREM(N); 1328 case ISD::UDIVREM: return visitUDIVREM(N); 1329 case ISD::AND: return visitAND(N); 1330 case ISD::OR: return visitOR(N); 1331 case ISD::XOR: return visitXOR(N); 1332 case ISD::SHL: return visitSHL(N); 1333 case ISD::SRA: return visitSRA(N); 1334 case ISD::SRL: return visitSRL(N); 1335 case ISD::ROTR: 1336 case ISD::ROTL: return visitRotate(N); 1337 case ISD::CTLZ: return visitCTLZ(N); 1338 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1339 case ISD::CTTZ: return visitCTTZ(N); 1340 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1341 case ISD::CTPOP: return visitCTPOP(N); 1342 case ISD::SELECT: return visitSELECT(N); 1343 case ISD::VSELECT: return visitVSELECT(N); 1344 case ISD::SELECT_CC: return visitSELECT_CC(N); 1345 case ISD::SETCC: return visitSETCC(N); 1346 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1347 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1348 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1349 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1350 case ISD::TRUNCATE: return visitTRUNCATE(N); 1351 case ISD::BITCAST: return visitBITCAST(N); 1352 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1353 case ISD::FADD: return visitFADD(N); 1354 case ISD::FSUB: return visitFSUB(N); 1355 case ISD::FMUL: return visitFMUL(N); 1356 case ISD::FMA: return visitFMA(N); 1357 case ISD::FDIV: return visitFDIV(N); 1358 case ISD::FREM: return visitFREM(N); 1359 case ISD::FSQRT: return visitFSQRT(N); 1360 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1361 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1362 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1363 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1364 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1365 case ISD::FP_ROUND: return visitFP_ROUND(N); 1366 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1367 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1368 case ISD::FNEG: return visitFNEG(N); 1369 case ISD::FABS: return visitFABS(N); 1370 case ISD::FFLOOR: return visitFFLOOR(N); 1371 case ISD::FMINNUM: return visitFMINNUM(N); 1372 case ISD::FMAXNUM: return visitFMAXNUM(N); 1373 case ISD::FCEIL: return visitFCEIL(N); 1374 case ISD::FTRUNC: return visitFTRUNC(N); 1375 case ISD::BRCOND: return visitBRCOND(N); 1376 case ISD::BR_CC: return visitBR_CC(N); 1377 case ISD::LOAD: return visitLOAD(N); 1378 case ISD::STORE: return visitSTORE(N); 1379 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1380 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1381 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1382 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1383 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1384 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1385 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1386 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1387 case ISD::MGATHER: return visitMGATHER(N); 1388 case ISD::MLOAD: return visitMLOAD(N); 1389 case ISD::MSCATTER: return visitMSCATTER(N); 1390 case ISD::MSTORE: return visitMSTORE(N); 1391 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1392 } 1393 return SDValue(); 1394 } 1395 1396 SDValue DAGCombiner::combine(SDNode *N) { 1397 SDValue RV = visit(N); 1398 1399 // If nothing happened, try a target-specific DAG combine. 1400 if (!RV.getNode()) { 1401 assert(N->getOpcode() != ISD::DELETED_NODE && 1402 "Node was deleted but visit returned NULL!"); 1403 1404 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1405 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1406 1407 // Expose the DAG combiner to the target combiner impls. 1408 TargetLowering::DAGCombinerInfo 1409 DagCombineInfo(DAG, Level, false, this); 1410 1411 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1412 } 1413 } 1414 1415 // If nothing happened still, try promoting the operation. 1416 if (!RV.getNode()) { 1417 switch (N->getOpcode()) { 1418 default: break; 1419 case ISD::ADD: 1420 case ISD::SUB: 1421 case ISD::MUL: 1422 case ISD::AND: 1423 case ISD::OR: 1424 case ISD::XOR: 1425 RV = PromoteIntBinOp(SDValue(N, 0)); 1426 break; 1427 case ISD::SHL: 1428 case ISD::SRA: 1429 case ISD::SRL: 1430 RV = PromoteIntShiftOp(SDValue(N, 0)); 1431 break; 1432 case ISD::SIGN_EXTEND: 1433 case ISD::ZERO_EXTEND: 1434 case ISD::ANY_EXTEND: 1435 RV = PromoteExtend(SDValue(N, 0)); 1436 break; 1437 case ISD::LOAD: 1438 if (PromoteLoad(SDValue(N, 0))) 1439 RV = SDValue(N, 0); 1440 break; 1441 } 1442 } 1443 1444 // If N is a commutative binary node, try commuting it to enable more 1445 // sdisel CSE. 1446 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1447 N->getNumValues() == 1) { 1448 SDValue N0 = N->getOperand(0); 1449 SDValue N1 = N->getOperand(1); 1450 1451 // Constant operands are canonicalized to RHS. 1452 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1453 SDValue Ops[] = {N1, N0}; 1454 SDNode *CSENode; 1455 if (const BinaryWithFlagsSDNode *BinNode = 1456 dyn_cast<BinaryWithFlagsSDNode>(N)) { 1457 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1458 BinNode->Flags.hasNoUnsignedWrap(), 1459 BinNode->Flags.hasNoSignedWrap(), 1460 BinNode->Flags.hasExact()); 1461 } else { 1462 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops); 1463 } 1464 if (CSENode) 1465 return SDValue(CSENode, 0); 1466 } 1467 } 1468 1469 return RV; 1470 } 1471 1472 /// Given a node, return its input chain if it has one, otherwise return a null 1473 /// sd operand. 1474 static SDValue getInputChainForNode(SDNode *N) { 1475 if (unsigned NumOps = N->getNumOperands()) { 1476 if (N->getOperand(0).getValueType() == MVT::Other) 1477 return N->getOperand(0); 1478 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1479 return N->getOperand(NumOps-1); 1480 for (unsigned i = 1; i < NumOps-1; ++i) 1481 if (N->getOperand(i).getValueType() == MVT::Other) 1482 return N->getOperand(i); 1483 } 1484 return SDValue(); 1485 } 1486 1487 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1488 // If N has two operands, where one has an input chain equal to the other, 1489 // the 'other' chain is redundant. 1490 if (N->getNumOperands() == 2) { 1491 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1492 return N->getOperand(0); 1493 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1494 return N->getOperand(1); 1495 } 1496 1497 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1498 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1499 SmallPtrSet<SDNode*, 16> SeenOps; 1500 bool Changed = false; // If we should replace this token factor. 1501 1502 // Start out with this token factor. 1503 TFs.push_back(N); 1504 1505 // Iterate through token factors. The TFs grows when new token factors are 1506 // encountered. 1507 for (unsigned i = 0; i < TFs.size(); ++i) { 1508 SDNode *TF = TFs[i]; 1509 1510 // Check each of the operands. 1511 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1512 SDValue Op = TF->getOperand(i); 1513 1514 switch (Op.getOpcode()) { 1515 case ISD::EntryToken: 1516 // Entry tokens don't need to be added to the list. They are 1517 // redundant. 1518 Changed = true; 1519 break; 1520 1521 case ISD::TokenFactor: 1522 if (Op.hasOneUse() && 1523 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1524 // Queue up for processing. 1525 TFs.push_back(Op.getNode()); 1526 // Clean up in case the token factor is removed. 1527 AddToWorklist(Op.getNode()); 1528 Changed = true; 1529 break; 1530 } 1531 // Fall thru 1532 1533 default: 1534 // Only add if it isn't already in the list. 1535 if (SeenOps.insert(Op.getNode()).second) 1536 Ops.push_back(Op); 1537 else 1538 Changed = true; 1539 break; 1540 } 1541 } 1542 } 1543 1544 SDValue Result; 1545 1546 // If we've changed things around then replace token factor. 1547 if (Changed) { 1548 if (Ops.empty()) { 1549 // The entry token is the only possible outcome. 1550 Result = DAG.getEntryNode(); 1551 } else { 1552 // New and improved token factor. 1553 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1554 } 1555 1556 // Add users to worklist if AA is enabled, since it may introduce 1557 // a lot of new chained token factors while removing memory deps. 1558 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 1559 : DAG.getSubtarget().useAA(); 1560 return CombineTo(N, Result, UseAA /*add to worklist*/); 1561 } 1562 1563 return Result; 1564 } 1565 1566 /// MERGE_VALUES can always be eliminated. 1567 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1568 WorklistRemover DeadNodes(*this); 1569 // Replacing results may cause a different MERGE_VALUES to suddenly 1570 // be CSE'd with N, and carry its uses with it. Iterate until no 1571 // uses remain, to ensure that the node can be safely deleted. 1572 // First add the users of this node to the work list so that they 1573 // can be tried again once they have new operands. 1574 AddUsersToWorklist(N); 1575 do { 1576 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1577 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1578 } while (!N->use_empty()); 1579 deleteAndRecombine(N); 1580 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1581 } 1582 1583 static bool isNullConstant(SDValue V) { 1584 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1585 return Const != nullptr && Const->isNullValue(); 1586 } 1587 1588 static bool isAllOnesConstant(SDValue V) { 1589 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1590 return Const != nullptr && Const->isAllOnesValue(); 1591 } 1592 1593 static bool isOneConstant(SDValue V) { 1594 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 1595 return Const != nullptr && Const->isOne(); 1596 } 1597 1598 SDValue DAGCombiner::visitADD(SDNode *N) { 1599 SDValue N0 = N->getOperand(0); 1600 SDValue N1 = N->getOperand(1); 1601 EVT VT = N0.getValueType(); 1602 1603 // fold vector ops 1604 if (VT.isVector()) { 1605 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1606 return FoldedVOp; 1607 1608 // fold (add x, 0) -> x, vector edition 1609 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1610 return N0; 1611 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1612 return N1; 1613 } 1614 1615 // fold (add x, undef) -> undef 1616 if (N0.getOpcode() == ISD::UNDEF) 1617 return N0; 1618 if (N1.getOpcode() == ISD::UNDEF) 1619 return N1; 1620 // fold (add c1, c2) -> c1+c2 1621 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1622 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1623 if (N0C && N1C) 1624 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C); 1625 // canonicalize constant to RHS 1626 if (isConstantIntBuildVectorOrConstantInt(N0) && 1627 !isConstantIntBuildVectorOrConstantInt(N1)) 1628 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1629 // fold (add x, 0) -> x 1630 if (isNullConstant(N1)) 1631 return N0; 1632 // fold (add Sym, c) -> Sym+c 1633 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1634 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1635 GA->getOpcode() == ISD::GlobalAddress) 1636 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1637 GA->getOffset() + 1638 (uint64_t)N1C->getSExtValue()); 1639 // fold ((c1-A)+c2) -> (c1+c2)-A 1640 if (N1C && N0.getOpcode() == ISD::SUB) 1641 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 1642 SDLoc DL(N); 1643 return DAG.getNode(ISD::SUB, DL, VT, 1644 DAG.getConstant(N1C->getAPIntValue()+ 1645 N0C->getAPIntValue(), DL, VT), 1646 N0.getOperand(1)); 1647 } 1648 // reassociate add 1649 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1)) 1650 return RADD; 1651 // fold ((0-A) + B) -> B-A 1652 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0))) 1653 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1654 // fold (A + (0-B)) -> A-B 1655 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0))) 1656 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1657 // fold (A+(B-A)) -> B 1658 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1659 return N1.getOperand(0); 1660 // fold ((B-A)+A) -> B 1661 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1662 return N0.getOperand(0); 1663 // fold (A+(B-(A+C))) to (B-C) 1664 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1665 N0 == N1.getOperand(1).getOperand(0)) 1666 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1667 N1.getOperand(1).getOperand(1)); 1668 // fold (A+(B-(C+A))) to (B-C) 1669 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1670 N0 == N1.getOperand(1).getOperand(1)) 1671 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1672 N1.getOperand(1).getOperand(0)); 1673 // fold (A+((B-A)+or-C)) to (B+or-C) 1674 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1675 N1.getOperand(0).getOpcode() == ISD::SUB && 1676 N0 == N1.getOperand(0).getOperand(1)) 1677 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1678 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1679 1680 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1681 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1682 SDValue N00 = N0.getOperand(0); 1683 SDValue N01 = N0.getOperand(1); 1684 SDValue N10 = N1.getOperand(0); 1685 SDValue N11 = N1.getOperand(1); 1686 1687 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1688 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1689 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1690 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1691 } 1692 1693 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1694 return SDValue(N, 0); 1695 1696 // fold (a+b) -> (a|b) iff a and b share no bits. 1697 if (VT.isInteger() && !VT.isVector()) { 1698 APInt LHSZero, LHSOne; 1699 APInt RHSZero, RHSOne; 1700 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1701 1702 if (LHSZero.getBoolValue()) { 1703 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1704 1705 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1706 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1707 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1708 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1709 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1710 } 1711 } 1712 } 1713 1714 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1715 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 1716 isNullConstant(N1.getOperand(0).getOperand(0))) 1717 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1718 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1719 N1.getOperand(0).getOperand(1), 1720 N1.getOperand(1))); 1721 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB && 1722 isNullConstant(N0.getOperand(0).getOperand(0))) 1723 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1724 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1725 N0.getOperand(0).getOperand(1), 1726 N0.getOperand(1))); 1727 1728 if (N1.getOpcode() == ISD::AND) { 1729 SDValue AndOp0 = N1.getOperand(0); 1730 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1731 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1732 1733 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1734 // and similar xforms where the inner op is either ~0 or 0. 1735 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) { 1736 SDLoc DL(N); 1737 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1738 } 1739 } 1740 1741 // add (sext i1), X -> sub X, (zext i1) 1742 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1743 N0.getOperand(0).getValueType() == MVT::i1 && 1744 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1745 SDLoc DL(N); 1746 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1747 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1748 } 1749 1750 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1751 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1752 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1753 if (TN->getVT() == MVT::i1) { 1754 SDLoc DL(N); 1755 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1756 DAG.getConstant(1, DL, VT)); 1757 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1758 } 1759 } 1760 1761 return SDValue(); 1762 } 1763 1764 SDValue DAGCombiner::visitADDC(SDNode *N) { 1765 SDValue N0 = N->getOperand(0); 1766 SDValue N1 = N->getOperand(1); 1767 EVT VT = N0.getValueType(); 1768 1769 // If the flag result is dead, turn this into an ADD. 1770 if (!N->hasAnyUseOfValue(1)) 1771 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1772 DAG.getNode(ISD::CARRY_FALSE, 1773 SDLoc(N), MVT::Glue)); 1774 1775 // canonicalize constant to RHS. 1776 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1777 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1778 if (N0C && !N1C) 1779 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1780 1781 // fold (addc x, 0) -> x + no carry out 1782 if (isNullConstant(N1)) 1783 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1784 SDLoc(N), MVT::Glue)); 1785 1786 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1787 APInt LHSZero, LHSOne; 1788 APInt RHSZero, RHSOne; 1789 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1790 1791 if (LHSZero.getBoolValue()) { 1792 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1793 1794 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1795 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1796 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1797 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1798 DAG.getNode(ISD::CARRY_FALSE, 1799 SDLoc(N), MVT::Glue)); 1800 } 1801 1802 return SDValue(); 1803 } 1804 1805 SDValue DAGCombiner::visitADDE(SDNode *N) { 1806 SDValue N0 = N->getOperand(0); 1807 SDValue N1 = N->getOperand(1); 1808 SDValue CarryIn = N->getOperand(2); 1809 1810 // canonicalize constant to RHS 1811 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1812 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1813 if (N0C && !N1C) 1814 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1815 N1, N0, CarryIn); 1816 1817 // fold (adde x, y, false) -> (addc x, y) 1818 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1819 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1820 1821 return SDValue(); 1822 } 1823 1824 // Since it may not be valid to emit a fold to zero for vector initializers 1825 // check if we can before folding. 1826 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1827 SelectionDAG &DAG, 1828 bool LegalOperations, bool LegalTypes) { 1829 if (!VT.isVector()) 1830 return DAG.getConstant(0, DL, VT); 1831 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1832 return DAG.getConstant(0, DL, VT); 1833 return SDValue(); 1834 } 1835 1836 SDValue DAGCombiner::visitSUB(SDNode *N) { 1837 SDValue N0 = N->getOperand(0); 1838 SDValue N1 = N->getOperand(1); 1839 EVT VT = N0.getValueType(); 1840 1841 // fold vector ops 1842 if (VT.isVector()) { 1843 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 1844 return FoldedVOp; 1845 1846 // fold (sub x, 0) -> x, vector edition 1847 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1848 return N0; 1849 } 1850 1851 // fold (sub x, x) -> 0 1852 // FIXME: Refactor this and xor and other similar operations together. 1853 if (N0 == N1) 1854 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1855 // fold (sub c1, c2) -> c1-c2 1856 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1857 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1858 if (N0C && N1C) 1859 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C); 1860 // fold (sub x, c) -> (add x, -c) 1861 if (N1C) { 1862 SDLoc DL(N); 1863 return DAG.getNode(ISD::ADD, DL, VT, N0, 1864 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 1865 } 1866 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1867 if (isAllOnesConstant(N0)) 1868 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1869 // fold A-(A-B) -> B 1870 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1871 return N1.getOperand(1); 1872 // fold (A+B)-A -> B 1873 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1874 return N0.getOperand(1); 1875 // fold (A+B)-B -> A 1876 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1877 return N0.getOperand(0); 1878 // fold C2-(A+C1) -> (C2-C1)-A 1879 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1880 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1881 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1882 SDLoc DL(N); 1883 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1884 DL, VT); 1885 return DAG.getNode(ISD::SUB, DL, VT, NewC, 1886 N1.getOperand(0)); 1887 } 1888 // fold ((A+(B+or-C))-B) -> A+or-C 1889 if (N0.getOpcode() == ISD::ADD && 1890 (N0.getOperand(1).getOpcode() == ISD::SUB || 1891 N0.getOperand(1).getOpcode() == ISD::ADD) && 1892 N0.getOperand(1).getOperand(0) == N1) 1893 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1894 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1895 // fold ((A+(C+B))-B) -> A+C 1896 if (N0.getOpcode() == ISD::ADD && 1897 N0.getOperand(1).getOpcode() == ISD::ADD && 1898 N0.getOperand(1).getOperand(1) == N1) 1899 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1900 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1901 // fold ((A-(B-C))-C) -> A-B 1902 if (N0.getOpcode() == ISD::SUB && 1903 N0.getOperand(1).getOpcode() == ISD::SUB && 1904 N0.getOperand(1).getOperand(1) == N1) 1905 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1906 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1907 1908 // If either operand of a sub is undef, the result is undef 1909 if (N0.getOpcode() == ISD::UNDEF) 1910 return N0; 1911 if (N1.getOpcode() == ISD::UNDEF) 1912 return N1; 1913 1914 // If the relocation model supports it, consider symbol offsets. 1915 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1916 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1917 // fold (sub Sym, c) -> Sym-c 1918 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1919 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1920 GA->getOffset() - 1921 (uint64_t)N1C->getSExtValue()); 1922 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1923 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1924 if (GA->getGlobal() == GB->getGlobal()) 1925 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1926 SDLoc(N), VT); 1927 } 1928 1929 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1930 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1931 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1932 if (TN->getVT() == MVT::i1) { 1933 SDLoc DL(N); 1934 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1935 DAG.getConstant(1, DL, VT)); 1936 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1937 } 1938 } 1939 1940 return SDValue(); 1941 } 1942 1943 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1944 SDValue N0 = N->getOperand(0); 1945 SDValue N1 = N->getOperand(1); 1946 EVT VT = N0.getValueType(); 1947 1948 // If the flag result is dead, turn this into an SUB. 1949 if (!N->hasAnyUseOfValue(1)) 1950 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1951 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1952 MVT::Glue)); 1953 1954 // fold (subc x, x) -> 0 + no borrow 1955 if (N0 == N1) { 1956 SDLoc DL(N); 1957 return CombineTo(N, DAG.getConstant(0, DL, VT), 1958 DAG.getNode(ISD::CARRY_FALSE, DL, 1959 MVT::Glue)); 1960 } 1961 1962 // fold (subc x, 0) -> x + no borrow 1963 if (isNullConstant(N1)) 1964 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1965 MVT::Glue)); 1966 1967 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1968 if (isAllOnesConstant(N0)) 1969 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1970 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1971 MVT::Glue)); 1972 1973 return SDValue(); 1974 } 1975 1976 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1977 SDValue N0 = N->getOperand(0); 1978 SDValue N1 = N->getOperand(1); 1979 SDValue CarryIn = N->getOperand(2); 1980 1981 // fold (sube x, y, false) -> (subc x, y) 1982 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1983 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1984 1985 return SDValue(); 1986 } 1987 1988 SDValue DAGCombiner::visitMUL(SDNode *N) { 1989 SDValue N0 = N->getOperand(0); 1990 SDValue N1 = N->getOperand(1); 1991 EVT VT = N0.getValueType(); 1992 1993 // fold (mul x, undef) -> 0 1994 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1995 return DAG.getConstant(0, SDLoc(N), VT); 1996 1997 bool N0IsConst = false; 1998 bool N1IsConst = false; 1999 APInt ConstValue0, ConstValue1; 2000 // fold vector ops 2001 if (VT.isVector()) { 2002 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2003 return FoldedVOp; 2004 2005 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 2006 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 2007 } else { 2008 N0IsConst = isa<ConstantSDNode>(N0); 2009 if (N0IsConst) 2010 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 2011 N1IsConst = isa<ConstantSDNode>(N1); 2012 if (N1IsConst) 2013 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 2014 } 2015 2016 // fold (mul c1, c2) -> c1*c2 2017 if (N0IsConst && N1IsConst) 2018 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 2019 N0.getNode(), N1.getNode()); 2020 2021 // canonicalize constant to RHS (vector doesn't have to splat) 2022 if (isConstantIntBuildVectorOrConstantInt(N0) && 2023 !isConstantIntBuildVectorOrConstantInt(N1)) 2024 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 2025 // fold (mul x, 0) -> 0 2026 if (N1IsConst && ConstValue1 == 0) 2027 return N1; 2028 // We require a splat of the entire scalar bit width for non-contiguous 2029 // bit patterns. 2030 bool IsFullSplat = 2031 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2032 // fold (mul x, 1) -> x 2033 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2034 return N0; 2035 // fold (mul x, -1) -> 0-x 2036 if (N1IsConst && ConstValue1.isAllOnesValue()) { 2037 SDLoc DL(N); 2038 return DAG.getNode(ISD::SUB, DL, VT, 2039 DAG.getConstant(0, DL, VT), N0); 2040 } 2041 // fold (mul x, (1 << c)) -> x << c 2042 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) { 2043 SDLoc DL(N); 2044 return DAG.getNode(ISD::SHL, DL, VT, N0, 2045 DAG.getConstant(ConstValue1.logBase2(), DL, 2046 getShiftAmountTy(N0.getValueType()))); 2047 } 2048 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2049 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 2050 unsigned Log2Val = (-ConstValue1).logBase2(); 2051 SDLoc DL(N); 2052 // FIXME: If the input is something that is easily negated (e.g. a 2053 // single-use add), we should put the negate there. 2054 return DAG.getNode(ISD::SUB, DL, VT, 2055 DAG.getConstant(0, DL, VT), 2056 DAG.getNode(ISD::SHL, DL, VT, N0, 2057 DAG.getConstant(Log2Val, DL, 2058 getShiftAmountTy(N0.getValueType())))); 2059 } 2060 2061 APInt Val; 2062 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2063 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2064 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2065 isa<ConstantSDNode>(N0.getOperand(1)))) { 2066 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2067 N1, N0.getOperand(1)); 2068 AddToWorklist(C3.getNode()); 2069 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2070 N0.getOperand(0), C3); 2071 } 2072 2073 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2074 // use. 2075 { 2076 SDValue Sh(nullptr,0), Y(nullptr,0); 2077 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2078 if (N0.getOpcode() == ISD::SHL && 2079 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2080 isa<ConstantSDNode>(N0.getOperand(1))) && 2081 N0.getNode()->hasOneUse()) { 2082 Sh = N0; Y = N1; 2083 } else if (N1.getOpcode() == ISD::SHL && 2084 isa<ConstantSDNode>(N1.getOperand(1)) && 2085 N1.getNode()->hasOneUse()) { 2086 Sh = N1; Y = N0; 2087 } 2088 2089 if (Sh.getNode()) { 2090 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2091 Sh.getOperand(0), Y); 2092 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2093 Mul, Sh.getOperand(1)); 2094 } 2095 } 2096 2097 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2098 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 2099 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2100 isa<ConstantSDNode>(N0.getOperand(1)))) 2101 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2102 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2103 N0.getOperand(0), N1), 2104 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2105 N0.getOperand(1), N1)); 2106 2107 // reassociate mul 2108 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1)) 2109 return RMUL; 2110 2111 return SDValue(); 2112 } 2113 2114 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2115 SDValue N0 = N->getOperand(0); 2116 SDValue N1 = N->getOperand(1); 2117 EVT VT = N->getValueType(0); 2118 2119 // fold vector ops 2120 if (VT.isVector()) 2121 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2122 return FoldedVOp; 2123 2124 // fold (sdiv c1, c2) -> c1/c2 2125 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2126 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2127 if (N0C && N1C && !N1C->isNullValue()) 2128 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C); 2129 // fold (sdiv X, 1) -> X 2130 if (N1C && N1C->isOne()) 2131 return N0; 2132 // fold (sdiv X, -1) -> 0-X 2133 if (N1C && N1C->isAllOnesValue()) { 2134 SDLoc DL(N); 2135 return DAG.getNode(ISD::SUB, DL, VT, 2136 DAG.getConstant(0, DL, VT), N0); 2137 } 2138 // If we know the sign bits of both operands are zero, strength reduce to a 2139 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2140 if (!VT.isVector()) { 2141 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2142 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2143 N0, N1); 2144 } 2145 2146 // fold (sdiv X, pow2) -> simple ops after legalize 2147 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() || 2148 (-N1C->getAPIntValue()).isPowerOf2())) { 2149 // If dividing by powers of two is cheap, then don't perform the following 2150 // fold. 2151 if (TLI.isPow2SDivCheap()) 2152 return SDValue(); 2153 2154 // Target-specific implementation of sdiv x, pow2. 2155 SDValue Res = BuildSDIVPow2(N); 2156 if (Res.getNode()) 2157 return Res; 2158 2159 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2160 SDLoc DL(N); 2161 2162 // Splat the sign bit into the register 2163 SDValue SGN = 2164 DAG.getNode(ISD::SRA, DL, VT, N0, 2165 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, 2166 getShiftAmountTy(N0.getValueType()))); 2167 AddToWorklist(SGN.getNode()); 2168 2169 // Add (N0 < 0) ? abs2 - 1 : 0; 2170 SDValue SRL = 2171 DAG.getNode(ISD::SRL, DL, VT, SGN, 2172 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL, 2173 getShiftAmountTy(SGN.getValueType()))); 2174 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL); 2175 AddToWorklist(SRL.getNode()); 2176 AddToWorklist(ADD.getNode()); // Divide by pow2 2177 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD, 2178 DAG.getConstant(lg2, DL, 2179 getShiftAmountTy(ADD.getValueType()))); 2180 2181 // If we're dividing by a positive value, we're done. Otherwise, we must 2182 // negate the result. 2183 if (N1C->getAPIntValue().isNonNegative()) 2184 return SRA; 2185 2186 AddToWorklist(SRA.getNode()); 2187 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 2188 } 2189 2190 // If integer divide is expensive and we satisfy the requirements, emit an 2191 // alternate sequence. 2192 if (N1C && !TLI.isIntDivCheap()) { 2193 SDValue Op = BuildSDIV(N); 2194 if (Op.getNode()) return Op; 2195 } 2196 2197 // undef / X -> 0 2198 if (N0.getOpcode() == ISD::UNDEF) 2199 return DAG.getConstant(0, SDLoc(N), VT); 2200 // X / undef -> undef 2201 if (N1.getOpcode() == ISD::UNDEF) 2202 return N1; 2203 2204 return SDValue(); 2205 } 2206 2207 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2208 SDValue N0 = N->getOperand(0); 2209 SDValue N1 = N->getOperand(1); 2210 EVT VT = N->getValueType(0); 2211 2212 // fold vector ops 2213 if (VT.isVector()) 2214 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2215 return FoldedVOp; 2216 2217 // fold (udiv c1, c2) -> c1/c2 2218 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2219 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2220 if (N0C && N1C && !N1C->isNullValue()) 2221 return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C); 2222 // fold (udiv x, (1 << c)) -> x >>u c 2223 if (N1C && N1C->getAPIntValue().isPowerOf2()) { 2224 SDLoc DL(N); 2225 return DAG.getNode(ISD::SRL, DL, VT, N0, 2226 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL, 2227 getShiftAmountTy(N0.getValueType()))); 2228 } 2229 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2230 if (N1.getOpcode() == ISD::SHL) { 2231 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2232 if (SHC->getAPIntValue().isPowerOf2()) { 2233 EVT ADDVT = N1.getOperand(1).getValueType(); 2234 SDLoc DL(N); 2235 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, 2236 N1.getOperand(1), 2237 DAG.getConstant(SHC->getAPIntValue() 2238 .logBase2(), 2239 DL, ADDVT)); 2240 AddToWorklist(Add.getNode()); 2241 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 2242 } 2243 } 2244 } 2245 // fold (udiv x, c) -> alternate 2246 if (N1C && !TLI.isIntDivCheap()) { 2247 SDValue Op = BuildUDIV(N); 2248 if (Op.getNode()) return Op; 2249 } 2250 2251 // undef / X -> 0 2252 if (N0.getOpcode() == ISD::UNDEF) 2253 return DAG.getConstant(0, SDLoc(N), VT); 2254 // X / undef -> undef 2255 if (N1.getOpcode() == ISD::UNDEF) 2256 return N1; 2257 2258 return SDValue(); 2259 } 2260 2261 SDValue DAGCombiner::visitSREM(SDNode *N) { 2262 SDValue N0 = N->getOperand(0); 2263 SDValue N1 = N->getOperand(1); 2264 EVT VT = N->getValueType(0); 2265 2266 // fold (srem c1, c2) -> c1%c2 2267 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2268 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2269 if (N0C && N1C && !N1C->isNullValue()) 2270 return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C); 2271 // If we know the sign bits of both operands are zero, strength reduce to a 2272 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2273 if (!VT.isVector()) { 2274 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2275 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2276 } 2277 2278 // If X/C can be simplified by the division-by-constant logic, lower 2279 // X%C to the equivalent of X-X/C*C. 2280 if (N1C && !N1C->isNullValue()) { 2281 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2282 AddToWorklist(Div.getNode()); 2283 SDValue OptimizedDiv = combine(Div.getNode()); 2284 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2285 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2286 OptimizedDiv, N1); 2287 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2288 AddToWorklist(Mul.getNode()); 2289 return Sub; 2290 } 2291 } 2292 2293 // undef % X -> 0 2294 if (N0.getOpcode() == ISD::UNDEF) 2295 return DAG.getConstant(0, SDLoc(N), VT); 2296 // X % undef -> undef 2297 if (N1.getOpcode() == ISD::UNDEF) 2298 return N1; 2299 2300 return SDValue(); 2301 } 2302 2303 SDValue DAGCombiner::visitUREM(SDNode *N) { 2304 SDValue N0 = N->getOperand(0); 2305 SDValue N1 = N->getOperand(1); 2306 EVT VT = N->getValueType(0); 2307 2308 // fold (urem c1, c2) -> c1%c2 2309 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2310 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2311 if (N0C && N1C && !N1C->isNullValue()) 2312 return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C); 2313 // fold (urem x, pow2) -> (and x, pow2-1) 2314 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) { 2315 SDLoc DL(N); 2316 return DAG.getNode(ISD::AND, DL, VT, N0, 2317 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT)); 2318 } 2319 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2320 if (N1.getOpcode() == ISD::SHL) { 2321 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2322 if (SHC->getAPIntValue().isPowerOf2()) { 2323 SDLoc DL(N); 2324 SDValue Add = 2325 DAG.getNode(ISD::ADD, DL, VT, N1, 2326 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, 2327 VT)); 2328 AddToWorklist(Add.getNode()); 2329 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 2330 } 2331 } 2332 } 2333 2334 // If X/C can be simplified by the division-by-constant logic, lower 2335 // X%C to the equivalent of X-X/C*C. 2336 if (N1C && !N1C->isNullValue()) { 2337 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2338 AddToWorklist(Div.getNode()); 2339 SDValue OptimizedDiv = combine(Div.getNode()); 2340 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2341 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2342 OptimizedDiv, N1); 2343 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2344 AddToWorklist(Mul.getNode()); 2345 return Sub; 2346 } 2347 } 2348 2349 // undef % X -> 0 2350 if (N0.getOpcode() == ISD::UNDEF) 2351 return DAG.getConstant(0, SDLoc(N), VT); 2352 // X % undef -> undef 2353 if (N1.getOpcode() == ISD::UNDEF) 2354 return N1; 2355 2356 return SDValue(); 2357 } 2358 2359 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2360 SDValue N0 = N->getOperand(0); 2361 SDValue N1 = N->getOperand(1); 2362 EVT VT = N->getValueType(0); 2363 SDLoc DL(N); 2364 2365 // fold (mulhs x, 0) -> 0 2366 if (isNullConstant(N1)) 2367 return N1; 2368 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2369 if (isOneConstant(N1)) { 2370 SDLoc DL(N); 2371 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 2372 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2373 DL, 2374 getShiftAmountTy(N0.getValueType()))); 2375 } 2376 // fold (mulhs x, undef) -> 0 2377 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2378 return DAG.getConstant(0, SDLoc(N), VT); 2379 2380 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2381 // plus a shift. 2382 if (VT.isSimple() && !VT.isVector()) { 2383 MVT Simple = VT.getSimpleVT(); 2384 unsigned SimpleSize = Simple.getSizeInBits(); 2385 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2386 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2387 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2388 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2389 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2390 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2391 DAG.getConstant(SimpleSize, DL, 2392 getShiftAmountTy(N1.getValueType()))); 2393 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2394 } 2395 } 2396 2397 return SDValue(); 2398 } 2399 2400 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2401 SDValue N0 = N->getOperand(0); 2402 SDValue N1 = N->getOperand(1); 2403 EVT VT = N->getValueType(0); 2404 SDLoc DL(N); 2405 2406 // fold (mulhu x, 0) -> 0 2407 if (isNullConstant(N1)) 2408 return N1; 2409 // fold (mulhu x, 1) -> 0 2410 if (isOneConstant(N1)) 2411 return DAG.getConstant(0, DL, N0.getValueType()); 2412 // fold (mulhu x, undef) -> 0 2413 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2414 return DAG.getConstant(0, DL, VT); 2415 2416 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2417 // plus a shift. 2418 if (VT.isSimple() && !VT.isVector()) { 2419 MVT Simple = VT.getSimpleVT(); 2420 unsigned SimpleSize = Simple.getSizeInBits(); 2421 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2422 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2423 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2424 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2425 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2426 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2427 DAG.getConstant(SimpleSize, DL, 2428 getShiftAmountTy(N1.getValueType()))); 2429 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2430 } 2431 } 2432 2433 return SDValue(); 2434 } 2435 2436 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2437 /// give the opcodes for the two computations that are being performed. Return 2438 /// true if a simplification was made. 2439 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2440 unsigned HiOp) { 2441 // If the high half is not needed, just compute the low half. 2442 bool HiExists = N->hasAnyUseOfValue(1); 2443 if (!HiExists && 2444 (!LegalOperations || 2445 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2446 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2447 return CombineTo(N, Res, Res); 2448 } 2449 2450 // If the low half is not needed, just compute the high half. 2451 bool LoExists = N->hasAnyUseOfValue(0); 2452 if (!LoExists && 2453 (!LegalOperations || 2454 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2455 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2456 return CombineTo(N, Res, Res); 2457 } 2458 2459 // If both halves are used, return as it is. 2460 if (LoExists && HiExists) 2461 return SDValue(); 2462 2463 // If the two computed results can be simplified separately, separate them. 2464 if (LoExists) { 2465 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2466 AddToWorklist(Lo.getNode()); 2467 SDValue LoOpt = combine(Lo.getNode()); 2468 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2469 (!LegalOperations || 2470 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2471 return CombineTo(N, LoOpt, LoOpt); 2472 } 2473 2474 if (HiExists) { 2475 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2476 AddToWorklist(Hi.getNode()); 2477 SDValue HiOpt = combine(Hi.getNode()); 2478 if (HiOpt.getNode() && HiOpt != Hi && 2479 (!LegalOperations || 2480 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2481 return CombineTo(N, HiOpt, HiOpt); 2482 } 2483 2484 return SDValue(); 2485 } 2486 2487 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2488 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2489 if (Res.getNode()) return Res; 2490 2491 EVT VT = N->getValueType(0); 2492 SDLoc DL(N); 2493 2494 // If the type is twice as wide is legal, transform the mulhu to a wider 2495 // multiply plus a shift. 2496 if (VT.isSimple() && !VT.isVector()) { 2497 MVT Simple = VT.getSimpleVT(); 2498 unsigned SimpleSize = Simple.getSizeInBits(); 2499 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2500 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2501 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2502 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2503 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2504 // Compute the high part as N1. 2505 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2506 DAG.getConstant(SimpleSize, DL, 2507 getShiftAmountTy(Lo.getValueType()))); 2508 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2509 // Compute the low part as N0. 2510 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2511 return CombineTo(N, Lo, Hi); 2512 } 2513 } 2514 2515 return SDValue(); 2516 } 2517 2518 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2519 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2520 if (Res.getNode()) return Res; 2521 2522 EVT VT = N->getValueType(0); 2523 SDLoc DL(N); 2524 2525 // If the type is twice as wide is legal, transform the mulhu to a wider 2526 // multiply plus a shift. 2527 if (VT.isSimple() && !VT.isVector()) { 2528 MVT Simple = VT.getSimpleVT(); 2529 unsigned SimpleSize = Simple.getSizeInBits(); 2530 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2531 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2532 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2533 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2534 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2535 // Compute the high part as N1. 2536 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2537 DAG.getConstant(SimpleSize, DL, 2538 getShiftAmountTy(Lo.getValueType()))); 2539 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2540 // Compute the low part as N0. 2541 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2542 return CombineTo(N, Lo, Hi); 2543 } 2544 } 2545 2546 return SDValue(); 2547 } 2548 2549 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2550 // (smulo x, 2) -> (saddo x, x) 2551 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2552 if (C2->getAPIntValue() == 2) 2553 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2554 N->getOperand(0), N->getOperand(0)); 2555 2556 return SDValue(); 2557 } 2558 2559 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2560 // (umulo x, 2) -> (uaddo x, x) 2561 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2562 if (C2->getAPIntValue() == 2) 2563 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2564 N->getOperand(0), N->getOperand(0)); 2565 2566 return SDValue(); 2567 } 2568 2569 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2570 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2571 if (Res.getNode()) return Res; 2572 2573 return SDValue(); 2574 } 2575 2576 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2577 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2578 if (Res.getNode()) return Res; 2579 2580 return SDValue(); 2581 } 2582 2583 /// If this is a binary operator with two operands of the same opcode, try to 2584 /// simplify it. 2585 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2586 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2587 EVT VT = N0.getValueType(); 2588 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2589 2590 // Bail early if none of these transforms apply. 2591 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2592 2593 // For each of OP in AND/OR/XOR: 2594 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2595 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2596 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2597 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2598 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2599 // 2600 // do not sink logical op inside of a vector extend, since it may combine 2601 // into a vsetcc. 2602 EVT Op0VT = N0.getOperand(0).getValueType(); 2603 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2604 N0.getOpcode() == ISD::SIGN_EXTEND || 2605 N0.getOpcode() == ISD::BSWAP || 2606 // Avoid infinite looping with PromoteIntBinOp. 2607 (N0.getOpcode() == ISD::ANY_EXTEND && 2608 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2609 (N0.getOpcode() == ISD::TRUNCATE && 2610 (!TLI.isZExtFree(VT, Op0VT) || 2611 !TLI.isTruncateFree(Op0VT, VT)) && 2612 TLI.isTypeLegal(Op0VT))) && 2613 !VT.isVector() && 2614 Op0VT == N1.getOperand(0).getValueType() && 2615 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2616 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2617 N0.getOperand(0).getValueType(), 2618 N0.getOperand(0), N1.getOperand(0)); 2619 AddToWorklist(ORNode.getNode()); 2620 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2621 } 2622 2623 // For each of OP in SHL/SRL/SRA/AND... 2624 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2625 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2626 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2627 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2628 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2629 N0.getOperand(1) == N1.getOperand(1)) { 2630 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2631 N0.getOperand(0).getValueType(), 2632 N0.getOperand(0), N1.getOperand(0)); 2633 AddToWorklist(ORNode.getNode()); 2634 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2635 ORNode, N0.getOperand(1)); 2636 } 2637 2638 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2639 // Only perform this optimization after type legalization and before 2640 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2641 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2642 // we don't want to undo this promotion. 2643 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2644 // on scalars. 2645 if ((N0.getOpcode() == ISD::BITCAST || 2646 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2647 Level == AfterLegalizeTypes) { 2648 SDValue In0 = N0.getOperand(0); 2649 SDValue In1 = N1.getOperand(0); 2650 EVT In0Ty = In0.getValueType(); 2651 EVT In1Ty = In1.getValueType(); 2652 SDLoc DL(N); 2653 // If both incoming values are integers, and the original types are the 2654 // same. 2655 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2656 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2657 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2658 AddToWorklist(Op.getNode()); 2659 return BC; 2660 } 2661 } 2662 2663 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2664 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2665 // If both shuffles use the same mask, and both shuffle within a single 2666 // vector, then it is worthwhile to move the swizzle after the operation. 2667 // The type-legalizer generates this pattern when loading illegal 2668 // vector types from memory. In many cases this allows additional shuffle 2669 // optimizations. 2670 // There are other cases where moving the shuffle after the xor/and/or 2671 // is profitable even if shuffles don't perform a swizzle. 2672 // If both shuffles use the same mask, and both shuffles have the same first 2673 // or second operand, then it might still be profitable to move the shuffle 2674 // after the xor/and/or operation. 2675 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2676 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2677 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2678 2679 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2680 "Inputs to shuffles are not the same type"); 2681 2682 // Check that both shuffles use the same mask. The masks are known to be of 2683 // the same length because the result vector type is the same. 2684 // Check also that shuffles have only one use to avoid introducing extra 2685 // instructions. 2686 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2687 SVN0->getMask().equals(SVN1->getMask())) { 2688 SDValue ShOp = N0->getOperand(1); 2689 2690 // Don't try to fold this node if it requires introducing a 2691 // build vector of all zeros that might be illegal at this stage. 2692 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2693 if (!LegalTypes) 2694 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2695 else 2696 ShOp = SDValue(); 2697 } 2698 2699 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2700 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2701 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2702 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2703 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2704 N0->getOperand(0), N1->getOperand(0)); 2705 AddToWorklist(NewNode.getNode()); 2706 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2707 &SVN0->getMask()[0]); 2708 } 2709 2710 // Don't try to fold this node if it requires introducing a 2711 // build vector of all zeros that might be illegal at this stage. 2712 ShOp = N0->getOperand(0); 2713 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2714 if (!LegalTypes) 2715 ShOp = DAG.getConstant(0, SDLoc(N), VT); 2716 else 2717 ShOp = SDValue(); 2718 } 2719 2720 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2721 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2722 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2723 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2724 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2725 N0->getOperand(1), N1->getOperand(1)); 2726 AddToWorklist(NewNode.getNode()); 2727 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2728 &SVN0->getMask()[0]); 2729 } 2730 } 2731 } 2732 2733 return SDValue(); 2734 } 2735 2736 /// This contains all DAGCombine rules which reduce two values combined by 2737 /// an And operation to a single value. This makes them reusable in the context 2738 /// of visitSELECT(). Rules involving constants are not included as 2739 /// visitSELECT() already handles those cases. 2740 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, 2741 SDNode *LocReference) { 2742 EVT VT = N1.getValueType(); 2743 2744 // fold (and x, undef) -> 0 2745 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2746 return DAG.getConstant(0, SDLoc(LocReference), VT); 2747 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2748 SDValue LL, LR, RL, RR, CC0, CC1; 2749 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2750 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2751 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2752 2753 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2754 LL.getValueType().isInteger()) { 2755 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2756 if (isNullConstant(LR) && Op1 == ISD::SETEQ) { 2757 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2758 LR.getValueType(), LL, RL); 2759 AddToWorklist(ORNode.getNode()); 2760 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2761 } 2762 if (isAllOnesConstant(LR)) { 2763 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2764 if (Op1 == ISD::SETEQ) { 2765 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2766 LR.getValueType(), LL, RL); 2767 AddToWorklist(ANDNode.getNode()); 2768 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 2769 } 2770 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2771 if (Op1 == ISD::SETGT) { 2772 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2773 LR.getValueType(), LL, RL); 2774 AddToWorklist(ORNode.getNode()); 2775 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 2776 } 2777 } 2778 } 2779 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2780 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2781 Op0 == Op1 && LL.getValueType().isInteger() && 2782 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) || 2783 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 2784 SDLoc DL(N0); 2785 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(), 2786 LL, DAG.getConstant(1, DL, 2787 LL.getValueType())); 2788 AddToWorklist(ADDNode.getNode()); 2789 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode, 2790 DAG.getConstant(2, DL, LL.getValueType()), 2791 ISD::SETUGE); 2792 } 2793 // canonicalize equivalent to ll == rl 2794 if (LL == RR && LR == RL) { 2795 Op1 = ISD::getSetCCSwappedOperands(Op1); 2796 std::swap(RL, RR); 2797 } 2798 if (LL == RL && LR == RR) { 2799 bool isInteger = LL.getValueType().isInteger(); 2800 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2801 if (Result != ISD::SETCC_INVALID && 2802 (!LegalOperations || 2803 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2804 TLI.isOperationLegal(ISD::SETCC, 2805 getSetCCResultType(N0.getSimpleValueType()))))) 2806 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 2807 LL, LR, Result); 2808 } 2809 } 2810 2811 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 2812 VT.getSizeInBits() <= 64) { 2813 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2814 APInt ADDC = ADDI->getAPIntValue(); 2815 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2816 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 2817 // immediate for an add, but it is legal if its top c2 bits are set, 2818 // transform the ADD so the immediate doesn't need to be materialized 2819 // in a register. 2820 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 2821 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 2822 SRLI->getZExtValue()); 2823 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 2824 ADDC |= Mask; 2825 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 2826 SDLoc DL(N0); 2827 SDValue NewAdd = 2828 DAG.getNode(ISD::ADD, DL, VT, 2829 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 2830 CombineTo(N0.getNode(), NewAdd); 2831 // Return N so it doesn't get rechecked! 2832 return SDValue(LocReference, 0); 2833 } 2834 } 2835 } 2836 } 2837 } 2838 } 2839 2840 return SDValue(); 2841 } 2842 2843 SDValue DAGCombiner::visitAND(SDNode *N) { 2844 SDValue N0 = N->getOperand(0); 2845 SDValue N1 = N->getOperand(1); 2846 EVT VT = N1.getValueType(); 2847 2848 // fold vector ops 2849 if (VT.isVector()) { 2850 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2851 return FoldedVOp; 2852 2853 // fold (and x, 0) -> 0, vector edition 2854 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2855 // do not return N0, because undef node may exist in N0 2856 return DAG.getConstant( 2857 APInt::getNullValue( 2858 N0.getValueType().getScalarType().getSizeInBits()), 2859 SDLoc(N), N0.getValueType()); 2860 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2861 // do not return N1, because undef node may exist in N1 2862 return DAG.getConstant( 2863 APInt::getNullValue( 2864 N1.getValueType().getScalarType().getSizeInBits()), 2865 SDLoc(N), N1.getValueType()); 2866 2867 // fold (and x, -1) -> x, vector edition 2868 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2869 return N1; 2870 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2871 return N0; 2872 } 2873 2874 // fold (and c1, c2) -> c1&c2 2875 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2876 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2877 if (N0C && N1C) 2878 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 2879 // canonicalize constant to RHS 2880 if (isConstantIntBuildVectorOrConstantInt(N0) && 2881 !isConstantIntBuildVectorOrConstantInt(N1)) 2882 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2883 // fold (and x, -1) -> x 2884 if (isAllOnesConstant(N1)) 2885 return N0; 2886 // if (and x, c) is known to be zero, return 0 2887 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2888 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2889 APInt::getAllOnesValue(BitWidth))) 2890 return DAG.getConstant(0, SDLoc(N), VT); 2891 // reassociate and 2892 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1)) 2893 return RAND; 2894 // fold (and (or x, C), D) -> D if (C & D) == D 2895 if (N1C && N0.getOpcode() == ISD::OR) 2896 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2897 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2898 return N1; 2899 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2900 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2901 SDValue N0Op0 = N0.getOperand(0); 2902 APInt Mask = ~N1C->getAPIntValue(); 2903 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2904 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2905 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2906 N0.getValueType(), N0Op0); 2907 2908 // Replace uses of the AND with uses of the Zero extend node. 2909 CombineTo(N, Zext); 2910 2911 // We actually want to replace all uses of the any_extend with the 2912 // zero_extend, to avoid duplicating things. This will later cause this 2913 // AND to be folded. 2914 CombineTo(N0.getNode(), Zext); 2915 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2916 } 2917 } 2918 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2919 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2920 // already be zero by virtue of the width of the base type of the load. 2921 // 2922 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2923 // more cases. 2924 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2925 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2926 N0.getOpcode() == ISD::LOAD) { 2927 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2928 N0 : N0.getOperand(0) ); 2929 2930 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2931 // This can be a pure constant or a vector splat, in which case we treat the 2932 // vector as a scalar and use the splat value. 2933 APInt Constant = APInt::getNullValue(1); 2934 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2935 Constant = C->getAPIntValue(); 2936 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2937 APInt SplatValue, SplatUndef; 2938 unsigned SplatBitSize; 2939 bool HasAnyUndefs; 2940 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2941 SplatBitSize, HasAnyUndefs); 2942 if (IsSplat) { 2943 // Undef bits can contribute to a possible optimisation if set, so 2944 // set them. 2945 SplatValue |= SplatUndef; 2946 2947 // The splat value may be something like "0x00FFFFFF", which means 0 for 2948 // the first vector value and FF for the rest, repeating. We need a mask 2949 // that will apply equally to all members of the vector, so AND all the 2950 // lanes of the constant together. 2951 EVT VT = Vector->getValueType(0); 2952 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2953 2954 // If the splat value has been compressed to a bitlength lower 2955 // than the size of the vector lane, we need to re-expand it to 2956 // the lane size. 2957 if (BitWidth > SplatBitSize) 2958 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2959 SplatBitSize < BitWidth; 2960 SplatBitSize = SplatBitSize * 2) 2961 SplatValue |= SplatValue.shl(SplatBitSize); 2962 2963 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 2964 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 2965 if (SplatBitSize % BitWidth == 0) { 2966 Constant = APInt::getAllOnesValue(BitWidth); 2967 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2968 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2969 } 2970 } 2971 } 2972 2973 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2974 // actually legal and isn't going to get expanded, else this is a false 2975 // optimisation. 2976 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2977 Load->getValueType(0), 2978 Load->getMemoryVT()); 2979 2980 // Resize the constant to the same size as the original memory access before 2981 // extension. If it is still the AllOnesValue then this AND is completely 2982 // unneeded. 2983 Constant = 2984 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2985 2986 bool B; 2987 switch (Load->getExtensionType()) { 2988 default: B = false; break; 2989 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2990 case ISD::ZEXTLOAD: 2991 case ISD::NON_EXTLOAD: B = true; break; 2992 } 2993 2994 if (B && Constant.isAllOnesValue()) { 2995 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2996 // preserve semantics once we get rid of the AND. 2997 SDValue NewLoad(Load, 0); 2998 if (Load->getExtensionType() == ISD::EXTLOAD) { 2999 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 3000 Load->getValueType(0), SDLoc(Load), 3001 Load->getChain(), Load->getBasePtr(), 3002 Load->getOffset(), Load->getMemoryVT(), 3003 Load->getMemOperand()); 3004 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 3005 if (Load->getNumValues() == 3) { 3006 // PRE/POST_INC loads have 3 values. 3007 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 3008 NewLoad.getValue(2) }; 3009 CombineTo(Load, To, 3, true); 3010 } else { 3011 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 3012 } 3013 } 3014 3015 // Fold the AND away, taking care not to fold to the old load node if we 3016 // replaced it. 3017 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 3018 3019 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3020 } 3021 } 3022 3023 // fold (and (load x), 255) -> (zextload x, i8) 3024 // fold (and (extload x, i16), 255) -> (zextload x, i8) 3025 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 3026 if (N1C && (N0.getOpcode() == ISD::LOAD || 3027 (N0.getOpcode() == ISD::ANY_EXTEND && 3028 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 3029 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 3030 LoadSDNode *LN0 = HasAnyExt 3031 ? cast<LoadSDNode>(N0.getOperand(0)) 3032 : cast<LoadSDNode>(N0); 3033 if (LN0->getExtensionType() != ISD::SEXTLOAD && 3034 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 3035 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 3036 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 3037 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 3038 EVT LoadedVT = LN0->getMemoryVT(); 3039 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 3040 3041 if (ExtVT == LoadedVT && 3042 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3043 ExtVT))) { 3044 3045 SDValue NewLoad = 3046 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3047 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3048 LN0->getMemOperand()); 3049 AddToWorklist(N); 3050 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3051 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3052 } 3053 3054 // Do not change the width of a volatile load. 3055 // Do not generate loads of non-round integer types since these can 3056 // be expensive (and would be wrong if the type is not byte sized). 3057 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 3058 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3059 ExtVT))) { 3060 EVT PtrType = LN0->getOperand(1).getValueType(); 3061 3062 unsigned Alignment = LN0->getAlignment(); 3063 SDValue NewPtr = LN0->getBasePtr(); 3064 3065 // For big endian targets, we need to add an offset to the pointer 3066 // to load the correct bytes. For little endian systems, we merely 3067 // need to read fewer bytes from the same pointer. 3068 if (TLI.isBigEndian()) { 3069 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3070 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3071 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3072 SDLoc DL(LN0); 3073 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, 3074 NewPtr, DAG.getConstant(PtrOff, DL, PtrType)); 3075 Alignment = MinAlign(Alignment, PtrOff); 3076 } 3077 3078 AddToWorklist(NewPtr.getNode()); 3079 3080 SDValue Load = 3081 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3082 LN0->getChain(), NewPtr, 3083 LN0->getPointerInfo(), 3084 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3085 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3086 AddToWorklist(N); 3087 CombineTo(LN0, Load, Load.getValue(1)); 3088 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3089 } 3090 } 3091 } 3092 } 3093 3094 if (SDValue Combined = visitANDLike(N0, N1, N)) 3095 return Combined; 3096 3097 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 3098 if (N0.getOpcode() == N1.getOpcode()) { 3099 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3100 if (Tmp.getNode()) return Tmp; 3101 } 3102 3103 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 3104 // fold (and (sra)) -> (and (srl)) when possible. 3105 if (!VT.isVector() && 3106 SimplifyDemandedBits(SDValue(N, 0))) 3107 return SDValue(N, 0); 3108 3109 // fold (zext_inreg (extload x)) -> (zextload x) 3110 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 3111 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3112 EVT MemVT = LN0->getMemoryVT(); 3113 // If we zero all the possible extended bits, then we can turn this into 3114 // a zextload if we are running before legalize or the operation is legal. 3115 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3116 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3117 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3118 ((!LegalOperations && !LN0->isVolatile()) || 3119 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3120 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3121 LN0->getChain(), LN0->getBasePtr(), 3122 MemVT, LN0->getMemOperand()); 3123 AddToWorklist(N); 3124 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3125 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3126 } 3127 } 3128 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 3129 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 3130 N0.hasOneUse()) { 3131 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 3132 EVT MemVT = LN0->getMemoryVT(); 3133 // If we zero all the possible extended bits, then we can turn this into 3134 // a zextload if we are running before legalize or the operation is legal. 3135 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 3136 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 3137 BitWidth - MemVT.getScalarType().getSizeInBits())) && 3138 ((!LegalOperations && !LN0->isVolatile()) || 3139 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 3140 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 3141 LN0->getChain(), LN0->getBasePtr(), 3142 MemVT, LN0->getMemOperand()); 3143 AddToWorklist(N); 3144 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 3145 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3146 } 3147 } 3148 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3149 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3150 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3151 N0.getOperand(1), false); 3152 if (BSwap.getNode()) 3153 return BSwap; 3154 } 3155 3156 return SDValue(); 3157 } 3158 3159 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3160 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3161 bool DemandHighBits) { 3162 if (!LegalOperations) 3163 return SDValue(); 3164 3165 EVT VT = N->getValueType(0); 3166 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3167 return SDValue(); 3168 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3169 return SDValue(); 3170 3171 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3172 bool LookPassAnd0 = false; 3173 bool LookPassAnd1 = false; 3174 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3175 std::swap(N0, N1); 3176 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3177 std::swap(N0, N1); 3178 if (N0.getOpcode() == ISD::AND) { 3179 if (!N0.getNode()->hasOneUse()) 3180 return SDValue(); 3181 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3182 if (!N01C || N01C->getZExtValue() != 0xFF00) 3183 return SDValue(); 3184 N0 = N0.getOperand(0); 3185 LookPassAnd0 = true; 3186 } 3187 3188 if (N1.getOpcode() == ISD::AND) { 3189 if (!N1.getNode()->hasOneUse()) 3190 return SDValue(); 3191 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3192 if (!N11C || N11C->getZExtValue() != 0xFF) 3193 return SDValue(); 3194 N1 = N1.getOperand(0); 3195 LookPassAnd1 = true; 3196 } 3197 3198 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3199 std::swap(N0, N1); 3200 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3201 return SDValue(); 3202 if (!N0.getNode()->hasOneUse() || 3203 !N1.getNode()->hasOneUse()) 3204 return SDValue(); 3205 3206 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3207 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3208 if (!N01C || !N11C) 3209 return SDValue(); 3210 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3211 return SDValue(); 3212 3213 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3214 SDValue N00 = N0->getOperand(0); 3215 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3216 if (!N00.getNode()->hasOneUse()) 3217 return SDValue(); 3218 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3219 if (!N001C || N001C->getZExtValue() != 0xFF) 3220 return SDValue(); 3221 N00 = N00.getOperand(0); 3222 LookPassAnd0 = true; 3223 } 3224 3225 SDValue N10 = N1->getOperand(0); 3226 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3227 if (!N10.getNode()->hasOneUse()) 3228 return SDValue(); 3229 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3230 if (!N101C || N101C->getZExtValue() != 0xFF00) 3231 return SDValue(); 3232 N10 = N10.getOperand(0); 3233 LookPassAnd1 = true; 3234 } 3235 3236 if (N00 != N10) 3237 return SDValue(); 3238 3239 // Make sure everything beyond the low halfword gets set to zero since the SRL 3240 // 16 will clear the top bits. 3241 unsigned OpSizeInBits = VT.getSizeInBits(); 3242 if (DemandHighBits && OpSizeInBits > 16) { 3243 // If the left-shift isn't masked out then the only way this is a bswap is 3244 // if all bits beyond the low 8 are 0. In that case the entire pattern 3245 // reduces to a left shift anyway: leave it for other parts of the combiner. 3246 if (!LookPassAnd0) 3247 return SDValue(); 3248 3249 // However, if the right shift isn't masked out then it might be because 3250 // it's not needed. See if we can spot that too. 3251 if (!LookPassAnd1 && 3252 !DAG.MaskedValueIsZero( 3253 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3254 return SDValue(); 3255 } 3256 3257 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3258 if (OpSizeInBits > 16) { 3259 SDLoc DL(N); 3260 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 3261 DAG.getConstant(OpSizeInBits - 16, DL, 3262 getShiftAmountTy(VT))); 3263 } 3264 return Res; 3265 } 3266 3267 /// Return true if the specified node is an element that makes up a 32-bit 3268 /// packed halfword byteswap. 3269 /// ((x & 0x000000ff) << 8) | 3270 /// ((x & 0x0000ff00) >> 8) | 3271 /// ((x & 0x00ff0000) << 8) | 3272 /// ((x & 0xff000000) >> 8) 3273 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3274 if (!N.getNode()->hasOneUse()) 3275 return false; 3276 3277 unsigned Opc = N.getOpcode(); 3278 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3279 return false; 3280 3281 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3282 if (!N1C) 3283 return false; 3284 3285 unsigned Num; 3286 switch (N1C->getZExtValue()) { 3287 default: 3288 return false; 3289 case 0xFF: Num = 0; break; 3290 case 0xFF00: Num = 1; break; 3291 case 0xFF0000: Num = 2; break; 3292 case 0xFF000000: Num = 3; break; 3293 } 3294 3295 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3296 SDValue N0 = N.getOperand(0); 3297 if (Opc == ISD::AND) { 3298 if (Num == 0 || Num == 2) { 3299 // (x >> 8) & 0xff 3300 // (x >> 8) & 0xff0000 3301 if (N0.getOpcode() != ISD::SRL) 3302 return false; 3303 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3304 if (!C || C->getZExtValue() != 8) 3305 return false; 3306 } else { 3307 // (x << 8) & 0xff00 3308 // (x << 8) & 0xff000000 3309 if (N0.getOpcode() != ISD::SHL) 3310 return false; 3311 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3312 if (!C || C->getZExtValue() != 8) 3313 return false; 3314 } 3315 } else if (Opc == ISD::SHL) { 3316 // (x & 0xff) << 8 3317 // (x & 0xff0000) << 8 3318 if (Num != 0 && Num != 2) 3319 return false; 3320 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3321 if (!C || C->getZExtValue() != 8) 3322 return false; 3323 } else { // Opc == ISD::SRL 3324 // (x & 0xff00) >> 8 3325 // (x & 0xff000000) >> 8 3326 if (Num != 1 && Num != 3) 3327 return false; 3328 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3329 if (!C || C->getZExtValue() != 8) 3330 return false; 3331 } 3332 3333 if (Parts[Num]) 3334 return false; 3335 3336 Parts[Num] = N0.getOperand(0).getNode(); 3337 return true; 3338 } 3339 3340 /// Match a 32-bit packed halfword bswap. That is 3341 /// ((x & 0x000000ff) << 8) | 3342 /// ((x & 0x0000ff00) >> 8) | 3343 /// ((x & 0x00ff0000) << 8) | 3344 /// ((x & 0xff000000) >> 8) 3345 /// => (rotl (bswap x), 16) 3346 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3347 if (!LegalOperations) 3348 return SDValue(); 3349 3350 EVT VT = N->getValueType(0); 3351 if (VT != MVT::i32) 3352 return SDValue(); 3353 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3354 return SDValue(); 3355 3356 // Look for either 3357 // (or (or (and), (and)), (or (and), (and))) 3358 // (or (or (or (and), (and)), (and)), (and)) 3359 if (N0.getOpcode() != ISD::OR) 3360 return SDValue(); 3361 SDValue N00 = N0.getOperand(0); 3362 SDValue N01 = N0.getOperand(1); 3363 SDNode *Parts[4] = {}; 3364 3365 if (N1.getOpcode() == ISD::OR && 3366 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3367 // (or (or (and), (and)), (or (and), (and))) 3368 SDValue N000 = N00.getOperand(0); 3369 if (!isBSwapHWordElement(N000, Parts)) 3370 return SDValue(); 3371 3372 SDValue N001 = N00.getOperand(1); 3373 if (!isBSwapHWordElement(N001, Parts)) 3374 return SDValue(); 3375 SDValue N010 = N01.getOperand(0); 3376 if (!isBSwapHWordElement(N010, Parts)) 3377 return SDValue(); 3378 SDValue N011 = N01.getOperand(1); 3379 if (!isBSwapHWordElement(N011, Parts)) 3380 return SDValue(); 3381 } else { 3382 // (or (or (or (and), (and)), (and)), (and)) 3383 if (!isBSwapHWordElement(N1, Parts)) 3384 return SDValue(); 3385 if (!isBSwapHWordElement(N01, Parts)) 3386 return SDValue(); 3387 if (N00.getOpcode() != ISD::OR) 3388 return SDValue(); 3389 SDValue N000 = N00.getOperand(0); 3390 if (!isBSwapHWordElement(N000, Parts)) 3391 return SDValue(); 3392 SDValue N001 = N00.getOperand(1); 3393 if (!isBSwapHWordElement(N001, Parts)) 3394 return SDValue(); 3395 } 3396 3397 // Make sure the parts are all coming from the same node. 3398 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3399 return SDValue(); 3400 3401 SDLoc DL(N); 3402 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 3403 SDValue(Parts[0], 0)); 3404 3405 // Result of the bswap should be rotated by 16. If it's not legal, then 3406 // do (x << 16) | (x >> 16). 3407 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 3408 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3409 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 3410 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3411 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 3412 return DAG.getNode(ISD::OR, DL, VT, 3413 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 3414 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 3415 } 3416 3417 /// This contains all DAGCombine rules which reduce two values combined by 3418 /// an Or operation to a single value \see visitANDLike(). 3419 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) { 3420 EVT VT = N1.getValueType(); 3421 // fold (or x, undef) -> -1 3422 if (!LegalOperations && 3423 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3424 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3425 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), 3426 SDLoc(LocReference), VT); 3427 } 3428 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3429 SDValue LL, LR, RL, RR, CC0, CC1; 3430 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3431 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3432 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3433 3434 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) { 3435 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3436 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3437 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3438 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3439 LR.getValueType(), LL, RL); 3440 AddToWorklist(ORNode.getNode()); 3441 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1); 3442 } 3443 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3444 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3445 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3446 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3447 LR.getValueType(), LL, RL); 3448 AddToWorklist(ANDNode.getNode()); 3449 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1); 3450 } 3451 } 3452 // canonicalize equivalent to ll == rl 3453 if (LL == RR && LR == RL) { 3454 Op1 = ISD::getSetCCSwappedOperands(Op1); 3455 std::swap(RL, RR); 3456 } 3457 if (LL == RL && LR == RR) { 3458 bool isInteger = LL.getValueType().isInteger(); 3459 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3460 if (Result != ISD::SETCC_INVALID && 3461 (!LegalOperations || 3462 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3463 TLI.isOperationLegal(ISD::SETCC, 3464 getSetCCResultType(N0.getValueType()))))) 3465 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(), 3466 LL, LR, Result); 3467 } 3468 } 3469 3470 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3471 if (N0.getOpcode() == ISD::AND && 3472 N1.getOpcode() == ISD::AND && 3473 N0.getOperand(1).getOpcode() == ISD::Constant && 3474 N1.getOperand(1).getOpcode() == ISD::Constant && 3475 // Don't increase # computations. 3476 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3477 // We can only do this xform if we know that bits from X that are set in C2 3478 // but not in C1 are already zero. Likewise for Y. 3479 const APInt &LHSMask = 3480 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3481 const APInt &RHSMask = 3482 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3483 3484 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3485 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3486 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3487 N0.getOperand(0), N1.getOperand(0)); 3488 SDLoc DL(LocReference); 3489 return DAG.getNode(ISD::AND, DL, VT, X, 3490 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 3491 } 3492 } 3493 3494 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3495 if (N0.getOpcode() == ISD::AND && 3496 N1.getOpcode() == ISD::AND && 3497 N0.getOperand(0) == N1.getOperand(0) && 3498 // Don't increase # computations. 3499 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3500 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3501 N0.getOperand(1), N1.getOperand(1)); 3502 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X); 3503 } 3504 3505 return SDValue(); 3506 } 3507 3508 SDValue DAGCombiner::visitOR(SDNode *N) { 3509 SDValue N0 = N->getOperand(0); 3510 SDValue N1 = N->getOperand(1); 3511 EVT VT = N1.getValueType(); 3512 3513 // fold vector ops 3514 if (VT.isVector()) { 3515 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3516 return FoldedVOp; 3517 3518 // fold (or x, 0) -> x, vector edition 3519 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3520 return N1; 3521 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3522 return N0; 3523 3524 // fold (or x, -1) -> -1, vector edition 3525 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3526 // do not return N0, because undef node may exist in N0 3527 return DAG.getConstant( 3528 APInt::getAllOnesValue( 3529 N0.getValueType().getScalarType().getSizeInBits()), 3530 SDLoc(N), N0.getValueType()); 3531 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3532 // do not return N1, because undef node may exist in N1 3533 return DAG.getConstant( 3534 APInt::getAllOnesValue( 3535 N1.getValueType().getScalarType().getSizeInBits()), 3536 SDLoc(N), N1.getValueType()); 3537 3538 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3539 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3540 // Do this only if the resulting shuffle is legal. 3541 if (isa<ShuffleVectorSDNode>(N0) && 3542 isa<ShuffleVectorSDNode>(N1) && 3543 // Avoid folding a node with illegal type. 3544 TLI.isTypeLegal(VT) && 3545 N0->getOperand(1) == N1->getOperand(1) && 3546 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3547 bool CanFold = true; 3548 unsigned NumElts = VT.getVectorNumElements(); 3549 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3550 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3551 // We construct two shuffle masks: 3552 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3553 // and N1 as the second operand. 3554 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3555 // and N0 as the second operand. 3556 // We do this because OR is commutable and therefore there might be 3557 // two ways to fold this node into a shuffle. 3558 SmallVector<int,4> Mask1; 3559 SmallVector<int,4> Mask2; 3560 3561 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3562 int M0 = SV0->getMaskElt(i); 3563 int M1 = SV1->getMaskElt(i); 3564 3565 // Both shuffle indexes are undef. Propagate Undef. 3566 if (M0 < 0 && M1 < 0) { 3567 Mask1.push_back(M0); 3568 Mask2.push_back(M0); 3569 continue; 3570 } 3571 3572 if (M0 < 0 || M1 < 0 || 3573 (M0 < (int)NumElts && M1 < (int)NumElts) || 3574 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3575 CanFold = false; 3576 break; 3577 } 3578 3579 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3580 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3581 } 3582 3583 if (CanFold) { 3584 // Fold this sequence only if the resulting shuffle is 'legal'. 3585 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3586 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3587 N1->getOperand(0), &Mask1[0]); 3588 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3589 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3590 N0->getOperand(0), &Mask2[0]); 3591 } 3592 } 3593 } 3594 3595 // fold (or c1, c2) -> c1|c2 3596 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3597 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3598 if (N0C && N1C) 3599 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 3600 // canonicalize constant to RHS 3601 if (isConstantIntBuildVectorOrConstantInt(N0) && 3602 !isConstantIntBuildVectorOrConstantInt(N1)) 3603 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3604 // fold (or x, 0) -> x 3605 if (isNullConstant(N1)) 3606 return N0; 3607 // fold (or x, -1) -> -1 3608 if (isAllOnesConstant(N1)) 3609 return N1; 3610 // fold (or x, c) -> c iff (x & ~c) == 0 3611 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3612 return N1; 3613 3614 if (SDValue Combined = visitORLike(N0, N1, N)) 3615 return Combined; 3616 3617 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3618 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3619 if (BSwap.getNode()) 3620 return BSwap; 3621 BSwap = MatchBSwapHWordLow(N, N0, N1); 3622 if (BSwap.getNode()) 3623 return BSwap; 3624 3625 // reassociate or 3626 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1)) 3627 return ROR; 3628 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3629 // iff (c1 & c2) == 0. 3630 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3631 isa<ConstantSDNode>(N0.getOperand(1))) { 3632 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3633 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3634 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 3635 N1C, C1)) 3636 return DAG.getNode( 3637 ISD::AND, SDLoc(N), VT, 3638 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3639 return SDValue(); 3640 } 3641 } 3642 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3643 if (N0.getOpcode() == N1.getOpcode()) { 3644 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3645 if (Tmp.getNode()) return Tmp; 3646 } 3647 3648 // See if this is some rotate idiom. 3649 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3650 return SDValue(Rot, 0); 3651 3652 // Simplify the operands using demanded-bits information. 3653 if (!VT.isVector() && 3654 SimplifyDemandedBits(SDValue(N, 0))) 3655 return SDValue(N, 0); 3656 3657 return SDValue(); 3658 } 3659 3660 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3661 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3662 if (Op.getOpcode() == ISD::AND) { 3663 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3664 Mask = Op.getOperand(1); 3665 Op = Op.getOperand(0); 3666 } else { 3667 return false; 3668 } 3669 } 3670 3671 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3672 Shift = Op; 3673 return true; 3674 } 3675 3676 return false; 3677 } 3678 3679 // Return true if we can prove that, whenever Neg and Pos are both in the 3680 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3681 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3682 // 3683 // (or (shift1 X, Neg), (shift2 X, Pos)) 3684 // 3685 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3686 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3687 // to consider shift amounts with defined behavior. 3688 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3689 // If OpSize is a power of 2 then: 3690 // 3691 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3692 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3693 // 3694 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3695 // for the stronger condition: 3696 // 3697 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3698 // 3699 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3700 // we can just replace Neg with Neg' for the rest of the function. 3701 // 3702 // In other cases we check for the even stronger condition: 3703 // 3704 // Neg == OpSize - Pos [B] 3705 // 3706 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3707 // behavior if Pos == 0 (and consequently Neg == OpSize). 3708 // 3709 // We could actually use [A] whenever OpSize is a power of 2, but the 3710 // only extra cases that it would match are those uninteresting ones 3711 // where Neg and Pos are never in range at the same time. E.g. for 3712 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3713 // as well as (sub 32, Pos), but: 3714 // 3715 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3716 // 3717 // always invokes undefined behavior for 32-bit X. 3718 // 3719 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3720 unsigned MaskLoBits = 0; 3721 if (Neg.getOpcode() == ISD::AND && 3722 isPowerOf2_64(OpSize) && 3723 Neg.getOperand(1).getOpcode() == ISD::Constant && 3724 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3725 Neg = Neg.getOperand(0); 3726 MaskLoBits = Log2_64(OpSize); 3727 } 3728 3729 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3730 if (Neg.getOpcode() != ISD::SUB) 3731 return 0; 3732 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3733 if (!NegC) 3734 return 0; 3735 SDValue NegOp1 = Neg.getOperand(1); 3736 3737 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3738 // Pos'. The truncation is redundant for the purpose of the equality. 3739 if (MaskLoBits && 3740 Pos.getOpcode() == ISD::AND && 3741 Pos.getOperand(1).getOpcode() == ISD::Constant && 3742 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3743 Pos = Pos.getOperand(0); 3744 3745 // The condition we need is now: 3746 // 3747 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3748 // 3749 // If NegOp1 == Pos then we need: 3750 // 3751 // OpSize & Mask == NegC & Mask 3752 // 3753 // (because "x & Mask" is a truncation and distributes through subtraction). 3754 APInt Width; 3755 if (Pos == NegOp1) 3756 Width = NegC->getAPIntValue(); 3757 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3758 // Then the condition we want to prove becomes: 3759 // 3760 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3761 // 3762 // which, again because "x & Mask" is a truncation, becomes: 3763 // 3764 // NegC & Mask == (OpSize - PosC) & Mask 3765 // OpSize & Mask == (NegC + PosC) & Mask 3766 else if (Pos.getOpcode() == ISD::ADD && 3767 Pos.getOperand(0) == NegOp1 && 3768 Pos.getOperand(1).getOpcode() == ISD::Constant) 3769 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3770 NegC->getAPIntValue()); 3771 else 3772 return false; 3773 3774 // Now we just need to check that OpSize & Mask == Width & Mask. 3775 if (MaskLoBits) 3776 // Opsize & Mask is 0 since Mask is Opsize - 1. 3777 return Width.getLoBits(MaskLoBits) == 0; 3778 return Width == OpSize; 3779 } 3780 3781 // A subroutine of MatchRotate used once we have found an OR of two opposite 3782 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3783 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3784 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3785 // Neg with outer conversions stripped away. 3786 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3787 SDValue Neg, SDValue InnerPos, 3788 SDValue InnerNeg, unsigned PosOpcode, 3789 unsigned NegOpcode, SDLoc DL) { 3790 // fold (or (shl x, (*ext y)), 3791 // (srl x, (*ext (sub 32, y)))) -> 3792 // (rotl x, y) or (rotr x, (sub 32, y)) 3793 // 3794 // fold (or (shl x, (*ext (sub 32, y))), 3795 // (srl x, (*ext y))) -> 3796 // (rotr x, y) or (rotl x, (sub 32, y)) 3797 EVT VT = Shifted.getValueType(); 3798 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3799 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3800 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3801 HasPos ? Pos : Neg).getNode(); 3802 } 3803 3804 return nullptr; 3805 } 3806 3807 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3808 // idioms for rotate, and if the target supports rotation instructions, generate 3809 // a rot[lr]. 3810 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3811 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3812 EVT VT = LHS.getValueType(); 3813 if (!TLI.isTypeLegal(VT)) return nullptr; 3814 3815 // The target must have at least one rotate flavor. 3816 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3817 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3818 if (!HasROTL && !HasROTR) return nullptr; 3819 3820 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3821 SDValue LHSShift; // The shift. 3822 SDValue LHSMask; // AND value if any. 3823 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3824 return nullptr; // Not part of a rotate. 3825 3826 SDValue RHSShift; // The shift. 3827 SDValue RHSMask; // AND value if any. 3828 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3829 return nullptr; // Not part of a rotate. 3830 3831 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3832 return nullptr; // Not shifting the same value. 3833 3834 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3835 return nullptr; // Shifts must disagree. 3836 3837 // Canonicalize shl to left side in a shl/srl pair. 3838 if (RHSShift.getOpcode() == ISD::SHL) { 3839 std::swap(LHS, RHS); 3840 std::swap(LHSShift, RHSShift); 3841 std::swap(LHSMask , RHSMask ); 3842 } 3843 3844 unsigned OpSizeInBits = VT.getSizeInBits(); 3845 SDValue LHSShiftArg = LHSShift.getOperand(0); 3846 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3847 SDValue RHSShiftArg = RHSShift.getOperand(0); 3848 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3849 3850 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3851 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3852 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3853 RHSShiftAmt.getOpcode() == ISD::Constant) { 3854 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3855 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3856 if ((LShVal + RShVal) != OpSizeInBits) 3857 return nullptr; 3858 3859 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3860 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3861 3862 // If there is an AND of either shifted operand, apply it to the result. 3863 if (LHSMask.getNode() || RHSMask.getNode()) { 3864 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3865 3866 if (LHSMask.getNode()) { 3867 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3868 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3869 } 3870 if (RHSMask.getNode()) { 3871 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3872 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3873 } 3874 3875 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT)); 3876 } 3877 3878 return Rot.getNode(); 3879 } 3880 3881 // If there is a mask here, and we have a variable shift, we can't be sure 3882 // that we're masking out the right stuff. 3883 if (LHSMask.getNode() || RHSMask.getNode()) 3884 return nullptr; 3885 3886 // If the shift amount is sign/zext/any-extended just peel it off. 3887 SDValue LExtOp0 = LHSShiftAmt; 3888 SDValue RExtOp0 = RHSShiftAmt; 3889 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3890 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3891 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3892 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3893 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3894 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3895 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3896 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3897 LExtOp0 = LHSShiftAmt.getOperand(0); 3898 RExtOp0 = RHSShiftAmt.getOperand(0); 3899 } 3900 3901 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3902 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3903 if (TryL) 3904 return TryL; 3905 3906 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3907 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3908 if (TryR) 3909 return TryR; 3910 3911 return nullptr; 3912 } 3913 3914 SDValue DAGCombiner::visitXOR(SDNode *N) { 3915 SDValue N0 = N->getOperand(0); 3916 SDValue N1 = N->getOperand(1); 3917 EVT VT = N0.getValueType(); 3918 3919 // fold vector ops 3920 if (VT.isVector()) { 3921 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3922 return FoldedVOp; 3923 3924 // fold (xor x, 0) -> x, vector edition 3925 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3926 return N1; 3927 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3928 return N0; 3929 } 3930 3931 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3932 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3933 return DAG.getConstant(0, SDLoc(N), VT); 3934 // fold (xor x, undef) -> undef 3935 if (N0.getOpcode() == ISD::UNDEF) 3936 return N0; 3937 if (N1.getOpcode() == ISD::UNDEF) 3938 return N1; 3939 // fold (xor c1, c2) -> c1^c2 3940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3941 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3942 if (N0C && N1C) 3943 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C); 3944 // canonicalize constant to RHS 3945 if (isConstantIntBuildVectorOrConstantInt(N0) && 3946 !isConstantIntBuildVectorOrConstantInt(N1)) 3947 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3948 // fold (xor x, 0) -> x 3949 if (isNullConstant(N1)) 3950 return N0; 3951 // reassociate xor 3952 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1)) 3953 return RXOR; 3954 3955 // fold !(x cc y) -> (x !cc y) 3956 SDValue LHS, RHS, CC; 3957 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3958 bool isInt = LHS.getValueType().isInteger(); 3959 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3960 isInt); 3961 3962 if (!LegalOperations || 3963 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3964 switch (N0.getOpcode()) { 3965 default: 3966 llvm_unreachable("Unhandled SetCC Equivalent!"); 3967 case ISD::SETCC: 3968 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3969 case ISD::SELECT_CC: 3970 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3971 N0.getOperand(3), NotCC); 3972 } 3973 } 3974 } 3975 3976 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3977 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND && 3978 N0.getNode()->hasOneUse() && 3979 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3980 SDValue V = N0.getOperand(0); 3981 SDLoc DL(N0); 3982 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V, 3983 DAG.getConstant(1, DL, V.getValueType())); 3984 AddToWorklist(V.getNode()); 3985 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3986 } 3987 3988 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3989 if (isOneConstant(N1) && VT == MVT::i1 && 3990 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3991 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3992 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3993 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3994 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3995 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3996 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3997 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3998 } 3999 } 4000 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 4001 if (isAllOnesConstant(N1) && 4002 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 4003 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 4004 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 4005 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 4006 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 4007 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 4008 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 4009 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 4010 } 4011 } 4012 // fold (xor (and x, y), y) -> (and (not x), y) 4013 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 4014 N0->getOperand(1) == N1) { 4015 SDValue X = N0->getOperand(0); 4016 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 4017 AddToWorklist(NotX.getNode()); 4018 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 4019 } 4020 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 4021 if (N1C && N0.getOpcode() == ISD::XOR) { 4022 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 4023 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 4024 if (N00C) { 4025 SDLoc DL(N); 4026 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 4027 DAG.getConstant(N1C->getAPIntValue() ^ 4028 N00C->getAPIntValue(), DL, VT)); 4029 } 4030 if (N01C) { 4031 SDLoc DL(N); 4032 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 4033 DAG.getConstant(N1C->getAPIntValue() ^ 4034 N01C->getAPIntValue(), DL, VT)); 4035 } 4036 } 4037 // fold (xor x, x) -> 0 4038 if (N0 == N1) 4039 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 4040 4041 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 4042 // Here is a concrete example of this equivalence: 4043 // i16 x == 14 4044 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 4045 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 4046 // 4047 // => 4048 // 4049 // i16 ~1 == 0b1111111111111110 4050 // i16 rol(~1, 14) == 0b1011111111111111 4051 // 4052 // Some additional tips to help conceptualize this transform: 4053 // - Try to see the operation as placing a single zero in a value of all ones. 4054 // - There exists no value for x which would allow the result to contain zero. 4055 // - Values of x larger than the bitwidth are undefined and do not require a 4056 // consistent result. 4057 // - Pushing the zero left requires shifting one bits in from the right. 4058 // A rotate left of ~1 is a nice way of achieving the desired result. 4059 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL 4060 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 4061 SDLoc DL(N); 4062 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 4063 N0.getOperand(1)); 4064 } 4065 4066 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 4067 if (N0.getOpcode() == N1.getOpcode()) { 4068 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 4069 if (Tmp.getNode()) return Tmp; 4070 } 4071 4072 // Simplify the expression using non-local knowledge. 4073 if (!VT.isVector() && 4074 SimplifyDemandedBits(SDValue(N, 0))) 4075 return SDValue(N, 0); 4076 4077 return SDValue(); 4078 } 4079 4080 /// Handle transforms common to the three shifts, when the shift amount is a 4081 /// constant. 4082 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 4083 // We can't and shouldn't fold opaque constants. 4084 if (Amt->isOpaque()) 4085 return SDValue(); 4086 4087 SDNode *LHS = N->getOperand(0).getNode(); 4088 if (!LHS->hasOneUse()) return SDValue(); 4089 4090 // We want to pull some binops through shifts, so that we have (and (shift)) 4091 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 4092 // thing happens with address calculations, so it's important to canonicalize 4093 // it. 4094 bool HighBitSet = false; // Can we transform this if the high bit is set? 4095 4096 switch (LHS->getOpcode()) { 4097 default: return SDValue(); 4098 case ISD::OR: 4099 case ISD::XOR: 4100 HighBitSet = false; // We can only transform sra if the high bit is clear. 4101 break; 4102 case ISD::AND: 4103 HighBitSet = true; // We can only transform sra if the high bit is set. 4104 break; 4105 case ISD::ADD: 4106 if (N->getOpcode() != ISD::SHL) 4107 return SDValue(); // only shl(add) not sr[al](add). 4108 HighBitSet = false; // We can only transform sra if the high bit is clear. 4109 break; 4110 } 4111 4112 // We require the RHS of the binop to be a constant and not opaque as well. 4113 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 4114 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue(); 4115 4116 // FIXME: disable this unless the input to the binop is a shift by a constant. 4117 // If it is not a shift, it pessimizes some common cases like: 4118 // 4119 // void foo(int *X, int i) { X[i & 1235] = 1; } 4120 // int bar(int *X, int i) { return X[i & 255]; } 4121 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4122 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4123 BinOpLHSVal->getOpcode() != ISD::SRA && 4124 BinOpLHSVal->getOpcode() != ISD::SRL) || 4125 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4126 return SDValue(); 4127 4128 EVT VT = N->getValueType(0); 4129 4130 // If this is a signed shift right, and the high bit is modified by the 4131 // logical operation, do not perform the transformation. The highBitSet 4132 // boolean indicates the value of the high bit of the constant which would 4133 // cause it to be modified for this operation. 4134 if (N->getOpcode() == ISD::SRA) { 4135 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4136 if (BinOpRHSSignSet != HighBitSet) 4137 return SDValue(); 4138 } 4139 4140 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4141 return SDValue(); 4142 4143 // Fold the constants, shifting the binop RHS by the shift amount. 4144 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4145 N->getValueType(0), 4146 LHS->getOperand(1), N->getOperand(1)); 4147 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4148 4149 // Create the new shift. 4150 SDValue NewShift = DAG.getNode(N->getOpcode(), 4151 SDLoc(LHS->getOperand(0)), 4152 VT, LHS->getOperand(0), N->getOperand(1)); 4153 4154 // Create the new binop. 4155 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4156 } 4157 4158 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4159 assert(N->getOpcode() == ISD::TRUNCATE); 4160 assert(N->getOperand(0).getOpcode() == ISD::AND); 4161 4162 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4163 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4164 SDValue N01 = N->getOperand(0).getOperand(1); 4165 4166 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4167 EVT TruncVT = N->getValueType(0); 4168 SDValue N00 = N->getOperand(0).getOperand(0); 4169 APInt TruncC = N01C->getAPIntValue(); 4170 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4171 SDLoc DL(N); 4172 4173 return DAG.getNode(ISD::AND, DL, TruncVT, 4174 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00), 4175 DAG.getConstant(TruncC, DL, TruncVT)); 4176 } 4177 } 4178 4179 return SDValue(); 4180 } 4181 4182 SDValue DAGCombiner::visitRotate(SDNode *N) { 4183 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4184 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4185 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4186 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4187 if (NewOp1.getNode()) 4188 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4189 N->getOperand(0), NewOp1); 4190 } 4191 return SDValue(); 4192 } 4193 4194 SDValue DAGCombiner::visitSHL(SDNode *N) { 4195 SDValue N0 = N->getOperand(0); 4196 SDValue N1 = N->getOperand(1); 4197 EVT VT = N0.getValueType(); 4198 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4199 4200 // fold vector ops 4201 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4202 if (VT.isVector()) { 4203 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4204 return FoldedVOp; 4205 4206 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4207 // If setcc produces all-one true value then: 4208 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4209 if (N1CV && N1CV->isConstant()) { 4210 if (N0.getOpcode() == ISD::AND) { 4211 SDValue N00 = N0->getOperand(0); 4212 SDValue N01 = N0->getOperand(1); 4213 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4214 4215 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4216 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4217 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4218 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 4219 N01CV, N1CV)) 4220 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4221 } 4222 } else { 4223 N1C = isConstOrConstSplat(N1); 4224 } 4225 } 4226 } 4227 4228 // fold (shl c1, c2) -> c1<<c2 4229 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4230 if (N0C && N1C) 4231 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 4232 // fold (shl 0, x) -> 0 4233 if (isNullConstant(N0)) 4234 return N0; 4235 // fold (shl x, c >= size(x)) -> undef 4236 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4237 return DAG.getUNDEF(VT); 4238 // fold (shl x, 0) -> x 4239 if (N1C && N1C->isNullValue()) 4240 return N0; 4241 // fold (shl undef, x) -> 0 4242 if (N0.getOpcode() == ISD::UNDEF) 4243 return DAG.getConstant(0, SDLoc(N), VT); 4244 // if (shl x, c) is known to be zero, return 0 4245 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4246 APInt::getAllOnesValue(OpSizeInBits))) 4247 return DAG.getConstant(0, SDLoc(N), VT); 4248 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4249 if (N1.getOpcode() == ISD::TRUNCATE && 4250 N1.getOperand(0).getOpcode() == ISD::AND) { 4251 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4252 if (NewOp1.getNode()) 4253 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4254 } 4255 4256 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4257 return SDValue(N, 0); 4258 4259 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4260 if (N1C && N0.getOpcode() == ISD::SHL) { 4261 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4262 uint64_t c1 = N0C1->getZExtValue(); 4263 uint64_t c2 = N1C->getZExtValue(); 4264 SDLoc DL(N); 4265 if (c1 + c2 >= OpSizeInBits) 4266 return DAG.getConstant(0, DL, VT); 4267 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4268 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4269 } 4270 } 4271 4272 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4273 // For this to be valid, the second form must not preserve any of the bits 4274 // that are shifted out by the inner shift in the first form. This means 4275 // the outer shift size must be >= the number of bits added by the ext. 4276 // As a corollary, we don't care what kind of ext it is. 4277 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4278 N0.getOpcode() == ISD::ANY_EXTEND || 4279 N0.getOpcode() == ISD::SIGN_EXTEND) && 4280 N0.getOperand(0).getOpcode() == ISD::SHL) { 4281 SDValue N0Op0 = N0.getOperand(0); 4282 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4283 uint64_t c1 = N0Op0C1->getZExtValue(); 4284 uint64_t c2 = N1C->getZExtValue(); 4285 EVT InnerShiftVT = N0Op0.getValueType(); 4286 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4287 if (c2 >= OpSizeInBits - InnerShiftSize) { 4288 SDLoc DL(N0); 4289 if (c1 + c2 >= OpSizeInBits) 4290 return DAG.getConstant(0, DL, VT); 4291 return DAG.getNode(ISD::SHL, DL, VT, 4292 DAG.getNode(N0.getOpcode(), DL, VT, 4293 N0Op0->getOperand(0)), 4294 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4295 } 4296 } 4297 } 4298 4299 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4300 // Only fold this if the inner zext has no other uses to avoid increasing 4301 // the total number of instructions. 4302 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4303 N0.getOperand(0).getOpcode() == ISD::SRL) { 4304 SDValue N0Op0 = N0.getOperand(0); 4305 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4306 uint64_t c1 = N0Op0C1->getZExtValue(); 4307 if (c1 < VT.getScalarSizeInBits()) { 4308 uint64_t c2 = N1C->getZExtValue(); 4309 if (c1 == c2) { 4310 SDValue NewOp0 = N0.getOperand(0); 4311 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4312 SDLoc DL(N); 4313 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 4314 NewOp0, 4315 DAG.getConstant(c2, DL, CountVT)); 4316 AddToWorklist(NewSHL.getNode()); 4317 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4318 } 4319 } 4320 } 4321 } 4322 4323 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4324 // (and (srl x, (sub c1, c2), MASK) 4325 // Only fold this if the inner shift has no other uses -- if it does, folding 4326 // this will increase the total number of instructions. 4327 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4328 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4329 uint64_t c1 = N0C1->getZExtValue(); 4330 if (c1 < OpSizeInBits) { 4331 uint64_t c2 = N1C->getZExtValue(); 4332 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4333 SDValue Shift; 4334 if (c2 > c1) { 4335 Mask = Mask.shl(c2 - c1); 4336 SDLoc DL(N); 4337 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 4338 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 4339 } else { 4340 Mask = Mask.lshr(c1 - c2); 4341 SDLoc DL(N); 4342 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4343 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 4344 } 4345 SDLoc DL(N0); 4346 return DAG.getNode(ISD::AND, DL, VT, Shift, 4347 DAG.getConstant(Mask, DL, VT)); 4348 } 4349 } 4350 } 4351 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4352 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4353 unsigned BitSize = VT.getScalarSizeInBits(); 4354 SDLoc DL(N); 4355 SDValue HiBitsMask = 4356 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4357 BitSize - N1C->getZExtValue()), 4358 DL, VT); 4359 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4360 HiBitsMask); 4361 } 4362 4363 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4364 // Variant of version done on multiply, except mul by a power of 2 is turned 4365 // into a shift. 4366 APInt Val; 4367 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4368 (isa<ConstantSDNode>(N0.getOperand(1)) || 4369 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4370 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4371 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4372 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4373 } 4374 4375 if (N1C) { 4376 SDValue NewSHL = visitShiftByConstant(N, N1C); 4377 if (NewSHL.getNode()) 4378 return NewSHL; 4379 } 4380 4381 return SDValue(); 4382 } 4383 4384 SDValue DAGCombiner::visitSRA(SDNode *N) { 4385 SDValue N0 = N->getOperand(0); 4386 SDValue N1 = N->getOperand(1); 4387 EVT VT = N0.getValueType(); 4388 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4389 4390 // fold vector ops 4391 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4392 if (VT.isVector()) { 4393 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4394 return FoldedVOp; 4395 4396 N1C = isConstOrConstSplat(N1); 4397 } 4398 4399 // fold (sra c1, c2) -> (sra c1, c2) 4400 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4401 if (N0C && N1C) 4402 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 4403 // fold (sra 0, x) -> 0 4404 if (isNullConstant(N0)) 4405 return N0; 4406 // fold (sra -1, x) -> -1 4407 if (isAllOnesConstant(N0)) 4408 return N0; 4409 // fold (sra x, (setge c, size(x))) -> undef 4410 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4411 return DAG.getUNDEF(VT); 4412 // fold (sra x, 0) -> x 4413 if (N1C && N1C->isNullValue()) 4414 return N0; 4415 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4416 // sext_inreg. 4417 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4418 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4419 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4420 if (VT.isVector()) 4421 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4422 ExtVT, VT.getVectorNumElements()); 4423 if ((!LegalOperations || 4424 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4425 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4426 N0.getOperand(0), DAG.getValueType(ExtVT)); 4427 } 4428 4429 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4430 if (N1C && N0.getOpcode() == ISD::SRA) { 4431 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4432 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4433 if (Sum >= OpSizeInBits) 4434 Sum = OpSizeInBits - 1; 4435 SDLoc DL(N); 4436 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), 4437 DAG.getConstant(Sum, DL, N1.getValueType())); 4438 } 4439 } 4440 4441 // fold (sra (shl X, m), (sub result_size, n)) 4442 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4443 // result_size - n != m. 4444 // If truncate is free for the target sext(shl) is likely to result in better 4445 // code. 4446 if (N0.getOpcode() == ISD::SHL && N1C) { 4447 // Get the two constanst of the shifts, CN0 = m, CN = n. 4448 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4449 if (N01C) { 4450 LLVMContext &Ctx = *DAG.getContext(); 4451 // Determine what the truncate's result bitsize and type would be. 4452 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4453 4454 if (VT.isVector()) 4455 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4456 4457 // Determine the residual right-shift amount. 4458 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4459 4460 // If the shift is not a no-op (in which case this should be just a sign 4461 // extend already), the truncated to type is legal, sign_extend is legal 4462 // on that type, and the truncate to that type is both legal and free, 4463 // perform the transform. 4464 if ((ShiftAmt > 0) && 4465 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4466 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4467 TLI.isTruncateFree(VT, TruncVT)) { 4468 4469 SDLoc DL(N); 4470 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 4471 getShiftAmountTy(N0.getOperand(0).getValueType())); 4472 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 4473 N0.getOperand(0), Amt); 4474 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 4475 Shift); 4476 return DAG.getNode(ISD::SIGN_EXTEND, DL, 4477 N->getValueType(0), Trunc); 4478 } 4479 } 4480 } 4481 4482 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4483 if (N1.getOpcode() == ISD::TRUNCATE && 4484 N1.getOperand(0).getOpcode() == ISD::AND) { 4485 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4486 if (NewOp1.getNode()) 4487 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4488 } 4489 4490 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4491 // if c1 is equal to the number of bits the trunc removes 4492 if (N0.getOpcode() == ISD::TRUNCATE && 4493 (N0.getOperand(0).getOpcode() == ISD::SRL || 4494 N0.getOperand(0).getOpcode() == ISD::SRA) && 4495 N0.getOperand(0).hasOneUse() && 4496 N0.getOperand(0).getOperand(1).hasOneUse() && 4497 N1C) { 4498 SDValue N0Op0 = N0.getOperand(0); 4499 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4500 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4501 EVT LargeVT = N0Op0.getValueType(); 4502 4503 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4504 SDLoc DL(N); 4505 SDValue Amt = 4506 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 4507 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4508 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 4509 N0Op0.getOperand(0), Amt); 4510 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 4511 } 4512 } 4513 } 4514 4515 // Simplify, based on bits shifted out of the LHS. 4516 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4517 return SDValue(N, 0); 4518 4519 4520 // If the sign bit is known to be zero, switch this to a SRL. 4521 if (DAG.SignBitIsZero(N0)) 4522 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4523 4524 if (N1C) { 4525 SDValue NewSRA = visitShiftByConstant(N, N1C); 4526 if (NewSRA.getNode()) 4527 return NewSRA; 4528 } 4529 4530 return SDValue(); 4531 } 4532 4533 SDValue DAGCombiner::visitSRL(SDNode *N) { 4534 SDValue N0 = N->getOperand(0); 4535 SDValue N1 = N->getOperand(1); 4536 EVT VT = N0.getValueType(); 4537 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4538 4539 // fold vector ops 4540 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4541 if (VT.isVector()) { 4542 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4543 return FoldedVOp; 4544 4545 N1C = isConstOrConstSplat(N1); 4546 } 4547 4548 // fold (srl c1, c2) -> c1 >>u c2 4549 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4550 if (N0C && N1C) 4551 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 4552 // fold (srl 0, x) -> 0 4553 if (isNullConstant(N0)) 4554 return N0; 4555 // fold (srl x, c >= size(x)) -> undef 4556 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4557 return DAG.getUNDEF(VT); 4558 // fold (srl x, 0) -> x 4559 if (N1C && N1C->isNullValue()) 4560 return N0; 4561 // if (srl x, c) is known to be zero, return 0 4562 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4563 APInt::getAllOnesValue(OpSizeInBits))) 4564 return DAG.getConstant(0, SDLoc(N), VT); 4565 4566 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4567 if (N1C && N0.getOpcode() == ISD::SRL) { 4568 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4569 uint64_t c1 = N01C->getZExtValue(); 4570 uint64_t c2 = N1C->getZExtValue(); 4571 SDLoc DL(N); 4572 if (c1 + c2 >= OpSizeInBits) 4573 return DAG.getConstant(0, DL, VT); 4574 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 4575 DAG.getConstant(c1 + c2, DL, N1.getValueType())); 4576 } 4577 } 4578 4579 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4580 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4581 N0.getOperand(0).getOpcode() == ISD::SRL && 4582 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4583 uint64_t c1 = 4584 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4585 uint64_t c2 = N1C->getZExtValue(); 4586 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4587 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4588 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4589 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4590 if (c1 + OpSizeInBits == InnerShiftSize) { 4591 SDLoc DL(N0); 4592 if (c1 + c2 >= InnerShiftSize) 4593 return DAG.getConstant(0, DL, VT); 4594 return DAG.getNode(ISD::TRUNCATE, DL, VT, 4595 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 4596 N0.getOperand(0)->getOperand(0), 4597 DAG.getConstant(c1 + c2, DL, 4598 ShiftCountVT))); 4599 } 4600 } 4601 4602 // fold (srl (shl x, c), c) -> (and x, cst2) 4603 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4604 unsigned BitSize = N0.getScalarValueSizeInBits(); 4605 if (BitSize <= 64) { 4606 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4607 SDLoc DL(N); 4608 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), 4609 DAG.getConstant(~0ULL >> ShAmt, DL, VT)); 4610 } 4611 } 4612 4613 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4614 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4615 // Shifting in all undef bits? 4616 EVT SmallVT = N0.getOperand(0).getValueType(); 4617 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4618 if (N1C->getZExtValue() >= BitSize) 4619 return DAG.getUNDEF(VT); 4620 4621 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4622 uint64_t ShiftAmt = N1C->getZExtValue(); 4623 SDLoc DL0(N0); 4624 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 4625 N0.getOperand(0), 4626 DAG.getConstant(ShiftAmt, DL0, 4627 getShiftAmountTy(SmallVT))); 4628 AddToWorklist(SmallShift.getNode()); 4629 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4630 SDLoc DL(N); 4631 return DAG.getNode(ISD::AND, DL, VT, 4632 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 4633 DAG.getConstant(Mask, DL, VT)); 4634 } 4635 } 4636 4637 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4638 // bit, which is unmodified by sra. 4639 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4640 if (N0.getOpcode() == ISD::SRA) 4641 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4642 } 4643 4644 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4645 if (N1C && N0.getOpcode() == ISD::CTLZ && 4646 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4647 APInt KnownZero, KnownOne; 4648 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4649 4650 // If any of the input bits are KnownOne, then the input couldn't be all 4651 // zeros, thus the result of the srl will always be zero. 4652 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 4653 4654 // If all of the bits input the to ctlz node are known to be zero, then 4655 // the result of the ctlz is "32" and the result of the shift is one. 4656 APInt UnknownBits = ~KnownZero; 4657 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 4658 4659 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4660 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4661 // Okay, we know that only that the single bit specified by UnknownBits 4662 // could be set on input to the CTLZ node. If this bit is set, the SRL 4663 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4664 // to an SRL/XOR pair, which is likely to simplify more. 4665 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4666 SDValue Op = N0.getOperand(0); 4667 4668 if (ShAmt) { 4669 SDLoc DL(N0); 4670 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 4671 DAG.getConstant(ShAmt, DL, 4672 getShiftAmountTy(Op.getValueType()))); 4673 AddToWorklist(Op.getNode()); 4674 } 4675 4676 SDLoc DL(N); 4677 return DAG.getNode(ISD::XOR, DL, VT, 4678 Op, DAG.getConstant(1, DL, VT)); 4679 } 4680 } 4681 4682 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4683 if (N1.getOpcode() == ISD::TRUNCATE && 4684 N1.getOperand(0).getOpcode() == ISD::AND) { 4685 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4686 if (NewOp1.getNode()) 4687 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4688 } 4689 4690 // fold operands of srl based on knowledge that the low bits are not 4691 // demanded. 4692 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4693 return SDValue(N, 0); 4694 4695 if (N1C) { 4696 SDValue NewSRL = visitShiftByConstant(N, N1C); 4697 if (NewSRL.getNode()) 4698 return NewSRL; 4699 } 4700 4701 // Attempt to convert a srl of a load into a narrower zero-extending load. 4702 SDValue NarrowLoad = ReduceLoadWidth(N); 4703 if (NarrowLoad.getNode()) 4704 return NarrowLoad; 4705 4706 // Here is a common situation. We want to optimize: 4707 // 4708 // %a = ... 4709 // %b = and i32 %a, 2 4710 // %c = srl i32 %b, 1 4711 // brcond i32 %c ... 4712 // 4713 // into 4714 // 4715 // %a = ... 4716 // %b = and %a, 2 4717 // %c = setcc eq %b, 0 4718 // brcond %c ... 4719 // 4720 // However when after the source operand of SRL is optimized into AND, the SRL 4721 // itself may not be optimized further. Look for it and add the BRCOND into 4722 // the worklist. 4723 if (N->hasOneUse()) { 4724 SDNode *Use = *N->use_begin(); 4725 if (Use->getOpcode() == ISD::BRCOND) 4726 AddToWorklist(Use); 4727 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4728 // Also look pass the truncate. 4729 Use = *Use->use_begin(); 4730 if (Use->getOpcode() == ISD::BRCOND) 4731 AddToWorklist(Use); 4732 } 4733 } 4734 4735 return SDValue(); 4736 } 4737 4738 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4739 SDValue N0 = N->getOperand(0); 4740 EVT VT = N->getValueType(0); 4741 4742 // fold (ctlz c1) -> c2 4743 if (isa<ConstantSDNode>(N0)) 4744 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4745 return SDValue(); 4746 } 4747 4748 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4749 SDValue N0 = N->getOperand(0); 4750 EVT VT = N->getValueType(0); 4751 4752 // fold (ctlz_zero_undef c1) -> c2 4753 if (isa<ConstantSDNode>(N0)) 4754 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4755 return SDValue(); 4756 } 4757 4758 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4759 SDValue N0 = N->getOperand(0); 4760 EVT VT = N->getValueType(0); 4761 4762 // fold (cttz c1) -> c2 4763 if (isa<ConstantSDNode>(N0)) 4764 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4765 return SDValue(); 4766 } 4767 4768 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4769 SDValue N0 = N->getOperand(0); 4770 EVT VT = N->getValueType(0); 4771 4772 // fold (cttz_zero_undef c1) -> c2 4773 if (isa<ConstantSDNode>(N0)) 4774 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4775 return SDValue(); 4776 } 4777 4778 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4779 SDValue N0 = N->getOperand(0); 4780 EVT VT = N->getValueType(0); 4781 4782 // fold (ctpop c1) -> c2 4783 if (isa<ConstantSDNode>(N0)) 4784 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4785 return SDValue(); 4786 } 4787 4788 4789 /// \brief Generate Min/Max node 4790 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4791 SDValue True, SDValue False, 4792 ISD::CondCode CC, const TargetLowering &TLI, 4793 SelectionDAG &DAG) { 4794 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4795 return SDValue(); 4796 4797 switch (CC) { 4798 case ISD::SETOLT: 4799 case ISD::SETOLE: 4800 case ISD::SETLT: 4801 case ISD::SETLE: 4802 case ISD::SETULT: 4803 case ISD::SETULE: { 4804 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4805 if (TLI.isOperationLegal(Opcode, VT)) 4806 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4807 return SDValue(); 4808 } 4809 case ISD::SETOGT: 4810 case ISD::SETOGE: 4811 case ISD::SETGT: 4812 case ISD::SETGE: 4813 case ISD::SETUGT: 4814 case ISD::SETUGE: { 4815 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4816 if (TLI.isOperationLegal(Opcode, VT)) 4817 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4818 return SDValue(); 4819 } 4820 default: 4821 return SDValue(); 4822 } 4823 } 4824 4825 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4826 SDValue N0 = N->getOperand(0); 4827 SDValue N1 = N->getOperand(1); 4828 SDValue N2 = N->getOperand(2); 4829 EVT VT = N->getValueType(0); 4830 EVT VT0 = N0.getValueType(); 4831 4832 // fold (select C, X, X) -> X 4833 if (N1 == N2) 4834 return N1; 4835 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) { 4836 // fold (select true, X, Y) -> X 4837 // fold (select false, X, Y) -> Y 4838 return !N0C->isNullValue() ? N1 : N2; 4839 } 4840 // fold (select C, 1, X) -> (or C, X) 4841 if (VT == MVT::i1 && isOneConstant(N1)) 4842 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4843 // fold (select C, 0, 1) -> (xor C, 1) 4844 // We can't do this reliably if integer based booleans have different contents 4845 // to floating point based booleans. This is because we can't tell whether we 4846 // have an integer-based boolean or a floating-point-based boolean unless we 4847 // can find the SETCC that produced it and inspect its operands. This is 4848 // fairly easy if C is the SETCC node, but it can potentially be 4849 // undiscoverable (or not reasonably discoverable). For example, it could be 4850 // in another basic block or it could require searching a complicated 4851 // expression. 4852 if (VT.isInteger() && 4853 (VT0 == MVT::i1 || (VT0.isInteger() && 4854 TLI.getBooleanContents(false, false) == 4855 TLI.getBooleanContents(false, true) && 4856 TLI.getBooleanContents(false, false) == 4857 TargetLowering::ZeroOrOneBooleanContent)) && 4858 isNullConstant(N1) && isOneConstant(N2)) { 4859 SDValue XORNode; 4860 if (VT == VT0) { 4861 SDLoc DL(N); 4862 return DAG.getNode(ISD::XOR, DL, VT0, 4863 N0, DAG.getConstant(1, DL, VT0)); 4864 } 4865 SDLoc DL0(N0); 4866 XORNode = DAG.getNode(ISD::XOR, DL0, VT0, 4867 N0, DAG.getConstant(1, DL0, VT0)); 4868 AddToWorklist(XORNode.getNode()); 4869 if (VT.bitsGT(VT0)) 4870 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4871 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4872 } 4873 // fold (select C, 0, X) -> (and (not C), X) 4874 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 4875 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4876 AddToWorklist(NOTNode.getNode()); 4877 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4878 } 4879 // fold (select C, X, 1) -> (or (not C), X) 4880 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 4881 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4882 AddToWorklist(NOTNode.getNode()); 4883 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4884 } 4885 // fold (select C, X, 0) -> (and C, X) 4886 if (VT == MVT::i1 && isNullConstant(N2)) 4887 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4888 // fold (select X, X, Y) -> (or X, Y) 4889 // fold (select X, 1, Y) -> (or X, Y) 4890 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 4891 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4892 // fold (select X, Y, X) -> (and X, Y) 4893 // fold (select X, Y, 0) -> (and X, Y) 4894 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 4895 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4896 4897 // If we can fold this based on the true/false value, do so. 4898 if (SimplifySelectOps(N, N1, N2)) 4899 return SDValue(N, 0); // Don't revisit N. 4900 4901 // fold selects based on a setcc into other things, such as min/max/abs 4902 if (N0.getOpcode() == ISD::SETCC) { 4903 // select x, y (fcmp lt x, y) -> fminnum x, y 4904 // select x, y (fcmp gt x, y) -> fmaxnum x, y 4905 // 4906 // This is OK if we don't care about what happens if either operand is a 4907 // NaN. 4908 // 4909 4910 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 4911 // no signed zeros as well as no nans. 4912 const TargetOptions &Options = DAG.getTarget().Options; 4913 if (Options.UnsafeFPMath && 4914 VT.isFloatingPoint() && N0.hasOneUse() && 4915 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 4916 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4917 4918 SDValue FMinMax = 4919 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1), 4920 N1, N2, CC, TLI, DAG); 4921 if (FMinMax) 4922 return FMinMax; 4923 } 4924 4925 if ((!LegalOperations && 4926 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 4927 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 4928 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4929 N0.getOperand(0), N0.getOperand(1), 4930 N1, N2, N0.getOperand(2)); 4931 return SimplifySelect(SDLoc(N), N0, N1, N2); 4932 } 4933 4934 if (VT0 == MVT::i1) { 4935 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4936 // select (and Cond0, Cond1), X, Y 4937 // -> select Cond0, (select Cond1, X, Y), Y 4938 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 4939 SDValue Cond0 = N0->getOperand(0); 4940 SDValue Cond1 = N0->getOperand(1); 4941 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 4942 N1.getValueType(), Cond1, N1, N2); 4943 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, 4944 InnerSelect, N2); 4945 } 4946 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 4947 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 4948 SDValue Cond0 = N0->getOperand(0); 4949 SDValue Cond1 = N0->getOperand(1); 4950 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N), 4951 N1.getValueType(), Cond1, N1, N2); 4952 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1, 4953 InnerSelect); 4954 } 4955 } 4956 4957 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 4958 if (N1->getOpcode() == ISD::SELECT) { 4959 SDValue N1_0 = N1->getOperand(0); 4960 SDValue N1_1 = N1->getOperand(1); 4961 SDValue N1_2 = N1->getOperand(2); 4962 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 4963 // Create the actual and node if we can generate good code for it. 4964 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4965 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(), 4966 N0, N1_0); 4967 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And, 4968 N1_1, N2); 4969 } 4970 // Otherwise see if we can optimize the "and" to a better pattern. 4971 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 4972 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 4973 N1_1, N2); 4974 } 4975 } 4976 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 4977 if (N2->getOpcode() == ISD::SELECT) { 4978 SDValue N2_0 = N2->getOperand(0); 4979 SDValue N2_1 = N2->getOperand(1); 4980 SDValue N2_2 = N2->getOperand(2); 4981 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 4982 // Create the actual or node if we can generate good code for it. 4983 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) { 4984 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(), 4985 N0, N2_0); 4986 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or, 4987 N1, N2_2); 4988 } 4989 // Otherwise see if we can optimize to a better pattern. 4990 if (SDValue Combined = visitORLike(N0, N2_0, N)) 4991 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined, 4992 N1, N2_2); 4993 } 4994 } 4995 } 4996 4997 return SDValue(); 4998 } 4999 5000 static 5001 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 5002 SDLoc DL(N); 5003 EVT LoVT, HiVT; 5004 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 5005 5006 // Split the inputs. 5007 SDValue Lo, Hi, LL, LH, RL, RH; 5008 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 5009 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 5010 5011 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 5012 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 5013 5014 return std::make_pair(Lo, Hi); 5015 } 5016 5017 // This function assumes all the vselect's arguments are CONCAT_VECTOR 5018 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 5019 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 5020 SDLoc dl(N); 5021 SDValue Cond = N->getOperand(0); 5022 SDValue LHS = N->getOperand(1); 5023 SDValue RHS = N->getOperand(2); 5024 EVT VT = N->getValueType(0); 5025 int NumElems = VT.getVectorNumElements(); 5026 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 5027 RHS.getOpcode() == ISD::CONCAT_VECTORS && 5028 Cond.getOpcode() == ISD::BUILD_VECTOR); 5029 5030 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 5031 // binary ones here. 5032 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 5033 return SDValue(); 5034 5035 // We're sure we have an even number of elements due to the 5036 // concat_vectors we have as arguments to vselect. 5037 // Skip BV elements until we find one that's not an UNDEF 5038 // After we find an UNDEF element, keep looping until we get to half the 5039 // length of the BV and see if all the non-undef nodes are the same. 5040 ConstantSDNode *BottomHalf = nullptr; 5041 for (int i = 0; i < NumElems / 2; ++i) { 5042 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5043 continue; 5044 5045 if (BottomHalf == nullptr) 5046 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5047 else if (Cond->getOperand(i).getNode() != BottomHalf) 5048 return SDValue(); 5049 } 5050 5051 // Do the same for the second half of the BuildVector 5052 ConstantSDNode *TopHalf = nullptr; 5053 for (int i = NumElems / 2; i < NumElems; ++i) { 5054 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 5055 continue; 5056 5057 if (TopHalf == nullptr) 5058 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 5059 else if (Cond->getOperand(i).getNode() != TopHalf) 5060 return SDValue(); 5061 } 5062 5063 assert(TopHalf && BottomHalf && 5064 "One half of the selector was all UNDEFs and the other was all the " 5065 "same value. This should have been addressed before this function."); 5066 return DAG.getNode( 5067 ISD::CONCAT_VECTORS, dl, VT, 5068 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 5069 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 5070 } 5071 5072 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 5073 5074 if (Level >= AfterLegalizeTypes) 5075 return SDValue(); 5076 5077 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 5078 SDValue Mask = MSC->getMask(); 5079 SDValue Data = MSC->getValue(); 5080 SDLoc DL(N); 5081 5082 // If the MSCATTER data type requires splitting and the mask is provided by a 5083 // SETCC, then split both nodes and its operands before legalization. This 5084 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5085 // and enables future optimizations (e.g. min/max pattern matching on X86). 5086 if (Mask.getOpcode() != ISD::SETCC) 5087 return SDValue(); 5088 5089 // Check if any splitting is required. 5090 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5091 TargetLowering::TypeSplitVector) 5092 return SDValue(); 5093 SDValue MaskLo, MaskHi, Lo, Hi; 5094 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5095 5096 EVT LoVT, HiVT; 5097 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 5098 5099 SDValue Chain = MSC->getChain(); 5100 5101 EVT MemoryVT = MSC->getMemoryVT(); 5102 unsigned Alignment = MSC->getOriginalAlignment(); 5103 5104 EVT LoMemVT, HiMemVT; 5105 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5106 5107 SDValue DataLo, DataHi; 5108 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5109 5110 SDValue BasePtr = MSC->getBasePtr(); 5111 SDValue IndexLo, IndexHi; 5112 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 5113 5114 MachineMemOperand *MMO = DAG.getMachineFunction(). 5115 getMachineMemOperand(MSC->getPointerInfo(), 5116 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5117 Alignment, MSC->getAAInfo(), MSC->getRanges()); 5118 5119 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo }; 5120 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(), 5121 DL, OpsLo, MMO); 5122 5123 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi}; 5124 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 5125 DL, OpsHi, MMO); 5126 5127 AddToWorklist(Lo.getNode()); 5128 AddToWorklist(Hi.getNode()); 5129 5130 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5131 } 5132 5133 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 5134 5135 if (Level >= AfterLegalizeTypes) 5136 return SDValue(); 5137 5138 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 5139 SDValue Mask = MST->getMask(); 5140 SDValue Data = MST->getValue(); 5141 SDLoc DL(N); 5142 5143 // If the MSTORE data type requires splitting and the mask is provided by a 5144 // SETCC, then split both nodes and its operands before legalization. This 5145 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5146 // and enables future optimizations (e.g. min/max pattern matching on X86). 5147 if (Mask.getOpcode() == ISD::SETCC) { 5148 5149 // Check if any splitting is required. 5150 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 5151 TargetLowering::TypeSplitVector) 5152 return SDValue(); 5153 5154 SDValue MaskLo, MaskHi, Lo, Hi; 5155 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5156 5157 EVT LoVT, HiVT; 5158 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 5159 5160 SDValue Chain = MST->getChain(); 5161 SDValue Ptr = MST->getBasePtr(); 5162 5163 EVT MemoryVT = MST->getMemoryVT(); 5164 unsigned Alignment = MST->getOriginalAlignment(); 5165 5166 // if Alignment is equal to the vector size, 5167 // take the half of it for the second part 5168 unsigned SecondHalfAlignment = 5169 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 5170 Alignment/2 : Alignment; 5171 5172 EVT LoMemVT, HiMemVT; 5173 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5174 5175 SDValue DataLo, DataHi; 5176 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 5177 5178 MachineMemOperand *MMO = DAG.getMachineFunction(). 5179 getMachineMemOperand(MST->getPointerInfo(), 5180 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 5181 Alignment, MST->getAAInfo(), MST->getRanges()); 5182 5183 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 5184 MST->isTruncatingStore()); 5185 5186 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5187 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5188 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5189 5190 MMO = DAG.getMachineFunction(). 5191 getMachineMemOperand(MST->getPointerInfo(), 5192 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 5193 SecondHalfAlignment, MST->getAAInfo(), 5194 MST->getRanges()); 5195 5196 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 5197 MST->isTruncatingStore()); 5198 5199 AddToWorklist(Lo.getNode()); 5200 AddToWorklist(Hi.getNode()); 5201 5202 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 5203 } 5204 return SDValue(); 5205 } 5206 5207 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 5208 5209 if (Level >= AfterLegalizeTypes) 5210 return SDValue(); 5211 5212 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N); 5213 SDValue Mask = MGT->getMask(); 5214 SDLoc DL(N); 5215 5216 // If the MGATHER result requires splitting and the mask is provided by a 5217 // SETCC, then split both nodes and its operands before legalization. This 5218 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5219 // and enables future optimizations (e.g. min/max pattern matching on X86). 5220 5221 if (Mask.getOpcode() != ISD::SETCC) 5222 return SDValue(); 5223 5224 EVT VT = N->getValueType(0); 5225 5226 // Check if any splitting is required. 5227 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5228 TargetLowering::TypeSplitVector) 5229 return SDValue(); 5230 5231 SDValue MaskLo, MaskHi, Lo, Hi; 5232 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5233 5234 SDValue Src0 = MGT->getValue(); 5235 SDValue Src0Lo, Src0Hi; 5236 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5237 5238 EVT LoVT, HiVT; 5239 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 5240 5241 SDValue Chain = MGT->getChain(); 5242 EVT MemoryVT = MGT->getMemoryVT(); 5243 unsigned Alignment = MGT->getOriginalAlignment(); 5244 5245 EVT LoMemVT, HiMemVT; 5246 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5247 5248 SDValue BasePtr = MGT->getBasePtr(); 5249 SDValue Index = MGT->getIndex(); 5250 SDValue IndexLo, IndexHi; 5251 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 5252 5253 MachineMemOperand *MMO = DAG.getMachineFunction(). 5254 getMachineMemOperand(MGT->getPointerInfo(), 5255 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5256 Alignment, MGT->getAAInfo(), MGT->getRanges()); 5257 5258 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo }; 5259 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 5260 MMO); 5261 5262 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi}; 5263 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 5264 MMO); 5265 5266 AddToWorklist(Lo.getNode()); 5267 AddToWorklist(Hi.getNode()); 5268 5269 // Build a factor node to remember that this load is independent of the 5270 // other one. 5271 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5272 Hi.getValue(1)); 5273 5274 // Legalized the chain result - switch anything that used the old chain to 5275 // use the new one. 5276 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 5277 5278 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5279 5280 SDValue RetOps[] = { GatherRes, Chain }; 5281 return DAG.getMergeValues(RetOps, DL); 5282 } 5283 5284 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 5285 5286 if (Level >= AfterLegalizeTypes) 5287 return SDValue(); 5288 5289 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 5290 SDValue Mask = MLD->getMask(); 5291 SDLoc DL(N); 5292 5293 // If the MLOAD result requires splitting and the mask is provided by a 5294 // SETCC, then split both nodes and its operands before legalization. This 5295 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5296 // and enables future optimizations (e.g. min/max pattern matching on X86). 5297 5298 if (Mask.getOpcode() == ISD::SETCC) { 5299 EVT VT = N->getValueType(0); 5300 5301 // Check if any splitting is required. 5302 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5303 TargetLowering::TypeSplitVector) 5304 return SDValue(); 5305 5306 SDValue MaskLo, MaskHi, Lo, Hi; 5307 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 5308 5309 SDValue Src0 = MLD->getSrc0(); 5310 SDValue Src0Lo, Src0Hi; 5311 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 5312 5313 EVT LoVT, HiVT; 5314 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 5315 5316 SDValue Chain = MLD->getChain(); 5317 SDValue Ptr = MLD->getBasePtr(); 5318 EVT MemoryVT = MLD->getMemoryVT(); 5319 unsigned Alignment = MLD->getOriginalAlignment(); 5320 5321 // if Alignment is equal to the vector size, 5322 // take the half of it for the second part 5323 unsigned SecondHalfAlignment = 5324 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 5325 Alignment/2 : Alignment; 5326 5327 EVT LoMemVT, HiMemVT; 5328 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 5329 5330 MachineMemOperand *MMO = DAG.getMachineFunction(). 5331 getMachineMemOperand(MLD->getPointerInfo(), 5332 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 5333 Alignment, MLD->getAAInfo(), MLD->getRanges()); 5334 5335 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 5336 ISD::NON_EXTLOAD); 5337 5338 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5339 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5340 DAG.getConstant(IncrementSize, DL, Ptr.getValueType())); 5341 5342 MMO = DAG.getMachineFunction(). 5343 getMachineMemOperand(MLD->getPointerInfo(), 5344 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5345 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5346 5347 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5348 ISD::NON_EXTLOAD); 5349 5350 AddToWorklist(Lo.getNode()); 5351 AddToWorklist(Hi.getNode()); 5352 5353 // Build a factor node to remember that this load is independent of the 5354 // other one. 5355 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5356 Hi.getValue(1)); 5357 5358 // Legalized the chain result - switch anything that used the old chain to 5359 // use the new one. 5360 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5361 5362 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5363 5364 SDValue RetOps[] = { LoadRes, Chain }; 5365 return DAG.getMergeValues(RetOps, DL); 5366 } 5367 return SDValue(); 5368 } 5369 5370 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5371 SDValue N0 = N->getOperand(0); 5372 SDValue N1 = N->getOperand(1); 5373 SDValue N2 = N->getOperand(2); 5374 SDLoc DL(N); 5375 5376 // Canonicalize integer abs. 5377 // vselect (setg[te] X, 0), X, -X -> 5378 // vselect (setgt X, -1), X, -X -> 5379 // vselect (setl[te] X, 0), -X, X -> 5380 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5381 if (N0.getOpcode() == ISD::SETCC) { 5382 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5383 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5384 bool isAbs = false; 5385 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5386 5387 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5388 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5389 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5390 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5391 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5392 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5393 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5394 5395 if (isAbs) { 5396 EVT VT = LHS.getValueType(); 5397 SDValue Shift = DAG.getNode( 5398 ISD::SRA, DL, VT, LHS, 5399 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT)); 5400 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5401 AddToWorklist(Shift.getNode()); 5402 AddToWorklist(Add.getNode()); 5403 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5404 } 5405 } 5406 5407 if (SimplifySelectOps(N, N1, N2)) 5408 return SDValue(N, 0); // Don't revisit N. 5409 5410 // If the VSELECT result requires splitting and the mask is provided by a 5411 // SETCC, then split both nodes and its operands before legalization. This 5412 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5413 // and enables future optimizations (e.g. min/max pattern matching on X86). 5414 if (N0.getOpcode() == ISD::SETCC) { 5415 EVT VT = N->getValueType(0); 5416 5417 // Check if any splitting is required. 5418 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5419 TargetLowering::TypeSplitVector) 5420 return SDValue(); 5421 5422 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5423 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5424 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5425 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5426 5427 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5428 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5429 5430 // Add the new VSELECT nodes to the work list in case they need to be split 5431 // again. 5432 AddToWorklist(Lo.getNode()); 5433 AddToWorklist(Hi.getNode()); 5434 5435 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5436 } 5437 5438 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5439 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5440 return N1; 5441 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5442 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5443 return N2; 5444 5445 // The ConvertSelectToConcatVector function is assuming both the above 5446 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5447 // and addressed. 5448 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5449 N2.getOpcode() == ISD::CONCAT_VECTORS && 5450 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5451 SDValue CV = ConvertSelectToConcatVector(N, DAG); 5452 if (CV.getNode()) 5453 return CV; 5454 } 5455 5456 return SDValue(); 5457 } 5458 5459 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5460 SDValue N0 = N->getOperand(0); 5461 SDValue N1 = N->getOperand(1); 5462 SDValue N2 = N->getOperand(2); 5463 SDValue N3 = N->getOperand(3); 5464 SDValue N4 = N->getOperand(4); 5465 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5466 5467 // fold select_cc lhs, rhs, x, x, cc -> x 5468 if (N2 == N3) 5469 return N2; 5470 5471 // Determine if the condition we're dealing with is constant 5472 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5473 N0, N1, CC, SDLoc(N), false); 5474 if (SCC.getNode()) { 5475 AddToWorklist(SCC.getNode()); 5476 5477 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5478 if (!SCCC->isNullValue()) 5479 return N2; // cond always true -> true val 5480 else 5481 return N3; // cond always false -> false val 5482 } else if (SCC->getOpcode() == ISD::UNDEF) { 5483 // When the condition is UNDEF, just return the first operand. This is 5484 // coherent the DAG creation, no setcc node is created in this case 5485 return N2; 5486 } else if (SCC.getOpcode() == ISD::SETCC) { 5487 // Fold to a simpler select_cc 5488 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5489 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5490 SCC.getOperand(2)); 5491 } 5492 } 5493 5494 // If we can fold this based on the true/false value, do so. 5495 if (SimplifySelectOps(N, N2, N3)) 5496 return SDValue(N, 0); // Don't revisit N. 5497 5498 // fold select_cc into other things, such as min/max/abs 5499 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5500 } 5501 5502 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5503 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5504 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5505 SDLoc(N)); 5506 } 5507 5508 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 5509 // dag node into a ConstantSDNode or a build_vector of constants. 5510 // This function is called by the DAGCombiner when visiting sext/zext/aext 5511 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5512 // Vector extends are not folded if operations are legal; this is to 5513 // avoid introducing illegal build_vector dag nodes. 5514 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5515 SelectionDAG &DAG, bool LegalTypes, 5516 bool LegalOperations) { 5517 unsigned Opcode = N->getOpcode(); 5518 SDValue N0 = N->getOperand(0); 5519 EVT VT = N->getValueType(0); 5520 5521 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5522 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 5523 5524 // fold (sext c1) -> c1 5525 // fold (zext c1) -> c1 5526 // fold (aext c1) -> c1 5527 if (isa<ConstantSDNode>(N0)) 5528 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5529 5530 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5531 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5532 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5533 EVT SVT = VT.getScalarType(); 5534 if (!(VT.isVector() && 5535 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5536 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5537 return nullptr; 5538 5539 // We can fold this node into a build_vector. 5540 unsigned VTBits = SVT.getSizeInBits(); 5541 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5542 unsigned ShAmt = VTBits - EVTBits; 5543 SmallVector<SDValue, 8> Elts; 5544 unsigned NumElts = N0->getNumOperands(); 5545 SDLoc DL(N); 5546 5547 for (unsigned i=0; i != NumElts; ++i) { 5548 SDValue Op = N0->getOperand(i); 5549 if (Op->getOpcode() == ISD::UNDEF) { 5550 Elts.push_back(DAG.getUNDEF(SVT)); 5551 continue; 5552 } 5553 5554 SDLoc DL(Op); 5555 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 5556 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 5557 if (Opcode == ISD::SIGN_EXTEND) 5558 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 5559 DL, SVT)); 5560 else 5561 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 5562 DL, SVT)); 5563 } 5564 5565 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5566 } 5567 5568 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5569 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5570 // transformation. Returns true if extension are possible and the above 5571 // mentioned transformation is profitable. 5572 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5573 unsigned ExtOpc, 5574 SmallVectorImpl<SDNode *> &ExtendNodes, 5575 const TargetLowering &TLI) { 5576 bool HasCopyToRegUses = false; 5577 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5578 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5579 UE = N0.getNode()->use_end(); 5580 UI != UE; ++UI) { 5581 SDNode *User = *UI; 5582 if (User == N) 5583 continue; 5584 if (UI.getUse().getResNo() != N0.getResNo()) 5585 continue; 5586 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5587 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5588 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5589 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5590 // Sign bits will be lost after a zext. 5591 return false; 5592 bool Add = false; 5593 for (unsigned i = 0; i != 2; ++i) { 5594 SDValue UseOp = User->getOperand(i); 5595 if (UseOp == N0) 5596 continue; 5597 if (!isa<ConstantSDNode>(UseOp)) 5598 return false; 5599 Add = true; 5600 } 5601 if (Add) 5602 ExtendNodes.push_back(User); 5603 continue; 5604 } 5605 // If truncates aren't free and there are users we can't 5606 // extend, it isn't worthwhile. 5607 if (!isTruncFree) 5608 return false; 5609 // Remember if this value is live-out. 5610 if (User->getOpcode() == ISD::CopyToReg) 5611 HasCopyToRegUses = true; 5612 } 5613 5614 if (HasCopyToRegUses) { 5615 bool BothLiveOut = false; 5616 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5617 UI != UE; ++UI) { 5618 SDUse &Use = UI.getUse(); 5619 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5620 BothLiveOut = true; 5621 break; 5622 } 5623 } 5624 if (BothLiveOut) 5625 // Both unextended and extended values are live out. There had better be 5626 // a good reason for the transformation. 5627 return ExtendNodes.size(); 5628 } 5629 return true; 5630 } 5631 5632 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5633 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5634 ISD::NodeType ExtType) { 5635 // Extend SetCC uses if necessary. 5636 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5637 SDNode *SetCC = SetCCs[i]; 5638 SmallVector<SDValue, 4> Ops; 5639 5640 for (unsigned j = 0; j != 2; ++j) { 5641 SDValue SOp = SetCC->getOperand(j); 5642 if (SOp == Trunc) 5643 Ops.push_back(ExtLoad); 5644 else 5645 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5646 } 5647 5648 Ops.push_back(SetCC->getOperand(2)); 5649 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5650 } 5651 } 5652 5653 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 5654 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 5655 SDValue N0 = N->getOperand(0); 5656 EVT DstVT = N->getValueType(0); 5657 EVT SrcVT = N0.getValueType(); 5658 5659 assert((N->getOpcode() == ISD::SIGN_EXTEND || 5660 N->getOpcode() == ISD::ZERO_EXTEND) && 5661 "Unexpected node type (not an extend)!"); 5662 5663 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 5664 // For example, on a target with legal v4i32, but illegal v8i32, turn: 5665 // (v8i32 (sext (v8i16 (load x)))) 5666 // into: 5667 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5668 // (v4i32 (sextload (x + 16))))) 5669 // Where uses of the original load, i.e.: 5670 // (v8i16 (load x)) 5671 // are replaced with: 5672 // (v8i16 (truncate 5673 // (v8i32 (concat_vectors (v4i32 (sextload x)), 5674 // (v4i32 (sextload (x + 16))))))) 5675 // 5676 // This combine is only applicable to illegal, but splittable, vectors. 5677 // All legal types, and illegal non-vector types, are handled elsewhere. 5678 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 5679 // 5680 if (N0->getOpcode() != ISD::LOAD) 5681 return SDValue(); 5682 5683 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5684 5685 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 5686 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 5687 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 5688 return SDValue(); 5689 5690 SmallVector<SDNode *, 4> SetCCs; 5691 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI)) 5692 return SDValue(); 5693 5694 ISD::LoadExtType ExtType = 5695 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 5696 5697 // Try to split the vector types to get down to legal types. 5698 EVT SplitSrcVT = SrcVT; 5699 EVT SplitDstVT = DstVT; 5700 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 5701 SplitSrcVT.getVectorNumElements() > 1) { 5702 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 5703 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 5704 } 5705 5706 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 5707 return SDValue(); 5708 5709 SDLoc DL(N); 5710 const unsigned NumSplits = 5711 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 5712 const unsigned Stride = SplitSrcVT.getStoreSize(); 5713 SmallVector<SDValue, 4> Loads; 5714 SmallVector<SDValue, 4> Chains; 5715 5716 SDValue BasePtr = LN0->getBasePtr(); 5717 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 5718 const unsigned Offset = Idx * Stride; 5719 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 5720 5721 SDValue SplitLoad = DAG.getExtLoad( 5722 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr, 5723 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, 5724 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(), 5725 Align, LN0->getAAInfo()); 5726 5727 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 5728 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 5729 5730 Loads.push_back(SplitLoad.getValue(0)); 5731 Chains.push_back(SplitLoad.getValue(1)); 5732 } 5733 5734 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 5735 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 5736 5737 CombineTo(N, NewValue); 5738 5739 // Replace uses of the original load (before extension) 5740 // with a truncate of the concatenated sextloaded vectors. 5741 SDValue Trunc = 5742 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 5743 CombineTo(N0.getNode(), Trunc, NewChain); 5744 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL, 5745 (ISD::NodeType)N->getOpcode()); 5746 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5747 } 5748 5749 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5750 SDValue N0 = N->getOperand(0); 5751 EVT VT = N->getValueType(0); 5752 5753 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5754 LegalOperations)) 5755 return SDValue(Res, 0); 5756 5757 // fold (sext (sext x)) -> (sext x) 5758 // fold (sext (aext x)) -> (sext x) 5759 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5760 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5761 N0.getOperand(0)); 5762 5763 if (N0.getOpcode() == ISD::TRUNCATE) { 5764 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5765 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5766 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5767 if (NarrowLoad.getNode()) { 5768 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5769 if (NarrowLoad.getNode() != N0.getNode()) { 5770 CombineTo(N0.getNode(), NarrowLoad); 5771 // CombineTo deleted the truncate, if needed, but not what's under it. 5772 AddToWorklist(oye); 5773 } 5774 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5775 } 5776 5777 // See if the value being truncated is already sign extended. If so, just 5778 // eliminate the trunc/sext pair. 5779 SDValue Op = N0.getOperand(0); 5780 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5781 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5782 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5783 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5784 5785 if (OpBits == DestBits) { 5786 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5787 // bits, it is already ready. 5788 if (NumSignBits > DestBits-MidBits) 5789 return Op; 5790 } else if (OpBits < DestBits) { 5791 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5792 // bits, just sext from i32. 5793 if (NumSignBits > OpBits-MidBits) 5794 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5795 } else { 5796 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5797 // bits, just truncate to i32. 5798 if (NumSignBits > OpBits-MidBits) 5799 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5800 } 5801 5802 // fold (sext (truncate x)) -> (sextinreg x). 5803 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5804 N0.getValueType())) { 5805 if (OpBits < DestBits) 5806 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5807 else if (OpBits > DestBits) 5808 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5809 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5810 DAG.getValueType(N0.getValueType())); 5811 } 5812 } 5813 5814 // fold (sext (load x)) -> (sext (truncate (sextload x))) 5815 // Only generate vector extloads when 1) they're legal, and 2) they are 5816 // deemed desirable by the target. 5817 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5818 ((!LegalOperations && !VT.isVector() && 5819 !cast<LoadSDNode>(N0)->isVolatile()) || 5820 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 5821 bool DoXform = true; 5822 SmallVector<SDNode*, 4> SetCCs; 5823 if (!N0.hasOneUse()) 5824 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5825 if (VT.isVector()) 5826 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 5827 if (DoXform) { 5828 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5829 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5830 LN0->getChain(), 5831 LN0->getBasePtr(), N0.getValueType(), 5832 LN0->getMemOperand()); 5833 CombineTo(N, ExtLoad); 5834 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5835 N0.getValueType(), ExtLoad); 5836 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5837 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5838 ISD::SIGN_EXTEND); 5839 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5840 } 5841 } 5842 5843 // fold (sext (load x)) to multiple smaller sextloads. 5844 // Only on illegal but splittable vectors. 5845 if (SDValue ExtLoad = CombineExtLoad(N)) 5846 return ExtLoad; 5847 5848 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5849 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5850 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5851 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5852 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5853 EVT MemVT = LN0->getMemoryVT(); 5854 if ((!LegalOperations && !LN0->isVolatile()) || 5855 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 5856 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5857 LN0->getChain(), 5858 LN0->getBasePtr(), MemVT, 5859 LN0->getMemOperand()); 5860 CombineTo(N, ExtLoad); 5861 CombineTo(N0.getNode(), 5862 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5863 N0.getValueType(), ExtLoad), 5864 ExtLoad.getValue(1)); 5865 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5866 } 5867 } 5868 5869 // fold (sext (and/or/xor (load x), cst)) -> 5870 // (and/or/xor (sextload x), (sext cst)) 5871 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5872 N0.getOpcode() == ISD::XOR) && 5873 isa<LoadSDNode>(N0.getOperand(0)) && 5874 N0.getOperand(1).getOpcode() == ISD::Constant && 5875 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 5876 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5877 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5878 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5879 bool DoXform = true; 5880 SmallVector<SDNode*, 4> SetCCs; 5881 if (!N0.hasOneUse()) 5882 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 5883 SetCCs, TLI); 5884 if (DoXform) { 5885 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 5886 LN0->getChain(), LN0->getBasePtr(), 5887 LN0->getMemoryVT(), 5888 LN0->getMemOperand()); 5889 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5890 Mask = Mask.sext(VT.getSizeInBits()); 5891 SDLoc DL(N); 5892 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 5893 ExtLoad, DAG.getConstant(Mask, DL, VT)); 5894 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5895 SDLoc(N0.getOperand(0)), 5896 N0.getOperand(0).getValueType(), ExtLoad); 5897 CombineTo(N, And); 5898 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5899 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 5900 ISD::SIGN_EXTEND); 5901 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5902 } 5903 } 5904 } 5905 5906 if (N0.getOpcode() == ISD::SETCC) { 5907 EVT N0VT = N0.getOperand(0).getValueType(); 5908 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 5909 // Only do this before legalize for now. 5910 if (VT.isVector() && !LegalOperations && 5911 TLI.getBooleanContents(N0VT) == 5912 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5913 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 5914 // of the same size as the compared operands. Only optimize sext(setcc()) 5915 // if this is the case. 5916 EVT SVT = getSetCCResultType(N0VT); 5917 5918 // We know that the # elements of the results is the same as the 5919 // # elements of the compare (and the # elements of the compare result 5920 // for that matter). Check to see that they are the same size. If so, 5921 // we know that the element size of the sext'd result matches the 5922 // element size of the compare operands. 5923 if (VT.getSizeInBits() == SVT.getSizeInBits()) 5924 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5925 N0.getOperand(1), 5926 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5927 5928 // If the desired elements are smaller or larger than the source 5929 // elements we can use a matching integer vector type and then 5930 // truncate/sign extend 5931 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5932 if (SVT == MatchingVectorType) { 5933 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 5934 N0.getOperand(0), N0.getOperand(1), 5935 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5936 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5937 } 5938 } 5939 5940 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 5941 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 5942 SDLoc DL(N); 5943 SDValue NegOne = 5944 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT); 5945 SDValue SCC = 5946 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 5947 NegOne, DAG.getConstant(0, DL, VT), 5948 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5949 if (SCC.getNode()) return SCC; 5950 5951 if (!VT.isVector()) { 5952 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 5953 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 5954 SDLoc DL(N); 5955 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5956 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 5957 N0.getOperand(0), N0.getOperand(1), CC); 5958 return DAG.getSelect(DL, VT, SetCC, 5959 NegOne, DAG.getConstant(0, DL, VT)); 5960 } 5961 } 5962 } 5963 5964 // fold (sext x) -> (zext x) if the sign bit is known zero. 5965 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 5966 DAG.SignBitIsZero(N0)) 5967 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 5968 5969 return SDValue(); 5970 } 5971 5972 // isTruncateOf - If N is a truncate of some other value, return true, record 5973 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 5974 // This function computes KnownZero to avoid a duplicated call to 5975 // computeKnownBits in the caller. 5976 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 5977 APInt &KnownZero) { 5978 APInt KnownOne; 5979 if (N->getOpcode() == ISD::TRUNCATE) { 5980 Op = N->getOperand(0); 5981 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5982 return true; 5983 } 5984 5985 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 5986 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 5987 return false; 5988 5989 SDValue Op0 = N->getOperand(0); 5990 SDValue Op1 = N->getOperand(1); 5991 assert(Op0.getValueType() == Op1.getValueType()); 5992 5993 if (isNullConstant(Op0)) 5994 Op = Op1; 5995 else if (isNullConstant(Op1)) 5996 Op = Op0; 5997 else 5998 return false; 5999 6000 DAG.computeKnownBits(Op, KnownZero, KnownOne); 6001 6002 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 6003 return false; 6004 6005 return true; 6006 } 6007 6008 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 6009 SDValue N0 = N->getOperand(0); 6010 EVT VT = N->getValueType(0); 6011 6012 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6013 LegalOperations)) 6014 return SDValue(Res, 0); 6015 6016 // fold (zext (zext x)) -> (zext x) 6017 // fold (zext (aext x)) -> (zext x) 6018 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 6019 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 6020 N0.getOperand(0)); 6021 6022 // fold (zext (truncate x)) -> (zext x) or 6023 // (zext (truncate x)) -> (truncate x) 6024 // This is valid when the truncated bits of x are already zero. 6025 // FIXME: We should extend this to work for vectors too. 6026 SDValue Op; 6027 APInt KnownZero; 6028 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 6029 APInt TruncatedBits = 6030 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 6031 APInt(Op.getValueSizeInBits(), 0) : 6032 APInt::getBitsSet(Op.getValueSizeInBits(), 6033 N0.getValueSizeInBits(), 6034 std::min(Op.getValueSizeInBits(), 6035 VT.getSizeInBits())); 6036 if (TruncatedBits == (KnownZero & TruncatedBits)) { 6037 if (VT.bitsGT(Op.getValueType())) 6038 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 6039 if (VT.bitsLT(Op.getValueType())) 6040 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6041 6042 return Op; 6043 } 6044 } 6045 6046 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6047 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 6048 if (N0.getOpcode() == ISD::TRUNCATE) { 6049 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 6050 if (NarrowLoad.getNode()) { 6051 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6052 if (NarrowLoad.getNode() != N0.getNode()) { 6053 CombineTo(N0.getNode(), NarrowLoad); 6054 // CombineTo deleted the truncate, if needed, but not what's under it. 6055 AddToWorklist(oye); 6056 } 6057 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6058 } 6059 } 6060 6061 // fold (zext (truncate x)) -> (and x, mask) 6062 if (N0.getOpcode() == ISD::TRUNCATE && 6063 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 6064 6065 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 6066 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 6067 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 6068 if (NarrowLoad.getNode()) { 6069 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6070 if (NarrowLoad.getNode() != N0.getNode()) { 6071 CombineTo(N0.getNode(), NarrowLoad); 6072 // CombineTo deleted the truncate, if needed, but not what's under it. 6073 AddToWorklist(oye); 6074 } 6075 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6076 } 6077 6078 SDValue Op = N0.getOperand(0); 6079 if (Op.getValueType().bitsLT(VT)) { 6080 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 6081 AddToWorklist(Op.getNode()); 6082 } else if (Op.getValueType().bitsGT(VT)) { 6083 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 6084 AddToWorklist(Op.getNode()); 6085 } 6086 return DAG.getZeroExtendInReg(Op, SDLoc(N), 6087 N0.getValueType().getScalarType()); 6088 } 6089 6090 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 6091 // if either of the casts is not free. 6092 if (N0.getOpcode() == ISD::AND && 6093 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6094 N0.getOperand(1).getOpcode() == ISD::Constant && 6095 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6096 N0.getValueType()) || 6097 !TLI.isZExtFree(N0.getValueType(), VT))) { 6098 SDValue X = N0.getOperand(0).getOperand(0); 6099 if (X.getValueType().bitsLT(VT)) { 6100 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 6101 } else if (X.getValueType().bitsGT(VT)) { 6102 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6103 } 6104 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6105 Mask = Mask.zext(VT.getSizeInBits()); 6106 SDLoc DL(N); 6107 return DAG.getNode(ISD::AND, DL, VT, 6108 X, DAG.getConstant(Mask, DL, VT)); 6109 } 6110 6111 // fold (zext (load x)) -> (zext (truncate (zextload x))) 6112 // Only generate vector extloads when 1) they're legal, and 2) they are 6113 // deemed desirable by the target. 6114 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6115 ((!LegalOperations && !VT.isVector() && 6116 !cast<LoadSDNode>(N0)->isVolatile()) || 6117 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 6118 bool DoXform = true; 6119 SmallVector<SDNode*, 4> SetCCs; 6120 if (!N0.hasOneUse()) 6121 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 6122 if (VT.isVector()) 6123 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 6124 if (DoXform) { 6125 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6126 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6127 LN0->getChain(), 6128 LN0->getBasePtr(), N0.getValueType(), 6129 LN0->getMemOperand()); 6130 CombineTo(N, ExtLoad); 6131 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6132 N0.getValueType(), ExtLoad); 6133 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6134 6135 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6136 ISD::ZERO_EXTEND); 6137 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6138 } 6139 } 6140 6141 // fold (zext (load x)) to multiple smaller zextloads. 6142 // Only on illegal but splittable vectors. 6143 if (SDValue ExtLoad = CombineExtLoad(N)) 6144 return ExtLoad; 6145 6146 // fold (zext (and/or/xor (load x), cst)) -> 6147 // (and/or/xor (zextload x), (zext cst)) 6148 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 6149 N0.getOpcode() == ISD::XOR) && 6150 isa<LoadSDNode>(N0.getOperand(0)) && 6151 N0.getOperand(1).getOpcode() == ISD::Constant && 6152 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 6153 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 6154 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 6155 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 6156 bool DoXform = true; 6157 SmallVector<SDNode*, 4> SetCCs; 6158 if (!N0.hasOneUse()) 6159 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 6160 SetCCs, TLI); 6161 if (DoXform) { 6162 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 6163 LN0->getChain(), LN0->getBasePtr(), 6164 LN0->getMemoryVT(), 6165 LN0->getMemOperand()); 6166 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6167 Mask = Mask.zext(VT.getSizeInBits()); 6168 SDLoc DL(N); 6169 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 6170 ExtLoad, DAG.getConstant(Mask, DL, VT)); 6171 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 6172 SDLoc(N0.getOperand(0)), 6173 N0.getOperand(0).getValueType(), ExtLoad); 6174 CombineTo(N, And); 6175 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 6176 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, 6177 ISD::ZERO_EXTEND); 6178 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6179 } 6180 } 6181 } 6182 6183 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 6184 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 6185 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 6186 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 6187 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6188 EVT MemVT = LN0->getMemoryVT(); 6189 if ((!LegalOperations && !LN0->isVolatile()) || 6190 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 6191 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 6192 LN0->getChain(), 6193 LN0->getBasePtr(), MemVT, 6194 LN0->getMemOperand()); 6195 CombineTo(N, ExtLoad); 6196 CombineTo(N0.getNode(), 6197 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 6198 ExtLoad), 6199 ExtLoad.getValue(1)); 6200 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6201 } 6202 } 6203 6204 if (N0.getOpcode() == ISD::SETCC) { 6205 if (!LegalOperations && VT.isVector() && 6206 N0.getValueType().getVectorElementType() == MVT::i1) { 6207 EVT N0VT = N0.getOperand(0).getValueType(); 6208 if (getSetCCResultType(N0VT) == N0.getValueType()) 6209 return SDValue(); 6210 6211 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 6212 // Only do this before legalize for now. 6213 EVT EltVT = VT.getVectorElementType(); 6214 SDLoc DL(N); 6215 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 6216 DAG.getConstant(1, DL, EltVT)); 6217 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6218 // We know that the # elements of the results is the same as the 6219 // # elements of the compare (and the # elements of the compare result 6220 // for that matter). Check to see that they are the same size. If so, 6221 // we know that the element size of the sext'd result matches the 6222 // element size of the compare operands. 6223 return DAG.getNode(ISD::AND, DL, VT, 6224 DAG.getSetCC(DL, VT, N0.getOperand(0), 6225 N0.getOperand(1), 6226 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 6227 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, 6228 OneOps)); 6229 6230 // If the desired elements are smaller or larger than the source 6231 // elements we can use a matching integer vector type and then 6232 // truncate/sign extend 6233 EVT MatchingElementType = 6234 EVT::getIntegerVT(*DAG.getContext(), 6235 N0VT.getScalarType().getSizeInBits()); 6236 EVT MatchingVectorType = 6237 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 6238 N0VT.getVectorNumElements()); 6239 SDValue VsetCC = 6240 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0), 6241 N0.getOperand(1), 6242 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6243 return DAG.getNode(ISD::AND, DL, VT, 6244 DAG.getSExtOrTrunc(VsetCC, DL, VT), 6245 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps)); 6246 } 6247 6248 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6249 SDLoc DL(N); 6250 SDValue SCC = 6251 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6252 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6253 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6254 if (SCC.getNode()) return SCC; 6255 } 6256 6257 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 6258 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 6259 isa<ConstantSDNode>(N0.getOperand(1)) && 6260 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 6261 N0.hasOneUse()) { 6262 SDValue ShAmt = N0.getOperand(1); 6263 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 6264 if (N0.getOpcode() == ISD::SHL) { 6265 SDValue InnerZExt = N0.getOperand(0); 6266 // If the original shl may be shifting out bits, do not perform this 6267 // transformation. 6268 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 6269 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 6270 if (ShAmtVal > KnownZeroBits) 6271 return SDValue(); 6272 } 6273 6274 SDLoc DL(N); 6275 6276 // Ensure that the shift amount is wide enough for the shifted value. 6277 if (VT.getSizeInBits() >= 256) 6278 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 6279 6280 return DAG.getNode(N0.getOpcode(), DL, VT, 6281 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 6282 ShAmt); 6283 } 6284 6285 return SDValue(); 6286 } 6287 6288 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 6289 SDValue N0 = N->getOperand(0); 6290 EVT VT = N->getValueType(0); 6291 6292 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 6293 LegalOperations)) 6294 return SDValue(Res, 0); 6295 6296 // fold (aext (aext x)) -> (aext x) 6297 // fold (aext (zext x)) -> (zext x) 6298 // fold (aext (sext x)) -> (sext x) 6299 if (N0.getOpcode() == ISD::ANY_EXTEND || 6300 N0.getOpcode() == ISD::ZERO_EXTEND || 6301 N0.getOpcode() == ISD::SIGN_EXTEND) 6302 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 6303 6304 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 6305 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 6306 if (N0.getOpcode() == ISD::TRUNCATE) { 6307 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 6308 if (NarrowLoad.getNode()) { 6309 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 6310 if (NarrowLoad.getNode() != N0.getNode()) { 6311 CombineTo(N0.getNode(), NarrowLoad); 6312 // CombineTo deleted the truncate, if needed, but not what's under it. 6313 AddToWorklist(oye); 6314 } 6315 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6316 } 6317 } 6318 6319 // fold (aext (truncate x)) 6320 if (N0.getOpcode() == ISD::TRUNCATE) { 6321 SDValue TruncOp = N0.getOperand(0); 6322 if (TruncOp.getValueType() == VT) 6323 return TruncOp; // x iff x size == zext size. 6324 if (TruncOp.getValueType().bitsGT(VT)) 6325 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 6326 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 6327 } 6328 6329 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 6330 // if the trunc is not free. 6331 if (N0.getOpcode() == ISD::AND && 6332 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 6333 N0.getOperand(1).getOpcode() == ISD::Constant && 6334 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 6335 N0.getValueType())) { 6336 SDValue X = N0.getOperand(0).getOperand(0); 6337 if (X.getValueType().bitsLT(VT)) { 6338 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 6339 } else if (X.getValueType().bitsGT(VT)) { 6340 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 6341 } 6342 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 6343 Mask = Mask.zext(VT.getSizeInBits()); 6344 SDLoc DL(N); 6345 return DAG.getNode(ISD::AND, DL, VT, 6346 X, DAG.getConstant(Mask, DL, VT)); 6347 } 6348 6349 // fold (aext (load x)) -> (aext (truncate (extload x))) 6350 // None of the supported targets knows how to perform load and any_ext 6351 // on vectors in one instruction. We only perform this transformation on 6352 // scalars. 6353 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 6354 ISD::isUNINDEXEDLoad(N0.getNode()) && 6355 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 6356 bool DoXform = true; 6357 SmallVector<SDNode*, 4> SetCCs; 6358 if (!N0.hasOneUse()) 6359 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 6360 if (DoXform) { 6361 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6362 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 6363 LN0->getChain(), 6364 LN0->getBasePtr(), N0.getValueType(), 6365 LN0->getMemOperand()); 6366 CombineTo(N, ExtLoad); 6367 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6368 N0.getValueType(), ExtLoad); 6369 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 6370 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 6371 ISD::ANY_EXTEND); 6372 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6373 } 6374 } 6375 6376 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 6377 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 6378 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 6379 if (N0.getOpcode() == ISD::LOAD && 6380 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6381 N0.hasOneUse()) { 6382 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6383 ISD::LoadExtType ExtType = LN0->getExtensionType(); 6384 EVT MemVT = LN0->getMemoryVT(); 6385 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 6386 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 6387 VT, LN0->getChain(), LN0->getBasePtr(), 6388 MemVT, LN0->getMemOperand()); 6389 CombineTo(N, ExtLoad); 6390 CombineTo(N0.getNode(), 6391 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 6392 N0.getValueType(), ExtLoad), 6393 ExtLoad.getValue(1)); 6394 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6395 } 6396 } 6397 6398 if (N0.getOpcode() == ISD::SETCC) { 6399 // For vectors: 6400 // aext(setcc) -> vsetcc 6401 // aext(setcc) -> truncate(vsetcc) 6402 // aext(setcc) -> aext(vsetcc) 6403 // Only do this before legalize for now. 6404 if (VT.isVector() && !LegalOperations) { 6405 EVT N0VT = N0.getOperand(0).getValueType(); 6406 // We know that the # elements of the results is the same as the 6407 // # elements of the compare (and the # elements of the compare result 6408 // for that matter). Check to see that they are the same size. If so, 6409 // we know that the element size of the sext'd result matches the 6410 // element size of the compare operands. 6411 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 6412 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 6413 N0.getOperand(1), 6414 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6415 // If the desired elements are smaller or larger than the source 6416 // elements we can use a matching integer vector type and then 6417 // truncate/any extend 6418 else { 6419 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 6420 SDValue VsetCC = 6421 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 6422 N0.getOperand(1), 6423 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 6424 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 6425 } 6426 } 6427 6428 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 6429 SDLoc DL(N); 6430 SDValue SCC = 6431 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), 6432 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT), 6433 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 6434 if (SCC.getNode()) 6435 return SCC; 6436 } 6437 6438 return SDValue(); 6439 } 6440 6441 /// See if the specified operand can be simplified with the knowledge that only 6442 /// the bits specified by Mask are used. If so, return the simpler operand, 6443 /// otherwise return a null SDValue. 6444 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 6445 switch (V.getOpcode()) { 6446 default: break; 6447 case ISD::Constant: { 6448 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 6449 assert(CV && "Const value should be ConstSDNode."); 6450 const APInt &CVal = CV->getAPIntValue(); 6451 APInt NewVal = CVal & Mask; 6452 if (NewVal != CVal) 6453 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType()); 6454 break; 6455 } 6456 case ISD::OR: 6457 case ISD::XOR: 6458 // If the LHS or RHS don't contribute bits to the or, drop them. 6459 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6460 return V.getOperand(1); 6461 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6462 return V.getOperand(0); 6463 break; 6464 case ISD::SRL: 6465 // Only look at single-use SRLs. 6466 if (!V.getNode()->hasOneUse()) 6467 break; 6468 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 6469 // See if we can recursively simplify the LHS. 6470 unsigned Amt = RHSC->getZExtValue(); 6471 6472 // Watch out for shift count overflow though. 6473 if (Amt >= Mask.getBitWidth()) break; 6474 APInt NewMask = Mask << Amt; 6475 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 6476 if (SimplifyLHS.getNode()) 6477 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6478 SimplifyLHS, V.getOperand(1)); 6479 } 6480 } 6481 return SDValue(); 6482 } 6483 6484 /// If the result of a wider load is shifted to right of N bits and then 6485 /// truncated to a narrower type and where N is a multiple of number of bits of 6486 /// the narrower type, transform it to a narrower load from address + N / num of 6487 /// bits of new type. If the result is to be extended, also fold the extension 6488 /// to form a extending load. 6489 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6490 unsigned Opc = N->getOpcode(); 6491 6492 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6493 SDValue N0 = N->getOperand(0); 6494 EVT VT = N->getValueType(0); 6495 EVT ExtVT = VT; 6496 6497 // This transformation isn't valid for vector loads. 6498 if (VT.isVector()) 6499 return SDValue(); 6500 6501 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6502 // extended to VT. 6503 if (Opc == ISD::SIGN_EXTEND_INREG) { 6504 ExtType = ISD::SEXTLOAD; 6505 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6506 } else if (Opc == ISD::SRL) { 6507 // Another special-case: SRL is basically zero-extending a narrower value. 6508 ExtType = ISD::ZEXTLOAD; 6509 N0 = SDValue(N, 0); 6510 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6511 if (!N01) return SDValue(); 6512 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6513 VT.getSizeInBits() - N01->getZExtValue()); 6514 } 6515 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6516 return SDValue(); 6517 6518 unsigned EVTBits = ExtVT.getSizeInBits(); 6519 6520 // Do not generate loads of non-round integer types since these can 6521 // be expensive (and would be wrong if the type is not byte sized). 6522 if (!ExtVT.isRound()) 6523 return SDValue(); 6524 6525 unsigned ShAmt = 0; 6526 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6527 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6528 ShAmt = N01->getZExtValue(); 6529 // Is the shift amount a multiple of size of VT? 6530 if ((ShAmt & (EVTBits-1)) == 0) { 6531 N0 = N0.getOperand(0); 6532 // Is the load width a multiple of size of VT? 6533 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6534 return SDValue(); 6535 } 6536 6537 // At this point, we must have a load or else we can't do the transform. 6538 if (!isa<LoadSDNode>(N0)) return SDValue(); 6539 6540 // Because a SRL must be assumed to *need* to zero-extend the high bits 6541 // (as opposed to anyext the high bits), we can't combine the zextload 6542 // lowering of SRL and an sextload. 6543 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6544 return SDValue(); 6545 6546 // If the shift amount is larger than the input type then we're not 6547 // accessing any of the loaded bytes. If the load was a zextload/extload 6548 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6549 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6550 return SDValue(); 6551 } 6552 } 6553 6554 // If the load is shifted left (and the result isn't shifted back right), 6555 // we can fold the truncate through the shift. 6556 unsigned ShLeftAmt = 0; 6557 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6558 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6559 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6560 ShLeftAmt = N01->getZExtValue(); 6561 N0 = N0.getOperand(0); 6562 } 6563 } 6564 6565 // If we haven't found a load, we can't narrow it. Don't transform one with 6566 // multiple uses, this would require adding a new load. 6567 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6568 return SDValue(); 6569 6570 // Don't change the width of a volatile load. 6571 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6572 if (LN0->isVolatile()) 6573 return SDValue(); 6574 6575 // Verify that we are actually reducing a load width here. 6576 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6577 return SDValue(); 6578 6579 // For the transform to be legal, the load must produce only two values 6580 // (the value loaded and the chain). Don't transform a pre-increment 6581 // load, for example, which produces an extra value. Otherwise the 6582 // transformation is not equivalent, and the downstream logic to replace 6583 // uses gets things wrong. 6584 if (LN0->getNumValues() > 2) 6585 return SDValue(); 6586 6587 // If the load that we're shrinking is an extload and we're not just 6588 // discarding the extension we can't simply shrink the load. Bail. 6589 // TODO: It would be possible to merge the extensions in some cases. 6590 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6591 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6592 return SDValue(); 6593 6594 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6595 return SDValue(); 6596 6597 EVT PtrType = N0.getOperand(1).getValueType(); 6598 6599 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6600 // It's not possible to generate a constant of extended or untyped type. 6601 return SDValue(); 6602 6603 // For big endian targets, we need to adjust the offset to the pointer to 6604 // load the correct bytes. 6605 if (TLI.isBigEndian()) { 6606 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6607 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6608 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6609 } 6610 6611 uint64_t PtrOff = ShAmt / 8; 6612 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6613 SDLoc DL(LN0); 6614 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 6615 PtrType, LN0->getBasePtr(), 6616 DAG.getConstant(PtrOff, DL, PtrType)); 6617 AddToWorklist(NewPtr.getNode()); 6618 6619 SDValue Load; 6620 if (ExtType == ISD::NON_EXTLOAD) 6621 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6622 LN0->getPointerInfo().getWithOffset(PtrOff), 6623 LN0->isVolatile(), LN0->isNonTemporal(), 6624 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6625 else 6626 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6627 LN0->getPointerInfo().getWithOffset(PtrOff), 6628 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6629 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6630 6631 // Replace the old load's chain with the new load's chain. 6632 WorklistRemover DeadNodes(*this); 6633 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6634 6635 // Shift the result left, if we've swallowed a left shift. 6636 SDValue Result = Load; 6637 if (ShLeftAmt != 0) { 6638 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6639 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6640 ShImmTy = VT; 6641 // If the shift amount is as large as the result size (but, presumably, 6642 // no larger than the source) then the useful bits of the result are 6643 // zero; we can't simply return the shortened shift, because the result 6644 // of that operation is undefined. 6645 SDLoc DL(N0); 6646 if (ShLeftAmt >= VT.getSizeInBits()) 6647 Result = DAG.getConstant(0, DL, VT); 6648 else 6649 Result = DAG.getNode(ISD::SHL, DL, VT, 6650 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 6651 } 6652 6653 // Return the new loaded value. 6654 return Result; 6655 } 6656 6657 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6658 SDValue N0 = N->getOperand(0); 6659 SDValue N1 = N->getOperand(1); 6660 EVT VT = N->getValueType(0); 6661 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6662 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6663 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6664 6665 // fold (sext_in_reg c1) -> c1 6666 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 6667 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6668 6669 // If the input is already sign extended, just drop the extension. 6670 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6671 return N0; 6672 6673 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6674 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6675 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6676 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6677 N0.getOperand(0), N1); 6678 6679 // fold (sext_in_reg (sext x)) -> (sext x) 6680 // fold (sext_in_reg (aext x)) -> (sext x) 6681 // if x is small enough. 6682 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6683 SDValue N00 = N0.getOperand(0); 6684 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6685 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6686 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6687 } 6688 6689 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6690 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6691 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6692 6693 // fold operands of sext_in_reg based on knowledge that the top bits are not 6694 // demanded. 6695 if (SimplifyDemandedBits(SDValue(N, 0))) 6696 return SDValue(N, 0); 6697 6698 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6699 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6700 SDValue NarrowLoad = ReduceLoadWidth(N); 6701 if (NarrowLoad.getNode()) 6702 return NarrowLoad; 6703 6704 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6705 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6706 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6707 if (N0.getOpcode() == ISD::SRL) { 6708 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6709 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6710 // We can turn this into an SRA iff the input to the SRL is already sign 6711 // extended enough. 6712 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6713 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6714 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6715 N0.getOperand(0), N0.getOperand(1)); 6716 } 6717 } 6718 6719 // fold (sext_inreg (extload x)) -> (sextload x) 6720 if (ISD::isEXTLoad(N0.getNode()) && 6721 ISD::isUNINDEXEDLoad(N0.getNode()) && 6722 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6723 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6724 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6725 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6726 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6727 LN0->getChain(), 6728 LN0->getBasePtr(), EVT, 6729 LN0->getMemOperand()); 6730 CombineTo(N, ExtLoad); 6731 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6732 AddToWorklist(ExtLoad.getNode()); 6733 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6734 } 6735 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6736 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6737 N0.hasOneUse() && 6738 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6739 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6740 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6741 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6742 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6743 LN0->getChain(), 6744 LN0->getBasePtr(), EVT, 6745 LN0->getMemOperand()); 6746 CombineTo(N, ExtLoad); 6747 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6748 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6749 } 6750 6751 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6752 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6753 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6754 N0.getOperand(1), false); 6755 if (BSwap.getNode()) 6756 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6757 BSwap, N1); 6758 } 6759 6760 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 6761 // into a build_vector. 6762 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6763 SmallVector<SDValue, 8> Elts; 6764 unsigned NumElts = N0->getNumOperands(); 6765 unsigned ShAmt = VTBits - EVTBits; 6766 6767 for (unsigned i = 0; i != NumElts; ++i) { 6768 SDValue Op = N0->getOperand(i); 6769 if (Op->getOpcode() == ISD::UNDEF) { 6770 Elts.push_back(Op); 6771 continue; 6772 } 6773 6774 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 6775 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 6776 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 6777 SDLoc(Op), Op.getValueType())); 6778 } 6779 6780 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts); 6781 } 6782 6783 return SDValue(); 6784 } 6785 6786 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6787 SDValue N0 = N->getOperand(0); 6788 EVT VT = N->getValueType(0); 6789 bool isLE = TLI.isLittleEndian(); 6790 6791 // noop truncate 6792 if (N0.getValueType() == N->getValueType(0)) 6793 return N0; 6794 // fold (truncate c1) -> c1 6795 if (isConstantIntBuildVectorOrConstantInt(N0)) 6796 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6797 // fold (truncate (truncate x)) -> (truncate x) 6798 if (N0.getOpcode() == ISD::TRUNCATE) 6799 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6800 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6801 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6802 N0.getOpcode() == ISD::SIGN_EXTEND || 6803 N0.getOpcode() == ISD::ANY_EXTEND) { 6804 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6805 // if the source is smaller than the dest, we still need an extend 6806 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6807 N0.getOperand(0)); 6808 if (N0.getOperand(0).getValueType().bitsGT(VT)) 6809 // if the source is larger than the dest, than we just need the truncate 6810 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6811 // if the source and dest are the same type, we can drop both the extend 6812 // and the truncate. 6813 return N0.getOperand(0); 6814 } 6815 6816 // Fold extract-and-trunc into a narrow extract. For example: 6817 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 6818 // i32 y = TRUNCATE(i64 x) 6819 // -- becomes -- 6820 // v16i8 b = BITCAST (v2i64 val) 6821 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 6822 // 6823 // Note: We only run this optimization after type legalization (which often 6824 // creates this pattern) and before operation legalization after which 6825 // we need to be more careful about the vector instructions that we generate. 6826 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6827 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 6828 6829 EVT VecTy = N0.getOperand(0).getValueType(); 6830 EVT ExTy = N0.getValueType(); 6831 EVT TrTy = N->getValueType(0); 6832 6833 unsigned NumElem = VecTy.getVectorNumElements(); 6834 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 6835 6836 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 6837 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 6838 6839 SDValue EltNo = N0->getOperand(1); 6840 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 6841 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6842 EVT IndexTy = TLI.getVectorIdxTy(); 6843 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6844 6845 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6846 NVT, N0.getOperand(0)); 6847 6848 SDLoc DL(N); 6849 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6850 DL, TrTy, V, 6851 DAG.getConstant(Index, DL, IndexTy)); 6852 } 6853 } 6854 6855 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 6856 if (N0.getOpcode() == ISD::SELECT) { 6857 EVT SrcVT = N0.getValueType(); 6858 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 6859 TLI.isTruncateFree(SrcVT, VT)) { 6860 SDLoc SL(N0); 6861 SDValue Cond = N0.getOperand(0); 6862 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 6863 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 6864 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 6865 } 6866 } 6867 6868 // Fold a series of buildvector, bitcast, and truncate if possible. 6869 // For example fold 6870 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 6871 // (2xi32 (buildvector x, y)). 6872 if (Level == AfterLegalizeVectorOps && VT.isVector() && 6873 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 6874 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 6875 N0.getOperand(0).hasOneUse()) { 6876 6877 SDValue BuildVect = N0.getOperand(0); 6878 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 6879 EVT TruncVecEltTy = VT.getVectorElementType(); 6880 6881 // Check that the element types match. 6882 if (BuildVectEltTy == TruncVecEltTy) { 6883 // Now we only need to compute the offset of the truncated elements. 6884 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 6885 unsigned TruncVecNumElts = VT.getVectorNumElements(); 6886 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 6887 6888 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 6889 "Invalid number of elements"); 6890 6891 SmallVector<SDValue, 8> Opnds; 6892 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 6893 Opnds.push_back(BuildVect.getOperand(i)); 6894 6895 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 6896 } 6897 } 6898 6899 // See if we can simplify the input to this truncate through knowledge that 6900 // only the low bits are being used. 6901 // For example "trunc (or (shl x, 8), y)" // -> trunc y 6902 // Currently we only perform this optimization on scalars because vectors 6903 // may have different active low bits. 6904 if (!VT.isVector()) { 6905 SDValue Shorter = 6906 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 6907 VT.getSizeInBits())); 6908 if (Shorter.getNode()) 6909 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 6910 } 6911 // fold (truncate (load x)) -> (smaller load x) 6912 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 6913 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 6914 SDValue Reduced = ReduceLoadWidth(N); 6915 if (Reduced.getNode()) 6916 return Reduced; 6917 // Handle the case where the load remains an extending load even 6918 // after truncation. 6919 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 6920 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6921 if (!LN0->isVolatile() && 6922 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 6923 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 6924 VT, LN0->getChain(), LN0->getBasePtr(), 6925 LN0->getMemoryVT(), 6926 LN0->getMemOperand()); 6927 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 6928 return NewLoad; 6929 } 6930 } 6931 } 6932 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 6933 // where ... are all 'undef'. 6934 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 6935 SmallVector<EVT, 8> VTs; 6936 SDValue V; 6937 unsigned Idx = 0; 6938 unsigned NumDefs = 0; 6939 6940 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 6941 SDValue X = N0.getOperand(i); 6942 if (X.getOpcode() != ISD::UNDEF) { 6943 V = X; 6944 Idx = i; 6945 NumDefs++; 6946 } 6947 // Stop if more than one members are non-undef. 6948 if (NumDefs > 1) 6949 break; 6950 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 6951 VT.getVectorElementType(), 6952 X.getValueType().getVectorNumElements())); 6953 } 6954 6955 if (NumDefs == 0) 6956 return DAG.getUNDEF(VT); 6957 6958 if (NumDefs == 1) { 6959 assert(V.getNode() && "The single defined operand is empty!"); 6960 SmallVector<SDValue, 8> Opnds; 6961 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 6962 if (i != Idx) { 6963 Opnds.push_back(DAG.getUNDEF(VTs[i])); 6964 continue; 6965 } 6966 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 6967 AddToWorklist(NV.getNode()); 6968 Opnds.push_back(NV); 6969 } 6970 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 6971 } 6972 } 6973 6974 // Simplify the operands using demanded-bits information. 6975 if (!VT.isVector() && 6976 SimplifyDemandedBits(SDValue(N, 0))) 6977 return SDValue(N, 0); 6978 6979 return SDValue(); 6980 } 6981 6982 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 6983 SDValue Elt = N->getOperand(i); 6984 if (Elt.getOpcode() != ISD::MERGE_VALUES) 6985 return Elt.getNode(); 6986 return Elt.getOperand(Elt.getResNo()).getNode(); 6987 } 6988 6989 /// build_pair (load, load) -> load 6990 /// if load locations are consecutive. 6991 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 6992 assert(N->getOpcode() == ISD::BUILD_PAIR); 6993 6994 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 6995 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 6996 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 6997 LD1->getAddressSpace() != LD2->getAddressSpace()) 6998 return SDValue(); 6999 EVT LD1VT = LD1->getValueType(0); 7000 7001 if (ISD::isNON_EXTLoad(LD2) && 7002 LD2->hasOneUse() && 7003 // If both are volatile this would reduce the number of volatile loads. 7004 // If one is volatile it might be ok, but play conservative and bail out. 7005 !LD1->isVolatile() && 7006 !LD2->isVolatile() && 7007 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 7008 unsigned Align = LD1->getAlignment(); 7009 unsigned NewAlign = TLI.getDataLayout()-> 7010 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 7011 7012 if (NewAlign <= Align && 7013 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 7014 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 7015 LD1->getBasePtr(), LD1->getPointerInfo(), 7016 false, false, false, Align); 7017 } 7018 7019 return SDValue(); 7020 } 7021 7022 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 7023 SDValue N0 = N->getOperand(0); 7024 EVT VT = N->getValueType(0); 7025 7026 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 7027 // Only do this before legalize, since afterward the target may be depending 7028 // on the bitconvert. 7029 // First check to see if this is all constant. 7030 if (!LegalTypes && 7031 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 7032 VT.isVector()) { 7033 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 7034 7035 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 7036 assert(!DestEltVT.isVector() && 7037 "Element type of vector ValueType must not be vector!"); 7038 if (isSimple) 7039 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 7040 } 7041 7042 // If the input is a constant, let getNode fold it. 7043 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 7044 // If we can't allow illegal operations, we need to check that this is just 7045 // a fp -> int or int -> conversion and that the resulting operation will 7046 // be legal. 7047 if (!LegalOperations || 7048 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 7049 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 7050 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 7051 TLI.isOperationLegal(ISD::Constant, VT))) 7052 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 7053 } 7054 7055 // (conv (conv x, t1), t2) -> (conv x, t2) 7056 if (N0.getOpcode() == ISD::BITCAST) 7057 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 7058 N0.getOperand(0)); 7059 7060 // fold (conv (load x)) -> (load (conv*)x) 7061 // If the resultant load doesn't need a higher alignment than the original! 7062 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7063 // Do not change the width of a volatile load. 7064 !cast<LoadSDNode>(N0)->isVolatile() && 7065 // Do not remove the cast if the types differ in endian layout. 7066 TLI.hasBigEndianPartOrdering(N0.getValueType()) == 7067 TLI.hasBigEndianPartOrdering(VT) && 7068 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 7069 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 7070 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7071 unsigned Align = TLI.getDataLayout()-> 7072 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 7073 unsigned OrigAlign = LN0->getAlignment(); 7074 7075 if (Align <= OrigAlign) { 7076 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 7077 LN0->getBasePtr(), LN0->getPointerInfo(), 7078 LN0->isVolatile(), LN0->isNonTemporal(), 7079 LN0->isInvariant(), OrigAlign, 7080 LN0->getAAInfo()); 7081 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 7082 return Load; 7083 } 7084 } 7085 7086 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 7087 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 7088 // This often reduces constant pool loads. 7089 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 7090 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 7091 N0.getNode()->hasOneUse() && VT.isInteger() && 7092 !VT.isVector() && !N0.getValueType().isVector()) { 7093 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 7094 N0.getOperand(0)); 7095 AddToWorklist(NewConv.getNode()); 7096 7097 SDLoc DL(N); 7098 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7099 if (N0.getOpcode() == ISD::FNEG) 7100 return DAG.getNode(ISD::XOR, DL, VT, 7101 NewConv, DAG.getConstant(SignBit, DL, VT)); 7102 assert(N0.getOpcode() == ISD::FABS); 7103 return DAG.getNode(ISD::AND, DL, VT, 7104 NewConv, DAG.getConstant(~SignBit, DL, VT)); 7105 } 7106 7107 // fold (bitconvert (fcopysign cst, x)) -> 7108 // (or (and (bitconvert x), sign), (and cst, (not sign))) 7109 // Note that we don't handle (copysign x, cst) because this can always be 7110 // folded to an fneg or fabs. 7111 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 7112 isa<ConstantFPSDNode>(N0.getOperand(0)) && 7113 VT.isInteger() && !VT.isVector()) { 7114 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 7115 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 7116 if (isTypeLegal(IntXVT)) { 7117 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7118 IntXVT, N0.getOperand(1)); 7119 AddToWorklist(X.getNode()); 7120 7121 // If X has a different width than the result/lhs, sext it or truncate it. 7122 unsigned VTWidth = VT.getSizeInBits(); 7123 if (OrigXWidth < VTWidth) { 7124 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 7125 AddToWorklist(X.getNode()); 7126 } else if (OrigXWidth > VTWidth) { 7127 // To get the sign bit in the right place, we have to shift it right 7128 // before truncating. 7129 SDLoc DL(X); 7130 X = DAG.getNode(ISD::SRL, DL, 7131 X.getValueType(), X, 7132 DAG.getConstant(OrigXWidth-VTWidth, DL, 7133 X.getValueType())); 7134 AddToWorklist(X.getNode()); 7135 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 7136 AddToWorklist(X.getNode()); 7137 } 7138 7139 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 7140 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 7141 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 7142 AddToWorklist(X.getNode()); 7143 7144 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 7145 VT, N0.getOperand(0)); 7146 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 7147 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 7148 AddToWorklist(Cst.getNode()); 7149 7150 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 7151 } 7152 } 7153 7154 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 7155 if (N0.getOpcode() == ISD::BUILD_PAIR) { 7156 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 7157 if (CombineLD.getNode()) 7158 return CombineLD; 7159 } 7160 7161 // Remove double bitcasts from shuffles - this is often a legacy of 7162 // XformToShuffleWithZero being used to combine bitmaskings (of 7163 // float vectors bitcast to integer vectors) into shuffles. 7164 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 7165 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 7166 N0->getOpcode() == ISD::VECTOR_SHUFFLE && 7167 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 7168 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 7169 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 7170 7171 // If operands are a bitcast, peek through if it casts the original VT. 7172 // If operands are a UNDEF or constant, just bitcast back to original VT. 7173 auto PeekThroughBitcast = [&](SDValue Op) { 7174 if (Op.getOpcode() == ISD::BITCAST && 7175 Op.getOperand(0)->getValueType(0) == VT) 7176 return SDValue(Op.getOperand(0)); 7177 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 7178 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 7179 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op); 7180 return SDValue(); 7181 }; 7182 7183 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 7184 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 7185 if (!(SV0 && SV1)) 7186 return SDValue(); 7187 7188 int MaskScale = 7189 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 7190 SmallVector<int, 8> NewMask; 7191 for (int M : SVN->getMask()) 7192 for (int i = 0; i != MaskScale; ++i) 7193 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 7194 7195 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7196 if (!LegalMask) { 7197 std::swap(SV0, SV1); 7198 ShuffleVectorSDNode::commuteMask(NewMask); 7199 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 7200 } 7201 7202 if (LegalMask) 7203 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 7204 } 7205 7206 return SDValue(); 7207 } 7208 7209 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 7210 EVT VT = N->getValueType(0); 7211 return CombineConsecutiveLoads(N, VT); 7212 } 7213 7214 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 7215 /// operands. DstEltVT indicates the destination element value type. 7216 SDValue DAGCombiner:: 7217 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 7218 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 7219 7220 // If this is already the right type, we're done. 7221 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 7222 7223 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 7224 unsigned DstBitSize = DstEltVT.getSizeInBits(); 7225 7226 // If this is a conversion of N elements of one type to N elements of another 7227 // type, convert each element. This handles FP<->INT cases. 7228 if (SrcBitSize == DstBitSize) { 7229 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7230 BV->getValueType(0).getVectorNumElements()); 7231 7232 // Due to the FP element handling below calling this routine recursively, 7233 // we can end up with a scalar-to-vector node here. 7234 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 7235 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 7236 DAG.getNode(ISD::BITCAST, SDLoc(BV), 7237 DstEltVT, BV->getOperand(0))); 7238 7239 SmallVector<SDValue, 8> Ops; 7240 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 7241 SDValue Op = BV->getOperand(i); 7242 // If the vector element type is not legal, the BUILD_VECTOR operands 7243 // are promoted and implicitly truncated. Make that explicit here. 7244 if (Op.getValueType() != SrcEltVT) 7245 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 7246 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 7247 DstEltVT, Op)); 7248 AddToWorklist(Ops.back().getNode()); 7249 } 7250 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 7251 } 7252 7253 // Otherwise, we're growing or shrinking the elements. To avoid having to 7254 // handle annoying details of growing/shrinking FP values, we convert them to 7255 // int first. 7256 if (SrcEltVT.isFloatingPoint()) { 7257 // Convert the input float vector to a int vector where the elements are the 7258 // same sizes. 7259 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 7260 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 7261 SrcEltVT = IntVT; 7262 } 7263 7264 // Now we know the input is an integer vector. If the output is a FP type, 7265 // convert to integer first, then to FP of the right size. 7266 if (DstEltVT.isFloatingPoint()) { 7267 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 7268 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 7269 7270 // Next, convert to FP elements of the same size. 7271 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 7272 } 7273 7274 SDLoc DL(BV); 7275 7276 // Okay, we know the src/dst types are both integers of differing types. 7277 // Handling growing first. 7278 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 7279 if (SrcBitSize < DstBitSize) { 7280 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 7281 7282 SmallVector<SDValue, 8> Ops; 7283 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 7284 i += NumInputsPerOutput) { 7285 bool isLE = TLI.isLittleEndian(); 7286 APInt NewBits = APInt(DstBitSize, 0); 7287 bool EltIsUndef = true; 7288 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 7289 // Shift the previously computed bits over. 7290 NewBits <<= SrcBitSize; 7291 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 7292 if (Op.getOpcode() == ISD::UNDEF) continue; 7293 EltIsUndef = false; 7294 7295 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 7296 zextOrTrunc(SrcBitSize).zext(DstBitSize); 7297 } 7298 7299 if (EltIsUndef) 7300 Ops.push_back(DAG.getUNDEF(DstEltVT)); 7301 else 7302 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 7303 } 7304 7305 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 7306 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7307 } 7308 7309 // Finally, this must be the case where we are shrinking elements: each input 7310 // turns into multiple outputs. 7311 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 7312 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 7313 NumOutputsPerInput*BV->getNumOperands()); 7314 SmallVector<SDValue, 8> Ops; 7315 7316 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 7317 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 7318 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 7319 continue; 7320 } 7321 7322 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 7323 getAPIntValue().zextOrTrunc(SrcBitSize); 7324 7325 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 7326 APInt ThisVal = OpVal.trunc(DstBitSize); 7327 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 7328 OpVal = OpVal.lshr(DstBitSize); 7329 } 7330 7331 // For big endian targets, swap the order of the pieces of each element. 7332 if (TLI.isBigEndian()) 7333 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 7334 } 7335 7336 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops); 7337 } 7338 7339 /// Try to perform FMA combining on a given FADD node. 7340 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 7341 SDValue N0 = N->getOperand(0); 7342 SDValue N1 = N->getOperand(1); 7343 EVT VT = N->getValueType(0); 7344 SDLoc SL(N); 7345 7346 const TargetOptions &Options = DAG.getTarget().Options; 7347 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast || 7348 Options.UnsafeFPMath); 7349 7350 // Floating-point multiply-add with intermediate rounding. 7351 bool HasFMAD = (LegalOperations && 7352 TLI.isOperationLegal(ISD::FMAD, VT)); 7353 7354 // Floating-point multiply-add without intermediate rounding. 7355 bool HasFMA = ((!LegalOperations || 7356 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) && 7357 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7358 UnsafeFPMath); 7359 7360 // No valid opcode, do not combine. 7361 if (!HasFMAD && !HasFMA) 7362 return SDValue(); 7363 7364 // Always prefer FMAD to FMA for precision. 7365 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7366 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7367 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7368 7369 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 7370 if (N0.getOpcode() == ISD::FMUL && 7371 (Aggressive || N0->hasOneUse())) { 7372 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7373 N0.getOperand(0), N0.getOperand(1), N1); 7374 } 7375 7376 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 7377 // Note: Commutes FADD operands. 7378 if (N1.getOpcode() == ISD::FMUL && 7379 (Aggressive || N1->hasOneUse())) { 7380 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7381 N1.getOperand(0), N1.getOperand(1), N0); 7382 } 7383 7384 // Look through FP_EXTEND nodes to do more combining. 7385 if (UnsafeFPMath && LookThroughFPExt) { 7386 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7387 if (N0.getOpcode() == ISD::FP_EXTEND) { 7388 SDValue N00 = N0.getOperand(0); 7389 if (N00.getOpcode() == ISD::FMUL) 7390 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7391 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7392 N00.getOperand(0)), 7393 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7394 N00.getOperand(1)), N1); 7395 } 7396 7397 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 7398 // Note: Commutes FADD operands. 7399 if (N1.getOpcode() == ISD::FP_EXTEND) { 7400 SDValue N10 = N1.getOperand(0); 7401 if (N10.getOpcode() == ISD::FMUL) 7402 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7403 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7404 N10.getOperand(0)), 7405 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7406 N10.getOperand(1)), N0); 7407 } 7408 } 7409 7410 // More folding opportunities when target permits. 7411 if ((UnsafeFPMath || HasFMAD) && Aggressive) { 7412 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7413 if (N0.getOpcode() == PreferredFusedOpcode && 7414 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7415 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7416 N0.getOperand(0), N0.getOperand(1), 7417 DAG.getNode(PreferredFusedOpcode, SL, VT, 7418 N0.getOperand(2).getOperand(0), 7419 N0.getOperand(2).getOperand(1), 7420 N1)); 7421 } 7422 7423 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7424 if (N1->getOpcode() == PreferredFusedOpcode && 7425 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7426 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7427 N1.getOperand(0), N1.getOperand(1), 7428 DAG.getNode(PreferredFusedOpcode, SL, VT, 7429 N1.getOperand(2).getOperand(0), 7430 N1.getOperand(2).getOperand(1), 7431 N0)); 7432 } 7433 7434 if (UnsafeFPMath && LookThroughFPExt) { 7435 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 7436 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 7437 auto FoldFAddFMAFPExtFMul = [&] ( 7438 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7439 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 7440 DAG.getNode(PreferredFusedOpcode, SL, VT, 7441 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7442 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7443 Z)); 7444 }; 7445 if (N0.getOpcode() == PreferredFusedOpcode) { 7446 SDValue N02 = N0.getOperand(2); 7447 if (N02.getOpcode() == ISD::FP_EXTEND) { 7448 SDValue N020 = N02.getOperand(0); 7449 if (N020.getOpcode() == ISD::FMUL) 7450 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 7451 N020.getOperand(0), N020.getOperand(1), 7452 N1); 7453 } 7454 } 7455 7456 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 7457 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 7458 // FIXME: This turns two single-precision and one double-precision 7459 // operation into two double-precision operations, which might not be 7460 // interesting for all targets, especially GPUs. 7461 auto FoldFAddFPExtFMAFMul = [&] ( 7462 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) { 7463 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7464 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 7465 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 7466 DAG.getNode(PreferredFusedOpcode, SL, VT, 7467 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 7468 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 7469 Z)); 7470 }; 7471 if (N0.getOpcode() == ISD::FP_EXTEND) { 7472 SDValue N00 = N0.getOperand(0); 7473 if (N00.getOpcode() == PreferredFusedOpcode) { 7474 SDValue N002 = N00.getOperand(2); 7475 if (N002.getOpcode() == ISD::FMUL) 7476 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 7477 N002.getOperand(0), N002.getOperand(1), 7478 N1); 7479 } 7480 } 7481 7482 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 7483 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 7484 if (N1.getOpcode() == PreferredFusedOpcode) { 7485 SDValue N12 = N1.getOperand(2); 7486 if (N12.getOpcode() == ISD::FP_EXTEND) { 7487 SDValue N120 = N12.getOperand(0); 7488 if (N120.getOpcode() == ISD::FMUL) 7489 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 7490 N120.getOperand(0), N120.getOperand(1), 7491 N0); 7492 } 7493 } 7494 7495 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 7496 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 7497 // FIXME: This turns two single-precision and one double-precision 7498 // operation into two double-precision operations, which might not be 7499 // interesting for all targets, especially GPUs. 7500 if (N1.getOpcode() == ISD::FP_EXTEND) { 7501 SDValue N10 = N1.getOperand(0); 7502 if (N10.getOpcode() == PreferredFusedOpcode) { 7503 SDValue N102 = N10.getOperand(2); 7504 if (N102.getOpcode() == ISD::FMUL) 7505 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 7506 N102.getOperand(0), N102.getOperand(1), 7507 N0); 7508 } 7509 } 7510 } 7511 } 7512 7513 return SDValue(); 7514 } 7515 7516 /// Try to perform FMA combining on a given FSUB node. 7517 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 7518 SDValue N0 = N->getOperand(0); 7519 SDValue N1 = N->getOperand(1); 7520 EVT VT = N->getValueType(0); 7521 SDLoc SL(N); 7522 7523 const TargetOptions &Options = DAG.getTarget().Options; 7524 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast || 7525 Options.UnsafeFPMath); 7526 7527 // Floating-point multiply-add with intermediate rounding. 7528 bool HasFMAD = (LegalOperations && 7529 TLI.isOperationLegal(ISD::FMAD, VT)); 7530 7531 // Floating-point multiply-add without intermediate rounding. 7532 bool HasFMA = ((!LegalOperations || 7533 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) && 7534 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7535 UnsafeFPMath); 7536 7537 // No valid opcode, do not combine. 7538 if (!HasFMAD && !HasFMA) 7539 return SDValue(); 7540 7541 // Always prefer FMAD to FMA for precision. 7542 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 7543 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 7544 bool LookThroughFPExt = TLI.isFPExtFree(VT); 7545 7546 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7547 if (N0.getOpcode() == ISD::FMUL && 7548 (Aggressive || N0->hasOneUse())) { 7549 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7550 N0.getOperand(0), N0.getOperand(1), 7551 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7552 } 7553 7554 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7555 // Note: Commutes FSUB operands. 7556 if (N1.getOpcode() == ISD::FMUL && 7557 (Aggressive || N1->hasOneUse())) 7558 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7559 DAG.getNode(ISD::FNEG, SL, VT, 7560 N1.getOperand(0)), 7561 N1.getOperand(1), N0); 7562 7563 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7564 if (N0.getOpcode() == ISD::FNEG && 7565 N0.getOperand(0).getOpcode() == ISD::FMUL && 7566 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 7567 SDValue N00 = N0.getOperand(0).getOperand(0); 7568 SDValue N01 = N0.getOperand(0).getOperand(1); 7569 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7570 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 7571 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7572 } 7573 7574 // Look through FP_EXTEND nodes to do more combining. 7575 if (UnsafeFPMath && LookThroughFPExt) { 7576 // fold (fsub (fpext (fmul x, y)), z) 7577 // -> (fma (fpext x), (fpext y), (fneg z)) 7578 if (N0.getOpcode() == ISD::FP_EXTEND) { 7579 SDValue N00 = N0.getOperand(0); 7580 if (N00.getOpcode() == ISD::FMUL) 7581 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7582 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7583 N00.getOperand(0)), 7584 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7585 N00.getOperand(1)), 7586 DAG.getNode(ISD::FNEG, SL, VT, N1)); 7587 } 7588 7589 // fold (fsub x, (fpext (fmul y, z))) 7590 // -> (fma (fneg (fpext y)), (fpext z), x) 7591 // Note: Commutes FSUB operands. 7592 if (N1.getOpcode() == ISD::FP_EXTEND) { 7593 SDValue N10 = N1.getOperand(0); 7594 if (N10.getOpcode() == ISD::FMUL) 7595 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7596 DAG.getNode(ISD::FNEG, SL, VT, 7597 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7598 N10.getOperand(0))), 7599 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7600 N10.getOperand(1)), 7601 N0); 7602 } 7603 7604 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7605 // -> (fneg (fma (fpext x), (fpext y), z)) 7606 // Note: This could be removed with appropriate canonicalization of the 7607 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7608 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7609 // from implementing the canonicalization in visitFSUB. 7610 if (N0.getOpcode() == ISD::FP_EXTEND) { 7611 SDValue N00 = N0.getOperand(0); 7612 if (N00.getOpcode() == ISD::FNEG) { 7613 SDValue N000 = N00.getOperand(0); 7614 if (N000.getOpcode() == ISD::FMUL) { 7615 return DAG.getNode(ISD::FNEG, SL, VT, 7616 DAG.getNode(PreferredFusedOpcode, SL, VT, 7617 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7618 N000.getOperand(0)), 7619 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7620 N000.getOperand(1)), 7621 N1)); 7622 } 7623 } 7624 } 7625 7626 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7627 // -> (fneg (fma (fpext x)), (fpext y), z) 7628 // Note: This could be removed with appropriate canonicalization of the 7629 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 7630 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 7631 // from implementing the canonicalization in visitFSUB. 7632 if (N0.getOpcode() == ISD::FNEG) { 7633 SDValue N00 = N0.getOperand(0); 7634 if (N00.getOpcode() == ISD::FP_EXTEND) { 7635 SDValue N000 = N00.getOperand(0); 7636 if (N000.getOpcode() == ISD::FMUL) { 7637 return DAG.getNode(ISD::FNEG, SL, VT, 7638 DAG.getNode(PreferredFusedOpcode, SL, VT, 7639 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7640 N000.getOperand(0)), 7641 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7642 N000.getOperand(1)), 7643 N1)); 7644 } 7645 } 7646 } 7647 7648 } 7649 7650 // More folding opportunities when target permits. 7651 if ((UnsafeFPMath || HasFMAD) && Aggressive) { 7652 // fold (fsub (fma x, y, (fmul u, v)), z) 7653 // -> (fma x, y (fma u, v, (fneg z))) 7654 if (N0.getOpcode() == PreferredFusedOpcode && 7655 N0.getOperand(2).getOpcode() == ISD::FMUL) { 7656 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7657 N0.getOperand(0), N0.getOperand(1), 7658 DAG.getNode(PreferredFusedOpcode, SL, VT, 7659 N0.getOperand(2).getOperand(0), 7660 N0.getOperand(2).getOperand(1), 7661 DAG.getNode(ISD::FNEG, SL, VT, 7662 N1))); 7663 } 7664 7665 // fold (fsub x, (fma y, z, (fmul u, v))) 7666 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7667 if (N1.getOpcode() == PreferredFusedOpcode && 7668 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7669 SDValue N20 = N1.getOperand(2).getOperand(0); 7670 SDValue N21 = N1.getOperand(2).getOperand(1); 7671 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7672 DAG.getNode(ISD::FNEG, SL, VT, 7673 N1.getOperand(0)), 7674 N1.getOperand(1), 7675 DAG.getNode(PreferredFusedOpcode, SL, VT, 7676 DAG.getNode(ISD::FNEG, SL, VT, N20), 7677 7678 N21, N0)); 7679 } 7680 7681 if (UnsafeFPMath && LookThroughFPExt) { 7682 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 7683 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 7684 if (N0.getOpcode() == PreferredFusedOpcode) { 7685 SDValue N02 = N0.getOperand(2); 7686 if (N02.getOpcode() == ISD::FP_EXTEND) { 7687 SDValue N020 = N02.getOperand(0); 7688 if (N020.getOpcode() == ISD::FMUL) 7689 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7690 N0.getOperand(0), N0.getOperand(1), 7691 DAG.getNode(PreferredFusedOpcode, SL, VT, 7692 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7693 N020.getOperand(0)), 7694 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7695 N020.getOperand(1)), 7696 DAG.getNode(ISD::FNEG, SL, VT, 7697 N1))); 7698 } 7699 } 7700 7701 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 7702 // -> (fma (fpext x), (fpext y), 7703 // (fma (fpext u), (fpext v), (fneg z))) 7704 // FIXME: This turns two single-precision and one double-precision 7705 // operation into two double-precision operations, which might not be 7706 // interesting for all targets, especially GPUs. 7707 if (N0.getOpcode() == ISD::FP_EXTEND) { 7708 SDValue N00 = N0.getOperand(0); 7709 if (N00.getOpcode() == PreferredFusedOpcode) { 7710 SDValue N002 = N00.getOperand(2); 7711 if (N002.getOpcode() == ISD::FMUL) 7712 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7713 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7714 N00.getOperand(0)), 7715 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7716 N00.getOperand(1)), 7717 DAG.getNode(PreferredFusedOpcode, SL, VT, 7718 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7719 N002.getOperand(0)), 7720 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7721 N002.getOperand(1)), 7722 DAG.getNode(ISD::FNEG, SL, VT, 7723 N1))); 7724 } 7725 } 7726 7727 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 7728 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 7729 if (N1.getOpcode() == PreferredFusedOpcode && 7730 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 7731 SDValue N120 = N1.getOperand(2).getOperand(0); 7732 if (N120.getOpcode() == ISD::FMUL) { 7733 SDValue N1200 = N120.getOperand(0); 7734 SDValue N1201 = N120.getOperand(1); 7735 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7736 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 7737 N1.getOperand(1), 7738 DAG.getNode(PreferredFusedOpcode, SL, VT, 7739 DAG.getNode(ISD::FNEG, SL, VT, 7740 DAG.getNode(ISD::FP_EXTEND, SL, 7741 VT, N1200)), 7742 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7743 N1201), 7744 N0)); 7745 } 7746 } 7747 7748 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 7749 // -> (fma (fneg (fpext y)), (fpext z), 7750 // (fma (fneg (fpext u)), (fpext v), x)) 7751 // FIXME: This turns two single-precision and one double-precision 7752 // operation into two double-precision operations, which might not be 7753 // interesting for all targets, especially GPUs. 7754 if (N1.getOpcode() == ISD::FP_EXTEND && 7755 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 7756 SDValue N100 = N1.getOperand(0).getOperand(0); 7757 SDValue N101 = N1.getOperand(0).getOperand(1); 7758 SDValue N102 = N1.getOperand(0).getOperand(2); 7759 if (N102.getOpcode() == ISD::FMUL) { 7760 SDValue N1020 = N102.getOperand(0); 7761 SDValue N1021 = N102.getOperand(1); 7762 return DAG.getNode(PreferredFusedOpcode, SL, VT, 7763 DAG.getNode(ISD::FNEG, SL, VT, 7764 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7765 N100)), 7766 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 7767 DAG.getNode(PreferredFusedOpcode, SL, VT, 7768 DAG.getNode(ISD::FNEG, SL, VT, 7769 DAG.getNode(ISD::FP_EXTEND, SL, 7770 VT, N1020)), 7771 DAG.getNode(ISD::FP_EXTEND, SL, VT, 7772 N1021), 7773 N0)); 7774 } 7775 } 7776 } 7777 } 7778 7779 return SDValue(); 7780 } 7781 7782 SDValue DAGCombiner::visitFADD(SDNode *N) { 7783 SDValue N0 = N->getOperand(0); 7784 SDValue N1 = N->getOperand(1); 7785 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7786 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7787 EVT VT = N->getValueType(0); 7788 SDLoc DL(N); 7789 const TargetOptions &Options = DAG.getTarget().Options; 7790 7791 // fold vector ops 7792 if (VT.isVector()) 7793 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7794 return FoldedVOp; 7795 7796 // fold (fadd c1, c2) -> c1 + c2 7797 if (N0CFP && N1CFP) 7798 return DAG.getNode(ISD::FADD, DL, VT, N0, N1); 7799 7800 // canonicalize constant to RHS 7801 if (N0CFP && !N1CFP) 7802 return DAG.getNode(ISD::FADD, DL, VT, N1, N0); 7803 7804 // fold (fadd A, (fneg B)) -> (fsub A, B) 7805 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7806 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 7807 return DAG.getNode(ISD::FSUB, DL, VT, N0, 7808 GetNegatedExpression(N1, DAG, LegalOperations)); 7809 7810 // fold (fadd (fneg A), B) -> (fsub B, A) 7811 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 7812 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 7813 return DAG.getNode(ISD::FSUB, DL, VT, N1, 7814 GetNegatedExpression(N0, DAG, LegalOperations)); 7815 7816 // If 'unsafe math' is enabled, fold lots of things. 7817 if (Options.UnsafeFPMath) { 7818 // No FP constant should be created after legalization as Instruction 7819 // Selection pass has a hard time dealing with FP constants. 7820 bool AllowNewConst = (Level < AfterLegalizeDAG); 7821 7822 // fold (fadd A, 0) -> A 7823 if (N1CFP && N1CFP->getValueAPF().isZero()) 7824 return N0; 7825 7826 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 7827 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 7828 isa<ConstantFPSDNode>(N0.getOperand(1))) 7829 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), 7830 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1)); 7831 7832 // If allowed, fold (fadd (fneg x), x) -> 0.0 7833 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 7834 return DAG.getConstantFP(0.0, DL, VT); 7835 7836 // If allowed, fold (fadd x, (fneg x)) -> 0.0 7837 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 7838 return DAG.getConstantFP(0.0, DL, VT); 7839 7840 // We can fold chains of FADD's of the same value into multiplications. 7841 // This transform is not safe in general because we are reducing the number 7842 // of rounding steps. 7843 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 7844 if (N0.getOpcode() == ISD::FMUL) { 7845 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7846 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7847 7848 // (fadd (fmul x, c), x) -> (fmul x, c+1) 7849 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 7850 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0), 7851 DAG.getConstantFP(1.0, DL, VT)); 7852 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP); 7853 } 7854 7855 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 7856 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 7857 N1.getOperand(0) == N1.getOperand(1) && 7858 N0.getOperand(0) == N1.getOperand(0)) { 7859 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0), 7860 DAG.getConstantFP(2.0, DL, VT)); 7861 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP); 7862 } 7863 } 7864 7865 if (N1.getOpcode() == ISD::FMUL) { 7866 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7867 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 7868 7869 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 7870 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 7871 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0), 7872 DAG.getConstantFP(1.0, DL, VT)); 7873 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP); 7874 } 7875 7876 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 7877 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 7878 N0.getOperand(0) == N0.getOperand(1) && 7879 N1.getOperand(0) == N0.getOperand(0)) { 7880 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0), 7881 DAG.getConstantFP(2.0, DL, VT)); 7882 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP); 7883 } 7884 } 7885 7886 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 7887 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 7888 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 7889 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 7890 (N0.getOperand(0) == N1)) { 7891 return DAG.getNode(ISD::FMUL, DL, VT, 7892 N1, DAG.getConstantFP(3.0, DL, VT)); 7893 } 7894 } 7895 7896 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 7897 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 7898 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 7899 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 7900 N1.getOperand(0) == N0) { 7901 return DAG.getNode(ISD::FMUL, DL, VT, 7902 N0, DAG.getConstantFP(3.0, DL, VT)); 7903 } 7904 } 7905 7906 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 7907 if (AllowNewConst && 7908 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 7909 N0.getOperand(0) == N0.getOperand(1) && 7910 N1.getOperand(0) == N1.getOperand(1) && 7911 N0.getOperand(0) == N1.getOperand(0)) { 7912 return DAG.getNode(ISD::FMUL, DL, VT, 7913 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT)); 7914 } 7915 } 7916 } // enable-unsafe-fp-math 7917 7918 // FADD -> FMA combines: 7919 SDValue Fused = visitFADDForFMACombine(N); 7920 if (Fused) { 7921 AddToWorklist(Fused.getNode()); 7922 return Fused; 7923 } 7924 7925 return SDValue(); 7926 } 7927 7928 SDValue DAGCombiner::visitFSUB(SDNode *N) { 7929 SDValue N0 = N->getOperand(0); 7930 SDValue N1 = N->getOperand(1); 7931 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7932 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7933 EVT VT = N->getValueType(0); 7934 SDLoc dl(N); 7935 const TargetOptions &Options = DAG.getTarget().Options; 7936 7937 // fold vector ops 7938 if (VT.isVector()) 7939 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7940 return FoldedVOp; 7941 7942 // fold (fsub c1, c2) -> c1-c2 7943 if (N0CFP && N1CFP) 7944 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1); 7945 7946 // fold (fsub A, (fneg B)) -> (fadd A, B) 7947 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7948 return DAG.getNode(ISD::FADD, dl, VT, N0, 7949 GetNegatedExpression(N1, DAG, LegalOperations)); 7950 7951 // If 'unsafe math' is enabled, fold lots of things. 7952 if (Options.UnsafeFPMath) { 7953 // (fsub A, 0) -> A 7954 if (N1CFP && N1CFP->getValueAPF().isZero()) 7955 return N0; 7956 7957 // (fsub 0, B) -> -B 7958 if (N0CFP && N0CFP->getValueAPF().isZero()) { 7959 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7960 return GetNegatedExpression(N1, DAG, LegalOperations); 7961 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7962 return DAG.getNode(ISD::FNEG, dl, VT, N1); 7963 } 7964 7965 // (fsub x, x) -> 0.0 7966 if (N0 == N1) 7967 return DAG.getConstantFP(0.0f, dl, VT); 7968 7969 // (fsub x, (fadd x, y)) -> (fneg y) 7970 // (fsub x, (fadd y, x)) -> (fneg y) 7971 if (N1.getOpcode() == ISD::FADD) { 7972 SDValue N10 = N1->getOperand(0); 7973 SDValue N11 = N1->getOperand(1); 7974 7975 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 7976 return GetNegatedExpression(N11, DAG, LegalOperations); 7977 7978 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 7979 return GetNegatedExpression(N10, DAG, LegalOperations); 7980 } 7981 } 7982 7983 // FSUB -> FMA combines: 7984 SDValue Fused = visitFSUBForFMACombine(N); 7985 if (Fused) { 7986 AddToWorklist(Fused.getNode()); 7987 return Fused; 7988 } 7989 7990 return SDValue(); 7991 } 7992 7993 SDValue DAGCombiner::visitFMUL(SDNode *N) { 7994 SDValue N0 = N->getOperand(0); 7995 SDValue N1 = N->getOperand(1); 7996 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7997 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7998 EVT VT = N->getValueType(0); 7999 SDLoc DL(N); 8000 const TargetOptions &Options = DAG.getTarget().Options; 8001 8002 // fold vector ops 8003 if (VT.isVector()) { 8004 // This just handles C1 * C2 for vectors. Other vector folds are below. 8005 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8006 return FoldedVOp; 8007 } 8008 8009 // fold (fmul c1, c2) -> c1*c2 8010 if (N0CFP && N1CFP) 8011 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1); 8012 8013 // canonicalize constant to RHS 8014 if (isConstantFPBuildVectorOrConstantFP(N0) && 8015 !isConstantFPBuildVectorOrConstantFP(N1)) 8016 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0); 8017 8018 // fold (fmul A, 1.0) -> A 8019 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8020 return N0; 8021 8022 if (Options.UnsafeFPMath) { 8023 // fold (fmul A, 0) -> 0 8024 if (N1CFP && N1CFP->getValueAPF().isZero()) 8025 return N1; 8026 8027 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 8028 if (N0.getOpcode() == ISD::FMUL) { 8029 // Fold scalars or any vector constants (not just splats). 8030 // This fold is done in general by InstCombine, but extra fmul insts 8031 // may have been generated during lowering. 8032 SDValue N00 = N0.getOperand(0); 8033 SDValue N01 = N0.getOperand(1); 8034 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 8035 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00); 8036 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 8037 8038 // Check 1: Make sure that the first operand of the inner multiply is NOT 8039 // a constant. Otherwise, we may induce infinite looping. 8040 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) { 8041 // Check 2: Make sure that the second operand of the inner multiply and 8042 // the second operand of the outer multiply are constants. 8043 if ((N1CFP && isConstOrConstSplatFP(N01)) || 8044 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 8045 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1); 8046 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts); 8047 } 8048 } 8049 } 8050 8051 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 8052 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 8053 // during an early run of DAGCombiner can prevent folding with fmuls 8054 // inserted during lowering. 8055 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) { 8056 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 8057 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1); 8058 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts); 8059 } 8060 } 8061 8062 // fold (fmul X, 2.0) -> (fadd X, X) 8063 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 8064 return DAG.getNode(ISD::FADD, DL, VT, N0, N0); 8065 8066 // fold (fmul X, -1.0) -> (fneg X) 8067 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 8068 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8069 return DAG.getNode(ISD::FNEG, DL, VT, N0); 8070 8071 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 8072 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8073 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8074 // Both can be negated for free, check to see if at least one is cheaper 8075 // negated. 8076 if (LHSNeg == 2 || RHSNeg == 2) 8077 return DAG.getNode(ISD::FMUL, DL, VT, 8078 GetNegatedExpression(N0, DAG, LegalOperations), 8079 GetNegatedExpression(N1, DAG, LegalOperations)); 8080 } 8081 } 8082 8083 return SDValue(); 8084 } 8085 8086 SDValue DAGCombiner::visitFMA(SDNode *N) { 8087 SDValue N0 = N->getOperand(0); 8088 SDValue N1 = N->getOperand(1); 8089 SDValue N2 = N->getOperand(2); 8090 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8091 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8092 EVT VT = N->getValueType(0); 8093 SDLoc dl(N); 8094 const TargetOptions &Options = DAG.getTarget().Options; 8095 8096 // Constant fold FMA. 8097 if (isa<ConstantFPSDNode>(N0) && 8098 isa<ConstantFPSDNode>(N1) && 8099 isa<ConstantFPSDNode>(N2)) { 8100 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 8101 } 8102 8103 if (Options.UnsafeFPMath) { 8104 if (N0CFP && N0CFP->isZero()) 8105 return N2; 8106 if (N1CFP && N1CFP->isZero()) 8107 return N2; 8108 } 8109 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8110 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 8111 if (N1CFP && N1CFP->isExactlyValue(1.0)) 8112 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 8113 8114 // Canonicalize (fma c, x, y) -> (fma x, c, y) 8115 if (N0CFP && !N1CFP) 8116 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 8117 8118 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 8119 if (Options.UnsafeFPMath && N1CFP && 8120 N2.getOpcode() == ISD::FMUL && 8121 N0 == N2.getOperand(0) && 8122 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 8123 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8124 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 8125 } 8126 8127 8128 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 8129 if (Options.UnsafeFPMath && 8130 N0.getOpcode() == ISD::FMUL && N1CFP && 8131 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 8132 return DAG.getNode(ISD::FMA, dl, VT, 8133 N0.getOperand(0), 8134 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 8135 N2); 8136 } 8137 8138 // (fma x, 1, y) -> (fadd x, y) 8139 // (fma x, -1, y) -> (fadd (fneg x), y) 8140 if (N1CFP) { 8141 if (N1CFP->isExactlyValue(1.0)) 8142 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 8143 8144 if (N1CFP->isExactlyValue(-1.0) && 8145 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 8146 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 8147 AddToWorklist(RHSNeg.getNode()); 8148 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 8149 } 8150 } 8151 8152 // (fma x, c, x) -> (fmul x, (c+1)) 8153 if (Options.UnsafeFPMath && N1CFP && N0 == N2) 8154 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8155 DAG.getNode(ISD::FADD, dl, VT, 8156 N1, DAG.getConstantFP(1.0, dl, VT))); 8157 8158 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 8159 if (Options.UnsafeFPMath && N1CFP && 8160 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 8161 return DAG.getNode(ISD::FMUL, dl, VT, N0, 8162 DAG.getNode(ISD::FADD, dl, VT, 8163 N1, DAG.getConstantFP(-1.0, dl, VT))); 8164 8165 8166 return SDValue(); 8167 } 8168 8169 SDValue DAGCombiner::visitFDIV(SDNode *N) { 8170 SDValue N0 = N->getOperand(0); 8171 SDValue N1 = N->getOperand(1); 8172 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8173 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8174 EVT VT = N->getValueType(0); 8175 SDLoc DL(N); 8176 const TargetOptions &Options = DAG.getTarget().Options; 8177 8178 // fold vector ops 8179 if (VT.isVector()) 8180 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 8181 return FoldedVOp; 8182 8183 // fold (fdiv c1, c2) -> c1/c2 8184 if (N0CFP && N1CFP) 8185 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 8186 8187 if (Options.UnsafeFPMath) { 8188 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 8189 if (N1CFP) { 8190 // Compute the reciprocal 1.0 / c2. 8191 APFloat N1APF = N1CFP->getValueAPF(); 8192 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 8193 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 8194 // Only do the transform if the reciprocal is a legal fp immediate that 8195 // isn't too nasty (eg NaN, denormal, ...). 8196 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 8197 (!LegalOperations || 8198 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 8199 // backend)... we should handle this gracefully after Legalize. 8200 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 8201 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 8202 TLI.isFPImmLegal(Recip, VT))) 8203 return DAG.getNode(ISD::FMUL, DL, VT, N0, 8204 DAG.getConstantFP(Recip, DL, VT)); 8205 } 8206 8207 // If this FDIV is part of a reciprocal square root, it may be folded 8208 // into a target-specific square root estimate instruction. 8209 if (N1.getOpcode() == ISD::FSQRT) { 8210 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) { 8211 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8212 } 8213 } else if (N1.getOpcode() == ISD::FP_EXTEND && 8214 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8215 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 8216 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 8217 AddToWorklist(RV.getNode()); 8218 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8219 } 8220 } else if (N1.getOpcode() == ISD::FP_ROUND && 8221 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8222 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 8223 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 8224 AddToWorklist(RV.getNode()); 8225 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8226 } 8227 } else if (N1.getOpcode() == ISD::FMUL) { 8228 // Look through an FMUL. Even though this won't remove the FDIV directly, 8229 // it's still worthwhile to get rid of the FSQRT if possible. 8230 SDValue SqrtOp; 8231 SDValue OtherOp; 8232 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 8233 SqrtOp = N1.getOperand(0); 8234 OtherOp = N1.getOperand(1); 8235 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 8236 SqrtOp = N1.getOperand(1); 8237 OtherOp = N1.getOperand(0); 8238 } 8239 if (SqrtOp.getNode()) { 8240 // We found a FSQRT, so try to make this fold: 8241 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 8242 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) { 8243 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp); 8244 AddToWorklist(RV.getNode()); 8245 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8246 } 8247 } 8248 } 8249 8250 // Fold into a reciprocal estimate and multiply instead of a real divide. 8251 if (SDValue RV = BuildReciprocalEstimate(N1)) { 8252 AddToWorklist(RV.getNode()); 8253 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 8254 } 8255 } 8256 8257 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 8258 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 8259 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 8260 // Both can be negated for free, check to see if at least one is cheaper 8261 // negated. 8262 if (LHSNeg == 2 || RHSNeg == 2) 8263 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 8264 GetNegatedExpression(N0, DAG, LegalOperations), 8265 GetNegatedExpression(N1, DAG, LegalOperations)); 8266 } 8267 } 8268 8269 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 8270 // reciprocal. 8271 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 8272 // Notice that this is not always beneficial. One reason is different target 8273 // may have different costs for FDIV and FMUL, so sometimes the cost of two 8274 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 8275 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 8276 if (Options.UnsafeFPMath) { 8277 // Skip if current node is a reciprocal. 8278 if (N0CFP && N0CFP->isExactlyValue(1.0)) 8279 return SDValue(); 8280 8281 SmallVector<SDNode *, 4> Users; 8282 // Find all FDIV users of the same divisor. 8283 for (auto *U : N1->uses()) { 8284 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) 8285 Users.push_back(U); 8286 } 8287 8288 if (TLI.combineRepeatedFPDivisors(Users.size())) { 8289 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 8290 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1); 8291 8292 // Dividend / Divisor -> Dividend * Reciprocal 8293 for (auto *U : Users) { 8294 SDValue Dividend = U->getOperand(0); 8295 if (Dividend != FPOne) { 8296 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 8297 Reciprocal); 8298 DAG.ReplaceAllUsesWith(U, NewNode.getNode()); 8299 } 8300 } 8301 return SDValue(); 8302 } 8303 } 8304 8305 return SDValue(); 8306 } 8307 8308 SDValue DAGCombiner::visitFREM(SDNode *N) { 8309 SDValue N0 = N->getOperand(0); 8310 SDValue N1 = N->getOperand(1); 8311 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8312 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8313 EVT VT = N->getValueType(0); 8314 8315 // fold (frem c1, c2) -> fmod(c1,c2) 8316 if (N0CFP && N1CFP) 8317 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 8318 8319 return SDValue(); 8320 } 8321 8322 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 8323 if (DAG.getTarget().Options.UnsafeFPMath && 8324 !TLI.isFsqrtCheap()) { 8325 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 8326 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) { 8327 EVT VT = RV.getValueType(); 8328 SDLoc DL(N); 8329 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV); 8330 AddToWorklist(RV.getNode()); 8331 8332 // Unfortunately, RV is now NaN if the input was exactly 0. 8333 // Select out this case and force the answer to 0. 8334 SDValue Zero = DAG.getConstantFP(0.0, DL, VT); 8335 SDValue ZeroCmp = 8336 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT), 8337 N->getOperand(0), Zero, ISD::SETEQ); 8338 AddToWorklist(ZeroCmp.getNode()); 8339 AddToWorklist(RV.getNode()); 8340 8341 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, 8342 DL, VT, ZeroCmp, Zero, RV); 8343 return RV; 8344 } 8345 } 8346 return SDValue(); 8347 } 8348 8349 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 8350 SDValue N0 = N->getOperand(0); 8351 SDValue N1 = N->getOperand(1); 8352 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8353 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8354 EVT VT = N->getValueType(0); 8355 8356 if (N0CFP && N1CFP) // Constant fold 8357 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 8358 8359 if (N1CFP) { 8360 const APFloat& V = N1CFP->getValueAPF(); 8361 // copysign(x, c1) -> fabs(x) iff ispos(c1) 8362 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 8363 if (!V.isNegative()) { 8364 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 8365 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8366 } else { 8367 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 8368 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 8369 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 8370 } 8371 } 8372 8373 // copysign(fabs(x), y) -> copysign(x, y) 8374 // copysign(fneg(x), y) -> copysign(x, y) 8375 // copysign(copysign(x,z), y) -> copysign(x, y) 8376 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 8377 N0.getOpcode() == ISD::FCOPYSIGN) 8378 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8379 N0.getOperand(0), N1); 8380 8381 // copysign(x, abs(y)) -> abs(x) 8382 if (N1.getOpcode() == ISD::FABS) 8383 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8384 8385 // copysign(x, copysign(y,z)) -> copysign(x, z) 8386 if (N1.getOpcode() == ISD::FCOPYSIGN) 8387 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8388 N0, N1.getOperand(1)); 8389 8390 // copysign(x, fp_extend(y)) -> copysign(x, y) 8391 // copysign(x, fp_round(y)) -> copysign(x, y) 8392 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 8393 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8394 N0, N1.getOperand(0)); 8395 8396 return SDValue(); 8397 } 8398 8399 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 8400 SDValue N0 = N->getOperand(0); 8401 EVT VT = N->getValueType(0); 8402 EVT OpVT = N0.getValueType(); 8403 8404 // fold (sint_to_fp c1) -> c1fp 8405 if (isConstantIntBuildVectorOrConstantInt(N0) && 8406 // ...but only if the target supports immediate floating-point values 8407 (!LegalOperations || 8408 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8409 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8410 8411 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 8412 // but UINT_TO_FP is legal on this target, try to convert. 8413 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 8414 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 8415 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 8416 if (DAG.SignBitIsZero(N0)) 8417 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8418 } 8419 8420 // The next optimizations are desirable only if SELECT_CC can be lowered. 8421 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8422 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8423 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 8424 !VT.isVector() && 8425 (!LegalOperations || 8426 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8427 SDLoc DL(N); 8428 SDValue Ops[] = 8429 { N0.getOperand(0), N0.getOperand(1), 8430 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8431 N0.getOperand(2) }; 8432 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8433 } 8434 8435 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 8436 // (select_cc x, y, 1.0, 0.0,, cc) 8437 if (N0.getOpcode() == ISD::ZERO_EXTEND && 8438 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 8439 (!LegalOperations || 8440 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8441 SDLoc DL(N); 8442 SDValue Ops[] = 8443 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 8444 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8445 N0.getOperand(0).getOperand(2) }; 8446 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8447 } 8448 } 8449 8450 return SDValue(); 8451 } 8452 8453 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 8454 SDValue N0 = N->getOperand(0); 8455 EVT VT = N->getValueType(0); 8456 EVT OpVT = N0.getValueType(); 8457 8458 // fold (uint_to_fp c1) -> c1fp 8459 if (isConstantIntBuildVectorOrConstantInt(N0) && 8460 // ...but only if the target supports immediate floating-point values 8461 (!LegalOperations || 8462 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 8463 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 8464 8465 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 8466 // but SINT_TO_FP is legal on this target, try to convert. 8467 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 8468 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 8469 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 8470 if (DAG.SignBitIsZero(N0)) 8471 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 8472 } 8473 8474 // The next optimizations are desirable only if SELECT_CC can be lowered. 8475 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 8476 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 8477 8478 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 8479 (!LegalOperations || 8480 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 8481 SDLoc DL(N); 8482 SDValue Ops[] = 8483 { N0.getOperand(0), N0.getOperand(1), 8484 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 8485 N0.getOperand(2) }; 8486 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 8487 } 8488 } 8489 8490 return SDValue(); 8491 } 8492 8493 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 8494 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 8495 SDValue N0 = N->getOperand(0); 8496 EVT VT = N->getValueType(0); 8497 8498 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 8499 return SDValue(); 8500 8501 SDValue Src = N0.getOperand(0); 8502 EVT SrcVT = Src.getValueType(); 8503 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 8504 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 8505 8506 // We can safely assume the conversion won't overflow the output range, 8507 // because (for example) (uint8_t)18293.f is undefined behavior. 8508 8509 // Since we can assume the conversion won't overflow, our decision as to 8510 // whether the input will fit in the float should depend on the minimum 8511 // of the input range and output range. 8512 8513 // This means this is also safe for a signed input and unsigned output, since 8514 // a negative input would lead to undefined behavior. 8515 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 8516 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 8517 unsigned ActualSize = std::min(InputSize, OutputSize); 8518 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 8519 8520 // We can only fold away the float conversion if the input range can be 8521 // represented exactly in the float range. 8522 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 8523 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 8524 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 8525 : ISD::ZERO_EXTEND; 8526 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 8527 } 8528 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 8529 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 8530 if (SrcVT == VT) 8531 return Src; 8532 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src); 8533 } 8534 return SDValue(); 8535 } 8536 8537 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 8538 SDValue N0 = N->getOperand(0); 8539 EVT VT = N->getValueType(0); 8540 8541 // fold (fp_to_sint c1fp) -> c1 8542 if (isConstantFPBuildVectorOrConstantFP(N0)) 8543 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 8544 8545 return FoldIntToFPToInt(N, DAG); 8546 } 8547 8548 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 8549 SDValue N0 = N->getOperand(0); 8550 EVT VT = N->getValueType(0); 8551 8552 // fold (fp_to_uint c1fp) -> c1 8553 if (isConstantFPBuildVectorOrConstantFP(N0)) 8554 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 8555 8556 return FoldIntToFPToInt(N, DAG); 8557 } 8558 8559 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 8560 SDValue N0 = N->getOperand(0); 8561 SDValue N1 = N->getOperand(1); 8562 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8563 EVT VT = N->getValueType(0); 8564 8565 // fold (fp_round c1fp) -> c1fp 8566 if (N0CFP) 8567 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 8568 8569 // fold (fp_round (fp_extend x)) -> x 8570 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 8571 return N0.getOperand(0); 8572 8573 // fold (fp_round (fp_round x)) -> (fp_round x) 8574 if (N0.getOpcode() == ISD::FP_ROUND) { 8575 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 8576 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1; 8577 // If the first fp_round isn't a value preserving truncation, it might 8578 // introduce a tie in the second fp_round, that wouldn't occur in the 8579 // single-step fp_round we want to fold to. 8580 // In other words, double rounding isn't the same as rounding. 8581 // Also, this is a value preserving truncation iff both fp_round's are. 8582 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 8583 SDLoc DL(N); 8584 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 8585 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 8586 } 8587 } 8588 8589 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 8590 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 8591 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 8592 N0.getOperand(0), N1); 8593 AddToWorklist(Tmp.getNode()); 8594 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 8595 Tmp, N0.getOperand(1)); 8596 } 8597 8598 return SDValue(); 8599 } 8600 8601 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 8602 SDValue N0 = N->getOperand(0); 8603 EVT VT = N->getValueType(0); 8604 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8605 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8606 8607 // fold (fp_round_inreg c1fp) -> c1fp 8608 if (N0CFP && isTypeLegal(EVT)) { 8609 SDLoc DL(N); 8610 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 8611 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 8612 } 8613 8614 return SDValue(); 8615 } 8616 8617 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 8618 SDValue N0 = N->getOperand(0); 8619 EVT VT = N->getValueType(0); 8620 8621 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 8622 if (N->hasOneUse() && 8623 N->use_begin()->getOpcode() == ISD::FP_ROUND) 8624 return SDValue(); 8625 8626 // fold (fp_extend c1fp) -> c1fp 8627 if (isConstantFPBuildVectorOrConstantFP(N0)) 8628 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 8629 8630 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 8631 if (N0.getOpcode() == ISD::FP16_TO_FP && 8632 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 8633 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 8634 8635 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 8636 // value of X. 8637 if (N0.getOpcode() == ISD::FP_ROUND 8638 && N0.getNode()->getConstantOperandVal(1) == 1) { 8639 SDValue In = N0.getOperand(0); 8640 if (In.getValueType() == VT) return In; 8641 if (VT.bitsLT(In.getValueType())) 8642 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 8643 In, N0.getOperand(1)); 8644 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 8645 } 8646 8647 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 8648 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 8649 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 8650 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8651 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 8652 LN0->getChain(), 8653 LN0->getBasePtr(), N0.getValueType(), 8654 LN0->getMemOperand()); 8655 CombineTo(N, ExtLoad); 8656 CombineTo(N0.getNode(), 8657 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 8658 N0.getValueType(), ExtLoad, 8659 DAG.getIntPtrConstant(1, SDLoc(N0))), 8660 ExtLoad.getValue(1)); 8661 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8662 } 8663 8664 return SDValue(); 8665 } 8666 8667 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 8668 SDValue N0 = N->getOperand(0); 8669 EVT VT = N->getValueType(0); 8670 8671 // fold (fceil c1) -> fceil(c1) 8672 if (isConstantFPBuildVectorOrConstantFP(N0)) 8673 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 8674 8675 return SDValue(); 8676 } 8677 8678 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 8679 SDValue N0 = N->getOperand(0); 8680 EVT VT = N->getValueType(0); 8681 8682 // fold (ftrunc c1) -> ftrunc(c1) 8683 if (isConstantFPBuildVectorOrConstantFP(N0)) 8684 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 8685 8686 return SDValue(); 8687 } 8688 8689 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 8690 SDValue N0 = N->getOperand(0); 8691 EVT VT = N->getValueType(0); 8692 8693 // fold (ffloor c1) -> ffloor(c1) 8694 if (isConstantFPBuildVectorOrConstantFP(N0)) 8695 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 8696 8697 return SDValue(); 8698 } 8699 8700 // FIXME: FNEG and FABS have a lot in common; refactor. 8701 SDValue DAGCombiner::visitFNEG(SDNode *N) { 8702 SDValue N0 = N->getOperand(0); 8703 EVT VT = N->getValueType(0); 8704 8705 // Constant fold FNEG. 8706 if (isConstantFPBuildVectorOrConstantFP(N0)) 8707 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 8708 8709 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 8710 &DAG.getTarget().Options)) 8711 return GetNegatedExpression(N0, DAG, LegalOperations); 8712 8713 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 8714 // constant pool values. 8715 if (!TLI.isFNegFree(VT) && 8716 N0.getOpcode() == ISD::BITCAST && 8717 N0.getNode()->hasOneUse()) { 8718 SDValue Int = N0.getOperand(0); 8719 EVT IntVT = Int.getValueType(); 8720 if (IntVT.isInteger() && !IntVT.isVector()) { 8721 APInt SignMask; 8722 if (N0.getValueType().isVector()) { 8723 // For a vector, get a mask such as 0x80... per scalar element 8724 // and splat it. 8725 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8726 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8727 } else { 8728 // For a scalar, just generate 0x80... 8729 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 8730 } 8731 SDLoc DL0(N0); 8732 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 8733 DAG.getConstant(SignMask, DL0, IntVT)); 8734 AddToWorklist(Int.getNode()); 8735 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 8736 } 8737 } 8738 8739 // (fneg (fmul c, x)) -> (fmul -c, x) 8740 if (N0.getOpcode() == ISD::FMUL) { 8741 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8742 if (CFP1) { 8743 APFloat CVal = CFP1->getValueAPF(); 8744 CVal.changeSign(); 8745 if (Level >= AfterLegalizeDAG && 8746 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 8747 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 8748 return DAG.getNode( 8749 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 8750 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1))); 8751 } 8752 } 8753 8754 return SDValue(); 8755 } 8756 8757 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 8758 SDValue N0 = N->getOperand(0); 8759 SDValue N1 = N->getOperand(1); 8760 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8761 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8762 8763 if (N0CFP && N1CFP) { 8764 const APFloat &C0 = N0CFP->getValueAPF(); 8765 const APFloat &C1 = N1CFP->getValueAPF(); 8766 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0)); 8767 } 8768 8769 if (N0CFP) { 8770 EVT VT = N->getValueType(0); 8771 // Canonicalize to constant on RHS. 8772 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 8773 } 8774 8775 return SDValue(); 8776 } 8777 8778 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 8779 SDValue N0 = N->getOperand(0); 8780 SDValue N1 = N->getOperand(1); 8781 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 8782 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 8783 8784 if (N0CFP && N1CFP) { 8785 const APFloat &C0 = N0CFP->getValueAPF(); 8786 const APFloat &C1 = N1CFP->getValueAPF(); 8787 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0)); 8788 } 8789 8790 if (N0CFP) { 8791 EVT VT = N->getValueType(0); 8792 // Canonicalize to constant on RHS. 8793 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 8794 } 8795 8796 return SDValue(); 8797 } 8798 8799 SDValue DAGCombiner::visitFABS(SDNode *N) { 8800 SDValue N0 = N->getOperand(0); 8801 EVT VT = N->getValueType(0); 8802 8803 // fold (fabs c1) -> fabs(c1) 8804 if (isConstantFPBuildVectorOrConstantFP(N0)) 8805 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8806 8807 // fold (fabs (fabs x)) -> (fabs x) 8808 if (N0.getOpcode() == ISD::FABS) 8809 return N->getOperand(0); 8810 8811 // fold (fabs (fneg x)) -> (fabs x) 8812 // fold (fabs (fcopysign x, y)) -> (fabs x) 8813 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 8814 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 8815 8816 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 8817 // constant pool values. 8818 if (!TLI.isFAbsFree(VT) && 8819 N0.getOpcode() == ISD::BITCAST && 8820 N0.getNode()->hasOneUse()) { 8821 SDValue Int = N0.getOperand(0); 8822 EVT IntVT = Int.getValueType(); 8823 if (IntVT.isInteger() && !IntVT.isVector()) { 8824 APInt SignMask; 8825 if (N0.getValueType().isVector()) { 8826 // For a vector, get a mask such as 0x7f... per scalar element 8827 // and splat it. 8828 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8829 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8830 } else { 8831 // For a scalar, just generate 0x7f... 8832 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 8833 } 8834 SDLoc DL(N0); 8835 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 8836 DAG.getConstant(SignMask, DL, IntVT)); 8837 AddToWorklist(Int.getNode()); 8838 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 8839 } 8840 } 8841 8842 return SDValue(); 8843 } 8844 8845 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 8846 SDValue Chain = N->getOperand(0); 8847 SDValue N1 = N->getOperand(1); 8848 SDValue N2 = N->getOperand(2); 8849 8850 // If N is a constant we could fold this into a fallthrough or unconditional 8851 // branch. However that doesn't happen very often in normal code, because 8852 // Instcombine/SimplifyCFG should have handled the available opportunities. 8853 // If we did this folding here, it would be necessary to update the 8854 // MachineBasicBlock CFG, which is awkward. 8855 8856 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 8857 // on the target. 8858 if (N1.getOpcode() == ISD::SETCC && 8859 TLI.isOperationLegalOrCustom(ISD::BR_CC, 8860 N1.getOperand(0).getValueType())) { 8861 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8862 Chain, N1.getOperand(2), 8863 N1.getOperand(0), N1.getOperand(1), N2); 8864 } 8865 8866 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 8867 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 8868 (N1.getOperand(0).hasOneUse() && 8869 N1.getOperand(0).getOpcode() == ISD::SRL))) { 8870 SDNode *Trunc = nullptr; 8871 if (N1.getOpcode() == ISD::TRUNCATE) { 8872 // Look pass the truncate. 8873 Trunc = N1.getNode(); 8874 N1 = N1.getOperand(0); 8875 } 8876 8877 // Match this pattern so that we can generate simpler code: 8878 // 8879 // %a = ... 8880 // %b = and i32 %a, 2 8881 // %c = srl i32 %b, 1 8882 // brcond i32 %c ... 8883 // 8884 // into 8885 // 8886 // %a = ... 8887 // %b = and i32 %a, 2 8888 // %c = setcc eq %b, 0 8889 // brcond %c ... 8890 // 8891 // This applies only when the AND constant value has one bit set and the 8892 // SRL constant is equal to the log2 of the AND constant. The back-end is 8893 // smart enough to convert the result into a TEST/JMP sequence. 8894 SDValue Op0 = N1.getOperand(0); 8895 SDValue Op1 = N1.getOperand(1); 8896 8897 if (Op0.getOpcode() == ISD::AND && 8898 Op1.getOpcode() == ISD::Constant) { 8899 SDValue AndOp1 = Op0.getOperand(1); 8900 8901 if (AndOp1.getOpcode() == ISD::Constant) { 8902 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 8903 8904 if (AndConst.isPowerOf2() && 8905 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 8906 SDLoc DL(N); 8907 SDValue SetCC = 8908 DAG.getSetCC(DL, 8909 getSetCCResultType(Op0.getValueType()), 8910 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 8911 ISD::SETNE); 8912 8913 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL, 8914 MVT::Other, Chain, SetCC, N2); 8915 // Don't add the new BRCond into the worklist or else SimplifySelectCC 8916 // will convert it back to (X & C1) >> C2. 8917 CombineTo(N, NewBRCond, false); 8918 // Truncate is dead. 8919 if (Trunc) 8920 deleteAndRecombine(Trunc); 8921 // Replace the uses of SRL with SETCC 8922 WorklistRemover DeadNodes(*this); 8923 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8924 deleteAndRecombine(N1.getNode()); 8925 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8926 } 8927 } 8928 } 8929 8930 if (Trunc) 8931 // Restore N1 if the above transformation doesn't match. 8932 N1 = N->getOperand(1); 8933 } 8934 8935 // Transform br(xor(x, y)) -> br(x != y) 8936 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 8937 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 8938 SDNode *TheXor = N1.getNode(); 8939 SDValue Op0 = TheXor->getOperand(0); 8940 SDValue Op1 = TheXor->getOperand(1); 8941 if (Op0.getOpcode() == Op1.getOpcode()) { 8942 // Avoid missing important xor optimizations. 8943 SDValue Tmp = visitXOR(TheXor); 8944 if (Tmp.getNode()) { 8945 if (Tmp.getNode() != TheXor) { 8946 DEBUG(dbgs() << "\nReplacing.8 "; 8947 TheXor->dump(&DAG); 8948 dbgs() << "\nWith: "; 8949 Tmp.getNode()->dump(&DAG); 8950 dbgs() << '\n'); 8951 WorklistRemover DeadNodes(*this); 8952 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 8953 deleteAndRecombine(TheXor); 8954 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8955 MVT::Other, Chain, Tmp, N2); 8956 } 8957 8958 // visitXOR has changed XOR's operands or replaced the XOR completely, 8959 // bail out. 8960 return SDValue(N, 0); 8961 } 8962 } 8963 8964 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 8965 bool Equal = false; 8966 if (isOneConstant(Op0) && Op0.hasOneUse() && 8967 Op0.getOpcode() == ISD::XOR) { 8968 TheXor = Op0.getNode(); 8969 Equal = true; 8970 } 8971 8972 EVT SetCCVT = N1.getValueType(); 8973 if (LegalTypes) 8974 SetCCVT = getSetCCResultType(SetCCVT); 8975 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 8976 SetCCVT, 8977 Op0, Op1, 8978 Equal ? ISD::SETEQ : ISD::SETNE); 8979 // Replace the uses of XOR with SETCC 8980 WorklistRemover DeadNodes(*this); 8981 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8982 deleteAndRecombine(N1.getNode()); 8983 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8984 MVT::Other, Chain, SetCC, N2); 8985 } 8986 } 8987 8988 return SDValue(); 8989 } 8990 8991 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 8992 // 8993 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 8994 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 8995 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 8996 8997 // If N is a constant we could fold this into a fallthrough or unconditional 8998 // branch. However that doesn't happen very often in normal code, because 8999 // Instcombine/SimplifyCFG should have handled the available opportunities. 9000 // If we did this folding here, it would be necessary to update the 9001 // MachineBasicBlock CFG, which is awkward. 9002 9003 // Use SimplifySetCC to simplify SETCC's. 9004 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 9005 CondLHS, CondRHS, CC->get(), SDLoc(N), 9006 false); 9007 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 9008 9009 // fold to a simpler setcc 9010 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 9011 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 9012 N->getOperand(0), Simp.getOperand(2), 9013 Simp.getOperand(0), Simp.getOperand(1), 9014 N->getOperand(4)); 9015 9016 return SDValue(); 9017 } 9018 9019 /// Return true if 'Use' is a load or a store that uses N as its base pointer 9020 /// and that N may be folded in the load / store addressing mode. 9021 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 9022 SelectionDAG &DAG, 9023 const TargetLowering &TLI) { 9024 EVT VT; 9025 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 9026 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 9027 return false; 9028 VT = LD->getMemoryVT(); 9029 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 9030 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 9031 return false; 9032 VT = ST->getMemoryVT(); 9033 } else 9034 return false; 9035 9036 TargetLowering::AddrMode AM; 9037 if (N->getOpcode() == ISD::ADD) { 9038 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9039 if (Offset) 9040 // [reg +/- imm] 9041 AM.BaseOffs = Offset->getSExtValue(); 9042 else 9043 // [reg +/- reg] 9044 AM.Scale = 1; 9045 } else if (N->getOpcode() == ISD::SUB) { 9046 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9047 if (Offset) 9048 // [reg +/- imm] 9049 AM.BaseOffs = -Offset->getSExtValue(); 9050 else 9051 // [reg +/- reg] 9052 AM.Scale = 1; 9053 } else 9054 return false; 9055 9056 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 9057 } 9058 9059 /// Try turning a load/store into a pre-indexed load/store when the base 9060 /// pointer is an add or subtract and it has other uses besides the load/store. 9061 /// After the transformation, the new indexed load/store has effectively folded 9062 /// the add/subtract in and all of its other uses are redirected to the 9063 /// new load/store. 9064 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 9065 if (Level < AfterLegalizeDAG) 9066 return false; 9067 9068 bool isLoad = true; 9069 SDValue Ptr; 9070 EVT VT; 9071 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9072 if (LD->isIndexed()) 9073 return false; 9074 VT = LD->getMemoryVT(); 9075 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 9076 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 9077 return false; 9078 Ptr = LD->getBasePtr(); 9079 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9080 if (ST->isIndexed()) 9081 return false; 9082 VT = ST->getMemoryVT(); 9083 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 9084 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 9085 return false; 9086 Ptr = ST->getBasePtr(); 9087 isLoad = false; 9088 } else { 9089 return false; 9090 } 9091 9092 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 9093 // out. There is no reason to make this a preinc/predec. 9094 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 9095 Ptr.getNode()->hasOneUse()) 9096 return false; 9097 9098 // Ask the target to do addressing mode selection. 9099 SDValue BasePtr; 9100 SDValue Offset; 9101 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9102 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 9103 return false; 9104 9105 // Backends without true r+i pre-indexed forms may need to pass a 9106 // constant base with a variable offset so that constant coercion 9107 // will work with the patterns in canonical form. 9108 bool Swapped = false; 9109 if (isa<ConstantSDNode>(BasePtr)) { 9110 std::swap(BasePtr, Offset); 9111 Swapped = true; 9112 } 9113 9114 // Don't create a indexed load / store with zero offset. 9115 if (isNullConstant(Offset)) 9116 return false; 9117 9118 // Try turning it into a pre-indexed load / store except when: 9119 // 1) The new base ptr is a frame index. 9120 // 2) If N is a store and the new base ptr is either the same as or is a 9121 // predecessor of the value being stored. 9122 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 9123 // that would create a cycle. 9124 // 4) All uses are load / store ops that use it as old base ptr. 9125 9126 // Check #1. Preinc'ing a frame index would require copying the stack pointer 9127 // (plus the implicit offset) to a register to preinc anyway. 9128 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9129 return false; 9130 9131 // Check #2. 9132 if (!isLoad) { 9133 SDValue Val = cast<StoreSDNode>(N)->getValue(); 9134 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 9135 return false; 9136 } 9137 9138 // If the offset is a constant, there may be other adds of constants that 9139 // can be folded with this one. We should do this to avoid having to keep 9140 // a copy of the original base pointer. 9141 SmallVector<SDNode *, 16> OtherUses; 9142 if (isa<ConstantSDNode>(Offset)) 9143 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 9144 UE = BasePtr.getNode()->use_end(); 9145 UI != UE; ++UI) { 9146 SDUse &Use = UI.getUse(); 9147 // Skip the use that is Ptr and uses of other results from BasePtr's 9148 // node (important for nodes that return multiple results). 9149 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 9150 continue; 9151 9152 if (Use.getUser()->isPredecessorOf(N)) 9153 continue; 9154 9155 if (Use.getUser()->getOpcode() != ISD::ADD && 9156 Use.getUser()->getOpcode() != ISD::SUB) { 9157 OtherUses.clear(); 9158 break; 9159 } 9160 9161 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 9162 if (!isa<ConstantSDNode>(Op1)) { 9163 OtherUses.clear(); 9164 break; 9165 } 9166 9167 // FIXME: In some cases, we can be smarter about this. 9168 if (Op1.getValueType() != Offset.getValueType()) { 9169 OtherUses.clear(); 9170 break; 9171 } 9172 9173 OtherUses.push_back(Use.getUser()); 9174 } 9175 9176 if (Swapped) 9177 std::swap(BasePtr, Offset); 9178 9179 // Now check for #3 and #4. 9180 bool RealUse = false; 9181 9182 // Caches for hasPredecessorHelper 9183 SmallPtrSet<const SDNode *, 32> Visited; 9184 SmallVector<const SDNode *, 16> Worklist; 9185 9186 for (SDNode *Use : Ptr.getNode()->uses()) { 9187 if (Use == N) 9188 continue; 9189 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 9190 return false; 9191 9192 // If Ptr may be folded in addressing mode of other use, then it's 9193 // not profitable to do this transformation. 9194 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 9195 RealUse = true; 9196 } 9197 9198 if (!RealUse) 9199 return false; 9200 9201 SDValue Result; 9202 if (isLoad) 9203 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9204 BasePtr, Offset, AM); 9205 else 9206 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9207 BasePtr, Offset, AM); 9208 ++PreIndexedNodes; 9209 ++NodesCombined; 9210 DEBUG(dbgs() << "\nReplacing.4 "; 9211 N->dump(&DAG); 9212 dbgs() << "\nWith: "; 9213 Result.getNode()->dump(&DAG); 9214 dbgs() << '\n'); 9215 WorklistRemover DeadNodes(*this); 9216 if (isLoad) { 9217 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9218 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9219 } else { 9220 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9221 } 9222 9223 // Finally, since the node is now dead, remove it from the graph. 9224 deleteAndRecombine(N); 9225 9226 if (Swapped) 9227 std::swap(BasePtr, Offset); 9228 9229 // Replace other uses of BasePtr that can be updated to use Ptr 9230 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 9231 unsigned OffsetIdx = 1; 9232 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 9233 OffsetIdx = 0; 9234 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 9235 BasePtr.getNode() && "Expected BasePtr operand"); 9236 9237 // We need to replace ptr0 in the following expression: 9238 // x0 * offset0 + y0 * ptr0 = t0 9239 // knowing that 9240 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 9241 // 9242 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 9243 // indexed load/store and the expresion that needs to be re-written. 9244 // 9245 // Therefore, we have: 9246 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 9247 9248 ConstantSDNode *CN = 9249 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 9250 int X0, X1, Y0, Y1; 9251 APInt Offset0 = CN->getAPIntValue(); 9252 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 9253 9254 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 9255 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 9256 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 9257 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 9258 9259 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 9260 9261 APInt CNV = Offset0; 9262 if (X0 < 0) CNV = -CNV; 9263 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 9264 else CNV = CNV - Offset1; 9265 9266 SDLoc DL(OtherUses[i]); 9267 9268 // We can now generate the new expression. 9269 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 9270 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 9271 9272 SDValue NewUse = DAG.getNode(Opcode, 9273 DL, 9274 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 9275 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 9276 deleteAndRecombine(OtherUses[i]); 9277 } 9278 9279 // Replace the uses of Ptr with uses of the updated base value. 9280 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 9281 deleteAndRecombine(Ptr.getNode()); 9282 9283 return true; 9284 } 9285 9286 /// Try to combine a load/store with a add/sub of the base pointer node into a 9287 /// post-indexed load/store. The transformation folded the add/subtract into the 9288 /// new indexed load/store effectively and all of its uses are redirected to the 9289 /// new load/store. 9290 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 9291 if (Level < AfterLegalizeDAG) 9292 return false; 9293 9294 bool isLoad = true; 9295 SDValue Ptr; 9296 EVT VT; 9297 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 9298 if (LD->isIndexed()) 9299 return false; 9300 VT = LD->getMemoryVT(); 9301 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 9302 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 9303 return false; 9304 Ptr = LD->getBasePtr(); 9305 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 9306 if (ST->isIndexed()) 9307 return false; 9308 VT = ST->getMemoryVT(); 9309 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 9310 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 9311 return false; 9312 Ptr = ST->getBasePtr(); 9313 isLoad = false; 9314 } else { 9315 return false; 9316 } 9317 9318 if (Ptr.getNode()->hasOneUse()) 9319 return false; 9320 9321 for (SDNode *Op : Ptr.getNode()->uses()) { 9322 if (Op == N || 9323 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 9324 continue; 9325 9326 SDValue BasePtr; 9327 SDValue Offset; 9328 ISD::MemIndexedMode AM = ISD::UNINDEXED; 9329 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 9330 // Don't create a indexed load / store with zero offset. 9331 if (isNullConstant(Offset)) 9332 continue; 9333 9334 // Try turning it into a post-indexed load / store except when 9335 // 1) All uses are load / store ops that use it as base ptr (and 9336 // it may be folded as addressing mmode). 9337 // 2) Op must be independent of N, i.e. Op is neither a predecessor 9338 // nor a successor of N. Otherwise, if Op is folded that would 9339 // create a cycle. 9340 9341 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 9342 continue; 9343 9344 // Check for #1. 9345 bool TryNext = false; 9346 for (SDNode *Use : BasePtr.getNode()->uses()) { 9347 if (Use == Ptr.getNode()) 9348 continue; 9349 9350 // If all the uses are load / store addresses, then don't do the 9351 // transformation. 9352 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 9353 bool RealUse = false; 9354 for (SDNode *UseUse : Use->uses()) { 9355 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 9356 RealUse = true; 9357 } 9358 9359 if (!RealUse) { 9360 TryNext = true; 9361 break; 9362 } 9363 } 9364 } 9365 9366 if (TryNext) 9367 continue; 9368 9369 // Check for #2 9370 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 9371 SDValue Result = isLoad 9372 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 9373 BasePtr, Offset, AM) 9374 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 9375 BasePtr, Offset, AM); 9376 ++PostIndexedNodes; 9377 ++NodesCombined; 9378 DEBUG(dbgs() << "\nReplacing.5 "; 9379 N->dump(&DAG); 9380 dbgs() << "\nWith: "; 9381 Result.getNode()->dump(&DAG); 9382 dbgs() << '\n'); 9383 WorklistRemover DeadNodes(*this); 9384 if (isLoad) { 9385 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 9386 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 9387 } else { 9388 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 9389 } 9390 9391 // Finally, since the node is now dead, remove it from the graph. 9392 deleteAndRecombine(N); 9393 9394 // Replace the uses of Use with uses of the updated base value. 9395 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 9396 Result.getValue(isLoad ? 1 : 0)); 9397 deleteAndRecombine(Op); 9398 return true; 9399 } 9400 } 9401 } 9402 9403 return false; 9404 } 9405 9406 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 9407 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 9408 ISD::MemIndexedMode AM = LD->getAddressingMode(); 9409 assert(AM != ISD::UNINDEXED); 9410 SDValue BP = LD->getOperand(1); 9411 SDValue Inc = LD->getOperand(2); 9412 9413 // Some backends use TargetConstants for load offsets, but don't expect 9414 // TargetConstants in general ADD nodes. We can convert these constants into 9415 // regular Constants (if the constant is not opaque). 9416 assert((Inc.getOpcode() != ISD::TargetConstant || 9417 !cast<ConstantSDNode>(Inc)->isOpaque()) && 9418 "Cannot split out indexing using opaque target constants"); 9419 if (Inc.getOpcode() == ISD::TargetConstant) { 9420 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 9421 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 9422 ConstInc->getValueType(0)); 9423 } 9424 9425 unsigned Opc = 9426 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 9427 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 9428 } 9429 9430 SDValue DAGCombiner::visitLOAD(SDNode *N) { 9431 LoadSDNode *LD = cast<LoadSDNode>(N); 9432 SDValue Chain = LD->getChain(); 9433 SDValue Ptr = LD->getBasePtr(); 9434 9435 // If load is not volatile and there are no uses of the loaded value (and 9436 // the updated indexed value in case of indexed loads), change uses of the 9437 // chain value into uses of the chain input (i.e. delete the dead load). 9438 if (!LD->isVolatile()) { 9439 if (N->getValueType(1) == MVT::Other) { 9440 // Unindexed loads. 9441 if (!N->hasAnyUseOfValue(0)) { 9442 // It's not safe to use the two value CombineTo variant here. e.g. 9443 // v1, chain2 = load chain1, loc 9444 // v2, chain3 = load chain2, loc 9445 // v3 = add v2, c 9446 // Now we replace use of chain2 with chain1. This makes the second load 9447 // isomorphic to the one we are deleting, and thus makes this load live. 9448 DEBUG(dbgs() << "\nReplacing.6 "; 9449 N->dump(&DAG); 9450 dbgs() << "\nWith chain: "; 9451 Chain.getNode()->dump(&DAG); 9452 dbgs() << "\n"); 9453 WorklistRemover DeadNodes(*this); 9454 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9455 9456 if (N->use_empty()) 9457 deleteAndRecombine(N); 9458 9459 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9460 } 9461 } else { 9462 // Indexed loads. 9463 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 9464 9465 // If this load has an opaque TargetConstant offset, then we cannot split 9466 // the indexing into an add/sub directly (that TargetConstant may not be 9467 // valid for a different type of node, and we cannot convert an opaque 9468 // target constant into a regular constant). 9469 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 9470 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 9471 9472 if (!N->hasAnyUseOfValue(0) && 9473 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 9474 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 9475 SDValue Index; 9476 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 9477 Index = SplitIndexingFromLoad(LD); 9478 // Try to fold the base pointer arithmetic into subsequent loads and 9479 // stores. 9480 AddUsersToWorklist(N); 9481 } else 9482 Index = DAG.getUNDEF(N->getValueType(1)); 9483 DEBUG(dbgs() << "\nReplacing.7 "; 9484 N->dump(&DAG); 9485 dbgs() << "\nWith: "; 9486 Undef.getNode()->dump(&DAG); 9487 dbgs() << " and 2 other values\n"); 9488 WorklistRemover DeadNodes(*this); 9489 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 9490 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 9491 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 9492 deleteAndRecombine(N); 9493 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9494 } 9495 } 9496 } 9497 9498 // If this load is directly stored, replace the load value with the stored 9499 // value. 9500 // TODO: Handle store large -> read small portion. 9501 // TODO: Handle TRUNCSTORE/LOADEXT 9502 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 9503 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 9504 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 9505 if (PrevST->getBasePtr() == Ptr && 9506 PrevST->getValue().getValueType() == N->getValueType(0)) 9507 return CombineTo(N, Chain.getOperand(1), Chain); 9508 } 9509 } 9510 9511 // Try to infer better alignment information than the load already has. 9512 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 9513 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 9514 if (Align > LD->getMemOperand()->getBaseAlignment()) { 9515 SDValue NewLoad = 9516 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 9517 LD->getValueType(0), 9518 Chain, Ptr, LD->getPointerInfo(), 9519 LD->getMemoryVT(), 9520 LD->isVolatile(), LD->isNonTemporal(), 9521 LD->isInvariant(), Align, LD->getAAInfo()); 9522 if (NewLoad.getNode() != N) 9523 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 9524 } 9525 } 9526 } 9527 9528 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 9529 : DAG.getSubtarget().useAA(); 9530 #ifndef NDEBUG 9531 if (CombinerAAOnlyFunc.getNumOccurrences() && 9532 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 9533 UseAA = false; 9534 #endif 9535 if (UseAA && LD->isUnindexed()) { 9536 // Walk up chain skipping non-aliasing memory nodes. 9537 SDValue BetterChain = FindBetterChain(N, Chain); 9538 9539 // If there is a better chain. 9540 if (Chain != BetterChain) { 9541 SDValue ReplLoad; 9542 9543 // Replace the chain to void dependency. 9544 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 9545 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 9546 BetterChain, Ptr, LD->getMemOperand()); 9547 } else { 9548 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 9549 LD->getValueType(0), 9550 BetterChain, Ptr, LD->getMemoryVT(), 9551 LD->getMemOperand()); 9552 } 9553 9554 // Create token factor to keep old chain connected. 9555 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 9556 MVT::Other, Chain, ReplLoad.getValue(1)); 9557 9558 // Make sure the new and old chains are cleaned up. 9559 AddToWorklist(Token.getNode()); 9560 9561 // Replace uses with load result and token factor. Don't add users 9562 // to work list. 9563 return CombineTo(N, ReplLoad.getValue(0), Token, false); 9564 } 9565 } 9566 9567 // Try transforming N to an indexed load. 9568 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9569 return SDValue(N, 0); 9570 9571 // Try to slice up N to more direct loads if the slices are mapped to 9572 // different register banks or pairing can take place. 9573 if (SliceUpLoad(N)) 9574 return SDValue(N, 0); 9575 9576 return SDValue(); 9577 } 9578 9579 namespace { 9580 /// \brief Helper structure used to slice a load in smaller loads. 9581 /// Basically a slice is obtained from the following sequence: 9582 /// Origin = load Ty1, Base 9583 /// Shift = srl Ty1 Origin, CstTy Amount 9584 /// Inst = trunc Shift to Ty2 9585 /// 9586 /// Then, it will be rewriten into: 9587 /// Slice = load SliceTy, Base + SliceOffset 9588 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 9589 /// 9590 /// SliceTy is deduced from the number of bits that are actually used to 9591 /// build Inst. 9592 struct LoadedSlice { 9593 /// \brief Helper structure used to compute the cost of a slice. 9594 struct Cost { 9595 /// Are we optimizing for code size. 9596 bool ForCodeSize; 9597 /// Various cost. 9598 unsigned Loads; 9599 unsigned Truncates; 9600 unsigned CrossRegisterBanksCopies; 9601 unsigned ZExts; 9602 unsigned Shift; 9603 9604 Cost(bool ForCodeSize = false) 9605 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 9606 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 9607 9608 /// \brief Get the cost of one isolated slice. 9609 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 9610 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 9611 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 9612 EVT TruncType = LS.Inst->getValueType(0); 9613 EVT LoadedType = LS.getLoadedType(); 9614 if (TruncType != LoadedType && 9615 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 9616 ZExts = 1; 9617 } 9618 9619 /// \brief Account for slicing gain in the current cost. 9620 /// Slicing provide a few gains like removing a shift or a 9621 /// truncate. This method allows to grow the cost of the original 9622 /// load with the gain from this slice. 9623 void addSliceGain(const LoadedSlice &LS) { 9624 // Each slice saves a truncate. 9625 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 9626 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 9627 LS.Inst->getOperand(0).getValueType())) 9628 ++Truncates; 9629 // If there is a shift amount, this slice gets rid of it. 9630 if (LS.Shift) 9631 ++Shift; 9632 // If this slice can merge a cross register bank copy, account for it. 9633 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 9634 ++CrossRegisterBanksCopies; 9635 } 9636 9637 Cost &operator+=(const Cost &RHS) { 9638 Loads += RHS.Loads; 9639 Truncates += RHS.Truncates; 9640 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 9641 ZExts += RHS.ZExts; 9642 Shift += RHS.Shift; 9643 return *this; 9644 } 9645 9646 bool operator==(const Cost &RHS) const { 9647 return Loads == RHS.Loads && Truncates == RHS.Truncates && 9648 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 9649 ZExts == RHS.ZExts && Shift == RHS.Shift; 9650 } 9651 9652 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 9653 9654 bool operator<(const Cost &RHS) const { 9655 // Assume cross register banks copies are as expensive as loads. 9656 // FIXME: Do we want some more target hooks? 9657 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 9658 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 9659 // Unless we are optimizing for code size, consider the 9660 // expensive operation first. 9661 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 9662 return ExpensiveOpsLHS < ExpensiveOpsRHS; 9663 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 9664 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 9665 } 9666 9667 bool operator>(const Cost &RHS) const { return RHS < *this; } 9668 9669 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 9670 9671 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 9672 }; 9673 // The last instruction that represent the slice. This should be a 9674 // truncate instruction. 9675 SDNode *Inst; 9676 // The original load instruction. 9677 LoadSDNode *Origin; 9678 // The right shift amount in bits from the original load. 9679 unsigned Shift; 9680 // The DAG from which Origin came from. 9681 // This is used to get some contextual information about legal types, etc. 9682 SelectionDAG *DAG; 9683 9684 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 9685 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 9686 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 9687 9688 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 9689 /// \return Result is \p BitWidth and has used bits set to 1 and 9690 /// not used bits set to 0. 9691 APInt getUsedBits() const { 9692 // Reproduce the trunc(lshr) sequence: 9693 // - Start from the truncated value. 9694 // - Zero extend to the desired bit width. 9695 // - Shift left. 9696 assert(Origin && "No original load to compare against."); 9697 unsigned BitWidth = Origin->getValueSizeInBits(0); 9698 assert(Inst && "This slice is not bound to an instruction"); 9699 assert(Inst->getValueSizeInBits(0) <= BitWidth && 9700 "Extracted slice is bigger than the whole type!"); 9701 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 9702 UsedBits.setAllBits(); 9703 UsedBits = UsedBits.zext(BitWidth); 9704 UsedBits <<= Shift; 9705 return UsedBits; 9706 } 9707 9708 /// \brief Get the size of the slice to be loaded in bytes. 9709 unsigned getLoadedSize() const { 9710 unsigned SliceSize = getUsedBits().countPopulation(); 9711 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 9712 return SliceSize / 8; 9713 } 9714 9715 /// \brief Get the type that will be loaded for this slice. 9716 /// Note: This may not be the final type for the slice. 9717 EVT getLoadedType() const { 9718 assert(DAG && "Missing context"); 9719 LLVMContext &Ctxt = *DAG->getContext(); 9720 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 9721 } 9722 9723 /// \brief Get the alignment of the load used for this slice. 9724 unsigned getAlignment() const { 9725 unsigned Alignment = Origin->getAlignment(); 9726 unsigned Offset = getOffsetFromBase(); 9727 if (Offset != 0) 9728 Alignment = MinAlign(Alignment, Alignment + Offset); 9729 return Alignment; 9730 } 9731 9732 /// \brief Check if this slice can be rewritten with legal operations. 9733 bool isLegal() const { 9734 // An invalid slice is not legal. 9735 if (!Origin || !Inst || !DAG) 9736 return false; 9737 9738 // Offsets are for indexed load only, we do not handle that. 9739 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 9740 return false; 9741 9742 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9743 9744 // Check that the type is legal. 9745 EVT SliceType = getLoadedType(); 9746 if (!TLI.isTypeLegal(SliceType)) 9747 return false; 9748 9749 // Check that the load is legal for this type. 9750 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 9751 return false; 9752 9753 // Check that the offset can be computed. 9754 // 1. Check its type. 9755 EVT PtrType = Origin->getBasePtr().getValueType(); 9756 if (PtrType == MVT::Untyped || PtrType.isExtended()) 9757 return false; 9758 9759 // 2. Check that it fits in the immediate. 9760 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 9761 return false; 9762 9763 // 3. Check that the computation is legal. 9764 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 9765 return false; 9766 9767 // Check that the zext is legal if it needs one. 9768 EVT TruncateType = Inst->getValueType(0); 9769 if (TruncateType != SliceType && 9770 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 9771 return false; 9772 9773 return true; 9774 } 9775 9776 /// \brief Get the offset in bytes of this slice in the original chunk of 9777 /// bits. 9778 /// \pre DAG != nullptr. 9779 uint64_t getOffsetFromBase() const { 9780 assert(DAG && "Missing context."); 9781 bool IsBigEndian = 9782 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 9783 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 9784 uint64_t Offset = Shift / 8; 9785 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 9786 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 9787 "The size of the original loaded type is not a multiple of a" 9788 " byte."); 9789 // If Offset is bigger than TySizeInBytes, it means we are loading all 9790 // zeros. This should have been optimized before in the process. 9791 assert(TySizeInBytes > Offset && 9792 "Invalid shift amount for given loaded size"); 9793 if (IsBigEndian) 9794 Offset = TySizeInBytes - Offset - getLoadedSize(); 9795 return Offset; 9796 } 9797 9798 /// \brief Generate the sequence of instructions to load the slice 9799 /// represented by this object and redirect the uses of this slice to 9800 /// this new sequence of instructions. 9801 /// \pre this->Inst && this->Origin are valid Instructions and this 9802 /// object passed the legal check: LoadedSlice::isLegal returned true. 9803 /// \return The last instruction of the sequence used to load the slice. 9804 SDValue loadSlice() const { 9805 assert(Inst && Origin && "Unable to replace a non-existing slice."); 9806 const SDValue &OldBaseAddr = Origin->getBasePtr(); 9807 SDValue BaseAddr = OldBaseAddr; 9808 // Get the offset in that chunk of bytes w.r.t. the endianess. 9809 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 9810 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 9811 if (Offset) { 9812 // BaseAddr = BaseAddr + Offset. 9813 EVT ArithType = BaseAddr.getValueType(); 9814 SDLoc DL(Origin); 9815 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 9816 DAG->getConstant(Offset, DL, ArithType)); 9817 } 9818 9819 // Create the type of the loaded slice according to its size. 9820 EVT SliceType = getLoadedType(); 9821 9822 // Create the load for the slice. 9823 SDValue LastInst = DAG->getLoad( 9824 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 9825 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 9826 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 9827 // If the final type is not the same as the loaded type, this means that 9828 // we have to pad with zero. Create a zero extend for that. 9829 EVT FinalType = Inst->getValueType(0); 9830 if (SliceType != FinalType) 9831 LastInst = 9832 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 9833 return LastInst; 9834 } 9835 9836 /// \brief Check if this slice can be merged with an expensive cross register 9837 /// bank copy. E.g., 9838 /// i = load i32 9839 /// f = bitcast i32 i to float 9840 bool canMergeExpensiveCrossRegisterBankCopy() const { 9841 if (!Inst || !Inst->hasOneUse()) 9842 return false; 9843 SDNode *Use = *Inst->use_begin(); 9844 if (Use->getOpcode() != ISD::BITCAST) 9845 return false; 9846 assert(DAG && "Missing context"); 9847 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9848 EVT ResVT = Use->getValueType(0); 9849 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 9850 const TargetRegisterClass *ArgRC = 9851 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 9852 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 9853 return false; 9854 9855 // At this point, we know that we perform a cross-register-bank copy. 9856 // Check if it is expensive. 9857 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 9858 // Assume bitcasts are cheap, unless both register classes do not 9859 // explicitly share a common sub class. 9860 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 9861 return false; 9862 9863 // Check if it will be merged with the load. 9864 // 1. Check the alignment constraint. 9865 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 9866 ResVT.getTypeForEVT(*DAG->getContext())); 9867 9868 if (RequiredAlignment > getAlignment()) 9869 return false; 9870 9871 // 2. Check that the load is a legal operation for that type. 9872 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 9873 return false; 9874 9875 // 3. Check that we do not have a zext in the way. 9876 if (Inst->getValueType(0) != getLoadedType()) 9877 return false; 9878 9879 return true; 9880 } 9881 }; 9882 } 9883 9884 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 9885 /// \p UsedBits looks like 0..0 1..1 0..0. 9886 static bool areUsedBitsDense(const APInt &UsedBits) { 9887 // If all the bits are one, this is dense! 9888 if (UsedBits.isAllOnesValue()) 9889 return true; 9890 9891 // Get rid of the unused bits on the right. 9892 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 9893 // Get rid of the unused bits on the left. 9894 if (NarrowedUsedBits.countLeadingZeros()) 9895 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 9896 // Check that the chunk of bits is completely used. 9897 return NarrowedUsedBits.isAllOnesValue(); 9898 } 9899 9900 /// \brief Check whether or not \p First and \p Second are next to each other 9901 /// in memory. This means that there is no hole between the bits loaded 9902 /// by \p First and the bits loaded by \p Second. 9903 static bool areSlicesNextToEachOther(const LoadedSlice &First, 9904 const LoadedSlice &Second) { 9905 assert(First.Origin == Second.Origin && First.Origin && 9906 "Unable to match different memory origins."); 9907 APInt UsedBits = First.getUsedBits(); 9908 assert((UsedBits & Second.getUsedBits()) == 0 && 9909 "Slices are not supposed to overlap."); 9910 UsedBits |= Second.getUsedBits(); 9911 return areUsedBitsDense(UsedBits); 9912 } 9913 9914 /// \brief Adjust the \p GlobalLSCost according to the target 9915 /// paring capabilities and the layout of the slices. 9916 /// \pre \p GlobalLSCost should account for at least as many loads as 9917 /// there is in the slices in \p LoadedSlices. 9918 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9919 LoadedSlice::Cost &GlobalLSCost) { 9920 unsigned NumberOfSlices = LoadedSlices.size(); 9921 // If there is less than 2 elements, no pairing is possible. 9922 if (NumberOfSlices < 2) 9923 return; 9924 9925 // Sort the slices so that elements that are likely to be next to each 9926 // other in memory are next to each other in the list. 9927 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 9928 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 9929 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 9930 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 9931 }); 9932 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 9933 // First (resp. Second) is the first (resp. Second) potentially candidate 9934 // to be placed in a paired load. 9935 const LoadedSlice *First = nullptr; 9936 const LoadedSlice *Second = nullptr; 9937 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 9938 // Set the beginning of the pair. 9939 First = Second) { 9940 9941 Second = &LoadedSlices[CurrSlice]; 9942 9943 // If First is NULL, it means we start a new pair. 9944 // Get to the next slice. 9945 if (!First) 9946 continue; 9947 9948 EVT LoadedType = First->getLoadedType(); 9949 9950 // If the types of the slices are different, we cannot pair them. 9951 if (LoadedType != Second->getLoadedType()) 9952 continue; 9953 9954 // Check if the target supplies paired loads for this type. 9955 unsigned RequiredAlignment = 0; 9956 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 9957 // move to the next pair, this type is hopeless. 9958 Second = nullptr; 9959 continue; 9960 } 9961 // Check if we meet the alignment requirement. 9962 if (RequiredAlignment > First->getAlignment()) 9963 continue; 9964 9965 // Check that both loads are next to each other in memory. 9966 if (!areSlicesNextToEachOther(*First, *Second)) 9967 continue; 9968 9969 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 9970 --GlobalLSCost.Loads; 9971 // Move to the next pair. 9972 Second = nullptr; 9973 } 9974 } 9975 9976 /// \brief Check the profitability of all involved LoadedSlice. 9977 /// Currently, it is considered profitable if there is exactly two 9978 /// involved slices (1) which are (2) next to each other in memory, and 9979 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 9980 /// 9981 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 9982 /// the elements themselves. 9983 /// 9984 /// FIXME: When the cost model will be mature enough, we can relax 9985 /// constraints (1) and (2). 9986 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9987 const APInt &UsedBits, bool ForCodeSize) { 9988 unsigned NumberOfSlices = LoadedSlices.size(); 9989 if (StressLoadSlicing) 9990 return NumberOfSlices > 1; 9991 9992 // Check (1). 9993 if (NumberOfSlices != 2) 9994 return false; 9995 9996 // Check (2). 9997 if (!areUsedBitsDense(UsedBits)) 9998 return false; 9999 10000 // Check (3). 10001 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 10002 // The original code has one big load. 10003 OrigCost.Loads = 1; 10004 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 10005 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 10006 // Accumulate the cost of all the slices. 10007 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 10008 GlobalSlicingCost += SliceCost; 10009 10010 // Account as cost in the original configuration the gain obtained 10011 // with the current slices. 10012 OrigCost.addSliceGain(LS); 10013 } 10014 10015 // If the target supports paired load, adjust the cost accordingly. 10016 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 10017 return OrigCost > GlobalSlicingCost; 10018 } 10019 10020 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 10021 /// operations, split it in the various pieces being extracted. 10022 /// 10023 /// This sort of thing is introduced by SROA. 10024 /// This slicing takes care not to insert overlapping loads. 10025 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 10026 bool DAGCombiner::SliceUpLoad(SDNode *N) { 10027 if (Level < AfterLegalizeDAG) 10028 return false; 10029 10030 LoadSDNode *LD = cast<LoadSDNode>(N); 10031 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 10032 !LD->getValueType(0).isInteger()) 10033 return false; 10034 10035 // Keep track of already used bits to detect overlapping values. 10036 // In that case, we will just abort the transformation. 10037 APInt UsedBits(LD->getValueSizeInBits(0), 0); 10038 10039 SmallVector<LoadedSlice, 4> LoadedSlices; 10040 10041 // Check if this load is used as several smaller chunks of bits. 10042 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 10043 // of computation for each trunc. 10044 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 10045 UI != UIEnd; ++UI) { 10046 // Skip the uses of the chain. 10047 if (UI.getUse().getResNo() != 0) 10048 continue; 10049 10050 SDNode *User = *UI; 10051 unsigned Shift = 0; 10052 10053 // Check if this is a trunc(lshr). 10054 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 10055 isa<ConstantSDNode>(User->getOperand(1))) { 10056 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 10057 User = *User->use_begin(); 10058 } 10059 10060 // At this point, User is a Truncate, iff we encountered, trunc or 10061 // trunc(lshr). 10062 if (User->getOpcode() != ISD::TRUNCATE) 10063 return false; 10064 10065 // The width of the type must be a power of 2 and greater than 8-bits. 10066 // Otherwise the load cannot be represented in LLVM IR. 10067 // Moreover, if we shifted with a non-8-bits multiple, the slice 10068 // will be across several bytes. We do not support that. 10069 unsigned Width = User->getValueSizeInBits(0); 10070 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 10071 return 0; 10072 10073 // Build the slice for this chain of computations. 10074 LoadedSlice LS(User, LD, Shift, &DAG); 10075 APInt CurrentUsedBits = LS.getUsedBits(); 10076 10077 // Check if this slice overlaps with another. 10078 if ((CurrentUsedBits & UsedBits) != 0) 10079 return false; 10080 // Update the bits used globally. 10081 UsedBits |= CurrentUsedBits; 10082 10083 // Check if the new slice would be legal. 10084 if (!LS.isLegal()) 10085 return false; 10086 10087 // Record the slice. 10088 LoadedSlices.push_back(LS); 10089 } 10090 10091 // Abort slicing if it does not seem to be profitable. 10092 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 10093 return false; 10094 10095 ++SlicedLoads; 10096 10097 // Rewrite each chain to use an independent load. 10098 // By construction, each chain can be represented by a unique load. 10099 10100 // Prepare the argument for the new token factor for all the slices. 10101 SmallVector<SDValue, 8> ArgChains; 10102 for (SmallVectorImpl<LoadedSlice>::const_iterator 10103 LSIt = LoadedSlices.begin(), 10104 LSItEnd = LoadedSlices.end(); 10105 LSIt != LSItEnd; ++LSIt) { 10106 SDValue SliceInst = LSIt->loadSlice(); 10107 CombineTo(LSIt->Inst, SliceInst, true); 10108 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 10109 SliceInst = SliceInst.getOperand(0); 10110 assert(SliceInst->getOpcode() == ISD::LOAD && 10111 "It takes more than a zext to get to the loaded slice!!"); 10112 ArgChains.push_back(SliceInst.getValue(1)); 10113 } 10114 10115 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 10116 ArgChains); 10117 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 10118 return true; 10119 } 10120 10121 /// Check to see if V is (and load (ptr), imm), where the load is having 10122 /// specific bytes cleared out. If so, return the byte size being masked out 10123 /// and the shift amount. 10124 static std::pair<unsigned, unsigned> 10125 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 10126 std::pair<unsigned, unsigned> Result(0, 0); 10127 10128 // Check for the structure we're looking for. 10129 if (V->getOpcode() != ISD::AND || 10130 !isa<ConstantSDNode>(V->getOperand(1)) || 10131 !ISD::isNormalLoad(V->getOperand(0).getNode())) 10132 return Result; 10133 10134 // Check the chain and pointer. 10135 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 10136 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 10137 10138 // The store should be chained directly to the load or be an operand of a 10139 // tokenfactor. 10140 if (LD == Chain.getNode()) 10141 ; // ok. 10142 else if (Chain->getOpcode() != ISD::TokenFactor) 10143 return Result; // Fail. 10144 else { 10145 bool isOk = false; 10146 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 10147 if (Chain->getOperand(i).getNode() == LD) { 10148 isOk = true; 10149 break; 10150 } 10151 if (!isOk) return Result; 10152 } 10153 10154 // This only handles simple types. 10155 if (V.getValueType() != MVT::i16 && 10156 V.getValueType() != MVT::i32 && 10157 V.getValueType() != MVT::i64) 10158 return Result; 10159 10160 // Check the constant mask. Invert it so that the bits being masked out are 10161 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 10162 // follow the sign bit for uniformity. 10163 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 10164 unsigned NotMaskLZ = countLeadingZeros(NotMask); 10165 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 10166 unsigned NotMaskTZ = countTrailingZeros(NotMask); 10167 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 10168 if (NotMaskLZ == 64) return Result; // All zero mask. 10169 10170 // See if we have a continuous run of bits. If so, we have 0*1+0* 10171 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 10172 return Result; 10173 10174 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 10175 if (V.getValueType() != MVT::i64 && NotMaskLZ) 10176 NotMaskLZ -= 64-V.getValueSizeInBits(); 10177 10178 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 10179 switch (MaskedBytes) { 10180 case 1: 10181 case 2: 10182 case 4: break; 10183 default: return Result; // All one mask, or 5-byte mask. 10184 } 10185 10186 // Verify that the first bit starts at a multiple of mask so that the access 10187 // is aligned the same as the access width. 10188 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 10189 10190 Result.first = MaskedBytes; 10191 Result.second = NotMaskTZ/8; 10192 return Result; 10193 } 10194 10195 10196 /// Check to see if IVal is something that provides a value as specified by 10197 /// MaskInfo. If so, replace the specified store with a narrower store of 10198 /// truncated IVal. 10199 static SDNode * 10200 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 10201 SDValue IVal, StoreSDNode *St, 10202 DAGCombiner *DC) { 10203 unsigned NumBytes = MaskInfo.first; 10204 unsigned ByteShift = MaskInfo.second; 10205 SelectionDAG &DAG = DC->getDAG(); 10206 10207 // Check to see if IVal is all zeros in the part being masked in by the 'or' 10208 // that uses this. If not, this is not a replacement. 10209 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 10210 ByteShift*8, (ByteShift+NumBytes)*8); 10211 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 10212 10213 // Check that it is legal on the target to do this. It is legal if the new 10214 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 10215 // legalization. 10216 MVT VT = MVT::getIntegerVT(NumBytes*8); 10217 if (!DC->isTypeLegal(VT)) 10218 return nullptr; 10219 10220 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 10221 // shifted by ByteShift and truncated down to NumBytes. 10222 if (ByteShift) { 10223 SDLoc DL(IVal); 10224 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 10225 DAG.getConstant(ByteShift*8, DL, 10226 DC->getShiftAmountTy(IVal.getValueType()))); 10227 } 10228 10229 // Figure out the offset for the store and the alignment of the access. 10230 unsigned StOffset; 10231 unsigned NewAlign = St->getAlignment(); 10232 10233 if (DAG.getTargetLoweringInfo().isLittleEndian()) 10234 StOffset = ByteShift; 10235 else 10236 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 10237 10238 SDValue Ptr = St->getBasePtr(); 10239 if (StOffset) { 10240 SDLoc DL(IVal); 10241 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 10242 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 10243 NewAlign = MinAlign(NewAlign, StOffset); 10244 } 10245 10246 // Truncate down to the new size. 10247 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 10248 10249 ++OpsNarrowed; 10250 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 10251 St->getPointerInfo().getWithOffset(StOffset), 10252 false, false, NewAlign).getNode(); 10253 } 10254 10255 10256 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 10257 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 10258 /// narrowing the load and store if it would end up being a win for performance 10259 /// or code size. 10260 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 10261 StoreSDNode *ST = cast<StoreSDNode>(N); 10262 if (ST->isVolatile()) 10263 return SDValue(); 10264 10265 SDValue Chain = ST->getChain(); 10266 SDValue Value = ST->getValue(); 10267 SDValue Ptr = ST->getBasePtr(); 10268 EVT VT = Value.getValueType(); 10269 10270 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 10271 return SDValue(); 10272 10273 unsigned Opc = Value.getOpcode(); 10274 10275 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 10276 // is a byte mask indicating a consecutive number of bytes, check to see if 10277 // Y is known to provide just those bytes. If so, we try to replace the 10278 // load + replace + store sequence with a single (narrower) store, which makes 10279 // the load dead. 10280 if (Opc == ISD::OR) { 10281 std::pair<unsigned, unsigned> MaskedLoad; 10282 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 10283 if (MaskedLoad.first) 10284 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10285 Value.getOperand(1), ST,this)) 10286 return SDValue(NewST, 0); 10287 10288 // Or is commutative, so try swapping X and Y. 10289 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 10290 if (MaskedLoad.first) 10291 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 10292 Value.getOperand(0), ST,this)) 10293 return SDValue(NewST, 0); 10294 } 10295 10296 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 10297 Value.getOperand(1).getOpcode() != ISD::Constant) 10298 return SDValue(); 10299 10300 SDValue N0 = Value.getOperand(0); 10301 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10302 Chain == SDValue(N0.getNode(), 1)) { 10303 LoadSDNode *LD = cast<LoadSDNode>(N0); 10304 if (LD->getBasePtr() != Ptr || 10305 LD->getPointerInfo().getAddrSpace() != 10306 ST->getPointerInfo().getAddrSpace()) 10307 return SDValue(); 10308 10309 // Find the type to narrow it the load / op / store to. 10310 SDValue N1 = Value.getOperand(1); 10311 unsigned BitWidth = N1.getValueSizeInBits(); 10312 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 10313 if (Opc == ISD::AND) 10314 Imm ^= APInt::getAllOnesValue(BitWidth); 10315 if (Imm == 0 || Imm.isAllOnesValue()) 10316 return SDValue(); 10317 unsigned ShAmt = Imm.countTrailingZeros(); 10318 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 10319 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 10320 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10321 // The narrowing should be profitable, the load/store operation should be 10322 // legal (or custom) and the store size should be equal to the NewVT width. 10323 while (NewBW < BitWidth && 10324 (NewVT.getStoreSizeInBits() != NewBW || 10325 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 10326 !TLI.isNarrowingProfitable(VT, NewVT))) { 10327 NewBW = NextPowerOf2(NewBW); 10328 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 10329 } 10330 if (NewBW >= BitWidth) 10331 return SDValue(); 10332 10333 // If the lsb changed does not start at the type bitwidth boundary, 10334 // start at the previous one. 10335 if (ShAmt % NewBW) 10336 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 10337 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 10338 std::min(BitWidth, ShAmt + NewBW)); 10339 if ((Imm & Mask) == Imm) { 10340 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 10341 if (Opc == ISD::AND) 10342 NewImm ^= APInt::getAllOnesValue(NewBW); 10343 uint64_t PtrOff = ShAmt / 8; 10344 // For big endian targets, we need to adjust the offset to the pointer to 10345 // load the correct bytes. 10346 if (TLI.isBigEndian()) 10347 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 10348 10349 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 10350 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 10351 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 10352 return SDValue(); 10353 10354 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 10355 Ptr.getValueType(), Ptr, 10356 DAG.getConstant(PtrOff, SDLoc(LD), 10357 Ptr.getValueType())); 10358 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 10359 LD->getChain(), NewPtr, 10360 LD->getPointerInfo().getWithOffset(PtrOff), 10361 LD->isVolatile(), LD->isNonTemporal(), 10362 LD->isInvariant(), NewAlign, 10363 LD->getAAInfo()); 10364 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 10365 DAG.getConstant(NewImm, SDLoc(Value), 10366 NewVT)); 10367 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 10368 NewVal, NewPtr, 10369 ST->getPointerInfo().getWithOffset(PtrOff), 10370 false, false, NewAlign); 10371 10372 AddToWorklist(NewPtr.getNode()); 10373 AddToWorklist(NewLD.getNode()); 10374 AddToWorklist(NewVal.getNode()); 10375 WorklistRemover DeadNodes(*this); 10376 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 10377 ++OpsNarrowed; 10378 return NewST; 10379 } 10380 } 10381 10382 return SDValue(); 10383 } 10384 10385 /// For a given floating point load / store pair, if the load value isn't used 10386 /// by any other operations, then consider transforming the pair to integer 10387 /// load / store operations if the target deems the transformation profitable. 10388 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 10389 StoreSDNode *ST = cast<StoreSDNode>(N); 10390 SDValue Chain = ST->getChain(); 10391 SDValue Value = ST->getValue(); 10392 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 10393 Value.hasOneUse() && 10394 Chain == SDValue(Value.getNode(), 1)) { 10395 LoadSDNode *LD = cast<LoadSDNode>(Value); 10396 EVT VT = LD->getMemoryVT(); 10397 if (!VT.isFloatingPoint() || 10398 VT != ST->getMemoryVT() || 10399 LD->isNonTemporal() || 10400 ST->isNonTemporal() || 10401 LD->getPointerInfo().getAddrSpace() != 0 || 10402 ST->getPointerInfo().getAddrSpace() != 0) 10403 return SDValue(); 10404 10405 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 10406 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 10407 !TLI.isOperationLegal(ISD::STORE, IntVT) || 10408 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 10409 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 10410 return SDValue(); 10411 10412 unsigned LDAlign = LD->getAlignment(); 10413 unsigned STAlign = ST->getAlignment(); 10414 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 10415 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 10416 if (LDAlign < ABIAlign || STAlign < ABIAlign) 10417 return SDValue(); 10418 10419 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 10420 LD->getChain(), LD->getBasePtr(), 10421 LD->getPointerInfo(), 10422 false, false, false, LDAlign); 10423 10424 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 10425 NewLD, ST->getBasePtr(), 10426 ST->getPointerInfo(), 10427 false, false, STAlign); 10428 10429 AddToWorklist(NewLD.getNode()); 10430 AddToWorklist(NewST.getNode()); 10431 WorklistRemover DeadNodes(*this); 10432 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 10433 ++LdStFP2Int; 10434 return NewST; 10435 } 10436 10437 return SDValue(); 10438 } 10439 10440 namespace { 10441 /// Helper struct to parse and store a memory address as base + index + offset. 10442 /// We ignore sign extensions when it is safe to do so. 10443 /// The following two expressions are not equivalent. To differentiate we need 10444 /// to store whether there was a sign extension involved in the index 10445 /// computation. 10446 /// (load (i64 add (i64 copyfromreg %c) 10447 /// (i64 signextend (add (i8 load %index) 10448 /// (i8 1)))) 10449 /// vs 10450 /// 10451 /// (load (i64 add (i64 copyfromreg %c) 10452 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 10453 /// (i32 1))))) 10454 struct BaseIndexOffset { 10455 SDValue Base; 10456 SDValue Index; 10457 int64_t Offset; 10458 bool IsIndexSignExt; 10459 10460 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 10461 10462 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 10463 bool IsIndexSignExt) : 10464 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 10465 10466 bool equalBaseIndex(const BaseIndexOffset &Other) { 10467 return Other.Base == Base && Other.Index == Index && 10468 Other.IsIndexSignExt == IsIndexSignExt; 10469 } 10470 10471 /// Parses tree in Ptr for base, index, offset addresses. 10472 static BaseIndexOffset match(SDValue Ptr) { 10473 bool IsIndexSignExt = false; 10474 10475 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 10476 // instruction, then it could be just the BASE or everything else we don't 10477 // know how to handle. Just use Ptr as BASE and give up. 10478 if (Ptr->getOpcode() != ISD::ADD) 10479 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10480 10481 // We know that we have at least an ADD instruction. Try to pattern match 10482 // the simple case of BASE + OFFSET. 10483 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 10484 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 10485 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 10486 IsIndexSignExt); 10487 } 10488 10489 // Inside a loop the current BASE pointer is calculated using an ADD and a 10490 // MUL instruction. In this case Ptr is the actual BASE pointer. 10491 // (i64 add (i64 %array_ptr) 10492 // (i64 mul (i64 %induction_var) 10493 // (i64 %element_size))) 10494 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 10495 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10496 10497 // Look at Base + Index + Offset cases. 10498 SDValue Base = Ptr->getOperand(0); 10499 SDValue IndexOffset = Ptr->getOperand(1); 10500 10501 // Skip signextends. 10502 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 10503 IndexOffset = IndexOffset->getOperand(0); 10504 IsIndexSignExt = true; 10505 } 10506 10507 // Either the case of Base + Index (no offset) or something else. 10508 if (IndexOffset->getOpcode() != ISD::ADD) 10509 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 10510 10511 // Now we have the case of Base + Index + offset. 10512 SDValue Index = IndexOffset->getOperand(0); 10513 SDValue Offset = IndexOffset->getOperand(1); 10514 10515 if (!isa<ConstantSDNode>(Offset)) 10516 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 10517 10518 // Ignore signextends. 10519 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 10520 Index = Index->getOperand(0); 10521 IsIndexSignExt = true; 10522 } else IsIndexSignExt = false; 10523 10524 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 10525 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 10526 } 10527 }; 10528 } // namespace 10529 10530 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 10531 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 10532 unsigned NumElem, bool IsConstantSrc, bool UseVector) { 10533 // Make sure we have something to merge. 10534 if (NumElem < 2) 10535 return false; 10536 10537 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 10538 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10539 unsigned LatestNodeUsed = 0; 10540 10541 for (unsigned i=0; i < NumElem; ++i) { 10542 // Find a chain for the new wide-store operand. Notice that some 10543 // of the store nodes that we found may not be selected for inclusion 10544 // in the wide store. The chain we use needs to be the chain of the 10545 // latest store node which is *used* and replaced by the wide store. 10546 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 10547 LatestNodeUsed = i; 10548 } 10549 10550 // The latest Node in the DAG. 10551 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 10552 SDLoc DL(StoreNodes[0].MemNode); 10553 10554 SDValue StoredVal; 10555 if (UseVector) { 10556 // Find a legal type for the vector store. 10557 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 10558 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 10559 if (IsConstantSrc) { 10560 // A vector store with a constant source implies that the constant is 10561 // zero; we only handle merging stores of constant zeros because the zero 10562 // can be materialized without a load. 10563 // It may be beneficial to loosen this restriction to allow non-zero 10564 // store merging. 10565 StoredVal = DAG.getConstant(0, DL, Ty); 10566 } else { 10567 SmallVector<SDValue, 8> Ops; 10568 for (unsigned i = 0; i < NumElem ; ++i) { 10569 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10570 SDValue Val = St->getValue(); 10571 // All of the operands of a BUILD_VECTOR must have the same type. 10572 if (Val.getValueType() != MemVT) 10573 return false; 10574 Ops.push_back(Val); 10575 } 10576 10577 // Build the extracted vector elements back into a vector. 10578 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops); 10579 } 10580 } else { 10581 // We should always use a vector store when merging extracted vector 10582 // elements, so this path implies a store of constants. 10583 assert(IsConstantSrc && "Merged vector elements should use vector store"); 10584 10585 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 10586 APInt StoreInt(StoreBW, 0); 10587 10588 // Construct a single integer constant which is made of the smaller 10589 // constant inputs. 10590 bool IsLE = TLI.isLittleEndian(); 10591 for (unsigned i = 0; i < NumElem ; ++i) { 10592 unsigned Idx = IsLE ? (NumElem - 1 - i) : i; 10593 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 10594 SDValue Val = St->getValue(); 10595 StoreInt <<= ElementSizeBytes*8; 10596 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 10597 StoreInt |= C->getAPIntValue().zext(StoreBW); 10598 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 10599 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 10600 } else { 10601 llvm_unreachable("Invalid constant element type"); 10602 } 10603 } 10604 10605 // Create the new Load and Store operations. 10606 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10607 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 10608 } 10609 10610 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal, 10611 FirstInChain->getBasePtr(), 10612 FirstInChain->getPointerInfo(), 10613 false, false, 10614 FirstInChain->getAlignment()); 10615 10616 // Replace the last store with the new store 10617 CombineTo(LatestOp, NewStore); 10618 // Erase all other stores. 10619 for (unsigned i = 0; i < NumElem ; ++i) { 10620 if (StoreNodes[i].MemNode == LatestOp) 10621 continue; 10622 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10623 // ReplaceAllUsesWith will replace all uses that existed when it was 10624 // called, but graph optimizations may cause new ones to appear. For 10625 // example, the case in pr14333 looks like 10626 // 10627 // St's chain -> St -> another store -> X 10628 // 10629 // And the only difference from St to the other store is the chain. 10630 // When we change it's chain to be St's chain they become identical, 10631 // get CSEed and the net result is that X is now a use of St. 10632 // Since we know that St is redundant, just iterate. 10633 while (!St->use_empty()) 10634 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 10635 deleteAndRecombine(St); 10636 } 10637 10638 return true; 10639 } 10640 10641 static bool allowableAlignment(const SelectionDAG &DAG, 10642 const TargetLowering &TLI, EVT EVTTy, 10643 unsigned AS, unsigned Align) { 10644 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align)) 10645 return true; 10646 10647 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext()); 10648 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty); 10649 return (Align >= ABIAlignment); 10650 } 10651 10652 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 10653 if (OptLevel == CodeGenOpt::None) 10654 return false; 10655 10656 EVT MemVT = St->getMemoryVT(); 10657 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 10658 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute( 10659 Attribute::NoImplicitFloat); 10660 10661 // This function cannot currently deal with non-byte-sized memory sizes. 10662 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 10663 return false; 10664 10665 // Don't merge vectors into wider inputs. 10666 if (MemVT.isVector() || !MemVT.isSimple()) 10667 return false; 10668 10669 // Perform an early exit check. Do not bother looking at stored values that 10670 // are not constants, loads, or extracted vector elements. 10671 SDValue StoredVal = St->getValue(); 10672 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 10673 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 10674 isa<ConstantFPSDNode>(StoredVal); 10675 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT); 10676 10677 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc) 10678 return false; 10679 10680 // Only look at ends of store sequences. 10681 SDValue Chain = SDValue(St, 0); 10682 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 10683 return false; 10684 10685 // This holds the base pointer, index, and the offset in bytes from the base 10686 // pointer. 10687 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 10688 10689 // We must have a base and an offset. 10690 if (!BasePtr.Base.getNode()) 10691 return false; 10692 10693 // Do not handle stores to undef base pointers. 10694 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 10695 return false; 10696 10697 // Save the LoadSDNodes that we find in the chain. 10698 // We need to make sure that these nodes do not interfere with 10699 // any of the store nodes. 10700 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 10701 10702 // Save the StoreSDNodes that we find in the chain. 10703 SmallVector<MemOpLink, 8> StoreNodes; 10704 10705 // Walk up the chain and look for nodes with offsets from the same 10706 // base pointer. Stop when reaching an instruction with a different kind 10707 // or instruction which has a different base pointer. 10708 unsigned Seq = 0; 10709 StoreSDNode *Index = St; 10710 while (Index) { 10711 // If the chain has more than one use, then we can't reorder the mem ops. 10712 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 10713 break; 10714 10715 // Find the base pointer and offset for this memory node. 10716 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 10717 10718 // Check that the base pointer is the same as the original one. 10719 if (!Ptr.equalBaseIndex(BasePtr)) 10720 break; 10721 10722 // The memory operands must not be volatile. 10723 if (Index->isVolatile() || Index->isIndexed()) 10724 break; 10725 10726 // No truncation. 10727 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 10728 if (St->isTruncatingStore()) 10729 break; 10730 10731 // The stored memory type must be the same. 10732 if (Index->getMemoryVT() != MemVT) 10733 break; 10734 10735 // We found a potential memory operand to merge. 10736 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 10737 10738 // Find the next memory operand in the chain. If the next operand in the 10739 // chain is a store then move up and continue the scan with the next 10740 // memory operand. If the next operand is a load save it and use alias 10741 // information to check if it interferes with anything. 10742 SDNode *NextInChain = Index->getChain().getNode(); 10743 while (1) { 10744 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 10745 // We found a store node. Use it for the next iteration. 10746 Index = STn; 10747 break; 10748 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 10749 if (Ldn->isVolatile()) { 10750 Index = nullptr; 10751 break; 10752 } 10753 10754 // Save the load node for later. Continue the scan. 10755 AliasLoadNodes.push_back(Ldn); 10756 NextInChain = Ldn->getChain().getNode(); 10757 continue; 10758 } else { 10759 Index = nullptr; 10760 break; 10761 } 10762 } 10763 } 10764 10765 // Check if there is anything to merge. 10766 if (StoreNodes.size() < 2) 10767 return false; 10768 10769 // Sort the memory operands according to their distance from the base pointer. 10770 std::sort(StoreNodes.begin(), StoreNodes.end(), 10771 [](MemOpLink LHS, MemOpLink RHS) { 10772 return LHS.OffsetFromBase < RHS.OffsetFromBase || 10773 (LHS.OffsetFromBase == RHS.OffsetFromBase && 10774 LHS.SequenceNum > RHS.SequenceNum); 10775 }); 10776 10777 // Scan the memory operations on the chain and find the first non-consecutive 10778 // store memory address. 10779 unsigned LastConsecutiveStore = 0; 10780 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 10781 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 10782 10783 // Check that the addresses are consecutive starting from the second 10784 // element in the list of stores. 10785 if (i > 0) { 10786 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 10787 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10788 break; 10789 } 10790 10791 bool Alias = false; 10792 // Check if this store interferes with any of the loads that we found. 10793 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 10794 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 10795 Alias = true; 10796 break; 10797 } 10798 // We found a load that alias with this store. Stop the sequence. 10799 if (Alias) 10800 break; 10801 10802 // Mark this node as useful. 10803 LastConsecutiveStore = i; 10804 } 10805 10806 // The node with the lowest store address. 10807 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10808 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 10809 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 10810 10811 // Store the constants into memory as one consecutive store. 10812 if (IsConstantSrc) { 10813 unsigned LastLegalType = 0; 10814 unsigned LastLegalVectorType = 0; 10815 bool NonZero = false; 10816 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10817 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10818 SDValue StoredVal = St->getValue(); 10819 10820 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 10821 NonZero |= !C->isNullValue(); 10822 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 10823 NonZero |= !C->getConstantFPValue()->isNullValue(); 10824 } else { 10825 // Non-constant. 10826 break; 10827 } 10828 10829 // Find a legal type for the constant store. 10830 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10831 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10832 if (TLI.isTypeLegal(StoreTy) && 10833 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, 10834 FirstStoreAlign)) { 10835 LastLegalType = i+1; 10836 // Or check whether a truncstore is legal. 10837 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10838 TargetLowering::TypePromoteInteger) { 10839 EVT LegalizedStoredValueTy = 10840 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 10841 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 10842 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS, 10843 FirstStoreAlign)) { 10844 LastLegalType = i + 1; 10845 } 10846 } 10847 10848 // Find a legal type for the vector store. 10849 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10850 if (TLI.isTypeLegal(Ty) && 10851 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) { 10852 LastLegalVectorType = i + 1; 10853 } 10854 } 10855 10856 // We only use vectors if the constant is known to be zero and the 10857 // function is not marked with the noimplicitfloat attribute. 10858 if (NonZero || NoVectors) 10859 LastLegalVectorType = 0; 10860 10861 // Check if we found a legal integer type to store. 10862 if (LastLegalType == 0 && LastLegalVectorType == 0) 10863 return false; 10864 10865 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 10866 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 10867 10868 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10869 true, UseVector); 10870 } 10871 10872 // When extracting multiple vector elements, try to store them 10873 // in one vector store rather than a sequence of scalar stores. 10874 if (IsExtractVecEltSrc) { 10875 unsigned NumElem = 0; 10876 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 10877 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10878 SDValue StoredVal = St->getValue(); 10879 // This restriction could be loosened. 10880 // Bail out if any stored values are not elements extracted from a vector. 10881 // It should be possible to handle mixed sources, but load sources need 10882 // more careful handling (see the block of code below that handles 10883 // consecutive loads). 10884 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10885 return false; 10886 10887 // Find a legal type for the vector store. 10888 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10889 if (TLI.isTypeLegal(Ty) && 10890 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) 10891 NumElem = i + 1; 10892 } 10893 10894 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10895 false, true); 10896 } 10897 10898 // Below we handle the case of multiple consecutive stores that 10899 // come from multiple consecutive loads. We merge them into a single 10900 // wide load and a single wide store. 10901 10902 // Look for load nodes which are used by the stored values. 10903 SmallVector<MemOpLink, 8> LoadNodes; 10904 10905 // Find acceptable loads. Loads need to have the same chain (token factor), 10906 // must not be zext, volatile, indexed, and they must be consecutive. 10907 BaseIndexOffset LdBasePtr; 10908 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10909 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10910 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 10911 if (!Ld) break; 10912 10913 // Loads must only have one use. 10914 if (!Ld->hasNUsesOfValue(1, 0)) 10915 break; 10916 10917 // The memory operands must not be volatile. 10918 if (Ld->isVolatile() || Ld->isIndexed()) 10919 break; 10920 10921 // We do not accept ext loads. 10922 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 10923 break; 10924 10925 // The stored memory type must be the same. 10926 if (Ld->getMemoryVT() != MemVT) 10927 break; 10928 10929 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 10930 // If this is not the first ptr that we check. 10931 if (LdBasePtr.Base.getNode()) { 10932 // The base ptr must be the same. 10933 if (!LdPtr.equalBaseIndex(LdBasePtr)) 10934 break; 10935 } else { 10936 // Check that all other base pointers are the same as this one. 10937 LdBasePtr = LdPtr; 10938 } 10939 10940 // We found a potential memory operand to merge. 10941 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 10942 } 10943 10944 if (LoadNodes.size() < 2) 10945 return false; 10946 10947 // If we have load/store pair instructions and we only have two values, 10948 // don't bother. 10949 unsigned RequiredAlignment; 10950 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 10951 St->getAlignment() >= RequiredAlignment) 10952 return false; 10953 10954 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 10955 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 10956 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 10957 10958 // Scan the memory operations on the chain and find the first non-consecutive 10959 // load memory address. These variables hold the index in the store node 10960 // array. 10961 unsigned LastConsecutiveLoad = 0; 10962 // This variable refers to the size and not index in the array. 10963 unsigned LastLegalVectorType = 0; 10964 unsigned LastLegalIntegerType = 0; 10965 StartAddress = LoadNodes[0].OffsetFromBase; 10966 SDValue FirstChain = FirstLoad->getChain(); 10967 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 10968 // All loads much share the same chain. 10969 if (LoadNodes[i].MemNode->getChain() != FirstChain) 10970 break; 10971 10972 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 10973 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10974 break; 10975 LastConsecutiveLoad = i; 10976 10977 // Find a legal type for the vector store. 10978 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10979 if (TLI.isTypeLegal(StoreTy) && 10980 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) && 10981 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) { 10982 LastLegalVectorType = i + 1; 10983 } 10984 10985 // Find a legal type for the integer store. 10986 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10987 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10988 if (TLI.isTypeLegal(StoreTy) && 10989 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) && 10990 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) 10991 LastLegalIntegerType = i + 1; 10992 // Or check whether a truncstore and extload is legal. 10993 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10994 TargetLowering::TypePromoteInteger) { 10995 EVT LegalizedStoredValueTy = 10996 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 10997 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 10998 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10999 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 11000 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) && 11001 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS, 11002 FirstStoreAlign) && 11003 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS, 11004 FirstLoadAlign)) 11005 LastLegalIntegerType = i+1; 11006 } 11007 } 11008 11009 // Only use vector types if the vector type is larger than the integer type. 11010 // If they are the same, use integers. 11011 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 11012 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 11013 11014 // We add +1 here because the LastXXX variables refer to location while 11015 // the NumElem refers to array/index size. 11016 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 11017 NumElem = std::min(LastLegalType, NumElem); 11018 11019 if (NumElem < 2) 11020 return false; 11021 11022 // The latest Node in the DAG. 11023 unsigned LatestNodeUsed = 0; 11024 for (unsigned i=1; i<NumElem; ++i) { 11025 // Find a chain for the new wide-store operand. Notice that some 11026 // of the store nodes that we found may not be selected for inclusion 11027 // in the wide store. The chain we use needs to be the chain of the 11028 // latest store node which is *used* and replaced by the wide store. 11029 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum) 11030 LatestNodeUsed = i; 11031 } 11032 11033 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode; 11034 11035 // Find if it is better to use vectors or integers to load and store 11036 // to memory. 11037 EVT JointMemOpVT; 11038 if (UseVectorTy) { 11039 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 11040 } else { 11041 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 11042 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 11043 } 11044 11045 SDLoc LoadDL(LoadNodes[0].MemNode); 11046 SDLoc StoreDL(StoreNodes[0].MemNode); 11047 11048 SDValue NewLoad = DAG.getLoad( 11049 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 11050 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign); 11051 11052 SDValue NewStore = DAG.getStore( 11053 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(), 11054 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign); 11055 11056 // Replace one of the loads with the new load. 11057 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 11058 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 11059 SDValue(NewLoad.getNode(), 1)); 11060 11061 // Remove the rest of the load chains. 11062 for (unsigned i = 1; i < NumElem ; ++i) { 11063 // Replace all chain users of the old load nodes with the chain of the new 11064 // load node. 11065 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 11066 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 11067 } 11068 11069 // Replace the last store with the new store. 11070 CombineTo(LatestOp, NewStore); 11071 // Erase all other stores. 11072 for (unsigned i = 0; i < NumElem ; ++i) { 11073 // Remove all Store nodes. 11074 if (StoreNodes[i].MemNode == LatestOp) 11075 continue; 11076 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 11077 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 11078 deleteAndRecombine(St); 11079 } 11080 11081 return true; 11082 } 11083 11084 SDValue DAGCombiner::visitSTORE(SDNode *N) { 11085 StoreSDNode *ST = cast<StoreSDNode>(N); 11086 SDValue Chain = ST->getChain(); 11087 SDValue Value = ST->getValue(); 11088 SDValue Ptr = ST->getBasePtr(); 11089 11090 // If this is a store of a bit convert, store the input value if the 11091 // resultant store does not need a higher alignment than the original. 11092 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 11093 ST->isUnindexed()) { 11094 unsigned OrigAlign = ST->getAlignment(); 11095 EVT SVT = Value.getOperand(0).getValueType(); 11096 unsigned Align = TLI.getDataLayout()-> 11097 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 11098 if (Align <= OrigAlign && 11099 ((!LegalOperations && !ST->isVolatile()) || 11100 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 11101 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 11102 Ptr, ST->getPointerInfo(), ST->isVolatile(), 11103 ST->isNonTemporal(), OrigAlign, 11104 ST->getAAInfo()); 11105 } 11106 11107 // Turn 'store undef, Ptr' -> nothing. 11108 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 11109 return Chain; 11110 11111 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 11112 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 11113 // NOTE: If the original store is volatile, this transform must not increase 11114 // the number of stores. For example, on x86-32 an f64 can be stored in one 11115 // processor operation but an i64 (which is not legal) requires two. So the 11116 // transform should not be done in this case. 11117 if (Value.getOpcode() != ISD::TargetConstantFP) { 11118 SDValue Tmp; 11119 switch (CFP->getSimpleValueType(0).SimpleTy) { 11120 default: llvm_unreachable("Unknown FP type"); 11121 case MVT::f16: // We don't do this for these yet. 11122 case MVT::f80: 11123 case MVT::f128: 11124 case MVT::ppcf128: 11125 break; 11126 case MVT::f32: 11127 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 11128 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11129 ; 11130 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 11131 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 11132 MVT::i32); 11133 return DAG.getStore(Chain, SDLoc(N), Tmp, 11134 Ptr, ST->getMemOperand()); 11135 } 11136 break; 11137 case MVT::f64: 11138 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 11139 !ST->isVolatile()) || 11140 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 11141 ; 11142 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 11143 getZExtValue(), SDLoc(CFP), MVT::i64); 11144 return DAG.getStore(Chain, SDLoc(N), Tmp, 11145 Ptr, ST->getMemOperand()); 11146 } 11147 11148 if (!ST->isVolatile() && 11149 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 11150 // Many FP stores are not made apparent until after legalize, e.g. for 11151 // argument passing. Since this is so common, custom legalize the 11152 // 64-bit integer store into two 32-bit stores. 11153 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 11154 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 11155 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 11156 if (TLI.isBigEndian()) std::swap(Lo, Hi); 11157 11158 unsigned Alignment = ST->getAlignment(); 11159 bool isVolatile = ST->isVolatile(); 11160 bool isNonTemporal = ST->isNonTemporal(); 11161 AAMDNodes AAInfo = ST->getAAInfo(); 11162 11163 SDLoc DL(N); 11164 11165 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 11166 Ptr, ST->getPointerInfo(), 11167 isVolatile, isNonTemporal, 11168 ST->getAlignment(), AAInfo); 11169 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 11170 DAG.getConstant(4, DL, Ptr.getValueType())); 11171 Alignment = MinAlign(Alignment, 4U); 11172 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 11173 Ptr, ST->getPointerInfo().getWithOffset(4), 11174 isVolatile, isNonTemporal, 11175 Alignment, AAInfo); 11176 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 11177 St0, St1); 11178 } 11179 11180 break; 11181 } 11182 } 11183 } 11184 11185 // Try to infer better alignment information than the store already has. 11186 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 11187 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 11188 if (Align > ST->getAlignment()) { 11189 SDValue NewStore = 11190 DAG.getTruncStore(Chain, SDLoc(N), Value, 11191 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 11192 ST->isVolatile(), ST->isNonTemporal(), Align, 11193 ST->getAAInfo()); 11194 if (NewStore.getNode() != N) 11195 return CombineTo(ST, NewStore, true); 11196 } 11197 } 11198 } 11199 11200 // Try transforming a pair floating point load / store ops to integer 11201 // load / store ops. 11202 SDValue NewST = TransformFPLoadStorePair(N); 11203 if (NewST.getNode()) 11204 return NewST; 11205 11206 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 11207 : DAG.getSubtarget().useAA(); 11208 #ifndef NDEBUG 11209 if (CombinerAAOnlyFunc.getNumOccurrences() && 11210 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 11211 UseAA = false; 11212 #endif 11213 if (UseAA && ST->isUnindexed()) { 11214 // Walk up chain skipping non-aliasing memory nodes. 11215 SDValue BetterChain = FindBetterChain(N, Chain); 11216 11217 // If there is a better chain. 11218 if (Chain != BetterChain) { 11219 SDValue ReplStore; 11220 11221 // Replace the chain to avoid dependency. 11222 if (ST->isTruncatingStore()) { 11223 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 11224 ST->getMemoryVT(), ST->getMemOperand()); 11225 } else { 11226 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 11227 ST->getMemOperand()); 11228 } 11229 11230 // Create token to keep both nodes around. 11231 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 11232 MVT::Other, Chain, ReplStore); 11233 11234 // Make sure the new and old chains are cleaned up. 11235 AddToWorklist(Token.getNode()); 11236 11237 // Don't add users to work list. 11238 return CombineTo(N, Token, false); 11239 } 11240 } 11241 11242 // Try transforming N to an indexed store. 11243 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 11244 return SDValue(N, 0); 11245 11246 // FIXME: is there such a thing as a truncating indexed store? 11247 if (ST->isTruncatingStore() && ST->isUnindexed() && 11248 Value.getValueType().isInteger()) { 11249 // See if we can simplify the input to this truncstore with knowledge that 11250 // only the low bits are being used. For example: 11251 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 11252 SDValue Shorter = 11253 GetDemandedBits(Value, 11254 APInt::getLowBitsSet( 11255 Value.getValueType().getScalarType().getSizeInBits(), 11256 ST->getMemoryVT().getScalarType().getSizeInBits())); 11257 AddToWorklist(Value.getNode()); 11258 if (Shorter.getNode()) 11259 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 11260 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11261 11262 // Otherwise, see if we can simplify the operation with 11263 // SimplifyDemandedBits, which only works if the value has a single use. 11264 if (SimplifyDemandedBits(Value, 11265 APInt::getLowBitsSet( 11266 Value.getValueType().getScalarType().getSizeInBits(), 11267 ST->getMemoryVT().getScalarType().getSizeInBits()))) 11268 return SDValue(N, 0); 11269 } 11270 11271 // If this is a load followed by a store to the same location, then the store 11272 // is dead/noop. 11273 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 11274 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 11275 ST->isUnindexed() && !ST->isVolatile() && 11276 // There can't be any side effects between the load and store, such as 11277 // a call or store. 11278 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 11279 // The store is dead, remove it. 11280 return Chain; 11281 } 11282 } 11283 11284 // If this is a store followed by a store with the same value to the same 11285 // location, then the store is dead/noop. 11286 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 11287 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 11288 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 11289 ST1->isUnindexed() && !ST1->isVolatile()) { 11290 // The store is dead, remove it. 11291 return Chain; 11292 } 11293 } 11294 11295 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 11296 // truncating store. We can do this even if this is already a truncstore. 11297 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 11298 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 11299 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 11300 ST->getMemoryVT())) { 11301 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 11302 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 11303 } 11304 11305 // Only perform this optimization before the types are legal, because we 11306 // don't want to perform this optimization on every DAGCombine invocation. 11307 if (!LegalTypes) { 11308 bool EverChanged = false; 11309 11310 do { 11311 // There can be multiple store sequences on the same chain. 11312 // Keep trying to merge store sequences until we are unable to do so 11313 // or until we merge the last store on the chain. 11314 bool Changed = MergeConsecutiveStores(ST); 11315 EverChanged |= Changed; 11316 if (!Changed) break; 11317 } while (ST->getOpcode() != ISD::DELETED_NODE); 11318 11319 if (EverChanged) 11320 return SDValue(N, 0); 11321 } 11322 11323 return ReduceLoadOpStoreWidth(N); 11324 } 11325 11326 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 11327 SDValue InVec = N->getOperand(0); 11328 SDValue InVal = N->getOperand(1); 11329 SDValue EltNo = N->getOperand(2); 11330 SDLoc dl(N); 11331 11332 // If the inserted element is an UNDEF, just use the input vector. 11333 if (InVal.getOpcode() == ISD::UNDEF) 11334 return InVec; 11335 11336 EVT VT = InVec.getValueType(); 11337 11338 // If we can't generate a legal BUILD_VECTOR, exit 11339 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 11340 return SDValue(); 11341 11342 // Check that we know which element is being inserted 11343 if (!isa<ConstantSDNode>(EltNo)) 11344 return SDValue(); 11345 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11346 11347 // Canonicalize insert_vector_elt dag nodes. 11348 // Example: 11349 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 11350 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 11351 // 11352 // Do this only if the child insert_vector node has one use; also 11353 // do this only if indices are both constants and Idx1 < Idx0. 11354 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 11355 && isa<ConstantSDNode>(InVec.getOperand(2))) { 11356 unsigned OtherElt = 11357 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 11358 if (Elt < OtherElt) { 11359 // Swap nodes. 11360 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 11361 InVec.getOperand(0), InVal, EltNo); 11362 AddToWorklist(NewOp.getNode()); 11363 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 11364 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 11365 } 11366 } 11367 11368 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 11369 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 11370 // vector elements. 11371 SmallVector<SDValue, 8> Ops; 11372 // Do not combine these two vectors if the output vector will not replace 11373 // the input vector. 11374 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 11375 Ops.append(InVec.getNode()->op_begin(), 11376 InVec.getNode()->op_end()); 11377 } else if (InVec.getOpcode() == ISD::UNDEF) { 11378 unsigned NElts = VT.getVectorNumElements(); 11379 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 11380 } else { 11381 return SDValue(); 11382 } 11383 11384 // Insert the element 11385 if (Elt < Ops.size()) { 11386 // All the operands of BUILD_VECTOR must have the same type; 11387 // we enforce that here. 11388 EVT OpVT = Ops[0].getValueType(); 11389 if (InVal.getValueType() != OpVT) 11390 InVal = OpVT.bitsGT(InVal.getValueType()) ? 11391 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 11392 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 11393 Ops[Elt] = InVal; 11394 } 11395 11396 // Return the new vector 11397 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 11398 } 11399 11400 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 11401 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 11402 EVT ResultVT = EVE->getValueType(0); 11403 EVT VecEltVT = InVecVT.getVectorElementType(); 11404 unsigned Align = OriginalLoad->getAlignment(); 11405 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment( 11406 VecEltVT.getTypeForEVT(*DAG.getContext())); 11407 11408 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 11409 return SDValue(); 11410 11411 Align = NewAlign; 11412 11413 SDValue NewPtr = OriginalLoad->getBasePtr(); 11414 SDValue Offset; 11415 EVT PtrType = NewPtr.getValueType(); 11416 MachinePointerInfo MPI; 11417 SDLoc DL(EVE); 11418 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 11419 int Elt = ConstEltNo->getZExtValue(); 11420 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 11421 Offset = DAG.getConstant(PtrOff, DL, PtrType); 11422 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 11423 } else { 11424 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 11425 Offset = DAG.getNode( 11426 ISD::MUL, DL, PtrType, Offset, 11427 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 11428 MPI = OriginalLoad->getPointerInfo(); 11429 } 11430 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 11431 11432 // The replacement we need to do here is a little tricky: we need to 11433 // replace an extractelement of a load with a load. 11434 // Use ReplaceAllUsesOfValuesWith to do the replacement. 11435 // Note that this replacement assumes that the extractvalue is the only 11436 // use of the load; that's okay because we don't want to perform this 11437 // transformation in other cases anyway. 11438 SDValue Load; 11439 SDValue Chain; 11440 if (ResultVT.bitsGT(VecEltVT)) { 11441 // If the result type of vextract is wider than the load, then issue an 11442 // extending load instead. 11443 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 11444 VecEltVT) 11445 ? ISD::ZEXTLOAD 11446 : ISD::EXTLOAD; 11447 Load = DAG.getExtLoad( 11448 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 11449 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11450 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11451 Chain = Load.getValue(1); 11452 } else { 11453 Load = DAG.getLoad( 11454 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 11455 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 11456 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 11457 Chain = Load.getValue(1); 11458 if (ResultVT.bitsLT(VecEltVT)) 11459 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 11460 else 11461 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 11462 } 11463 WorklistRemover DeadNodes(*this); 11464 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 11465 SDValue To[] = { Load, Chain }; 11466 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 11467 // Since we're explicitly calling ReplaceAllUses, add the new node to the 11468 // worklist explicitly as well. 11469 AddToWorklist(Load.getNode()); 11470 AddUsersToWorklist(Load.getNode()); // Add users too 11471 // Make sure to revisit this node to clean it up; it will usually be dead. 11472 AddToWorklist(EVE); 11473 ++OpsNarrowed; 11474 return SDValue(EVE, 0); 11475 } 11476 11477 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 11478 // (vextract (scalar_to_vector val, 0) -> val 11479 SDValue InVec = N->getOperand(0); 11480 EVT VT = InVec.getValueType(); 11481 EVT NVT = N->getValueType(0); 11482 11483 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 11484 // Check if the result type doesn't match the inserted element type. A 11485 // SCALAR_TO_VECTOR may truncate the inserted element and the 11486 // EXTRACT_VECTOR_ELT may widen the extracted vector. 11487 SDValue InOp = InVec.getOperand(0); 11488 if (InOp.getValueType() != NVT) { 11489 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11490 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 11491 } 11492 return InOp; 11493 } 11494 11495 SDValue EltNo = N->getOperand(1); 11496 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 11497 11498 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 11499 // We only perform this optimization before the op legalization phase because 11500 // we may introduce new vector instructions which are not backed by TD 11501 // patterns. For example on AVX, extracting elements from a wide vector 11502 // without using extract_subvector. However, if we can find an underlying 11503 // scalar value, then we can always use that. 11504 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 11505 && ConstEltNo) { 11506 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11507 int NumElem = VT.getVectorNumElements(); 11508 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 11509 // Find the new index to extract from. 11510 int OrigElt = SVOp->getMaskElt(Elt); 11511 11512 // Extracting an undef index is undef. 11513 if (OrigElt == -1) 11514 return DAG.getUNDEF(NVT); 11515 11516 // Select the right vector half to extract from. 11517 SDValue SVInVec; 11518 if (OrigElt < NumElem) { 11519 SVInVec = InVec->getOperand(0); 11520 } else { 11521 SVInVec = InVec->getOperand(1); 11522 OrigElt -= NumElem; 11523 } 11524 11525 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 11526 SDValue InOp = SVInVec.getOperand(OrigElt); 11527 if (InOp.getValueType() != NVT) { 11528 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 11529 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 11530 } 11531 11532 return InOp; 11533 } 11534 11535 // FIXME: We should handle recursing on other vector shuffles and 11536 // scalar_to_vector here as well. 11537 11538 if (!LegalOperations) { 11539 EVT IndexTy = TLI.getVectorIdxTy(); 11540 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec, 11541 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy)); 11542 } 11543 } 11544 11545 bool BCNumEltsChanged = false; 11546 EVT ExtVT = VT.getVectorElementType(); 11547 EVT LVT = ExtVT; 11548 11549 // If the result of load has to be truncated, then it's not necessarily 11550 // profitable. 11551 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 11552 return SDValue(); 11553 11554 if (InVec.getOpcode() == ISD::BITCAST) { 11555 // Don't duplicate a load with other uses. 11556 if (!InVec.hasOneUse()) 11557 return SDValue(); 11558 11559 EVT BCVT = InVec.getOperand(0).getValueType(); 11560 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 11561 return SDValue(); 11562 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 11563 BCNumEltsChanged = true; 11564 InVec = InVec.getOperand(0); 11565 ExtVT = BCVT.getVectorElementType(); 11566 } 11567 11568 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 11569 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 11570 ISD::isNormalLoad(InVec.getNode()) && 11571 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 11572 SDValue Index = N->getOperand(1); 11573 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 11574 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 11575 OrigLoad); 11576 } 11577 11578 // Perform only after legalization to ensure build_vector / vector_shuffle 11579 // optimizations have already been done. 11580 if (!LegalOperations) return SDValue(); 11581 11582 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 11583 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 11584 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 11585 11586 if (ConstEltNo) { 11587 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 11588 11589 LoadSDNode *LN0 = nullptr; 11590 const ShuffleVectorSDNode *SVN = nullptr; 11591 if (ISD::isNormalLoad(InVec.getNode())) { 11592 LN0 = cast<LoadSDNode>(InVec); 11593 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 11594 InVec.getOperand(0).getValueType() == ExtVT && 11595 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 11596 // Don't duplicate a load with other uses. 11597 if (!InVec.hasOneUse()) 11598 return SDValue(); 11599 11600 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 11601 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 11602 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 11603 // => 11604 // (load $addr+1*size) 11605 11606 // Don't duplicate a load with other uses. 11607 if (!InVec.hasOneUse()) 11608 return SDValue(); 11609 11610 // If the bit convert changed the number of elements, it is unsafe 11611 // to examine the mask. 11612 if (BCNumEltsChanged) 11613 return SDValue(); 11614 11615 // Select the input vector, guarding against out of range extract vector. 11616 unsigned NumElems = VT.getVectorNumElements(); 11617 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 11618 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 11619 11620 if (InVec.getOpcode() == ISD::BITCAST) { 11621 // Don't duplicate a load with other uses. 11622 if (!InVec.hasOneUse()) 11623 return SDValue(); 11624 11625 InVec = InVec.getOperand(0); 11626 } 11627 if (ISD::isNormalLoad(InVec.getNode())) { 11628 LN0 = cast<LoadSDNode>(InVec); 11629 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 11630 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType()); 11631 } 11632 } 11633 11634 // Make sure we found a non-volatile load and the extractelement is 11635 // the only use. 11636 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 11637 return SDValue(); 11638 11639 // If Idx was -1 above, Elt is going to be -1, so just return undef. 11640 if (Elt == -1) 11641 return DAG.getUNDEF(LVT); 11642 11643 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 11644 } 11645 11646 return SDValue(); 11647 } 11648 11649 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 11650 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 11651 // We perform this optimization post type-legalization because 11652 // the type-legalizer often scalarizes integer-promoted vectors. 11653 // Performing this optimization before may create bit-casts which 11654 // will be type-legalized to complex code sequences. 11655 // We perform this optimization only before the operation legalizer because we 11656 // may introduce illegal operations. 11657 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 11658 return SDValue(); 11659 11660 unsigned NumInScalars = N->getNumOperands(); 11661 SDLoc dl(N); 11662 EVT VT = N->getValueType(0); 11663 11664 // Check to see if this is a BUILD_VECTOR of a bunch of values 11665 // which come from any_extend or zero_extend nodes. If so, we can create 11666 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 11667 // optimizations. We do not handle sign-extend because we can't fill the sign 11668 // using shuffles. 11669 EVT SourceType = MVT::Other; 11670 bool AllAnyExt = true; 11671 11672 for (unsigned i = 0; i != NumInScalars; ++i) { 11673 SDValue In = N->getOperand(i); 11674 // Ignore undef inputs. 11675 if (In.getOpcode() == ISD::UNDEF) continue; 11676 11677 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 11678 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 11679 11680 // Abort if the element is not an extension. 11681 if (!ZeroExt && !AnyExt) { 11682 SourceType = MVT::Other; 11683 break; 11684 } 11685 11686 // The input is a ZeroExt or AnyExt. Check the original type. 11687 EVT InTy = In.getOperand(0).getValueType(); 11688 11689 // Check that all of the widened source types are the same. 11690 if (SourceType == MVT::Other) 11691 // First time. 11692 SourceType = InTy; 11693 else if (InTy != SourceType) { 11694 // Multiple income types. Abort. 11695 SourceType = MVT::Other; 11696 break; 11697 } 11698 11699 // Check if all of the extends are ANY_EXTENDs. 11700 AllAnyExt &= AnyExt; 11701 } 11702 11703 // In order to have valid types, all of the inputs must be extended from the 11704 // same source type and all of the inputs must be any or zero extend. 11705 // Scalar sizes must be a power of two. 11706 EVT OutScalarTy = VT.getScalarType(); 11707 bool ValidTypes = SourceType != MVT::Other && 11708 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 11709 isPowerOf2_32(SourceType.getSizeInBits()); 11710 11711 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 11712 // turn into a single shuffle instruction. 11713 if (!ValidTypes) 11714 return SDValue(); 11715 11716 bool isLE = TLI.isLittleEndian(); 11717 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 11718 assert(ElemRatio > 1 && "Invalid element size ratio"); 11719 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 11720 DAG.getConstant(0, SDLoc(N), SourceType); 11721 11722 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 11723 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 11724 11725 // Populate the new build_vector 11726 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11727 SDValue Cast = N->getOperand(i); 11728 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 11729 Cast.getOpcode() == ISD::ZERO_EXTEND || 11730 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 11731 SDValue In; 11732 if (Cast.getOpcode() == ISD::UNDEF) 11733 In = DAG.getUNDEF(SourceType); 11734 else 11735 In = Cast->getOperand(0); 11736 unsigned Index = isLE ? (i * ElemRatio) : 11737 (i * ElemRatio + (ElemRatio - 1)); 11738 11739 assert(Index < Ops.size() && "Invalid index"); 11740 Ops[Index] = In; 11741 } 11742 11743 // The type of the new BUILD_VECTOR node. 11744 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 11745 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 11746 "Invalid vector size"); 11747 // Check if the new vector type is legal. 11748 if (!isTypeLegal(VecVT)) return SDValue(); 11749 11750 // Make the new BUILD_VECTOR. 11751 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 11752 11753 // The new BUILD_VECTOR node has the potential to be further optimized. 11754 AddToWorklist(BV.getNode()); 11755 // Bitcast to the desired type. 11756 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 11757 } 11758 11759 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 11760 EVT VT = N->getValueType(0); 11761 11762 unsigned NumInScalars = N->getNumOperands(); 11763 SDLoc dl(N); 11764 11765 EVT SrcVT = MVT::Other; 11766 unsigned Opcode = ISD::DELETED_NODE; 11767 unsigned NumDefs = 0; 11768 11769 for (unsigned i = 0; i != NumInScalars; ++i) { 11770 SDValue In = N->getOperand(i); 11771 unsigned Opc = In.getOpcode(); 11772 11773 if (Opc == ISD::UNDEF) 11774 continue; 11775 11776 // If all scalar values are floats and converted from integers. 11777 if (Opcode == ISD::DELETED_NODE && 11778 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 11779 Opcode = Opc; 11780 } 11781 11782 if (Opc != Opcode) 11783 return SDValue(); 11784 11785 EVT InVT = In.getOperand(0).getValueType(); 11786 11787 // If all scalar values are typed differently, bail out. It's chosen to 11788 // simplify BUILD_VECTOR of integer types. 11789 if (SrcVT == MVT::Other) 11790 SrcVT = InVT; 11791 if (SrcVT != InVT) 11792 return SDValue(); 11793 NumDefs++; 11794 } 11795 11796 // If the vector has just one element defined, it's not worth to fold it into 11797 // a vectorized one. 11798 if (NumDefs < 2) 11799 return SDValue(); 11800 11801 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 11802 && "Should only handle conversion from integer to float."); 11803 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 11804 11805 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 11806 11807 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 11808 return SDValue(); 11809 11810 // Just because the floating-point vector type is legal does not necessarily 11811 // mean that the corresponding integer vector type is. 11812 if (!isTypeLegal(NVT)) 11813 return SDValue(); 11814 11815 SmallVector<SDValue, 8> Opnds; 11816 for (unsigned i = 0; i != NumInScalars; ++i) { 11817 SDValue In = N->getOperand(i); 11818 11819 if (In.getOpcode() == ISD::UNDEF) 11820 Opnds.push_back(DAG.getUNDEF(SrcVT)); 11821 else 11822 Opnds.push_back(In.getOperand(0)); 11823 } 11824 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 11825 AddToWorklist(BV.getNode()); 11826 11827 return DAG.getNode(Opcode, dl, VT, BV); 11828 } 11829 11830 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 11831 unsigned NumInScalars = N->getNumOperands(); 11832 SDLoc dl(N); 11833 EVT VT = N->getValueType(0); 11834 11835 // A vector built entirely of undefs is undef. 11836 if (ISD::allOperandsUndef(N)) 11837 return DAG.getUNDEF(VT); 11838 11839 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 11840 return V; 11841 11842 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N)) 11843 return V; 11844 11845 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 11846 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 11847 // at most two distinct vectors, turn this into a shuffle node. 11848 11849 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 11850 if (!isTypeLegal(VT)) 11851 return SDValue(); 11852 11853 // May only combine to shuffle after legalize if shuffle is legal. 11854 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 11855 return SDValue(); 11856 11857 SDValue VecIn1, VecIn2; 11858 bool UsesZeroVector = false; 11859 for (unsigned i = 0; i != NumInScalars; ++i) { 11860 SDValue Op = N->getOperand(i); 11861 // Ignore undef inputs. 11862 if (Op.getOpcode() == ISD::UNDEF) continue; 11863 11864 // See if we can combine this build_vector into a blend with a zero vector. 11865 if (!VecIn2.getNode() && (isNullConstant(Op) || 11866 (Op.getOpcode() == ISD::ConstantFP && 11867 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) { 11868 UsesZeroVector = true; 11869 continue; 11870 } 11871 11872 // If this input is something other than a EXTRACT_VECTOR_ELT with a 11873 // constant index, bail out. 11874 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11875 !isa<ConstantSDNode>(Op.getOperand(1))) { 11876 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11877 break; 11878 } 11879 11880 // We allow up to two distinct input vectors. 11881 SDValue ExtractedFromVec = Op.getOperand(0); 11882 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 11883 continue; 11884 11885 if (!VecIn1.getNode()) { 11886 VecIn1 = ExtractedFromVec; 11887 } else if (!VecIn2.getNode() && !UsesZeroVector) { 11888 VecIn2 = ExtractedFromVec; 11889 } else { 11890 // Too many inputs. 11891 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11892 break; 11893 } 11894 } 11895 11896 // If everything is good, we can make a shuffle operation. 11897 if (VecIn1.getNode()) { 11898 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 11899 SmallVector<int, 8> Mask; 11900 for (unsigned i = 0; i != NumInScalars; ++i) { 11901 unsigned Opcode = N->getOperand(i).getOpcode(); 11902 if (Opcode == ISD::UNDEF) { 11903 Mask.push_back(-1); 11904 continue; 11905 } 11906 11907 // Operands can also be zero. 11908 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 11909 assert(UsesZeroVector && 11910 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 11911 "Unexpected node found!"); 11912 Mask.push_back(NumInScalars+i); 11913 continue; 11914 } 11915 11916 // If extracting from the first vector, just use the index directly. 11917 SDValue Extract = N->getOperand(i); 11918 SDValue ExtVal = Extract.getOperand(1); 11919 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 11920 if (Extract.getOperand(0) == VecIn1) { 11921 Mask.push_back(ExtIndex); 11922 continue; 11923 } 11924 11925 // Otherwise, use InIdx + InputVecSize 11926 Mask.push_back(InNumElements + ExtIndex); 11927 } 11928 11929 // Avoid introducing illegal shuffles with zero. 11930 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 11931 return SDValue(); 11932 11933 // We can't generate a shuffle node with mismatched input and output types. 11934 // Attempt to transform a single input vector to the correct type. 11935 if ((VT != VecIn1.getValueType())) { 11936 // If the input vector type has a different base type to the output 11937 // vector type, bail out. 11938 EVT VTElemType = VT.getVectorElementType(); 11939 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 11940 (VecIn2.getNode() && 11941 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 11942 return SDValue(); 11943 11944 // If the input vector is too small, widen it. 11945 // We only support widening of vectors which are half the size of the 11946 // output registers. For example XMM->YMM widening on X86 with AVX. 11947 EVT VecInT = VecIn1.getValueType(); 11948 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 11949 // If we only have one small input, widen it by adding undef values. 11950 if (!VecIn2.getNode()) 11951 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 11952 DAG.getUNDEF(VecIn1.getValueType())); 11953 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 11954 // If we have two small inputs of the same type, try to concat them. 11955 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 11956 VecIn2 = SDValue(nullptr, 0); 11957 } else 11958 return SDValue(); 11959 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 11960 // If the input vector is too large, try to split it. 11961 // We don't support having two input vectors that are too large. 11962 // If the zero vector was used, we can not split the vector, 11963 // since we'd need 3 inputs. 11964 if (UsesZeroVector || VecIn2.getNode()) 11965 return SDValue(); 11966 11967 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 11968 return SDValue(); 11969 11970 // Try to replace VecIn1 with two extract_subvectors 11971 // No need to update the masks, they should still be correct. 11972 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11973 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy())); 11974 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11975 DAG.getConstant(0, dl, TLI.getVectorIdxTy())); 11976 } else 11977 return SDValue(); 11978 } 11979 11980 if (UsesZeroVector) 11981 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) : 11982 DAG.getConstantFP(0.0, dl, VT); 11983 else 11984 // If VecIn2 is unused then change it to undef. 11985 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 11986 11987 // Check that we were able to transform all incoming values to the same 11988 // type. 11989 if (VecIn2.getValueType() != VecIn1.getValueType() || 11990 VecIn1.getValueType() != VT) 11991 return SDValue(); 11992 11993 // Return the new VECTOR_SHUFFLE node. 11994 SDValue Ops[2]; 11995 Ops[0] = VecIn1; 11996 Ops[1] = VecIn2; 11997 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 11998 } 11999 12000 return SDValue(); 12001 } 12002 12003 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 12004 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 12005 EVT OpVT = N->getOperand(0).getValueType(); 12006 12007 // If the operands are legal vectors, leave them alone. 12008 if (TLI.isTypeLegal(OpVT)) 12009 return SDValue(); 12010 12011 SDLoc DL(N); 12012 EVT VT = N->getValueType(0); 12013 SmallVector<SDValue, 8> Ops; 12014 12015 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 12016 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12017 12018 // Keep track of what we encounter. 12019 bool AnyInteger = false; 12020 bool AnyFP = false; 12021 for (const SDValue &Op : N->ops()) { 12022 if (ISD::BITCAST == Op.getOpcode() && 12023 !Op.getOperand(0).getValueType().isVector()) 12024 Ops.push_back(Op.getOperand(0)); 12025 else if (ISD::UNDEF == Op.getOpcode()) 12026 Ops.push_back(ScalarUndef); 12027 else 12028 return SDValue(); 12029 12030 // Note whether we encounter an integer or floating point scalar. 12031 // If it's neither, bail out, it could be something weird like x86mmx. 12032 EVT LastOpVT = Ops.back().getValueType(); 12033 if (LastOpVT.isFloatingPoint()) 12034 AnyFP = true; 12035 else if (LastOpVT.isInteger()) 12036 AnyInteger = true; 12037 else 12038 return SDValue(); 12039 } 12040 12041 // If any of the operands is a floating point scalar bitcast to a vector, 12042 // use floating point types throughout, and bitcast everything. 12043 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 12044 if (AnyFP) { 12045 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 12046 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 12047 if (AnyInteger) { 12048 for (SDValue &Op : Ops) { 12049 if (Op.getValueType() == SVT) 12050 continue; 12051 if (Op.getOpcode() == ISD::UNDEF) 12052 Op = ScalarUndef; 12053 else 12054 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op); 12055 } 12056 } 12057 } 12058 12059 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 12060 VT.getSizeInBits() / SVT.getSizeInBits()); 12061 return DAG.getNode(ISD::BITCAST, DL, VT, 12062 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops)); 12063 } 12064 12065 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 12066 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 12067 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 12068 // inputs come from at most two distinct vectors, turn this into a shuffle 12069 // node. 12070 12071 // If we only have one input vector, we don't need to do any concatenation. 12072 if (N->getNumOperands() == 1) 12073 return N->getOperand(0); 12074 12075 // Check if all of the operands are undefs. 12076 EVT VT = N->getValueType(0); 12077 if (ISD::allOperandsUndef(N)) 12078 return DAG.getUNDEF(VT); 12079 12080 // Optimize concat_vectors where all but the first of the vectors are undef. 12081 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 12082 return Op.getOpcode() == ISD::UNDEF; 12083 })) { 12084 SDValue In = N->getOperand(0); 12085 assert(In.getValueType().isVector() && "Must concat vectors"); 12086 12087 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 12088 if (In->getOpcode() == ISD::BITCAST && 12089 !In->getOperand(0)->getValueType(0).isVector()) { 12090 SDValue Scalar = In->getOperand(0); 12091 12092 // If the bitcast type isn't legal, it might be a trunc of a legal type; 12093 // look through the trunc so we can still do the transform: 12094 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 12095 if (Scalar->getOpcode() == ISD::TRUNCATE && 12096 !TLI.isTypeLegal(Scalar.getValueType()) && 12097 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 12098 Scalar = Scalar->getOperand(0); 12099 12100 EVT SclTy = Scalar->getValueType(0); 12101 12102 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 12103 return SDValue(); 12104 12105 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 12106 VT.getSizeInBits() / SclTy.getSizeInBits()); 12107 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 12108 return SDValue(); 12109 12110 SDLoc dl = SDLoc(N); 12111 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 12112 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 12113 } 12114 } 12115 12116 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 12117 // We have already tested above for an UNDEF only concatenation. 12118 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 12119 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 12120 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 12121 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 12122 }; 12123 bool AllBuildVectorsOrUndefs = 12124 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef); 12125 if (AllBuildVectorsOrUndefs) { 12126 SmallVector<SDValue, 8> Opnds; 12127 EVT SVT = VT.getScalarType(); 12128 12129 EVT MinVT = SVT; 12130 if (!SVT.isFloatingPoint()) { 12131 // If BUILD_VECTOR are from built from integer, they may have different 12132 // operand types. Get the smallest type and truncate all operands to it. 12133 bool FoundMinVT = false; 12134 for (const SDValue &Op : N->ops()) 12135 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12136 EVT OpSVT = Op.getOperand(0)->getValueType(0); 12137 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 12138 FoundMinVT = true; 12139 } 12140 assert(FoundMinVT && "Concat vector type mismatch"); 12141 } 12142 12143 for (const SDValue &Op : N->ops()) { 12144 EVT OpVT = Op.getValueType(); 12145 unsigned NumElts = OpVT.getVectorNumElements(); 12146 12147 if (ISD::UNDEF == Op.getOpcode()) 12148 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 12149 12150 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 12151 if (SVT.isFloatingPoint()) { 12152 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 12153 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 12154 } else { 12155 for (unsigned i = 0; i != NumElts; ++i) 12156 Opnds.push_back( 12157 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 12158 } 12159 } 12160 } 12161 12162 assert(VT.getVectorNumElements() == Opnds.size() && 12163 "Concat vector type mismatch"); 12164 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 12165 } 12166 12167 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 12168 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 12169 return V; 12170 12171 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 12172 // nodes often generate nop CONCAT_VECTOR nodes. 12173 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 12174 // place the incoming vectors at the exact same location. 12175 SDValue SingleSource = SDValue(); 12176 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 12177 12178 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 12179 SDValue Op = N->getOperand(i); 12180 12181 if (Op.getOpcode() == ISD::UNDEF) 12182 continue; 12183 12184 // Check if this is the identity extract: 12185 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 12186 return SDValue(); 12187 12188 // Find the single incoming vector for the extract_subvector. 12189 if (SingleSource.getNode()) { 12190 if (Op.getOperand(0) != SingleSource) 12191 return SDValue(); 12192 } else { 12193 SingleSource = Op.getOperand(0); 12194 12195 // Check the source type is the same as the type of the result. 12196 // If not, this concat may extend the vector, so we can not 12197 // optimize it away. 12198 if (SingleSource.getValueType() != N->getValueType(0)) 12199 return SDValue(); 12200 } 12201 12202 unsigned IdentityIndex = i * PartNumElem; 12203 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 12204 // The extract index must be constant. 12205 if (!CS) 12206 return SDValue(); 12207 12208 // Check that we are reading from the identity index. 12209 if (CS->getZExtValue() != IdentityIndex) 12210 return SDValue(); 12211 } 12212 12213 if (SingleSource.getNode()) 12214 return SingleSource; 12215 12216 return SDValue(); 12217 } 12218 12219 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 12220 EVT NVT = N->getValueType(0); 12221 SDValue V = N->getOperand(0); 12222 12223 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 12224 // Combine: 12225 // (extract_subvec (concat V1, V2, ...), i) 12226 // Into: 12227 // Vi if possible 12228 // Only operand 0 is checked as 'concat' assumes all inputs of the same 12229 // type. 12230 if (V->getOperand(0).getValueType() != NVT) 12231 return SDValue(); 12232 unsigned Idx = N->getConstantOperandVal(1); 12233 unsigned NumElems = NVT.getVectorNumElements(); 12234 assert((Idx % NumElems) == 0 && 12235 "IDX in concat is not a multiple of the result vector length."); 12236 return V->getOperand(Idx / NumElems); 12237 } 12238 12239 // Skip bitcasting 12240 if (V->getOpcode() == ISD::BITCAST) 12241 V = V.getOperand(0); 12242 12243 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 12244 SDLoc dl(N); 12245 // Handle only simple case where vector being inserted and vector 12246 // being extracted are of same type, and are half size of larger vectors. 12247 EVT BigVT = V->getOperand(0).getValueType(); 12248 EVT SmallVT = V->getOperand(1).getValueType(); 12249 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 12250 return SDValue(); 12251 12252 // Only handle cases where both indexes are constants with the same type. 12253 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12254 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12255 12256 if (InsIdx && ExtIdx && 12257 InsIdx->getValueType(0).getSizeInBits() <= 64 && 12258 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 12259 // Combine: 12260 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 12261 // Into: 12262 // indices are equal or bit offsets are equal => V1 12263 // otherwise => (extract_subvec V1, ExtIdx) 12264 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 12265 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 12266 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 12267 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 12268 DAG.getNode(ISD::BITCAST, dl, 12269 N->getOperand(0).getValueType(), 12270 V->getOperand(0)), N->getOperand(1)); 12271 } 12272 } 12273 12274 return SDValue(); 12275 } 12276 12277 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 12278 SDValue V, SelectionDAG &DAG) { 12279 SDLoc DL(V); 12280 EVT VT = V.getValueType(); 12281 12282 switch (V.getOpcode()) { 12283 default: 12284 return V; 12285 12286 case ISD::CONCAT_VECTORS: { 12287 EVT OpVT = V->getOperand(0).getValueType(); 12288 int OpSize = OpVT.getVectorNumElements(); 12289 SmallBitVector OpUsedElements(OpSize, false); 12290 bool FoundSimplification = false; 12291 SmallVector<SDValue, 4> NewOps; 12292 NewOps.reserve(V->getNumOperands()); 12293 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 12294 SDValue Op = V->getOperand(i); 12295 bool OpUsed = false; 12296 for (int j = 0; j < OpSize; ++j) 12297 if (UsedElements[i * OpSize + j]) { 12298 OpUsedElements[j] = true; 12299 OpUsed = true; 12300 } 12301 NewOps.push_back( 12302 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 12303 : DAG.getUNDEF(OpVT)); 12304 FoundSimplification |= Op == NewOps.back(); 12305 OpUsedElements.reset(); 12306 } 12307 if (FoundSimplification) 12308 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 12309 return V; 12310 } 12311 12312 case ISD::INSERT_SUBVECTOR: { 12313 SDValue BaseV = V->getOperand(0); 12314 SDValue SubV = V->getOperand(1); 12315 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 12316 if (!IdxN) 12317 return V; 12318 12319 int SubSize = SubV.getValueType().getVectorNumElements(); 12320 int Idx = IdxN->getZExtValue(); 12321 bool SubVectorUsed = false; 12322 SmallBitVector SubUsedElements(SubSize, false); 12323 for (int i = 0; i < SubSize; ++i) 12324 if (UsedElements[i + Idx]) { 12325 SubVectorUsed = true; 12326 SubUsedElements[i] = true; 12327 UsedElements[i + Idx] = false; 12328 } 12329 12330 // Now recurse on both the base and sub vectors. 12331 SDValue SimplifiedSubV = 12332 SubVectorUsed 12333 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 12334 : DAG.getUNDEF(SubV.getValueType()); 12335 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 12336 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 12337 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 12338 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 12339 return V; 12340 } 12341 } 12342 } 12343 12344 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 12345 SDValue N1, SelectionDAG &DAG) { 12346 EVT VT = SVN->getValueType(0); 12347 int NumElts = VT.getVectorNumElements(); 12348 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 12349 for (int M : SVN->getMask()) 12350 if (M >= 0 && M < NumElts) 12351 N0UsedElements[M] = true; 12352 else if (M >= NumElts) 12353 N1UsedElements[M - NumElts] = true; 12354 12355 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 12356 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 12357 if (S0 == N0 && S1 == N1) 12358 return SDValue(); 12359 12360 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 12361 } 12362 12363 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 12364 // or turn a shuffle of a single concat into simpler shuffle then concat. 12365 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 12366 EVT VT = N->getValueType(0); 12367 unsigned NumElts = VT.getVectorNumElements(); 12368 12369 SDValue N0 = N->getOperand(0); 12370 SDValue N1 = N->getOperand(1); 12371 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12372 12373 SmallVector<SDValue, 4> Ops; 12374 EVT ConcatVT = N0.getOperand(0).getValueType(); 12375 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 12376 unsigned NumConcats = NumElts / NumElemsPerConcat; 12377 12378 // Special case: shuffle(concat(A,B)) can be more efficiently represented 12379 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 12380 // half vector elements. 12381 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 12382 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 12383 SVN->getMask().end(), [](int i) { return i == -1; })) { 12384 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 12385 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat)); 12386 N1 = DAG.getUNDEF(ConcatVT); 12387 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 12388 } 12389 12390 // Look at every vector that's inserted. We're looking for exact 12391 // subvector-sized copies from a concatenated vector 12392 for (unsigned I = 0; I != NumConcats; ++I) { 12393 // Make sure we're dealing with a copy. 12394 unsigned Begin = I * NumElemsPerConcat; 12395 bool AllUndef = true, NoUndef = true; 12396 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 12397 if (SVN->getMaskElt(J) >= 0) 12398 AllUndef = false; 12399 else 12400 NoUndef = false; 12401 } 12402 12403 if (NoUndef) { 12404 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 12405 return SDValue(); 12406 12407 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 12408 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 12409 return SDValue(); 12410 12411 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 12412 if (FirstElt < N0.getNumOperands()) 12413 Ops.push_back(N0.getOperand(FirstElt)); 12414 else 12415 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 12416 12417 } else if (AllUndef) { 12418 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 12419 } else { // Mixed with general masks and undefs, can't do optimization. 12420 return SDValue(); 12421 } 12422 } 12423 12424 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 12425 } 12426 12427 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 12428 EVT VT = N->getValueType(0); 12429 unsigned NumElts = VT.getVectorNumElements(); 12430 12431 SDValue N0 = N->getOperand(0); 12432 SDValue N1 = N->getOperand(1); 12433 12434 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 12435 12436 // Canonicalize shuffle undef, undef -> undef 12437 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 12438 return DAG.getUNDEF(VT); 12439 12440 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 12441 12442 // Canonicalize shuffle v, v -> v, undef 12443 if (N0 == N1) { 12444 SmallVector<int, 8> NewMask; 12445 for (unsigned i = 0; i != NumElts; ++i) { 12446 int Idx = SVN->getMaskElt(i); 12447 if (Idx >= (int)NumElts) Idx -= NumElts; 12448 NewMask.push_back(Idx); 12449 } 12450 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 12451 &NewMask[0]); 12452 } 12453 12454 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 12455 if (N0.getOpcode() == ISD::UNDEF) { 12456 SmallVector<int, 8> NewMask; 12457 for (unsigned i = 0; i != NumElts; ++i) { 12458 int Idx = SVN->getMaskElt(i); 12459 if (Idx >= 0) { 12460 if (Idx >= (int)NumElts) 12461 Idx -= NumElts; 12462 else 12463 Idx = -1; // remove reference to lhs 12464 } 12465 NewMask.push_back(Idx); 12466 } 12467 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 12468 &NewMask[0]); 12469 } 12470 12471 // Remove references to rhs if it is undef 12472 if (N1.getOpcode() == ISD::UNDEF) { 12473 bool Changed = false; 12474 SmallVector<int, 8> NewMask; 12475 for (unsigned i = 0; i != NumElts; ++i) { 12476 int Idx = SVN->getMaskElt(i); 12477 if (Idx >= (int)NumElts) { 12478 Idx = -1; 12479 Changed = true; 12480 } 12481 NewMask.push_back(Idx); 12482 } 12483 if (Changed) 12484 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 12485 } 12486 12487 // If it is a splat, check if the argument vector is another splat or a 12488 // build_vector. 12489 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 12490 SDNode *V = N0.getNode(); 12491 12492 // If this is a bit convert that changes the element type of the vector but 12493 // not the number of vector elements, look through it. Be careful not to 12494 // look though conversions that change things like v4f32 to v2f64. 12495 if (V->getOpcode() == ISD::BITCAST) { 12496 SDValue ConvInput = V->getOperand(0); 12497 if (ConvInput.getValueType().isVector() && 12498 ConvInput.getValueType().getVectorNumElements() == NumElts) 12499 V = ConvInput.getNode(); 12500 } 12501 12502 if (V->getOpcode() == ISD::BUILD_VECTOR) { 12503 assert(V->getNumOperands() == NumElts && 12504 "BUILD_VECTOR has wrong number of operands"); 12505 SDValue Base; 12506 bool AllSame = true; 12507 for (unsigned i = 0; i != NumElts; ++i) { 12508 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 12509 Base = V->getOperand(i); 12510 break; 12511 } 12512 } 12513 // Splat of <u, u, u, u>, return <u, u, u, u> 12514 if (!Base.getNode()) 12515 return N0; 12516 for (unsigned i = 0; i != NumElts; ++i) { 12517 if (V->getOperand(i) != Base) { 12518 AllSame = false; 12519 break; 12520 } 12521 } 12522 // Splat of <x, x, x, x>, return <x, x, x, x> 12523 if (AllSame) 12524 return N0; 12525 12526 // Canonicalize any other splat as a build_vector. 12527 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 12528 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 12529 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 12530 V->getValueType(0), Ops); 12531 12532 // We may have jumped through bitcasts, so the type of the 12533 // BUILD_VECTOR may not match the type of the shuffle. 12534 if (V->getValueType(0) != VT) 12535 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 12536 return NewBV; 12537 } 12538 } 12539 12540 // There are various patterns used to build up a vector from smaller vectors, 12541 // subvectors, or elements. Scan chains of these and replace unused insertions 12542 // or components with undef. 12543 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 12544 return S; 12545 12546 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 12547 Level < AfterLegalizeVectorOps && 12548 (N1.getOpcode() == ISD::UNDEF || 12549 (N1.getOpcode() == ISD::CONCAT_VECTORS && 12550 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 12551 SDValue V = partitionShuffleOfConcats(N, DAG); 12552 12553 if (V.getNode()) 12554 return V; 12555 } 12556 12557 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 12558 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 12559 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 12560 SmallVector<SDValue, 8> Ops; 12561 for (int M : SVN->getMask()) { 12562 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 12563 if (M >= 0) { 12564 int Idx = M % NumElts; 12565 SDValue &S = (M < (int)NumElts ? N0 : N1); 12566 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) { 12567 Op = S.getOperand(Idx); 12568 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) { 12569 if (Idx == 0) 12570 Op = S.getOperand(0); 12571 } else { 12572 // Operand can't be combined - bail out. 12573 break; 12574 } 12575 } 12576 Ops.push_back(Op); 12577 } 12578 if (Ops.size() == VT.getVectorNumElements()) { 12579 // BUILD_VECTOR requires all inputs to be of the same type, find the 12580 // maximum type and extend them all. 12581 EVT SVT = VT.getScalarType(); 12582 if (SVT.isInteger()) 12583 for (SDValue &Op : Ops) 12584 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 12585 if (SVT != VT.getScalarType()) 12586 for (SDValue &Op : Ops) 12587 Op = TLI.isZExtFree(Op.getValueType(), SVT) 12588 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT) 12589 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT); 12590 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops); 12591 } 12592 } 12593 12594 // If this shuffle only has a single input that is a bitcasted shuffle, 12595 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 12596 // back to their original types. 12597 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 12598 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps && 12599 TLI.isTypeLegal(VT)) { 12600 12601 // Peek through the bitcast only if there is one user. 12602 SDValue BC0 = N0; 12603 while (BC0.getOpcode() == ISD::BITCAST) { 12604 if (!BC0.hasOneUse()) 12605 break; 12606 BC0 = BC0.getOperand(0); 12607 } 12608 12609 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 12610 if (Scale == 1) 12611 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 12612 12613 SmallVector<int, 8> NewMask; 12614 for (int M : Mask) 12615 for (int s = 0; s != Scale; ++s) 12616 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 12617 return NewMask; 12618 }; 12619 12620 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 12621 EVT SVT = VT.getScalarType(); 12622 EVT InnerVT = BC0->getValueType(0); 12623 EVT InnerSVT = InnerVT.getScalarType(); 12624 12625 // Determine which shuffle works with the smaller scalar type. 12626 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 12627 EVT ScaleSVT = ScaleVT.getScalarType(); 12628 12629 if (TLI.isTypeLegal(ScaleVT) && 12630 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 12631 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 12632 12633 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 12634 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 12635 12636 // Scale the shuffle masks to the smaller scalar type. 12637 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 12638 SmallVector<int, 8> InnerMask = 12639 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 12640 SmallVector<int, 8> OuterMask = 12641 ScaleShuffleMask(SVN->getMask(), OuterScale); 12642 12643 // Merge the shuffle masks. 12644 SmallVector<int, 8> NewMask; 12645 for (int M : OuterMask) 12646 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 12647 12648 // Test for shuffle mask legality over both commutations. 12649 SDValue SV0 = BC0->getOperand(0); 12650 SDValue SV1 = BC0->getOperand(1); 12651 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 12652 if (!LegalMask) { 12653 std::swap(SV0, SV1); 12654 ShuffleVectorSDNode::commuteMask(NewMask); 12655 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 12656 } 12657 12658 if (LegalMask) { 12659 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0); 12660 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1); 12661 return DAG.getNode( 12662 ISD::BITCAST, SDLoc(N), VT, 12663 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 12664 } 12665 } 12666 } 12667 } 12668 12669 // Canonicalize shuffles according to rules: 12670 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 12671 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 12672 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 12673 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 12674 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 12675 TLI.isTypeLegal(VT)) { 12676 // The incoming shuffle must be of the same type as the result of the 12677 // current shuffle. 12678 assert(N1->getOperand(0).getValueType() == VT && 12679 "Shuffle types don't match"); 12680 12681 SDValue SV0 = N1->getOperand(0); 12682 SDValue SV1 = N1->getOperand(1); 12683 bool HasSameOp0 = N0 == SV0; 12684 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 12685 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 12686 // Commute the operands of this shuffle so that next rule 12687 // will trigger. 12688 return DAG.getCommutedVectorShuffle(*SVN); 12689 } 12690 12691 // Try to fold according to rules: 12692 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12693 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12694 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12695 // Don't try to fold shuffles with illegal type. 12696 // Only fold if this shuffle is the only user of the other shuffle. 12697 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 12698 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 12699 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 12700 12701 // The incoming shuffle must be of the same type as the result of the 12702 // current shuffle. 12703 assert(OtherSV->getOperand(0).getValueType() == VT && 12704 "Shuffle types don't match"); 12705 12706 SDValue SV0, SV1; 12707 SmallVector<int, 4> Mask; 12708 // Compute the combined shuffle mask for a shuffle with SV0 as the first 12709 // operand, and SV1 as the second operand. 12710 for (unsigned i = 0; i != NumElts; ++i) { 12711 int Idx = SVN->getMaskElt(i); 12712 if (Idx < 0) { 12713 // Propagate Undef. 12714 Mask.push_back(Idx); 12715 continue; 12716 } 12717 12718 SDValue CurrentVec; 12719 if (Idx < (int)NumElts) { 12720 // This shuffle index refers to the inner shuffle N0. Lookup the inner 12721 // shuffle mask to identify which vector is actually referenced. 12722 Idx = OtherSV->getMaskElt(Idx); 12723 if (Idx < 0) { 12724 // Propagate Undef. 12725 Mask.push_back(Idx); 12726 continue; 12727 } 12728 12729 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 12730 : OtherSV->getOperand(1); 12731 } else { 12732 // This shuffle index references an element within N1. 12733 CurrentVec = N1; 12734 } 12735 12736 // Simple case where 'CurrentVec' is UNDEF. 12737 if (CurrentVec.getOpcode() == ISD::UNDEF) { 12738 Mask.push_back(-1); 12739 continue; 12740 } 12741 12742 // Canonicalize the shuffle index. We don't know yet if CurrentVec 12743 // will be the first or second operand of the combined shuffle. 12744 Idx = Idx % NumElts; 12745 if (!SV0.getNode() || SV0 == CurrentVec) { 12746 // Ok. CurrentVec is the left hand side. 12747 // Update the mask accordingly. 12748 SV0 = CurrentVec; 12749 Mask.push_back(Idx); 12750 continue; 12751 } 12752 12753 // Bail out if we cannot convert the shuffle pair into a single shuffle. 12754 if (SV1.getNode() && SV1 != CurrentVec) 12755 return SDValue(); 12756 12757 // Ok. CurrentVec is the right hand side. 12758 // Update the mask accordingly. 12759 SV1 = CurrentVec; 12760 Mask.push_back(Idx + NumElts); 12761 } 12762 12763 // Check if all indices in Mask are Undef. In case, propagate Undef. 12764 bool isUndefMask = true; 12765 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 12766 isUndefMask &= Mask[i] < 0; 12767 12768 if (isUndefMask) 12769 return DAG.getUNDEF(VT); 12770 12771 if (!SV0.getNode()) 12772 SV0 = DAG.getUNDEF(VT); 12773 if (!SV1.getNode()) 12774 SV1 = DAG.getUNDEF(VT); 12775 12776 // Avoid introducing shuffles with illegal mask. 12777 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 12778 ShuffleVectorSDNode::commuteMask(Mask); 12779 12780 if (!TLI.isShuffleMaskLegal(Mask, VT)) 12781 return SDValue(); 12782 12783 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 12784 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 12785 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 12786 std::swap(SV0, SV1); 12787 } 12788 12789 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 12790 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 12791 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 12792 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 12793 } 12794 12795 return SDValue(); 12796 } 12797 12798 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 12799 SDValue InVal = N->getOperand(0); 12800 EVT VT = N->getValueType(0); 12801 12802 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 12803 // with a VECTOR_SHUFFLE. 12804 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 12805 SDValue InVec = InVal->getOperand(0); 12806 SDValue EltNo = InVal->getOperand(1); 12807 12808 // FIXME: We could support implicit truncation if the shuffle can be 12809 // scaled to a smaller vector scalar type. 12810 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo); 12811 if (C0 && VT == InVec.getValueType() && 12812 VT.getScalarType() == InVal.getValueType()) { 12813 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1); 12814 int Elt = C0->getZExtValue(); 12815 NewMask[0] = Elt; 12816 12817 if (TLI.isShuffleMaskLegal(NewMask, VT)) 12818 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT), 12819 NewMask); 12820 } 12821 } 12822 12823 return SDValue(); 12824 } 12825 12826 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 12827 SDValue N0 = N->getOperand(0); 12828 SDValue N2 = N->getOperand(2); 12829 12830 // If the input vector is a concatenation, and the insert replaces 12831 // one of the halves, we can optimize into a single concat_vectors. 12832 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 12833 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 12834 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 12835 EVT VT = N->getValueType(0); 12836 12837 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12838 // (concat_vectors Z, Y) 12839 if (InsIdx == 0) 12840 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12841 N->getOperand(1), N0.getOperand(1)); 12842 12843 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 12844 // (concat_vectors X, Z) 12845 if (InsIdx == VT.getVectorNumElements()/2) 12846 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 12847 N0.getOperand(0), N->getOperand(1)); 12848 } 12849 12850 return SDValue(); 12851 } 12852 12853 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 12854 SDValue N0 = N->getOperand(0); 12855 12856 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 12857 if (N0->getOpcode() == ISD::FP16_TO_FP) 12858 return N0->getOperand(0); 12859 12860 return SDValue(); 12861 } 12862 12863 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 12864 /// with the destination vector and a zero vector. 12865 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 12866 /// vector_shuffle V, Zero, <0, 4, 2, 4> 12867 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 12868 EVT VT = N->getValueType(0); 12869 SDValue LHS = N->getOperand(0); 12870 SDValue RHS = N->getOperand(1); 12871 SDLoc dl(N); 12872 12873 // Make sure we're not running after operation legalization where it 12874 // may have custom lowered the vector shuffles. 12875 if (LegalOperations) 12876 return SDValue(); 12877 12878 if (N->getOpcode() != ISD::AND) 12879 return SDValue(); 12880 12881 if (RHS.getOpcode() == ISD::BITCAST) 12882 RHS = RHS.getOperand(0); 12883 12884 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 12885 SmallVector<int, 8> Indices; 12886 unsigned NumElts = RHS.getNumOperands(); 12887 12888 for (unsigned i = 0; i != NumElts; ++i) { 12889 SDValue Elt = RHS.getOperand(i); 12890 if (isAllOnesConstant(Elt)) 12891 Indices.push_back(i); 12892 else if (isNullConstant(Elt)) 12893 Indices.push_back(NumElts+i); 12894 else 12895 return SDValue(); 12896 } 12897 12898 // Let's see if the target supports this vector_shuffle. 12899 EVT RVT = RHS.getValueType(); 12900 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 12901 return SDValue(); 12902 12903 // Return the new VECTOR_SHUFFLE node. 12904 EVT EltVT = RVT.getVectorElementType(); 12905 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 12906 DAG.getConstant(0, dl, EltVT)); 12907 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps); 12908 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 12909 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 12910 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 12911 } 12912 12913 return SDValue(); 12914 } 12915 12916 /// Visit a binary vector operation, like ADD. 12917 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 12918 assert(N->getValueType(0).isVector() && 12919 "SimplifyVBinOp only works on vectors!"); 12920 12921 SDValue LHS = N->getOperand(0); 12922 SDValue RHS = N->getOperand(1); 12923 12924 if (SDValue Shuffle = XformToShuffleWithZero(N)) 12925 return Shuffle; 12926 12927 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 12928 // this operation. 12929 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 12930 RHS.getOpcode() == ISD::BUILD_VECTOR) { 12931 // Check if both vectors are constants. If not bail out. 12932 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 12933 cast<BuildVectorSDNode>(RHS)->isConstant())) 12934 return SDValue(); 12935 12936 SmallVector<SDValue, 8> Ops; 12937 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 12938 SDValue LHSOp = LHS.getOperand(i); 12939 SDValue RHSOp = RHS.getOperand(i); 12940 12941 // Can't fold divide by zero. 12942 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 12943 N->getOpcode() == ISD::FDIV) { 12944 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP && 12945 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 12946 break; 12947 } 12948 12949 EVT VT = LHSOp.getValueType(); 12950 EVT RVT = RHSOp.getValueType(); 12951 if (RVT != VT) { 12952 // Integer BUILD_VECTOR operands may have types larger than the element 12953 // size (e.g., when the element type is not legal). Prior to type 12954 // legalization, the types may not match between the two BUILD_VECTORS. 12955 // Truncate one of the operands to make them match. 12956 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 12957 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 12958 } else { 12959 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 12960 VT = RVT; 12961 } 12962 } 12963 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 12964 LHSOp, RHSOp); 12965 if (FoldOp.getOpcode() != ISD::UNDEF && 12966 FoldOp.getOpcode() != ISD::Constant && 12967 FoldOp.getOpcode() != ISD::ConstantFP) 12968 break; 12969 Ops.push_back(FoldOp); 12970 AddToWorklist(FoldOp.getNode()); 12971 } 12972 12973 if (Ops.size() == LHS.getNumOperands()) 12974 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 12975 } 12976 12977 // Type legalization might introduce new shuffles in the DAG. 12978 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 12979 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 12980 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 12981 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 12982 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 12983 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 12984 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 12985 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 12986 12987 if (SVN0->getMask().equals(SVN1->getMask())) { 12988 EVT VT = N->getValueType(0); 12989 SDValue UndefVector = LHS.getOperand(1); 12990 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 12991 LHS.getOperand(0), RHS.getOperand(0)); 12992 AddUsersToWorklist(N); 12993 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 12994 &SVN0->getMask()[0]); 12995 } 12996 } 12997 12998 return SDValue(); 12999 } 13000 13001 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 13002 SDValue N1, SDValue N2){ 13003 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 13004 13005 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 13006 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 13007 13008 // If we got a simplified select_cc node back from SimplifySelectCC, then 13009 // break it down into a new SETCC node, and a new SELECT node, and then return 13010 // the SELECT node, since we were called with a SELECT node. 13011 if (SCC.getNode()) { 13012 // Check to see if we got a select_cc back (to turn into setcc/select). 13013 // Otherwise, just return whatever node we got back, like fabs. 13014 if (SCC.getOpcode() == ISD::SELECT_CC) { 13015 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 13016 N0.getValueType(), 13017 SCC.getOperand(0), SCC.getOperand(1), 13018 SCC.getOperand(4)); 13019 AddToWorklist(SETCC.getNode()); 13020 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 13021 SCC.getOperand(2), SCC.getOperand(3)); 13022 } 13023 13024 return SCC; 13025 } 13026 return SDValue(); 13027 } 13028 13029 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 13030 /// being selected between, see if we can simplify the select. Callers of this 13031 /// should assume that TheSelect is deleted if this returns true. As such, they 13032 /// should return the appropriate thing (e.g. the node) back to the top-level of 13033 /// the DAG combiner loop to avoid it being looked at. 13034 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 13035 SDValue RHS) { 13036 13037 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13038 // The select + setcc is redundant, because fsqrt returns NaN for X < -0. 13039 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 13040 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 13041 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 13042 SDValue Sqrt = RHS; 13043 ISD::CondCode CC; 13044 SDValue CmpLHS; 13045 const ConstantFPSDNode *NegZero = nullptr; 13046 13047 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 13048 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 13049 CmpLHS = TheSelect->getOperand(0); 13050 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 13051 } else { 13052 // SELECT or VSELECT 13053 SDValue Cmp = TheSelect->getOperand(0); 13054 if (Cmp.getOpcode() == ISD::SETCC) { 13055 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 13056 CmpLHS = Cmp.getOperand(0); 13057 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1)); 13058 } 13059 } 13060 if (NegZero && NegZero->isNegative() && NegZero->isZero() && 13061 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 13062 CC == ISD::SETULT || CC == ISD::SETLT)) { 13063 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x)) 13064 CombineTo(TheSelect, Sqrt); 13065 return true; 13066 } 13067 } 13068 } 13069 // Cannot simplify select with vector condition 13070 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 13071 13072 // If this is a select from two identical things, try to pull the operation 13073 // through the select. 13074 if (LHS.getOpcode() != RHS.getOpcode() || 13075 !LHS.hasOneUse() || !RHS.hasOneUse()) 13076 return false; 13077 13078 // If this is a load and the token chain is identical, replace the select 13079 // of two loads with a load through a select of the address to load from. 13080 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 13081 // constants have been dropped into the constant pool. 13082 if (LHS.getOpcode() == ISD::LOAD) { 13083 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 13084 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 13085 13086 // Token chains must be identical. 13087 if (LHS.getOperand(0) != RHS.getOperand(0) || 13088 // Do not let this transformation reduce the number of volatile loads. 13089 LLD->isVolatile() || RLD->isVolatile() || 13090 // FIXME: If either is a pre/post inc/dec load, 13091 // we'd need to split out the address adjustment. 13092 LLD->isIndexed() || RLD->isIndexed() || 13093 // If this is an EXTLOAD, the VT's must match. 13094 LLD->getMemoryVT() != RLD->getMemoryVT() || 13095 // If this is an EXTLOAD, the kind of extension must match. 13096 (LLD->getExtensionType() != RLD->getExtensionType() && 13097 // The only exception is if one of the extensions is anyext. 13098 LLD->getExtensionType() != ISD::EXTLOAD && 13099 RLD->getExtensionType() != ISD::EXTLOAD) || 13100 // FIXME: this discards src value information. This is 13101 // over-conservative. It would be beneficial to be able to remember 13102 // both potential memory locations. Since we are discarding 13103 // src value info, don't do the transformation if the memory 13104 // locations are not in the default address space. 13105 LLD->getPointerInfo().getAddrSpace() != 0 || 13106 RLD->getPointerInfo().getAddrSpace() != 0 || 13107 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 13108 LLD->getBasePtr().getValueType())) 13109 return false; 13110 13111 // Check that the select condition doesn't reach either load. If so, 13112 // folding this will induce a cycle into the DAG. If not, this is safe to 13113 // xform, so create a select of the addresses. 13114 SDValue Addr; 13115 if (TheSelect->getOpcode() == ISD::SELECT) { 13116 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 13117 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 13118 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 13119 return false; 13120 // The loads must not depend on one another. 13121 if (LLD->isPredecessorOf(RLD) || 13122 RLD->isPredecessorOf(LLD)) 13123 return false; 13124 Addr = DAG.getSelect(SDLoc(TheSelect), 13125 LLD->getBasePtr().getValueType(), 13126 TheSelect->getOperand(0), LLD->getBasePtr(), 13127 RLD->getBasePtr()); 13128 } else { // Otherwise SELECT_CC 13129 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 13130 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 13131 13132 if ((LLD->hasAnyUseOfValue(1) && 13133 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 13134 (RLD->hasAnyUseOfValue(1) && 13135 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 13136 return false; 13137 13138 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 13139 LLD->getBasePtr().getValueType(), 13140 TheSelect->getOperand(0), 13141 TheSelect->getOperand(1), 13142 LLD->getBasePtr(), RLD->getBasePtr(), 13143 TheSelect->getOperand(4)); 13144 } 13145 13146 SDValue Load; 13147 // It is safe to replace the two loads if they have different alignments, 13148 // but the new load must be the minimum (most restrictive) alignment of the 13149 // inputs. 13150 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 13151 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 13152 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 13153 Load = DAG.getLoad(TheSelect->getValueType(0), 13154 SDLoc(TheSelect), 13155 // FIXME: Discards pointer and AA info. 13156 LLD->getChain(), Addr, MachinePointerInfo(), 13157 LLD->isVolatile(), LLD->isNonTemporal(), 13158 isInvariant, Alignment); 13159 } else { 13160 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 13161 RLD->getExtensionType() : LLD->getExtensionType(), 13162 SDLoc(TheSelect), 13163 TheSelect->getValueType(0), 13164 // FIXME: Discards pointer and AA info. 13165 LLD->getChain(), Addr, MachinePointerInfo(), 13166 LLD->getMemoryVT(), LLD->isVolatile(), 13167 LLD->isNonTemporal(), isInvariant, Alignment); 13168 } 13169 13170 // Users of the select now use the result of the load. 13171 CombineTo(TheSelect, Load); 13172 13173 // Users of the old loads now use the new load's chain. We know the 13174 // old-load value is dead now. 13175 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 13176 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 13177 return true; 13178 } 13179 13180 return false; 13181 } 13182 13183 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 13184 /// where 'cond' is the comparison specified by CC. 13185 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 13186 SDValue N2, SDValue N3, 13187 ISD::CondCode CC, bool NotExtCompare) { 13188 // (x ? y : y) -> y. 13189 if (N2 == N3) return N2; 13190 13191 EVT VT = N2.getValueType(); 13192 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 13193 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 13194 13195 // Determine if the condition we're dealing with is constant 13196 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 13197 N0, N1, CC, DL, false); 13198 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 13199 13200 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) { 13201 // fold select_cc true, x, y -> x 13202 // fold select_cc false, x, y -> y 13203 return !SCCC->isNullValue() ? N2 : N3; 13204 } 13205 13206 // Check to see if we can simplify the select into an fabs node 13207 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 13208 // Allow either -0.0 or 0.0 13209 if (CFP->getValueAPF().isZero()) { 13210 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 13211 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 13212 N0 == N2 && N3.getOpcode() == ISD::FNEG && 13213 N2 == N3.getOperand(0)) 13214 return DAG.getNode(ISD::FABS, DL, VT, N0); 13215 13216 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 13217 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 13218 N0 == N3 && N2.getOpcode() == ISD::FNEG && 13219 N2.getOperand(0) == N3) 13220 return DAG.getNode(ISD::FABS, DL, VT, N3); 13221 } 13222 } 13223 13224 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 13225 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 13226 // in it. This is a win when the constant is not otherwise available because 13227 // it replaces two constant pool loads with one. We only do this if the FP 13228 // type is known to be legal, because if it isn't, then we are before legalize 13229 // types an we want the other legalization to happen first (e.g. to avoid 13230 // messing with soft float) and if the ConstantFP is not legal, because if 13231 // it is legal, we may not need to store the FP constant in a constant pool. 13232 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 13233 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 13234 if (TLI.isTypeLegal(N2.getValueType()) && 13235 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 13236 TargetLowering::Legal && 13237 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 13238 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 13239 // If both constants have multiple uses, then we won't need to do an 13240 // extra load, they are likely around in registers for other users. 13241 (TV->hasOneUse() || FV->hasOneUse())) { 13242 Constant *Elts[] = { 13243 const_cast<ConstantFP*>(FV->getConstantFPValue()), 13244 const_cast<ConstantFP*>(TV->getConstantFPValue()) 13245 }; 13246 Type *FPTy = Elts[0]->getType(); 13247 const DataLayout &TD = *TLI.getDataLayout(); 13248 13249 // Create a ConstantArray of the two constants. 13250 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 13251 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 13252 TD.getPrefTypeAlignment(FPTy)); 13253 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 13254 13255 // Get the offsets to the 0 and 1 element of the array so that we can 13256 // select between them. 13257 SDValue Zero = DAG.getIntPtrConstant(0, DL); 13258 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 13259 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 13260 13261 SDValue Cond = DAG.getSetCC(DL, 13262 getSetCCResultType(N0.getValueType()), 13263 N0, N1, CC); 13264 AddToWorklist(Cond.getNode()); 13265 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 13266 Cond, One, Zero); 13267 AddToWorklist(CstOffset.getNode()); 13268 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 13269 CstOffset); 13270 AddToWorklist(CPIdx.getNode()); 13271 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 13272 MachinePointerInfo::getConstantPool(), false, 13273 false, false, Alignment); 13274 } 13275 } 13276 13277 // Check to see if we can perform the "gzip trick", transforming 13278 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 13279 if (isNullConstant(N3) && CC == ISD::SETLT && 13280 (isNullConstant(N1) || // (a < 0) ? b : 0 13281 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0 13282 EVT XType = N0.getValueType(); 13283 EVT AType = N2.getValueType(); 13284 if (XType.bitsGE(AType)) { 13285 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 13286 // single-bit constant. 13287 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 13288 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 13289 ShCtV = XType.getSizeInBits() - ShCtV - 1; 13290 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0), 13291 getShiftAmountTy(N0.getValueType())); 13292 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 13293 XType, N0, ShCt); 13294 AddToWorklist(Shift.getNode()); 13295 13296 if (XType.bitsGT(AType)) { 13297 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13298 AddToWorklist(Shift.getNode()); 13299 } 13300 13301 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13302 } 13303 13304 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 13305 XType, N0, 13306 DAG.getConstant(XType.getSizeInBits() - 1, 13307 SDLoc(N0), 13308 getShiftAmountTy(N0.getValueType()))); 13309 AddToWorklist(Shift.getNode()); 13310 13311 if (XType.bitsGT(AType)) { 13312 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 13313 AddToWorklist(Shift.getNode()); 13314 } 13315 13316 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 13317 } 13318 } 13319 13320 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 13321 // where y is has a single bit set. 13322 // A plaintext description would be, we can turn the SELECT_CC into an AND 13323 // when the condition can be materialized as an all-ones register. Any 13324 // single bit-test can be materialized as an all-ones register with 13325 // shift-left and shift-right-arith. 13326 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 13327 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 13328 SDValue AndLHS = N0->getOperand(0); 13329 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 13330 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 13331 // Shift the tested bit over the sign bit. 13332 APInt AndMask = ConstAndRHS->getAPIntValue(); 13333 SDValue ShlAmt = 13334 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 13335 getShiftAmountTy(AndLHS.getValueType())); 13336 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 13337 13338 // Now arithmetic right shift it all the way over, so the result is either 13339 // all-ones, or zero. 13340 SDValue ShrAmt = 13341 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 13342 getShiftAmountTy(Shl.getValueType())); 13343 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 13344 13345 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 13346 } 13347 } 13348 13349 // fold select C, 16, 0 -> shl C, 4 13350 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() && 13351 TLI.getBooleanContents(N0.getValueType()) == 13352 TargetLowering::ZeroOrOneBooleanContent) { 13353 13354 // If the caller doesn't want us to simplify this into a zext of a compare, 13355 // don't do it. 13356 if (NotExtCompare && N2C->isOne()) 13357 return SDValue(); 13358 13359 // Get a SetCC of the condition 13360 // NOTE: Don't create a SETCC if it's not legal on this target. 13361 if (!LegalOperations || 13362 TLI.isOperationLegal(ISD::SETCC, 13363 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 13364 SDValue Temp, SCC; 13365 // cast from setcc result type to select result type 13366 if (LegalTypes) { 13367 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 13368 N0, N1, CC); 13369 if (N2.getValueType().bitsLT(SCC.getValueType())) 13370 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 13371 N2.getValueType()); 13372 else 13373 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13374 N2.getValueType(), SCC); 13375 } else { 13376 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 13377 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 13378 N2.getValueType(), SCC); 13379 } 13380 13381 AddToWorklist(SCC.getNode()); 13382 AddToWorklist(Temp.getNode()); 13383 13384 if (N2C->isOne()) 13385 return Temp; 13386 13387 // shl setcc result by log2 n2c 13388 return DAG.getNode( 13389 ISD::SHL, DL, N2.getValueType(), Temp, 13390 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp), 13391 getShiftAmountTy(Temp.getValueType()))); 13392 } 13393 } 13394 13395 // Check to see if this is the equivalent of setcc 13396 // FIXME: Turn all of these into setcc if setcc if setcc is legal 13397 // otherwise, go ahead with the folds. 13398 if (0 && isNullConstant(N3) && isOneConstant(N2)) { 13399 EVT XType = N0.getValueType(); 13400 if (!LegalOperations || 13401 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 13402 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 13403 if (Res.getValueType() != VT) 13404 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 13405 return Res; 13406 } 13407 13408 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 13409 if (isNullConstant(N1) && CC == ISD::SETEQ && 13410 (!LegalOperations || 13411 TLI.isOperationLegal(ISD::CTLZ, XType))) { 13412 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 13413 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 13414 DAG.getConstant(Log2_32(XType.getSizeInBits()), 13415 SDLoc(Ctlz), 13416 getShiftAmountTy(Ctlz.getValueType()))); 13417 } 13418 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 13419 if (isNullConstant(N1) && CC == ISD::SETGT) { 13420 SDLoc DL(N0); 13421 SDValue NegN0 = DAG.getNode(ISD::SUB, DL, 13422 XType, DAG.getConstant(0, DL, XType), N0); 13423 SDValue NotN0 = DAG.getNOT(DL, N0, XType); 13424 return DAG.getNode(ISD::SRL, DL, XType, 13425 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 13426 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13427 getShiftAmountTy(XType))); 13428 } 13429 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 13430 if (isAllOnesConstant(N1) && CC == ISD::SETGT) { 13431 SDLoc DL(N0); 13432 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0, 13433 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13434 getShiftAmountTy(N0.getValueType()))); 13435 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL, 13436 XType)); 13437 } 13438 } 13439 13440 // Check to see if this is an integer abs. 13441 // select_cc setg[te] X, 0, X, -X -> 13442 // select_cc setgt X, -1, X, -X -> 13443 // select_cc setl[te] X, 0, -X, X -> 13444 // select_cc setlt X, 1, -X, X -> 13445 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 13446 if (N1C) { 13447 ConstantSDNode *SubC = nullptr; 13448 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 13449 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 13450 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 13451 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 13452 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 13453 (N1C->isOne() && CC == ISD::SETLT)) && 13454 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 13455 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 13456 13457 EVT XType = N0.getValueType(); 13458 if (SubC && SubC->isNullValue() && XType.isInteger()) { 13459 SDLoc DL(N0); 13460 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, 13461 N0, 13462 DAG.getConstant(XType.getSizeInBits() - 1, DL, 13463 getShiftAmountTy(N0.getValueType()))); 13464 SDValue Add = DAG.getNode(ISD::ADD, DL, 13465 XType, N0, Shift); 13466 AddToWorklist(Shift.getNode()); 13467 AddToWorklist(Add.getNode()); 13468 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 13469 } 13470 } 13471 13472 return SDValue(); 13473 } 13474 13475 /// This is a stub for TargetLowering::SimplifySetCC. 13476 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 13477 SDValue N1, ISD::CondCode Cond, 13478 SDLoc DL, bool foldBooleans) { 13479 TargetLowering::DAGCombinerInfo 13480 DagCombineInfo(DAG, Level, false, this); 13481 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 13482 } 13483 13484 /// Given an ISD::SDIV node expressing a divide by constant, return 13485 /// a DAG expression to select that will generate the same value by multiplying 13486 /// by a magic number. 13487 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 13488 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 13489 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13490 if (!C) 13491 return SDValue(); 13492 13493 // Avoid division by zero. 13494 if (C->isNullValue()) 13495 return SDValue(); 13496 13497 std::vector<SDNode*> Built; 13498 SDValue S = 13499 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 13500 13501 for (SDNode *N : Built) 13502 AddToWorklist(N); 13503 return S; 13504 } 13505 13506 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 13507 /// DAG expression that will generate the same value by right shifting. 13508 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 13509 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13510 if (!C) 13511 return SDValue(); 13512 13513 // Avoid division by zero. 13514 if (C->isNullValue()) 13515 return SDValue(); 13516 13517 std::vector<SDNode *> Built; 13518 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 13519 13520 for (SDNode *N : Built) 13521 AddToWorklist(N); 13522 return S; 13523 } 13524 13525 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 13526 /// expression that will generate the same value by multiplying by a magic 13527 /// number. 13528 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 13529 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 13530 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 13531 if (!C) 13532 return SDValue(); 13533 13534 // Avoid division by zero. 13535 if (C->isNullValue()) 13536 return SDValue(); 13537 13538 std::vector<SDNode*> Built; 13539 SDValue S = 13540 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 13541 13542 for (SDNode *N : Built) 13543 AddToWorklist(N); 13544 return S; 13545 } 13546 13547 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) { 13548 if (Level >= AfterLegalizeDAG) 13549 return SDValue(); 13550 13551 // Expose the DAG combiner to the target combiner implementations. 13552 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 13553 13554 unsigned Iterations = 0; 13555 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 13556 if (Iterations) { 13557 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13558 // For the reciprocal, we need to find the zero of the function: 13559 // F(X) = A X - 1 [which has a zero at X = 1/A] 13560 // => 13561 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 13562 // does not require additional intermediate precision] 13563 EVT VT = Op.getValueType(); 13564 SDLoc DL(Op); 13565 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 13566 13567 AddToWorklist(Est.getNode()); 13568 13569 // Newton iterations: Est = Est + Est (1 - Arg * Est) 13570 for (unsigned i = 0; i < Iterations; ++i) { 13571 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est); 13572 AddToWorklist(NewEst.getNode()); 13573 13574 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst); 13575 AddToWorklist(NewEst.getNode()); 13576 13577 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 13578 AddToWorklist(NewEst.getNode()); 13579 13580 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst); 13581 AddToWorklist(Est.getNode()); 13582 } 13583 } 13584 return Est; 13585 } 13586 13587 return SDValue(); 13588 } 13589 13590 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13591 /// For the reciprocal sqrt, we need to find the zero of the function: 13592 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 13593 /// => 13594 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 13595 /// As a result, we precompute A/2 prior to the iteration loop. 13596 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 13597 unsigned Iterations) { 13598 EVT VT = Arg.getValueType(); 13599 SDLoc DL(Arg); 13600 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 13601 13602 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 13603 // this entire sequence requires only one FP constant. 13604 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg); 13605 AddToWorklist(HalfArg.getNode()); 13606 13607 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg); 13608 AddToWorklist(HalfArg.getNode()); 13609 13610 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 13611 for (unsigned i = 0; i < Iterations; ++i) { 13612 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 13613 AddToWorklist(NewEst.getNode()); 13614 13615 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst); 13616 AddToWorklist(NewEst.getNode()); 13617 13618 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst); 13619 AddToWorklist(NewEst.getNode()); 13620 13621 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 13622 AddToWorklist(Est.getNode()); 13623 } 13624 return Est; 13625 } 13626 13627 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 13628 /// For the reciprocal sqrt, we need to find the zero of the function: 13629 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 13630 /// => 13631 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 13632 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 13633 unsigned Iterations) { 13634 EVT VT = Arg.getValueType(); 13635 SDLoc DL(Arg); 13636 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 13637 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 13638 13639 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 13640 for (unsigned i = 0; i < Iterations; ++i) { 13641 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf); 13642 AddToWorklist(HalfEst.getNode()); 13643 13644 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 13645 AddToWorklist(Est.getNode()); 13646 13647 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg); 13648 AddToWorklist(Est.getNode()); 13649 13650 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree); 13651 AddToWorklist(Est.getNode()); 13652 13653 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst); 13654 AddToWorklist(Est.getNode()); 13655 } 13656 return Est; 13657 } 13658 13659 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) { 13660 if (Level >= AfterLegalizeDAG) 13661 return SDValue(); 13662 13663 // Expose the DAG combiner to the target combiner implementations. 13664 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 13665 unsigned Iterations = 0; 13666 bool UseOneConstNR = false; 13667 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 13668 AddToWorklist(Est.getNode()); 13669 if (Iterations) { 13670 Est = UseOneConstNR ? 13671 BuildRsqrtNROneConst(Op, Est, Iterations) : 13672 BuildRsqrtNRTwoConst(Op, Est, Iterations); 13673 } 13674 return Est; 13675 } 13676 13677 return SDValue(); 13678 } 13679 13680 /// Return true if base is a frame index, which is known not to alias with 13681 /// anything but itself. Provides base object and offset as results. 13682 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 13683 const GlobalValue *&GV, const void *&CV) { 13684 // Assume it is a primitive operation. 13685 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 13686 13687 // If it's an adding a simple constant then integrate the offset. 13688 if (Base.getOpcode() == ISD::ADD) { 13689 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 13690 Base = Base.getOperand(0); 13691 Offset += C->getZExtValue(); 13692 } 13693 } 13694 13695 // Return the underlying GlobalValue, and update the Offset. Return false 13696 // for GlobalAddressSDNode since the same GlobalAddress may be represented 13697 // by multiple nodes with different offsets. 13698 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 13699 GV = G->getGlobal(); 13700 Offset += G->getOffset(); 13701 return false; 13702 } 13703 13704 // Return the underlying Constant value, and update the Offset. Return false 13705 // for ConstantSDNodes since the same constant pool entry may be represented 13706 // by multiple nodes with different offsets. 13707 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 13708 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 13709 : (const void *)C->getConstVal(); 13710 Offset += C->getOffset(); 13711 return false; 13712 } 13713 // If it's any of the following then it can't alias with anything but itself. 13714 return isa<FrameIndexSDNode>(Base); 13715 } 13716 13717 /// Return true if there is any possibility that the two addresses overlap. 13718 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 13719 // If they are the same then they must be aliases. 13720 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 13721 13722 // If they are both volatile then they cannot be reordered. 13723 if (Op0->isVolatile() && Op1->isVolatile()) return true; 13724 13725 // Gather base node and offset information. 13726 SDValue Base1, Base2; 13727 int64_t Offset1, Offset2; 13728 const GlobalValue *GV1, *GV2; 13729 const void *CV1, *CV2; 13730 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 13731 Base1, Offset1, GV1, CV1); 13732 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 13733 Base2, Offset2, GV2, CV2); 13734 13735 // If they have a same base address then check to see if they overlap. 13736 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 13737 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 13738 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 13739 13740 // It is possible for different frame indices to alias each other, mostly 13741 // when tail call optimization reuses return address slots for arguments. 13742 // To catch this case, look up the actual index of frame indices to compute 13743 // the real alias relationship. 13744 if (isFrameIndex1 && isFrameIndex2) { 13745 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 13746 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 13747 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 13748 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 13749 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 13750 } 13751 13752 // Otherwise, if we know what the bases are, and they aren't identical, then 13753 // we know they cannot alias. 13754 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 13755 return false; 13756 13757 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 13758 // compared to the size and offset of the access, we may be able to prove they 13759 // do not alias. This check is conservative for now to catch cases created by 13760 // splitting vector types. 13761 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 13762 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 13763 (Op0->getMemoryVT().getSizeInBits() >> 3 == 13764 Op1->getMemoryVT().getSizeInBits() >> 3) && 13765 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 13766 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 13767 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 13768 13769 // There is no overlap between these relatively aligned accesses of similar 13770 // size, return no alias. 13771 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 13772 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 13773 return false; 13774 } 13775 13776 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 13777 ? CombinerGlobalAA 13778 : DAG.getSubtarget().useAA(); 13779 #ifndef NDEBUG 13780 if (CombinerAAOnlyFunc.getNumOccurrences() && 13781 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 13782 UseAA = false; 13783 #endif 13784 if (UseAA && 13785 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 13786 // Use alias analysis information. 13787 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 13788 Op1->getSrcValueOffset()); 13789 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 13790 Op0->getSrcValueOffset() - MinOffset; 13791 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 13792 Op1->getSrcValueOffset() - MinOffset; 13793 AliasAnalysis::AliasResult AAResult = 13794 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(), 13795 Overlap1, 13796 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 13797 AliasAnalysis::Location(Op1->getMemOperand()->getValue(), 13798 Overlap2, 13799 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 13800 if (AAResult == AliasAnalysis::NoAlias) 13801 return false; 13802 } 13803 13804 // Otherwise we have to assume they alias. 13805 return true; 13806 } 13807 13808 /// Walk up chain skipping non-aliasing memory nodes, 13809 /// looking for aliasing nodes and adding them to the Aliases vector. 13810 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 13811 SmallVectorImpl<SDValue> &Aliases) { 13812 SmallVector<SDValue, 8> Chains; // List of chains to visit. 13813 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 13814 13815 // Get alias information for node. 13816 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 13817 13818 // Starting off. 13819 Chains.push_back(OriginalChain); 13820 unsigned Depth = 0; 13821 13822 // Look at each chain and determine if it is an alias. If so, add it to the 13823 // aliases list. If not, then continue up the chain looking for the next 13824 // candidate. 13825 while (!Chains.empty()) { 13826 SDValue Chain = Chains.back(); 13827 Chains.pop_back(); 13828 13829 // For TokenFactor nodes, look at each operand and only continue up the 13830 // chain until we find two aliases. If we've seen two aliases, assume we'll 13831 // find more and revert to original chain since the xform is unlikely to be 13832 // profitable. 13833 // 13834 // FIXME: The depth check could be made to return the last non-aliasing 13835 // chain we found before we hit a tokenfactor rather than the original 13836 // chain. 13837 if (Depth > 6 || Aliases.size() == 2) { 13838 Aliases.clear(); 13839 Aliases.push_back(OriginalChain); 13840 return; 13841 } 13842 13843 // Don't bother if we've been before. 13844 if (!Visited.insert(Chain.getNode()).second) 13845 continue; 13846 13847 switch (Chain.getOpcode()) { 13848 case ISD::EntryToken: 13849 // Entry token is ideal chain operand, but handled in FindBetterChain. 13850 break; 13851 13852 case ISD::LOAD: 13853 case ISD::STORE: { 13854 // Get alias information for Chain. 13855 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 13856 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 13857 13858 // If chain is alias then stop here. 13859 if (!(IsLoad && IsOpLoad) && 13860 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 13861 Aliases.push_back(Chain); 13862 } else { 13863 // Look further up the chain. 13864 Chains.push_back(Chain.getOperand(0)); 13865 ++Depth; 13866 } 13867 break; 13868 } 13869 13870 case ISD::TokenFactor: 13871 // We have to check each of the operands of the token factor for "small" 13872 // token factors, so we queue them up. Adding the operands to the queue 13873 // (stack) in reverse order maintains the original order and increases the 13874 // likelihood that getNode will find a matching token factor (CSE.) 13875 if (Chain.getNumOperands() > 16) { 13876 Aliases.push_back(Chain); 13877 break; 13878 } 13879 for (unsigned n = Chain.getNumOperands(); n;) 13880 Chains.push_back(Chain.getOperand(--n)); 13881 ++Depth; 13882 break; 13883 13884 default: 13885 // For all other instructions we will just have to take what we can get. 13886 Aliases.push_back(Chain); 13887 break; 13888 } 13889 } 13890 13891 // We need to be careful here to also search for aliases through the 13892 // value operand of a store, etc. Consider the following situation: 13893 // Token1 = ... 13894 // L1 = load Token1, %52 13895 // S1 = store Token1, L1, %51 13896 // L2 = load Token1, %52+8 13897 // S2 = store Token1, L2, %51+8 13898 // Token2 = Token(S1, S2) 13899 // L3 = load Token2, %53 13900 // S3 = store Token2, L3, %52 13901 // L4 = load Token2, %53+8 13902 // S4 = store Token2, L4, %52+8 13903 // If we search for aliases of S3 (which loads address %52), and we look 13904 // only through the chain, then we'll miss the trivial dependence on L1 13905 // (which also loads from %52). We then might change all loads and 13906 // stores to use Token1 as their chain operand, which could result in 13907 // copying %53 into %52 before copying %52 into %51 (which should 13908 // happen first). 13909 // 13910 // The problem is, however, that searching for such data dependencies 13911 // can become expensive, and the cost is not directly related to the 13912 // chain depth. Instead, we'll rule out such configurations here by 13913 // insisting that we've visited all chain users (except for users 13914 // of the original chain, which is not necessary). When doing this, 13915 // we need to look through nodes we don't care about (otherwise, things 13916 // like register copies will interfere with trivial cases). 13917 13918 SmallVector<const SDNode *, 16> Worklist; 13919 for (const SDNode *N : Visited) 13920 if (N != OriginalChain.getNode()) 13921 Worklist.push_back(N); 13922 13923 while (!Worklist.empty()) { 13924 const SDNode *M = Worklist.pop_back_val(); 13925 13926 // We have already visited M, and want to make sure we've visited any uses 13927 // of M that we care about. For uses that we've not visisted, and don't 13928 // care about, queue them to the worklist. 13929 13930 for (SDNode::use_iterator UI = M->use_begin(), 13931 UIE = M->use_end(); UI != UIE; ++UI) 13932 if (UI.getUse().getValueType() == MVT::Other && 13933 Visited.insert(*UI).second) { 13934 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 13935 // We've not visited this use, and we care about it (it could have an 13936 // ordering dependency with the original node). 13937 Aliases.clear(); 13938 Aliases.push_back(OriginalChain); 13939 return; 13940 } 13941 13942 // We've not visited this use, but we don't care about it. Mark it as 13943 // visited and enqueue it to the worklist. 13944 Worklist.push_back(*UI); 13945 } 13946 } 13947 } 13948 13949 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 13950 /// (aliasing node.) 13951 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 13952 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 13953 13954 // Accumulate all the aliases to this node. 13955 GatherAllAliases(N, OldChain, Aliases); 13956 13957 // If no operands then chain to entry token. 13958 if (Aliases.size() == 0) 13959 return DAG.getEntryNode(); 13960 13961 // If a single operand then chain to it. We don't need to revisit it. 13962 if (Aliases.size() == 1) 13963 return Aliases[0]; 13964 13965 // Construct a custom tailored token factor. 13966 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 13967 } 13968 13969 /// This is the entry point for the file. 13970 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 13971 CodeGenOpt::Level OptLevel) { 13972 /// This is the main entry point to this class. 13973 DAGCombiner(*this, AA, OptLevel).Run(Level); 13974 } 13975