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 visitOR(SDNode *N); 250 SDValue visitXOR(SDNode *N); 251 SDValue SimplifyVBinOp(SDNode *N); 252 SDValue SimplifyVUnaryOp(SDNode *N); 253 SDValue visitSHL(SDNode *N); 254 SDValue visitSRA(SDNode *N); 255 SDValue visitSRL(SDNode *N); 256 SDValue visitRotate(SDNode *N); 257 SDValue visitCTLZ(SDNode *N); 258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 259 SDValue visitCTTZ(SDNode *N); 260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 261 SDValue visitCTPOP(SDNode *N); 262 SDValue visitSELECT(SDNode *N); 263 SDValue visitVSELECT(SDNode *N); 264 SDValue visitSELECT_CC(SDNode *N); 265 SDValue visitSETCC(SDNode *N); 266 SDValue visitSIGN_EXTEND(SDNode *N); 267 SDValue visitZERO_EXTEND(SDNode *N); 268 SDValue visitANY_EXTEND(SDNode *N); 269 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 270 SDValue visitTRUNCATE(SDNode *N); 271 SDValue visitBITCAST(SDNode *N); 272 SDValue visitBUILD_PAIR(SDNode *N); 273 SDValue visitFADD(SDNode *N); 274 SDValue visitFSUB(SDNode *N); 275 SDValue visitFMUL(SDNode *N); 276 SDValue visitFMA(SDNode *N); 277 SDValue visitFDIV(SDNode *N); 278 SDValue visitFREM(SDNode *N); 279 SDValue visitFSQRT(SDNode *N); 280 SDValue visitFCOPYSIGN(SDNode *N); 281 SDValue visitSINT_TO_FP(SDNode *N); 282 SDValue visitUINT_TO_FP(SDNode *N); 283 SDValue visitFP_TO_SINT(SDNode *N); 284 SDValue visitFP_TO_UINT(SDNode *N); 285 SDValue visitFP_ROUND(SDNode *N); 286 SDValue visitFP_ROUND_INREG(SDNode *N); 287 SDValue visitFP_EXTEND(SDNode *N); 288 SDValue visitFNEG(SDNode *N); 289 SDValue visitFABS(SDNode *N); 290 SDValue visitFCEIL(SDNode *N); 291 SDValue visitFTRUNC(SDNode *N); 292 SDValue visitFFLOOR(SDNode *N); 293 SDValue visitFMINNUM(SDNode *N); 294 SDValue visitFMAXNUM(SDNode *N); 295 SDValue visitBRCOND(SDNode *N); 296 SDValue visitBR_CC(SDNode *N); 297 SDValue visitLOAD(SDNode *N); 298 SDValue visitSTORE(SDNode *N); 299 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 300 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 301 SDValue visitBUILD_VECTOR(SDNode *N); 302 SDValue visitCONCAT_VECTORS(SDNode *N); 303 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 304 SDValue visitVECTOR_SHUFFLE(SDNode *N); 305 SDValue visitINSERT_SUBVECTOR(SDNode *N); 306 SDValue visitMLOAD(SDNode *N); 307 SDValue visitMSTORE(SDNode *N); 308 309 SDValue XformToShuffleWithZero(SDNode *N); 310 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS); 311 312 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 313 314 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 315 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N); 316 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2); 317 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2, 318 SDValue N3, ISD::CondCode CC, 319 bool NotExtCompare = false); 320 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 321 SDLoc DL, bool foldBooleans = true); 322 323 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 324 SDValue &CC) const; 325 bool isOneUseSetCC(SDValue N) const; 326 327 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 328 unsigned HiOp); 329 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 330 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 331 SDValue BuildSDIV(SDNode *N); 332 SDValue BuildSDIVPow2(SDNode *N); 333 SDValue BuildUDIV(SDNode *N); 334 SDValue BuildReciprocalEstimate(SDValue Op); 335 SDValue BuildRsqrtEstimate(SDValue Op); 336 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations); 337 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations); 338 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 339 bool DemandHighBits = true); 340 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 341 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 342 SDValue InnerPos, SDValue InnerNeg, 343 unsigned PosOpcode, unsigned NegOpcode, 344 SDLoc DL); 345 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL); 346 SDValue ReduceLoadWidth(SDNode *N); 347 SDValue ReduceLoadOpStoreWidth(SDNode *N); 348 SDValue TransformFPLoadStorePair(SDNode *N); 349 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 350 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N); 351 352 SDValue GetDemandedBits(SDValue V, const APInt &Mask); 353 354 /// Walk up chain skipping non-aliasing memory nodes, 355 /// looking for aliasing nodes and adding them to the Aliases vector. 356 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 357 SmallVectorImpl<SDValue> &Aliases); 358 359 /// Return true if there is any possibility that the two addresses overlap. 360 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const; 361 362 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 363 /// chain (aliasing node.) 364 SDValue FindBetterChain(SDNode *N, SDValue Chain); 365 366 /// Holds a pointer to an LSBaseSDNode as well as information on where it 367 /// is located in a sequence of memory operations connected by a chain. 368 struct MemOpLink { 369 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq): 370 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { } 371 // Ptr to the mem node. 372 LSBaseSDNode *MemNode; 373 // Offset from the base ptr. 374 int64_t OffsetFromBase; 375 // What is the sequence number of this mem node. 376 // Lowest mem operand in the DAG starts at zero. 377 unsigned SequenceNum; 378 }; 379 380 /// This is a helper function for MergeConsecutiveStores. When the source 381 /// elements of the consecutive stores are all constants or all extracted 382 /// vector elements, try to merge them into one larger store. 383 /// \return True if a merged store was created. 384 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 385 EVT MemVT, unsigned NumElem, 386 bool IsConstantSrc, bool UseVector); 387 388 /// Merge consecutive store operations into a wide store. 389 /// This optimization uses wide integers or vectors when possible. 390 /// \return True if some memory operations were changed. 391 bool MergeConsecutiveStores(StoreSDNode *N); 392 393 /// \brief Try to transform a truncation where C is a constant: 394 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 395 /// 396 /// \p N needs to be a truncation and its first operand an AND. Other 397 /// requirements are checked by the function (e.g. that trunc is 398 /// single-use) and if missed an empty SDValue is returned. 399 SDValue distributeTruncateThroughAnd(SDNode *N); 400 401 public: 402 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL) 403 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 404 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) { 405 AttributeSet FnAttrs = 406 DAG.getMachineFunction().getFunction()->getAttributes(); 407 ForCodeSize = 408 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, 409 Attribute::OptimizeForSize) || 410 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize); 411 } 412 413 /// Runs the dag combiner on all nodes in the work list 414 void Run(CombineLevel AtLevel); 415 416 SelectionDAG &getDAG() const { return DAG; } 417 418 /// Returns a type large enough to hold any valid shift amount - before type 419 /// legalization these can be huge. 420 EVT getShiftAmountTy(EVT LHSTy) { 421 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 422 if (LHSTy.isVector()) 423 return LHSTy; 424 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) 425 : TLI.getPointerTy(); 426 } 427 428 /// This method returns true if we are running before type legalization or 429 /// if the specified VT is legal. 430 bool isTypeLegal(const EVT &VT) { 431 if (!LegalTypes) return true; 432 return TLI.isTypeLegal(VT); 433 } 434 435 /// Convenience wrapper around TargetLowering::getSetCCResultType 436 EVT getSetCCResultType(EVT VT) const { 437 return TLI.getSetCCResultType(*DAG.getContext(), VT); 438 } 439 }; 440 } 441 442 443 namespace { 444 /// This class is a DAGUpdateListener that removes any deleted 445 /// nodes from the worklist. 446 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 447 DAGCombiner &DC; 448 public: 449 explicit WorklistRemover(DAGCombiner &dc) 450 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 451 452 void NodeDeleted(SDNode *N, SDNode *E) override { 453 DC.removeFromWorklist(N); 454 } 455 }; 456 } 457 458 //===----------------------------------------------------------------------===// 459 // TargetLowering::DAGCombinerInfo implementation 460 //===----------------------------------------------------------------------===// 461 462 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 463 ((DAGCombiner*)DC)->AddToWorklist(N); 464 } 465 466 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) { 467 ((DAGCombiner*)DC)->removeFromWorklist(N); 468 } 469 470 SDValue TargetLowering::DAGCombinerInfo:: 471 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) { 472 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 473 } 474 475 SDValue TargetLowering::DAGCombinerInfo:: 476 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 477 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 478 } 479 480 481 SDValue TargetLowering::DAGCombinerInfo:: 482 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 483 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 484 } 485 486 void TargetLowering::DAGCombinerInfo:: 487 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 488 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 489 } 490 491 //===----------------------------------------------------------------------===// 492 // Helper Functions 493 //===----------------------------------------------------------------------===// 494 495 void DAGCombiner::deleteAndRecombine(SDNode *N) { 496 removeFromWorklist(N); 497 498 // If the operands of this node are only used by the node, they will now be 499 // dead. Make sure to re-visit them and recursively delete dead nodes. 500 for (const SDValue &Op : N->ops()) 501 // For an operand generating multiple values, one of the values may 502 // become dead allowing further simplification (e.g. split index 503 // arithmetic from an indexed load). 504 if (Op->hasOneUse() || Op->getNumValues() > 1) 505 AddToWorklist(Op.getNode()); 506 507 DAG.DeleteNode(N); 508 } 509 510 /// Return 1 if we can compute the negated form of the specified expression for 511 /// the same cost as the expression itself, or 2 if we can compute the negated 512 /// form more cheaply than the expression itself. 513 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 514 const TargetLowering &TLI, 515 const TargetOptions *Options, 516 unsigned Depth = 0) { 517 // fneg is removable even if it has multiple uses. 518 if (Op.getOpcode() == ISD::FNEG) return 2; 519 520 // Don't allow anything with multiple uses. 521 if (!Op.hasOneUse()) return 0; 522 523 // Don't recurse exponentially. 524 if (Depth > 6) return 0; 525 526 switch (Op.getOpcode()) { 527 default: return false; 528 case ISD::ConstantFP: 529 // Don't invert constant FP values after legalize. The negated constant 530 // isn't necessarily legal. 531 return LegalOperations ? 0 : 1; 532 case ISD::FADD: 533 // FIXME: determine better conditions for this xform. 534 if (!Options->UnsafeFPMath) return 0; 535 536 // After operation legalization, it might not be legal to create new FSUBs. 537 if (LegalOperations && 538 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) 539 return 0; 540 541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 542 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 543 Options, Depth + 1)) 544 return V; 545 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 546 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 547 Depth + 1); 548 case ISD::FSUB: 549 // We can't turn -(A-B) into B-A when we honor signed zeros. 550 if (!Options->UnsafeFPMath) return 0; 551 552 // fold (fneg (fsub A, B)) -> (fsub B, A) 553 return 1; 554 555 case ISD::FMUL: 556 case ISD::FDIV: 557 if (Options->HonorSignDependentRoundingFPMath()) return 0; 558 559 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 560 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 561 Options, Depth + 1)) 562 return V; 563 564 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 565 Depth + 1); 566 567 case ISD::FP_EXTEND: 568 case ISD::FP_ROUND: 569 case ISD::FSIN: 570 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 571 Depth + 1); 572 } 573 } 574 575 /// If isNegatibleForFree returns true, return the newly negated expression. 576 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 577 bool LegalOperations, unsigned Depth = 0) { 578 const TargetOptions &Options = DAG.getTarget().Options; 579 // fneg is removable even if it has multiple uses. 580 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 581 582 // Don't allow anything with multiple uses. 583 assert(Op.hasOneUse() && "Unknown reuse!"); 584 585 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 586 switch (Op.getOpcode()) { 587 default: llvm_unreachable("Unknown code"); 588 case ISD::ConstantFP: { 589 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 590 V.changeSign(); 591 return DAG.getConstantFP(V, Op.getValueType()); 592 } 593 case ISD::FADD: 594 // FIXME: determine better conditions for this xform. 595 assert(Options.UnsafeFPMath); 596 597 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 598 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 599 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 600 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 601 GetNegatedExpression(Op.getOperand(0), DAG, 602 LegalOperations, Depth+1), 603 Op.getOperand(1)); 604 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 605 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 606 GetNegatedExpression(Op.getOperand(1), DAG, 607 LegalOperations, Depth+1), 608 Op.getOperand(0)); 609 case ISD::FSUB: 610 // We can't turn -(A-B) into B-A when we honor signed zeros. 611 assert(Options.UnsafeFPMath); 612 613 // fold (fneg (fsub 0, B)) -> B 614 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 615 if (N0CFP->getValueAPF().isZero()) 616 return Op.getOperand(1); 617 618 // fold (fneg (fsub A, B)) -> (fsub B, A) 619 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 620 Op.getOperand(1), Op.getOperand(0)); 621 622 case ISD::FMUL: 623 case ISD::FDIV: 624 assert(!Options.HonorSignDependentRoundingFPMath()); 625 626 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 627 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 628 DAG.getTargetLoweringInfo(), &Options, Depth+1)) 629 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 630 GetNegatedExpression(Op.getOperand(0), DAG, 631 LegalOperations, Depth+1), 632 Op.getOperand(1)); 633 634 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 636 Op.getOperand(0), 637 GetNegatedExpression(Op.getOperand(1), DAG, 638 LegalOperations, Depth+1)); 639 640 case ISD::FP_EXTEND: 641 case ISD::FSIN: 642 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 643 GetNegatedExpression(Op.getOperand(0), DAG, 644 LegalOperations, Depth+1)); 645 case ISD::FP_ROUND: 646 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 647 GetNegatedExpression(Op.getOperand(0), DAG, 648 LegalOperations, Depth+1), 649 Op.getOperand(1)); 650 } 651 } 652 653 // Return true if this node is a setcc, or is a select_cc 654 // that selects between the target values used for true and false, making it 655 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 656 // the appropriate nodes based on the type of node we are checking. This 657 // simplifies life a bit for the callers. 658 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 659 SDValue &CC) const { 660 if (N.getOpcode() == ISD::SETCC) { 661 LHS = N.getOperand(0); 662 RHS = N.getOperand(1); 663 CC = N.getOperand(2); 664 return true; 665 } 666 667 if (N.getOpcode() != ISD::SELECT_CC || 668 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 669 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 670 return false; 671 672 if (TLI.getBooleanContents(N.getValueType()) == 673 TargetLowering::UndefinedBooleanContent) 674 return false; 675 676 LHS = N.getOperand(0); 677 RHS = N.getOperand(1); 678 CC = N.getOperand(4); 679 return true; 680 } 681 682 /// Return true if this is a SetCC-equivalent operation with only one use. 683 /// If this is true, it allows the users to invert the operation for free when 684 /// it is profitable to do so. 685 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 686 SDValue N0, N1, N2; 687 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 688 return true; 689 return false; 690 } 691 692 /// Returns true if N is a BUILD_VECTOR node whose 693 /// elements are all the same constant or undefined. 694 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) { 695 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N); 696 if (!C) 697 return false; 698 699 APInt SplatUndef; 700 unsigned SplatBitSize; 701 bool HasAnyUndefs; 702 EVT EltVT = N->getValueType(0).getVectorElementType(); 703 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 704 HasAnyUndefs) && 705 EltVT.getSizeInBits() >= SplatBitSize); 706 } 707 708 // \brief Returns the SDNode if it is a constant BuildVector or constant. 709 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) { 710 if (isa<ConstantSDNode>(N)) 711 return N.getNode(); 712 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 713 if (BV && BV->isConstant()) 714 return BV; 715 return nullptr; 716 } 717 718 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 719 // int. 720 static ConstantSDNode *isConstOrConstSplat(SDValue N) { 721 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 722 return CN; 723 724 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 725 BitVector UndefElements; 726 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 727 728 // BuildVectors can truncate their operands. Ignore that case here. 729 // FIXME: We blindly ignore splats which include undef which is overly 730 // pessimistic. 731 if (CN && UndefElements.none() && 732 CN->getValueType(0) == N.getValueType().getScalarType()) 733 return CN; 734 } 735 736 return nullptr; 737 } 738 739 // \brief Returns the SDNode if it is a constant splat BuildVector or constant 740 // float. 741 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) { 742 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 743 return CN; 744 745 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 746 BitVector UndefElements; 747 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 748 749 if (CN && UndefElements.none()) 750 return CN; 751 } 752 753 return nullptr; 754 } 755 756 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL, 757 SDValue N0, SDValue N1) { 758 EVT VT = N0.getValueType(); 759 if (N0.getOpcode() == Opc) { 760 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) { 761 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) { 762 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 763 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R)) 764 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 765 return SDValue(); 766 } 767 if (N0.hasOneUse()) { 768 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 769 // use 770 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 771 if (!OpNode.getNode()) 772 return SDValue(); 773 AddToWorklist(OpNode.getNode()); 774 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 775 } 776 } 777 } 778 779 if (N1.getOpcode() == Opc) { 780 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) { 781 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) { 782 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 783 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L)) 784 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 785 return SDValue(); 786 } 787 if (N1.hasOneUse()) { 788 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one 789 // use 790 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0); 791 if (!OpNode.getNode()) 792 return SDValue(); 793 AddToWorklist(OpNode.getNode()); 794 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 795 } 796 } 797 } 798 799 return SDValue(); 800 } 801 802 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 803 bool AddTo) { 804 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 805 ++NodesCombined; 806 DEBUG(dbgs() << "\nReplacing.1 "; 807 N->dump(&DAG); 808 dbgs() << "\nWith: "; 809 To[0].getNode()->dump(&DAG); 810 dbgs() << " and " << NumTo-1 << " other values\n"); 811 for (unsigned i = 0, e = NumTo; i != e; ++i) 812 assert((!To[i].getNode() || 813 N->getValueType(i) == To[i].getValueType()) && 814 "Cannot combine value to value of different type!"); 815 816 WorklistRemover DeadNodes(*this); 817 DAG.ReplaceAllUsesWith(N, To); 818 if (AddTo) { 819 // Push the new nodes and any users onto the worklist 820 for (unsigned i = 0, e = NumTo; i != e; ++i) { 821 if (To[i].getNode()) { 822 AddToWorklist(To[i].getNode()); 823 AddUsersToWorklist(To[i].getNode()); 824 } 825 } 826 } 827 828 // Finally, if the node is now dead, remove it from the graph. The node 829 // may not be dead if the replacement process recursively simplified to 830 // something else needing this node. 831 if (N->use_empty()) 832 deleteAndRecombine(N); 833 return SDValue(N, 0); 834 } 835 836 void DAGCombiner:: 837 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 838 // Replace all uses. If any nodes become isomorphic to other nodes and 839 // are deleted, make sure to remove them from our worklist. 840 WorklistRemover DeadNodes(*this); 841 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 842 843 // Push the new node and any (possibly new) users onto the worklist. 844 AddToWorklist(TLO.New.getNode()); 845 AddUsersToWorklist(TLO.New.getNode()); 846 847 // Finally, if the node is now dead, remove it from the graph. The node 848 // may not be dead if the replacement process recursively simplified to 849 // something else needing this node. 850 if (TLO.Old.getNode()->use_empty()) 851 deleteAndRecombine(TLO.Old.getNode()); 852 } 853 854 /// Check the specified integer node value to see if it can be simplified or if 855 /// things it uses can be simplified by bit propagation. If so, return true. 856 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) { 857 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 858 APInt KnownZero, KnownOne; 859 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) 860 return false; 861 862 // Revisit the node. 863 AddToWorklist(Op.getNode()); 864 865 // Replace the old value with the new one. 866 ++NodesCombined; 867 DEBUG(dbgs() << "\nReplacing.2 "; 868 TLO.Old.getNode()->dump(&DAG); 869 dbgs() << "\nWith: "; 870 TLO.New.getNode()->dump(&DAG); 871 dbgs() << '\n'); 872 873 CommitTargetLoweringOpt(TLO); 874 return true; 875 } 876 877 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 878 SDLoc dl(Load); 879 EVT VT = Load->getValueType(0); 880 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0)); 881 882 DEBUG(dbgs() << "\nReplacing.9 "; 883 Load->dump(&DAG); 884 dbgs() << "\nWith: "; 885 Trunc.getNode()->dump(&DAG); 886 dbgs() << '\n'); 887 WorklistRemover DeadNodes(*this); 888 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 889 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 890 deleteAndRecombine(Load); 891 AddToWorklist(Trunc.getNode()); 892 } 893 894 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 895 Replace = false; 896 SDLoc dl(Op); 897 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 898 EVT MemVT = LD->getMemoryVT(); 899 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 900 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 901 : ISD::EXTLOAD) 902 : LD->getExtensionType(); 903 Replace = true; 904 return DAG.getExtLoad(ExtType, dl, PVT, 905 LD->getChain(), LD->getBasePtr(), 906 MemVT, LD->getMemOperand()); 907 } 908 909 unsigned Opc = Op.getOpcode(); 910 switch (Opc) { 911 default: break; 912 case ISD::AssertSext: 913 return DAG.getNode(ISD::AssertSext, dl, PVT, 914 SExtPromoteOperand(Op.getOperand(0), PVT), 915 Op.getOperand(1)); 916 case ISD::AssertZext: 917 return DAG.getNode(ISD::AssertZext, dl, PVT, 918 ZExtPromoteOperand(Op.getOperand(0), PVT), 919 Op.getOperand(1)); 920 case ISD::Constant: { 921 unsigned ExtOpc = 922 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 923 return DAG.getNode(ExtOpc, dl, PVT, Op); 924 } 925 } 926 927 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 928 return SDValue(); 929 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op); 930 } 931 932 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 933 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 934 return SDValue(); 935 EVT OldVT = Op.getValueType(); 936 SDLoc dl(Op); 937 bool Replace = false; 938 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 939 if (!NewOp.getNode()) 940 return SDValue(); 941 AddToWorklist(NewOp.getNode()); 942 943 if (Replace) 944 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 945 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp, 946 DAG.getValueType(OldVT)); 947 } 948 949 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 950 EVT OldVT = Op.getValueType(); 951 SDLoc dl(Op); 952 bool Replace = false; 953 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 954 if (!NewOp.getNode()) 955 return SDValue(); 956 AddToWorklist(NewOp.getNode()); 957 958 if (Replace) 959 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 960 return DAG.getZeroExtendInReg(NewOp, dl, OldVT); 961 } 962 963 /// Promote the specified integer binary operation if the target indicates it is 964 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 965 /// i32 since i16 instructions are longer. 966 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 967 if (!LegalOperations) 968 return SDValue(); 969 970 EVT VT = Op.getValueType(); 971 if (VT.isVector() || !VT.isInteger()) 972 return SDValue(); 973 974 // If operation type is 'undesirable', e.g. i16 on x86, consider 975 // promoting it. 976 unsigned Opc = Op.getOpcode(); 977 if (TLI.isTypeDesirableForOp(Opc, VT)) 978 return SDValue(); 979 980 EVT PVT = VT; 981 // Consult target whether it is a good idea to promote this operation and 982 // what's the right type to promote it to. 983 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 984 assert(PVT != VT && "Don't know what type to promote to!"); 985 986 bool Replace0 = false; 987 SDValue N0 = Op.getOperand(0); 988 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 989 if (!NN0.getNode()) 990 return SDValue(); 991 992 bool Replace1 = false; 993 SDValue N1 = Op.getOperand(1); 994 SDValue NN1; 995 if (N0 == N1) 996 NN1 = NN0; 997 else { 998 NN1 = PromoteOperand(N1, PVT, Replace1); 999 if (!NN1.getNode()) 1000 return SDValue(); 1001 } 1002 1003 AddToWorklist(NN0.getNode()); 1004 if (NN1.getNode()) 1005 AddToWorklist(NN1.getNode()); 1006 1007 if (Replace0) 1008 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1009 if (Replace1) 1010 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1011 1012 DEBUG(dbgs() << "\nPromoting "; 1013 Op.getNode()->dump(&DAG)); 1014 SDLoc dl(Op); 1015 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1016 DAG.getNode(Opc, dl, PVT, NN0, NN1)); 1017 } 1018 return SDValue(); 1019 } 1020 1021 /// Promote the specified integer shift operation if the target indicates it is 1022 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1023 /// i32 since i16 instructions are longer. 1024 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1025 if (!LegalOperations) 1026 return SDValue(); 1027 1028 EVT VT = Op.getValueType(); 1029 if (VT.isVector() || !VT.isInteger()) 1030 return SDValue(); 1031 1032 // If operation type is 'undesirable', e.g. i16 on x86, consider 1033 // promoting it. 1034 unsigned Opc = Op.getOpcode(); 1035 if (TLI.isTypeDesirableForOp(Opc, VT)) 1036 return SDValue(); 1037 1038 EVT PVT = VT; 1039 // Consult target whether it is a good idea to promote this operation and 1040 // what's the right type to promote it to. 1041 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1042 assert(PVT != VT && "Don't know what type to promote to!"); 1043 1044 bool Replace = false; 1045 SDValue N0 = Op.getOperand(0); 1046 if (Opc == ISD::SRA) 1047 N0 = SExtPromoteOperand(Op.getOperand(0), PVT); 1048 else if (Opc == ISD::SRL) 1049 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT); 1050 else 1051 N0 = PromoteOperand(N0, PVT, Replace); 1052 if (!N0.getNode()) 1053 return SDValue(); 1054 1055 AddToWorklist(N0.getNode()); 1056 if (Replace) 1057 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1058 1059 DEBUG(dbgs() << "\nPromoting "; 1060 Op.getNode()->dump(&DAG)); 1061 SDLoc dl(Op); 1062 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1063 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1))); 1064 } 1065 return SDValue(); 1066 } 1067 1068 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1069 if (!LegalOperations) 1070 return SDValue(); 1071 1072 EVT VT = Op.getValueType(); 1073 if (VT.isVector() || !VT.isInteger()) 1074 return SDValue(); 1075 1076 // If operation type is 'undesirable', e.g. i16 on x86, consider 1077 // promoting it. 1078 unsigned Opc = Op.getOpcode(); 1079 if (TLI.isTypeDesirableForOp(Opc, VT)) 1080 return SDValue(); 1081 1082 EVT PVT = VT; 1083 // Consult target whether it is a good idea to promote this operation and 1084 // what's the right type to promote it to. 1085 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1086 assert(PVT != VT && "Don't know what type to promote to!"); 1087 // fold (aext (aext x)) -> (aext x) 1088 // fold (aext (zext x)) -> (zext x) 1089 // fold (aext (sext x)) -> (sext x) 1090 DEBUG(dbgs() << "\nPromoting "; 1091 Op.getNode()->dump(&DAG)); 1092 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1093 } 1094 return SDValue(); 1095 } 1096 1097 bool DAGCombiner::PromoteLoad(SDValue Op) { 1098 if (!LegalOperations) 1099 return false; 1100 1101 EVT VT = Op.getValueType(); 1102 if (VT.isVector() || !VT.isInteger()) 1103 return false; 1104 1105 // If operation type is 'undesirable', e.g. i16 on x86, consider 1106 // promoting it. 1107 unsigned Opc = Op.getOpcode(); 1108 if (TLI.isTypeDesirableForOp(Opc, VT)) 1109 return false; 1110 1111 EVT PVT = VT; 1112 // Consult target whether it is a good idea to promote this operation and 1113 // what's the right type to promote it to. 1114 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1115 assert(PVT != VT && "Don't know what type to promote to!"); 1116 1117 SDLoc dl(Op); 1118 SDNode *N = Op.getNode(); 1119 LoadSDNode *LD = cast<LoadSDNode>(N); 1120 EVT MemVT = LD->getMemoryVT(); 1121 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) 1122 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD 1123 : ISD::EXTLOAD) 1124 : LD->getExtensionType(); 1125 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT, 1126 LD->getChain(), LD->getBasePtr(), 1127 MemVT, LD->getMemOperand()); 1128 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD); 1129 1130 DEBUG(dbgs() << "\nPromoting "; 1131 N->dump(&DAG); 1132 dbgs() << "\nTo: "; 1133 Result.getNode()->dump(&DAG); 1134 dbgs() << '\n'); 1135 WorklistRemover DeadNodes(*this); 1136 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1137 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1138 deleteAndRecombine(N); 1139 AddToWorklist(Result.getNode()); 1140 return true; 1141 } 1142 return false; 1143 } 1144 1145 /// \brief Recursively delete a node which has no uses and any operands for 1146 /// which it is the only use. 1147 /// 1148 /// Note that this both deletes the nodes and removes them from the worklist. 1149 /// It also adds any nodes who have had a user deleted to the worklist as they 1150 /// may now have only one use and subject to other combines. 1151 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1152 if (!N->use_empty()) 1153 return false; 1154 1155 SmallSetVector<SDNode *, 16> Nodes; 1156 Nodes.insert(N); 1157 do { 1158 N = Nodes.pop_back_val(); 1159 if (!N) 1160 continue; 1161 1162 if (N->use_empty()) { 1163 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1164 Nodes.insert(N->getOperand(i).getNode()); 1165 1166 removeFromWorklist(N); 1167 DAG.DeleteNode(N); 1168 } else { 1169 AddToWorklist(N); 1170 } 1171 } while (!Nodes.empty()); 1172 return true; 1173 } 1174 1175 //===----------------------------------------------------------------------===// 1176 // Main DAG Combiner implementation 1177 //===----------------------------------------------------------------------===// 1178 1179 void DAGCombiner::Run(CombineLevel AtLevel) { 1180 // set the instance variables, so that the various visit routines may use it. 1181 Level = AtLevel; 1182 LegalOperations = Level >= AfterLegalizeVectorOps; 1183 LegalTypes = Level >= AfterLegalizeTypes; 1184 1185 // Early exit if this basic block is in an optnone function. 1186 AttributeSet FnAttrs = 1187 DAG.getMachineFunction().getFunction()->getAttributes(); 1188 if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex, 1189 Attribute::OptimizeNone)) 1190 return; 1191 1192 // Add all the dag nodes to the worklist. 1193 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(), 1194 E = DAG.allnodes_end(); I != E; ++I) 1195 AddToWorklist(I); 1196 1197 // Create a dummy node (which is not added to allnodes), that adds a reference 1198 // to the root node, preventing it from being deleted, and tracking any 1199 // changes of the root. 1200 HandleSDNode Dummy(DAG.getRoot()); 1201 1202 // while the worklist isn't empty, find a node and 1203 // try and combine it. 1204 while (!WorklistMap.empty()) { 1205 SDNode *N; 1206 // The Worklist holds the SDNodes in order, but it may contain null entries. 1207 do { 1208 N = Worklist.pop_back_val(); 1209 } while (!N); 1210 1211 bool GoodWorklistEntry = WorklistMap.erase(N); 1212 (void)GoodWorklistEntry; 1213 assert(GoodWorklistEntry && 1214 "Found a worklist entry without a corresponding map entry!"); 1215 1216 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1217 // N is deleted from the DAG, since they too may now be dead or may have a 1218 // reduced number of uses, allowing other xforms. 1219 if (recursivelyDeleteUnusedNodes(N)) 1220 continue; 1221 1222 WorklistRemover DeadNodes(*this); 1223 1224 // If this combine is running after legalizing the DAG, re-legalize any 1225 // nodes pulled off the worklist. 1226 if (Level == AfterLegalizeDAG) { 1227 SmallSetVector<SDNode *, 16> UpdatedNodes; 1228 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1229 1230 for (SDNode *LN : UpdatedNodes) { 1231 AddToWorklist(LN); 1232 AddUsersToWorklist(LN); 1233 } 1234 if (!NIsValid) 1235 continue; 1236 } 1237 1238 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1239 1240 // Add any operands of the new node which have not yet been combined to the 1241 // worklist as well. Because the worklist uniques things already, this 1242 // won't repeatedly process the same operand. 1243 CombinedNodes.insert(N); 1244 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1245 if (!CombinedNodes.count(N->getOperand(i).getNode())) 1246 AddToWorklist(N->getOperand(i).getNode()); 1247 1248 SDValue RV = combine(N); 1249 1250 if (!RV.getNode()) 1251 continue; 1252 1253 ++NodesCombined; 1254 1255 // If we get back the same node we passed in, rather than a new node or 1256 // zero, we know that the node must have defined multiple values and 1257 // CombineTo was used. Since CombineTo takes care of the worklist 1258 // mechanics for us, we have no work to do in this case. 1259 if (RV.getNode() == N) 1260 continue; 1261 1262 assert(N->getOpcode() != ISD::DELETED_NODE && 1263 RV.getNode()->getOpcode() != ISD::DELETED_NODE && 1264 "Node was deleted but visit returned new node!"); 1265 1266 DEBUG(dbgs() << " ... into: "; 1267 RV.getNode()->dump(&DAG)); 1268 1269 // Transfer debug value. 1270 DAG.TransferDbgValues(SDValue(N, 0), RV); 1271 if (N->getNumValues() == RV.getNode()->getNumValues()) 1272 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1273 else { 1274 assert(N->getValueType(0) == RV.getValueType() && 1275 N->getNumValues() == 1 && "Type mismatch"); 1276 SDValue OpV = RV; 1277 DAG.ReplaceAllUsesWith(N, &OpV); 1278 } 1279 1280 // Push the new node and any users onto the worklist 1281 AddToWorklist(RV.getNode()); 1282 AddUsersToWorklist(RV.getNode()); 1283 1284 // Finally, if the node is now dead, remove it from the graph. The node 1285 // may not be dead if the replacement process recursively simplified to 1286 // something else needing this node. This will also take care of adding any 1287 // operands which have lost a user to the worklist. 1288 recursivelyDeleteUnusedNodes(N); 1289 } 1290 1291 // If the root changed (e.g. it was a dead load, update the root). 1292 DAG.setRoot(Dummy.getValue()); 1293 DAG.RemoveDeadNodes(); 1294 } 1295 1296 SDValue DAGCombiner::visit(SDNode *N) { 1297 switch (N->getOpcode()) { 1298 default: break; 1299 case ISD::TokenFactor: return visitTokenFactor(N); 1300 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1301 case ISD::ADD: return visitADD(N); 1302 case ISD::SUB: return visitSUB(N); 1303 case ISD::ADDC: return visitADDC(N); 1304 case ISD::SUBC: return visitSUBC(N); 1305 case ISD::ADDE: return visitADDE(N); 1306 case ISD::SUBE: return visitSUBE(N); 1307 case ISD::MUL: return visitMUL(N); 1308 case ISD::SDIV: return visitSDIV(N); 1309 case ISD::UDIV: return visitUDIV(N); 1310 case ISD::SREM: return visitSREM(N); 1311 case ISD::UREM: return visitUREM(N); 1312 case ISD::MULHU: return visitMULHU(N); 1313 case ISD::MULHS: return visitMULHS(N); 1314 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1315 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1316 case ISD::SMULO: return visitSMULO(N); 1317 case ISD::UMULO: return visitUMULO(N); 1318 case ISD::SDIVREM: return visitSDIVREM(N); 1319 case ISD::UDIVREM: return visitUDIVREM(N); 1320 case ISD::AND: return visitAND(N); 1321 case ISD::OR: return visitOR(N); 1322 case ISD::XOR: return visitXOR(N); 1323 case ISD::SHL: return visitSHL(N); 1324 case ISD::SRA: return visitSRA(N); 1325 case ISD::SRL: return visitSRL(N); 1326 case ISD::ROTR: 1327 case ISD::ROTL: return visitRotate(N); 1328 case ISD::CTLZ: return visitCTLZ(N); 1329 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1330 case ISD::CTTZ: return visitCTTZ(N); 1331 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1332 case ISD::CTPOP: return visitCTPOP(N); 1333 case ISD::SELECT: return visitSELECT(N); 1334 case ISD::VSELECT: return visitVSELECT(N); 1335 case ISD::SELECT_CC: return visitSELECT_CC(N); 1336 case ISD::SETCC: return visitSETCC(N); 1337 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1338 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1339 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1340 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1341 case ISD::TRUNCATE: return visitTRUNCATE(N); 1342 case ISD::BITCAST: return visitBITCAST(N); 1343 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1344 case ISD::FADD: return visitFADD(N); 1345 case ISD::FSUB: return visitFSUB(N); 1346 case ISD::FMUL: return visitFMUL(N); 1347 case ISD::FMA: return visitFMA(N); 1348 case ISD::FDIV: return visitFDIV(N); 1349 case ISD::FREM: return visitFREM(N); 1350 case ISD::FSQRT: return visitFSQRT(N); 1351 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1352 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1353 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1354 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1355 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1356 case ISD::FP_ROUND: return visitFP_ROUND(N); 1357 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1358 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1359 case ISD::FNEG: return visitFNEG(N); 1360 case ISD::FABS: return visitFABS(N); 1361 case ISD::FFLOOR: return visitFFLOOR(N); 1362 case ISD::FMINNUM: return visitFMINNUM(N); 1363 case ISD::FMAXNUM: return visitFMAXNUM(N); 1364 case ISD::FCEIL: return visitFCEIL(N); 1365 case ISD::FTRUNC: return visitFTRUNC(N); 1366 case ISD::BRCOND: return visitBRCOND(N); 1367 case ISD::BR_CC: return visitBR_CC(N); 1368 case ISD::LOAD: return visitLOAD(N); 1369 case ISD::STORE: return visitSTORE(N); 1370 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1371 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1372 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1373 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1374 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1375 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1376 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1377 case ISD::MLOAD: return visitMLOAD(N); 1378 case ISD::MSTORE: return visitMSTORE(N); 1379 } 1380 return SDValue(); 1381 } 1382 1383 SDValue DAGCombiner::combine(SDNode *N) { 1384 SDValue RV = visit(N); 1385 1386 // If nothing happened, try a target-specific DAG combine. 1387 if (!RV.getNode()) { 1388 assert(N->getOpcode() != ISD::DELETED_NODE && 1389 "Node was deleted but visit returned NULL!"); 1390 1391 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1392 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1393 1394 // Expose the DAG combiner to the target combiner impls. 1395 TargetLowering::DAGCombinerInfo 1396 DagCombineInfo(DAG, Level, false, this); 1397 1398 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1399 } 1400 } 1401 1402 // If nothing happened still, try promoting the operation. 1403 if (!RV.getNode()) { 1404 switch (N->getOpcode()) { 1405 default: break; 1406 case ISD::ADD: 1407 case ISD::SUB: 1408 case ISD::MUL: 1409 case ISD::AND: 1410 case ISD::OR: 1411 case ISD::XOR: 1412 RV = PromoteIntBinOp(SDValue(N, 0)); 1413 break; 1414 case ISD::SHL: 1415 case ISD::SRA: 1416 case ISD::SRL: 1417 RV = PromoteIntShiftOp(SDValue(N, 0)); 1418 break; 1419 case ISD::SIGN_EXTEND: 1420 case ISD::ZERO_EXTEND: 1421 case ISD::ANY_EXTEND: 1422 RV = PromoteExtend(SDValue(N, 0)); 1423 break; 1424 case ISD::LOAD: 1425 if (PromoteLoad(SDValue(N, 0))) 1426 RV = SDValue(N, 0); 1427 break; 1428 } 1429 } 1430 1431 // If N is a commutative binary node, try commuting it to enable more 1432 // sdisel CSE. 1433 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) && 1434 N->getNumValues() == 1) { 1435 SDValue N0 = N->getOperand(0); 1436 SDValue N1 = N->getOperand(1); 1437 1438 // Constant operands are canonicalized to RHS. 1439 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) { 1440 SDValue Ops[] = {N1, N0}; 1441 SDNode *CSENode; 1442 if (const BinaryWithFlagsSDNode *BinNode = 1443 dyn_cast<BinaryWithFlagsSDNode>(N)) { 1444 CSENode = DAG.getNodeIfExists( 1445 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(), 1446 BinNode->hasNoSignedWrap(), BinNode->isExact()); 1447 } else { 1448 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops); 1449 } 1450 if (CSENode) 1451 return SDValue(CSENode, 0); 1452 } 1453 } 1454 1455 return RV; 1456 } 1457 1458 /// Given a node, return its input chain if it has one, otherwise return a null 1459 /// sd operand. 1460 static SDValue getInputChainForNode(SDNode *N) { 1461 if (unsigned NumOps = N->getNumOperands()) { 1462 if (N->getOperand(0).getValueType() == MVT::Other) 1463 return N->getOperand(0); 1464 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1465 return N->getOperand(NumOps-1); 1466 for (unsigned i = 1; i < NumOps-1; ++i) 1467 if (N->getOperand(i).getValueType() == MVT::Other) 1468 return N->getOperand(i); 1469 } 1470 return SDValue(); 1471 } 1472 1473 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1474 // If N has two operands, where one has an input chain equal to the other, 1475 // the 'other' chain is redundant. 1476 if (N->getNumOperands() == 2) { 1477 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1478 return N->getOperand(0); 1479 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1480 return N->getOperand(1); 1481 } 1482 1483 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1484 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1485 SmallPtrSet<SDNode*, 16> SeenOps; 1486 bool Changed = false; // If we should replace this token factor. 1487 1488 // Start out with this token factor. 1489 TFs.push_back(N); 1490 1491 // Iterate through token factors. The TFs grows when new token factors are 1492 // encountered. 1493 for (unsigned i = 0; i < TFs.size(); ++i) { 1494 SDNode *TF = TFs[i]; 1495 1496 // Check each of the operands. 1497 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) { 1498 SDValue Op = TF->getOperand(i); 1499 1500 switch (Op.getOpcode()) { 1501 case ISD::EntryToken: 1502 // Entry tokens don't need to be added to the list. They are 1503 // rededundant. 1504 Changed = true; 1505 break; 1506 1507 case ISD::TokenFactor: 1508 if (Op.hasOneUse() && 1509 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) { 1510 // Queue up for processing. 1511 TFs.push_back(Op.getNode()); 1512 // Clean up in case the token factor is removed. 1513 AddToWorklist(Op.getNode()); 1514 Changed = true; 1515 break; 1516 } 1517 // Fall thru 1518 1519 default: 1520 // Only add if it isn't already in the list. 1521 if (SeenOps.insert(Op.getNode()).second) 1522 Ops.push_back(Op); 1523 else 1524 Changed = true; 1525 break; 1526 } 1527 } 1528 } 1529 1530 SDValue Result; 1531 1532 // If we've change things around then replace token factor. 1533 if (Changed) { 1534 if (Ops.empty()) { 1535 // The entry token is the only possible outcome. 1536 Result = DAG.getEntryNode(); 1537 } else { 1538 // New and improved token factor. 1539 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops); 1540 } 1541 1542 // Don't add users to work list. 1543 return CombineTo(N, Result, false); 1544 } 1545 1546 return Result; 1547 } 1548 1549 /// MERGE_VALUES can always be eliminated. 1550 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1551 WorklistRemover DeadNodes(*this); 1552 // Replacing results may cause a different MERGE_VALUES to suddenly 1553 // be CSE'd with N, and carry its uses with it. Iterate until no 1554 // uses remain, to ensure that the node can be safely deleted. 1555 // First add the users of this node to the work list so that they 1556 // can be tried again once they have new operands. 1557 AddUsersToWorklist(N); 1558 do { 1559 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1560 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i)); 1561 } while (!N->use_empty()); 1562 deleteAndRecombine(N); 1563 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1564 } 1565 1566 SDValue DAGCombiner::visitADD(SDNode *N) { 1567 SDValue N0 = N->getOperand(0); 1568 SDValue N1 = N->getOperand(1); 1569 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1570 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1571 EVT VT = N0.getValueType(); 1572 1573 // fold vector ops 1574 if (VT.isVector()) { 1575 SDValue FoldedVOp = SimplifyVBinOp(N); 1576 if (FoldedVOp.getNode()) return FoldedVOp; 1577 1578 // fold (add x, 0) -> x, vector edition 1579 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1580 return N0; 1581 if (ISD::isBuildVectorAllZeros(N0.getNode())) 1582 return N1; 1583 } 1584 1585 // fold (add x, undef) -> undef 1586 if (N0.getOpcode() == ISD::UNDEF) 1587 return N0; 1588 if (N1.getOpcode() == ISD::UNDEF) 1589 return N1; 1590 // fold (add c1, c2) -> c1+c2 1591 if (N0C && N1C) 1592 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C); 1593 // canonicalize constant to RHS 1594 if (N0C && !N1C) 1595 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0); 1596 // fold (add x, 0) -> x 1597 if (N1C && N1C->isNullValue()) 1598 return N0; 1599 // fold (add Sym, c) -> Sym+c 1600 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1601 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C && 1602 GA->getOpcode() == ISD::GlobalAddress) 1603 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1604 GA->getOffset() + 1605 (uint64_t)N1C->getSExtValue()); 1606 // fold ((c1-A)+c2) -> (c1+c2)-A 1607 if (N1C && N0.getOpcode() == ISD::SUB) 1608 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) 1609 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1610 DAG.getConstant(N1C->getAPIntValue()+ 1611 N0C->getAPIntValue(), VT), 1612 N0.getOperand(1)); 1613 // reassociate add 1614 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1); 1615 if (RADD.getNode()) 1616 return RADD; 1617 // fold ((0-A) + B) -> B-A 1618 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) && 1619 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue()) 1620 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1)); 1621 // fold (A + (0-B)) -> A-B 1622 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) && 1623 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue()) 1624 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1)); 1625 // fold (A+(B-A)) -> B 1626 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 1627 return N1.getOperand(0); 1628 // fold ((B-A)+A) -> B 1629 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 1630 return N0.getOperand(0); 1631 // fold (A+(B-(A+C))) to (B-C) 1632 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1633 N0 == N1.getOperand(1).getOperand(0)) 1634 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1635 N1.getOperand(1).getOperand(1)); 1636 // fold (A+(B-(C+A))) to (B-C) 1637 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 1638 N0 == N1.getOperand(1).getOperand(1)) 1639 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0), 1640 N1.getOperand(1).getOperand(0)); 1641 // fold (A+((B-A)+or-C)) to (B+or-C) 1642 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 1643 N1.getOperand(0).getOpcode() == ISD::SUB && 1644 N0 == N1.getOperand(0).getOperand(1)) 1645 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT, 1646 N1.getOperand(0).getOperand(0), N1.getOperand(1)); 1647 1648 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 1649 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 1650 SDValue N00 = N0.getOperand(0); 1651 SDValue N01 = N0.getOperand(1); 1652 SDValue N10 = N1.getOperand(0); 1653 SDValue N11 = N1.getOperand(1); 1654 1655 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) 1656 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1657 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 1658 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 1659 } 1660 1661 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0))) 1662 return SDValue(N, 0); 1663 1664 // fold (a+b) -> (a|b) iff a and b share no bits. 1665 if (VT.isInteger() && !VT.isVector()) { 1666 APInt LHSZero, LHSOne; 1667 APInt RHSZero, RHSOne; 1668 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1669 1670 if (LHSZero.getBoolValue()) { 1671 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1672 1673 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1674 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1675 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){ 1676 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) 1677 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1); 1678 } 1679 } 1680 } 1681 1682 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 1683 if (N1.getOpcode() == ISD::SHL && 1684 N1.getOperand(0).getOpcode() == ISD::SUB) 1685 if (ConstantSDNode *C = 1686 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0))) 1687 if (C->getAPIntValue() == 0) 1688 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, 1689 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1690 N1.getOperand(0).getOperand(1), 1691 N1.getOperand(1))); 1692 if (N0.getOpcode() == ISD::SHL && 1693 N0.getOperand(0).getOpcode() == ISD::SUB) 1694 if (ConstantSDNode *C = 1695 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0))) 1696 if (C->getAPIntValue() == 0) 1697 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, 1698 DAG.getNode(ISD::SHL, SDLoc(N), VT, 1699 N0.getOperand(0).getOperand(1), 1700 N0.getOperand(1))); 1701 1702 if (N1.getOpcode() == ISD::AND) { 1703 SDValue AndOp0 = N1.getOperand(0); 1704 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 1705 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0); 1706 unsigned DestBits = VT.getScalarType().getSizeInBits(); 1707 1708 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x)) 1709 // and similar xforms where the inner op is either ~0 or 0. 1710 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) { 1711 SDLoc DL(N); 1712 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0); 1713 } 1714 } 1715 1716 // add (sext i1), X -> sub X, (zext i1) 1717 if (N0.getOpcode() == ISD::SIGN_EXTEND && 1718 N0.getOperand(0).getValueType() == MVT::i1 && 1719 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) { 1720 SDLoc DL(N); 1721 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 1722 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 1723 } 1724 1725 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 1726 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1727 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1728 if (TN->getVT() == MVT::i1) { 1729 SDLoc DL(N); 1730 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1731 DAG.getConstant(1, VT)); 1732 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 1733 } 1734 } 1735 1736 return SDValue(); 1737 } 1738 1739 SDValue DAGCombiner::visitADDC(SDNode *N) { 1740 SDValue N0 = N->getOperand(0); 1741 SDValue N1 = N->getOperand(1); 1742 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1743 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1744 EVT VT = N0.getValueType(); 1745 1746 // If the flag result is dead, turn this into an ADD. 1747 if (!N->hasAnyUseOfValue(1)) 1748 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1), 1749 DAG.getNode(ISD::CARRY_FALSE, 1750 SDLoc(N), MVT::Glue)); 1751 1752 // canonicalize constant to RHS. 1753 if (N0C && !N1C) 1754 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0); 1755 1756 // fold (addc x, 0) -> x + no carry out 1757 if (N1C && N1C->isNullValue()) 1758 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 1759 SDLoc(N), MVT::Glue)); 1760 1761 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits. 1762 APInt LHSZero, LHSOne; 1763 APInt RHSZero, RHSOne; 1764 DAG.computeKnownBits(N0, LHSZero, LHSOne); 1765 1766 if (LHSZero.getBoolValue()) { 1767 DAG.computeKnownBits(N1, RHSZero, RHSOne); 1768 1769 // If all possibly-set bits on the LHS are clear on the RHS, return an OR. 1770 // If all possibly-set bits on the RHS are clear on the LHS, return an OR. 1771 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero) 1772 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1), 1773 DAG.getNode(ISD::CARRY_FALSE, 1774 SDLoc(N), MVT::Glue)); 1775 } 1776 1777 return SDValue(); 1778 } 1779 1780 SDValue DAGCombiner::visitADDE(SDNode *N) { 1781 SDValue N0 = N->getOperand(0); 1782 SDValue N1 = N->getOperand(1); 1783 SDValue CarryIn = N->getOperand(2); 1784 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1785 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1786 1787 // canonicalize constant to RHS 1788 if (N0C && !N1C) 1789 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 1790 N1, N0, CarryIn); 1791 1792 // fold (adde x, y, false) -> (addc x, y) 1793 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1794 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 1795 1796 return SDValue(); 1797 } 1798 1799 // Since it may not be valid to emit a fold to zero for vector initializers 1800 // check if we can before folding. 1801 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT, 1802 SelectionDAG &DAG, 1803 bool LegalOperations, bool LegalTypes) { 1804 if (!VT.isVector()) 1805 return DAG.getConstant(0, VT); 1806 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 1807 return DAG.getConstant(0, VT); 1808 return SDValue(); 1809 } 1810 1811 SDValue DAGCombiner::visitSUB(SDNode *N) { 1812 SDValue N0 = N->getOperand(0); 1813 SDValue N1 = N->getOperand(1); 1814 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode()); 1815 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 1816 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr : 1817 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode()); 1818 EVT VT = N0.getValueType(); 1819 1820 // fold vector ops 1821 if (VT.isVector()) { 1822 SDValue FoldedVOp = SimplifyVBinOp(N); 1823 if (FoldedVOp.getNode()) return FoldedVOp; 1824 1825 // fold (sub x, 0) -> x, vector edition 1826 if (ISD::isBuildVectorAllZeros(N1.getNode())) 1827 return N0; 1828 } 1829 1830 // fold (sub x, x) -> 0 1831 // FIXME: Refactor this and xor and other similar operations together. 1832 if (N0 == N1) 1833 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 1834 // fold (sub c1, c2) -> c1-c2 1835 if (N0C && N1C) 1836 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C); 1837 // fold (sub x, c) -> (add x, -c) 1838 if (N1C) 1839 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, 1840 DAG.getConstant(-N1C->getAPIntValue(), VT)); 1841 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 1842 if (N0C && N0C->isAllOnesValue()) 1843 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 1844 // fold A-(A-B) -> B 1845 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 1846 return N1.getOperand(1); 1847 // fold (A+B)-A -> B 1848 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 1849 return N0.getOperand(1); 1850 // fold (A+B)-B -> A 1851 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 1852 return N0.getOperand(0); 1853 // fold C2-(A+C1) -> (C2-C1)-A 1854 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) { 1855 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(), 1856 VT); 1857 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC, 1858 N1.getOperand(0)); 1859 } 1860 // fold ((A+(B+or-C))-B) -> A+or-C 1861 if (N0.getOpcode() == ISD::ADD && 1862 (N0.getOperand(1).getOpcode() == ISD::SUB || 1863 N0.getOperand(1).getOpcode() == ISD::ADD) && 1864 N0.getOperand(1).getOperand(0) == N1) 1865 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT, 1866 N0.getOperand(0), N0.getOperand(1).getOperand(1)); 1867 // fold ((A+(C+B))-B) -> A+C 1868 if (N0.getOpcode() == ISD::ADD && 1869 N0.getOperand(1).getOpcode() == ISD::ADD && 1870 N0.getOperand(1).getOperand(1) == N1) 1871 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 1872 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1873 // fold ((A-(B-C))-C) -> A-B 1874 if (N0.getOpcode() == ISD::SUB && 1875 N0.getOperand(1).getOpcode() == ISD::SUB && 1876 N0.getOperand(1).getOperand(1) == N1) 1877 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 1878 N0.getOperand(0), N0.getOperand(1).getOperand(0)); 1879 1880 // If either operand of a sub is undef, the result is undef 1881 if (N0.getOpcode() == ISD::UNDEF) 1882 return N0; 1883 if (N1.getOpcode() == ISD::UNDEF) 1884 return N1; 1885 1886 // If the relocation model supports it, consider symbol offsets. 1887 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 1888 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 1889 // fold (sub Sym, c) -> Sym-c 1890 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 1891 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 1892 GA->getOffset() - 1893 (uint64_t)N1C->getSExtValue()); 1894 // fold (sub Sym+c1, Sym+c2) -> c1-c2 1895 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 1896 if (GA->getGlobal() == GB->getGlobal()) 1897 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 1898 VT); 1899 } 1900 1901 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 1902 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 1903 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 1904 if (TN->getVT() == MVT::i1) { 1905 SDLoc DL(N); 1906 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 1907 DAG.getConstant(1, VT)); 1908 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 1909 } 1910 } 1911 1912 return SDValue(); 1913 } 1914 1915 SDValue DAGCombiner::visitSUBC(SDNode *N) { 1916 SDValue N0 = N->getOperand(0); 1917 SDValue N1 = N->getOperand(1); 1918 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 1919 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 1920 EVT VT = N0.getValueType(); 1921 1922 // If the flag result is dead, turn this into an SUB. 1923 if (!N->hasAnyUseOfValue(1)) 1924 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1), 1925 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1926 MVT::Glue)); 1927 1928 // fold (subc x, x) -> 0 + no borrow 1929 if (N0 == N1) 1930 return CombineTo(N, DAG.getConstant(0, VT), 1931 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1932 MVT::Glue)); 1933 1934 // fold (subc x, 0) -> x + no borrow 1935 if (N1C && N1C->isNullValue()) 1936 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1937 MVT::Glue)); 1938 1939 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 1940 if (N0C && N0C->isAllOnesValue()) 1941 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0), 1942 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N), 1943 MVT::Glue)); 1944 1945 return SDValue(); 1946 } 1947 1948 SDValue DAGCombiner::visitSUBE(SDNode *N) { 1949 SDValue N0 = N->getOperand(0); 1950 SDValue N1 = N->getOperand(1); 1951 SDValue CarryIn = N->getOperand(2); 1952 1953 // fold (sube x, y, false) -> (subc x, y) 1954 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 1955 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 1956 1957 return SDValue(); 1958 } 1959 1960 SDValue DAGCombiner::visitMUL(SDNode *N) { 1961 SDValue N0 = N->getOperand(0); 1962 SDValue N1 = N->getOperand(1); 1963 EVT VT = N0.getValueType(); 1964 1965 // fold (mul x, undef) -> 0 1966 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 1967 return DAG.getConstant(0, VT); 1968 1969 bool N0IsConst = false; 1970 bool N1IsConst = false; 1971 APInt ConstValue0, ConstValue1; 1972 // fold vector ops 1973 if (VT.isVector()) { 1974 SDValue FoldedVOp = SimplifyVBinOp(N); 1975 if (FoldedVOp.getNode()) return FoldedVOp; 1976 1977 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0); 1978 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1); 1979 } else { 1980 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr; 1981 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() 1982 : APInt(); 1983 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr; 1984 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() 1985 : APInt(); 1986 } 1987 1988 // fold (mul c1, c2) -> c1*c2 1989 if (N0IsConst && N1IsConst) 1990 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode()); 1991 1992 // canonicalize constant to RHS 1993 if (N0IsConst && !N1IsConst) 1994 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 1995 // fold (mul x, 0) -> 0 1996 if (N1IsConst && ConstValue1 == 0) 1997 return N1; 1998 // We require a splat of the entire scalar bit width for non-contiguous 1999 // bit patterns. 2000 bool IsFullSplat = 2001 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits(); 2002 // fold (mul x, 1) -> x 2003 if (N1IsConst && ConstValue1 == 1 && IsFullSplat) 2004 return N0; 2005 // fold (mul x, -1) -> 0-x 2006 if (N1IsConst && ConstValue1.isAllOnesValue()) 2007 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2008 DAG.getConstant(0, VT), N0); 2009 // fold (mul x, (1 << c)) -> x << c 2010 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) 2011 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 2012 DAG.getConstant(ConstValue1.logBase2(), 2013 getShiftAmountTy(N0.getValueType()))); 2014 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 2015 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) { 2016 unsigned Log2Val = (-ConstValue1).logBase2(); 2017 // FIXME: If the input is something that is easily negated (e.g. a 2018 // single-use add), we should put the negate there. 2019 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2020 DAG.getConstant(0, VT), 2021 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 2022 DAG.getConstant(Log2Val, 2023 getShiftAmountTy(N0.getValueType())))); 2024 } 2025 2026 APInt Val; 2027 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 2028 if (N1IsConst && N0.getOpcode() == ISD::SHL && 2029 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2030 isa<ConstantSDNode>(N0.getOperand(1)))) { 2031 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, 2032 N1, N0.getOperand(1)); 2033 AddToWorklist(C3.getNode()); 2034 return DAG.getNode(ISD::MUL, SDLoc(N), VT, 2035 N0.getOperand(0), C3); 2036 } 2037 2038 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 2039 // use. 2040 { 2041 SDValue Sh(nullptr,0), Y(nullptr,0); 2042 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 2043 if (N0.getOpcode() == ISD::SHL && 2044 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2045 isa<ConstantSDNode>(N0.getOperand(1))) && 2046 N0.getNode()->hasOneUse()) { 2047 Sh = N0; Y = N1; 2048 } else if (N1.getOpcode() == ISD::SHL && 2049 isa<ConstantSDNode>(N1.getOperand(1)) && 2050 N1.getNode()->hasOneUse()) { 2051 Sh = N1; Y = N0; 2052 } 2053 2054 if (Sh.getNode()) { 2055 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2056 Sh.getOperand(0), Y); 2057 return DAG.getNode(ISD::SHL, SDLoc(N), VT, 2058 Mul, Sh.getOperand(1)); 2059 } 2060 } 2061 2062 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 2063 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 2064 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) || 2065 isa<ConstantSDNode>(N0.getOperand(1)))) 2066 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 2067 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 2068 N0.getOperand(0), N1), 2069 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 2070 N0.getOperand(1), N1)); 2071 2072 // reassociate mul 2073 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1); 2074 if (RMUL.getNode()) 2075 return RMUL; 2076 2077 return SDValue(); 2078 } 2079 2080 SDValue DAGCombiner::visitSDIV(SDNode *N) { 2081 SDValue N0 = N->getOperand(0); 2082 SDValue N1 = N->getOperand(1); 2083 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2084 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2085 EVT VT = N->getValueType(0); 2086 2087 // fold vector ops 2088 if (VT.isVector()) { 2089 SDValue FoldedVOp = SimplifyVBinOp(N); 2090 if (FoldedVOp.getNode()) return FoldedVOp; 2091 } 2092 2093 // fold (sdiv c1, c2) -> c1/c2 2094 if (N0C && N1C && !N1C->isNullValue()) 2095 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C); 2096 // fold (sdiv X, 1) -> X 2097 if (N1C && N1C->getAPIntValue() == 1LL) 2098 return N0; 2099 // fold (sdiv X, -1) -> 0-X 2100 if (N1C && N1C->isAllOnesValue()) 2101 return DAG.getNode(ISD::SUB, SDLoc(N), VT, 2102 DAG.getConstant(0, VT), N0); 2103 // If we know the sign bits of both operands are zero, strength reduce to a 2104 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 2105 if (!VT.isVector()) { 2106 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2107 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(), 2108 N0, N1); 2109 } 2110 2111 // fold (sdiv X, pow2) -> simple ops after legalize 2112 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() || 2113 (-N1C->getAPIntValue()).isPowerOf2())) { 2114 // If dividing by powers of two is cheap, then don't perform the following 2115 // fold. 2116 if (TLI.isPow2SDivCheap()) 2117 return SDValue(); 2118 2119 // Target-specific implementation of sdiv x, pow2. 2120 SDValue Res = BuildSDIVPow2(N); 2121 if (Res.getNode()) 2122 return Res; 2123 2124 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros(); 2125 2126 // Splat the sign bit into the register 2127 SDValue SGN = 2128 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, 2129 DAG.getConstant(VT.getScalarSizeInBits() - 1, 2130 getShiftAmountTy(N0.getValueType()))); 2131 AddToWorklist(SGN.getNode()); 2132 2133 // Add (N0 < 0) ? abs2 - 1 : 0; 2134 SDValue SRL = 2135 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN, 2136 DAG.getConstant(VT.getScalarSizeInBits() - lg2, 2137 getShiftAmountTy(SGN.getValueType()))); 2138 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL); 2139 AddToWorklist(SRL.getNode()); 2140 AddToWorklist(ADD.getNode()); // Divide by pow2 2141 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD, 2142 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType()))); 2143 2144 // If we're dividing by a positive value, we're done. Otherwise, we must 2145 // negate the result. 2146 if (N1C->getAPIntValue().isNonNegative()) 2147 return SRA; 2148 2149 AddToWorklist(SRA.getNode()); 2150 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA); 2151 } 2152 2153 // if integer divide is expensive and we satisfy the requirements, emit an 2154 // alternate sequence. 2155 if (N1C && !TLI.isIntDivCheap()) { 2156 SDValue Op = BuildSDIV(N); 2157 if (Op.getNode()) return Op; 2158 } 2159 2160 // undef / X -> 0 2161 if (N0.getOpcode() == ISD::UNDEF) 2162 return DAG.getConstant(0, VT); 2163 // X / undef -> undef 2164 if (N1.getOpcode() == ISD::UNDEF) 2165 return N1; 2166 2167 return SDValue(); 2168 } 2169 2170 SDValue DAGCombiner::visitUDIV(SDNode *N) { 2171 SDValue N0 = N->getOperand(0); 2172 SDValue N1 = N->getOperand(1); 2173 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2174 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2175 EVT VT = N->getValueType(0); 2176 2177 // fold vector ops 2178 if (VT.isVector()) { 2179 SDValue FoldedVOp = SimplifyVBinOp(N); 2180 if (FoldedVOp.getNode()) return FoldedVOp; 2181 } 2182 2183 // fold (udiv c1, c2) -> c1/c2 2184 if (N0C && N1C && !N1C->isNullValue()) 2185 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C); 2186 // fold (udiv x, (1 << c)) -> x >>u c 2187 if (N1C && N1C->getAPIntValue().isPowerOf2()) 2188 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, 2189 DAG.getConstant(N1C->getAPIntValue().logBase2(), 2190 getShiftAmountTy(N0.getValueType()))); 2191 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 2192 if (N1.getOpcode() == ISD::SHL) { 2193 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2194 if (SHC->getAPIntValue().isPowerOf2()) { 2195 EVT ADDVT = N1.getOperand(1).getValueType(); 2196 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT, 2197 N1.getOperand(1), 2198 DAG.getConstant(SHC->getAPIntValue() 2199 .logBase2(), 2200 ADDVT)); 2201 AddToWorklist(Add.getNode()); 2202 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add); 2203 } 2204 } 2205 } 2206 // fold (udiv x, c) -> alternate 2207 if (N1C && !TLI.isIntDivCheap()) { 2208 SDValue Op = BuildUDIV(N); 2209 if (Op.getNode()) return Op; 2210 } 2211 2212 // undef / X -> 0 2213 if (N0.getOpcode() == ISD::UNDEF) 2214 return DAG.getConstant(0, VT); 2215 // X / undef -> undef 2216 if (N1.getOpcode() == ISD::UNDEF) 2217 return N1; 2218 2219 return SDValue(); 2220 } 2221 2222 SDValue DAGCombiner::visitSREM(SDNode *N) { 2223 SDValue N0 = N->getOperand(0); 2224 SDValue N1 = N->getOperand(1); 2225 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2226 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2227 EVT VT = N->getValueType(0); 2228 2229 // fold (srem c1, c2) -> c1%c2 2230 if (N0C && N1C && !N1C->isNullValue()) 2231 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C); 2232 // If we know the sign bits of both operands are zero, strength reduce to a 2233 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 2234 if (!VT.isVector()) { 2235 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 2236 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1); 2237 } 2238 2239 // If X/C can be simplified by the division-by-constant logic, lower 2240 // X%C to the equivalent of X-X/C*C. 2241 if (N1C && !N1C->isNullValue()) { 2242 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1); 2243 AddToWorklist(Div.getNode()); 2244 SDValue OptimizedDiv = combine(Div.getNode()); 2245 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2246 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2247 OptimizedDiv, N1); 2248 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2249 AddToWorklist(Mul.getNode()); 2250 return Sub; 2251 } 2252 } 2253 2254 // undef % X -> 0 2255 if (N0.getOpcode() == ISD::UNDEF) 2256 return DAG.getConstant(0, VT); 2257 // X % undef -> undef 2258 if (N1.getOpcode() == ISD::UNDEF) 2259 return N1; 2260 2261 return SDValue(); 2262 } 2263 2264 SDValue DAGCombiner::visitUREM(SDNode *N) { 2265 SDValue N0 = N->getOperand(0); 2266 SDValue N1 = N->getOperand(1); 2267 ConstantSDNode *N0C = isConstOrConstSplat(N0); 2268 ConstantSDNode *N1C = isConstOrConstSplat(N1); 2269 EVT VT = N->getValueType(0); 2270 2271 // fold (urem c1, c2) -> c1%c2 2272 if (N0C && N1C && !N1C->isNullValue()) 2273 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C); 2274 // fold (urem x, pow2) -> (and x, pow2-1) 2275 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) 2276 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, 2277 DAG.getConstant(N1C->getAPIntValue()-1,VT)); 2278 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 2279 if (N1.getOpcode() == ISD::SHL) { 2280 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) { 2281 if (SHC->getAPIntValue().isPowerOf2()) { 2282 SDValue Add = 2283 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, 2284 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), 2285 VT)); 2286 AddToWorklist(Add.getNode()); 2287 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add); 2288 } 2289 } 2290 } 2291 2292 // If X/C can be simplified by the division-by-constant logic, lower 2293 // X%C to the equivalent of X-X/C*C. 2294 if (N1C && !N1C->isNullValue()) { 2295 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1); 2296 AddToWorklist(Div.getNode()); 2297 SDValue OptimizedDiv = combine(Div.getNode()); 2298 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) { 2299 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, 2300 OptimizedDiv, N1); 2301 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul); 2302 AddToWorklist(Mul.getNode()); 2303 return Sub; 2304 } 2305 } 2306 2307 // undef % X -> 0 2308 if (N0.getOpcode() == ISD::UNDEF) 2309 return DAG.getConstant(0, VT); 2310 // X % undef -> undef 2311 if (N1.getOpcode() == ISD::UNDEF) 2312 return N1; 2313 2314 return SDValue(); 2315 } 2316 2317 SDValue DAGCombiner::visitMULHS(SDNode *N) { 2318 SDValue N0 = N->getOperand(0); 2319 SDValue N1 = N->getOperand(1); 2320 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2321 EVT VT = N->getValueType(0); 2322 SDLoc DL(N); 2323 2324 // fold (mulhs x, 0) -> 0 2325 if (N1C && N1C->isNullValue()) 2326 return N1; 2327 // fold (mulhs x, 1) -> (sra x, size(x)-1) 2328 if (N1C && N1C->getAPIntValue() == 1) 2329 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0, 2330 DAG.getConstant(N0.getValueType().getSizeInBits() - 1, 2331 getShiftAmountTy(N0.getValueType()))); 2332 // fold (mulhs x, undef) -> 0 2333 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2334 return DAG.getConstant(0, VT); 2335 2336 // If the type twice as wide is legal, transform the mulhs to a wider multiply 2337 // plus a shift. 2338 if (VT.isSimple() && !VT.isVector()) { 2339 MVT Simple = VT.getSimpleVT(); 2340 unsigned SimpleSize = Simple.getSizeInBits(); 2341 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2342 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2343 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 2344 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 2345 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2346 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2347 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2348 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2349 } 2350 } 2351 2352 return SDValue(); 2353 } 2354 2355 SDValue DAGCombiner::visitMULHU(SDNode *N) { 2356 SDValue N0 = N->getOperand(0); 2357 SDValue N1 = N->getOperand(1); 2358 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2359 EVT VT = N->getValueType(0); 2360 SDLoc DL(N); 2361 2362 // fold (mulhu x, 0) -> 0 2363 if (N1C && N1C->isNullValue()) 2364 return N1; 2365 // fold (mulhu x, 1) -> 0 2366 if (N1C && N1C->getAPIntValue() == 1) 2367 return DAG.getConstant(0, N0.getValueType()); 2368 // fold (mulhu x, undef) -> 0 2369 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2370 return DAG.getConstant(0, VT); 2371 2372 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2373 // plus a shift. 2374 if (VT.isSimple() && !VT.isVector()) { 2375 MVT Simple = VT.getSimpleVT(); 2376 unsigned SimpleSize = Simple.getSizeInBits(); 2377 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2378 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2379 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 2380 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 2381 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 2382 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 2383 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType()))); 2384 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 2385 } 2386 } 2387 2388 return SDValue(); 2389 } 2390 2391 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 2392 /// give the opcodes for the two computations that are being performed. Return 2393 /// true if a simplification was made. 2394 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 2395 unsigned HiOp) { 2396 // If the high half is not needed, just compute the low half. 2397 bool HiExists = N->hasAnyUseOfValue(1); 2398 if (!HiExists && 2399 (!LegalOperations || 2400 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 2401 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2402 return CombineTo(N, Res, Res); 2403 } 2404 2405 // If the low half is not needed, just compute the high half. 2406 bool LoExists = N->hasAnyUseOfValue(0); 2407 if (!LoExists && 2408 (!LegalOperations || 2409 TLI.isOperationLegal(HiOp, N->getValueType(1)))) { 2410 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2411 return CombineTo(N, Res, Res); 2412 } 2413 2414 // If both halves are used, return as it is. 2415 if (LoExists && HiExists) 2416 return SDValue(); 2417 2418 // If the two computed results can be simplified separately, separate them. 2419 if (LoExists) { 2420 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 2421 AddToWorklist(Lo.getNode()); 2422 SDValue LoOpt = combine(Lo.getNode()); 2423 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 2424 (!LegalOperations || 2425 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))) 2426 return CombineTo(N, LoOpt, LoOpt); 2427 } 2428 2429 if (HiExists) { 2430 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 2431 AddToWorklist(Hi.getNode()); 2432 SDValue HiOpt = combine(Hi.getNode()); 2433 if (HiOpt.getNode() && HiOpt != Hi && 2434 (!LegalOperations || 2435 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))) 2436 return CombineTo(N, HiOpt, HiOpt); 2437 } 2438 2439 return SDValue(); 2440 } 2441 2442 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 2443 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS); 2444 if (Res.getNode()) return Res; 2445 2446 EVT VT = N->getValueType(0); 2447 SDLoc DL(N); 2448 2449 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2450 // plus a shift. 2451 if (VT.isSimple() && !VT.isVector()) { 2452 MVT Simple = VT.getSimpleVT(); 2453 unsigned SimpleSize = Simple.getSizeInBits(); 2454 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2455 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2456 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 2457 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 2458 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2459 // Compute the high part as N1. 2460 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2461 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2462 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2463 // Compute the low part as N0. 2464 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2465 return CombineTo(N, Lo, Hi); 2466 } 2467 } 2468 2469 return SDValue(); 2470 } 2471 2472 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 2473 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU); 2474 if (Res.getNode()) return Res; 2475 2476 EVT VT = N->getValueType(0); 2477 SDLoc DL(N); 2478 2479 // If the type twice as wide is legal, transform the mulhu to a wider multiply 2480 // plus a shift. 2481 if (VT.isSimple() && !VT.isVector()) { 2482 MVT Simple = VT.getSimpleVT(); 2483 unsigned SimpleSize = Simple.getSizeInBits(); 2484 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 2485 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 2486 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 2487 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 2488 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 2489 // Compute the high part as N1. 2490 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 2491 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType()))); 2492 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 2493 // Compute the low part as N0. 2494 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 2495 return CombineTo(N, Lo, Hi); 2496 } 2497 } 2498 2499 return SDValue(); 2500 } 2501 2502 SDValue DAGCombiner::visitSMULO(SDNode *N) { 2503 // (smulo x, 2) -> (saddo x, x) 2504 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2505 if (C2->getAPIntValue() == 2) 2506 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(), 2507 N->getOperand(0), N->getOperand(0)); 2508 2509 return SDValue(); 2510 } 2511 2512 SDValue DAGCombiner::visitUMULO(SDNode *N) { 2513 // (umulo x, 2) -> (uaddo x, x) 2514 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2515 if (C2->getAPIntValue() == 2) 2516 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(), 2517 N->getOperand(0), N->getOperand(0)); 2518 2519 return SDValue(); 2520 } 2521 2522 SDValue DAGCombiner::visitSDIVREM(SDNode *N) { 2523 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM); 2524 if (Res.getNode()) return Res; 2525 2526 return SDValue(); 2527 } 2528 2529 SDValue DAGCombiner::visitUDIVREM(SDNode *N) { 2530 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM); 2531 if (Res.getNode()) return Res; 2532 2533 return SDValue(); 2534 } 2535 2536 /// If this is a binary operator with two operands of the same opcode, try to 2537 /// simplify it. 2538 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) { 2539 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 2540 EVT VT = N0.getValueType(); 2541 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!"); 2542 2543 // Bail early if none of these transforms apply. 2544 if (N0.getNode()->getNumOperands() == 0) return SDValue(); 2545 2546 // For each of OP in AND/OR/XOR: 2547 // fold (OP (zext x), (zext y)) -> (zext (OP x, y)) 2548 // fold (OP (sext x), (sext y)) -> (sext (OP x, y)) 2549 // fold (OP (aext x), (aext y)) -> (aext (OP x, y)) 2550 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y)) 2551 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free) 2552 // 2553 // do not sink logical op inside of a vector extend, since it may combine 2554 // into a vsetcc. 2555 EVT Op0VT = N0.getOperand(0).getValueType(); 2556 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 2557 N0.getOpcode() == ISD::SIGN_EXTEND || 2558 N0.getOpcode() == ISD::BSWAP || 2559 // Avoid infinite looping with PromoteIntBinOp. 2560 (N0.getOpcode() == ISD::ANY_EXTEND && 2561 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) || 2562 (N0.getOpcode() == ISD::TRUNCATE && 2563 (!TLI.isZExtFree(VT, Op0VT) || 2564 !TLI.isTruncateFree(Op0VT, VT)) && 2565 TLI.isTypeLegal(Op0VT))) && 2566 !VT.isVector() && 2567 Op0VT == N1.getOperand(0).getValueType() && 2568 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) { 2569 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2570 N0.getOperand(0).getValueType(), 2571 N0.getOperand(0), N1.getOperand(0)); 2572 AddToWorklist(ORNode.getNode()); 2573 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode); 2574 } 2575 2576 // For each of OP in SHL/SRL/SRA/AND... 2577 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z) 2578 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z) 2579 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z) 2580 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL || 2581 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) && 2582 N0.getOperand(1) == N1.getOperand(1)) { 2583 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0), 2584 N0.getOperand(0).getValueType(), 2585 N0.getOperand(0), N1.getOperand(0)); 2586 AddToWorklist(ORNode.getNode()); 2587 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 2588 ORNode, N0.getOperand(1)); 2589 } 2590 2591 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 2592 // Only perform this optimization after type legalization and before 2593 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 2594 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 2595 // we don't want to undo this promotion. 2596 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 2597 // on scalars. 2598 if ((N0.getOpcode() == ISD::BITCAST || 2599 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) && 2600 Level == AfterLegalizeTypes) { 2601 SDValue In0 = N0.getOperand(0); 2602 SDValue In1 = N1.getOperand(0); 2603 EVT In0Ty = In0.getValueType(); 2604 EVT In1Ty = In1.getValueType(); 2605 SDLoc DL(N); 2606 // If both incoming values are integers, and the original types are the 2607 // same. 2608 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) { 2609 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1); 2610 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op); 2611 AddToWorklist(Op.getNode()); 2612 return BC; 2613 } 2614 } 2615 2616 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 2617 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 2618 // If both shuffles use the same mask, and both shuffle within a single 2619 // vector, then it is worthwhile to move the swizzle after the operation. 2620 // The type-legalizer generates this pattern when loading illegal 2621 // vector types from memory. In many cases this allows additional shuffle 2622 // optimizations. 2623 // There are other cases where moving the shuffle after the xor/and/or 2624 // is profitable even if shuffles don't perform a swizzle. 2625 // If both shuffles use the same mask, and both shuffles have the same first 2626 // or second operand, then it might still be profitable to move the shuffle 2627 // after the xor/and/or operation. 2628 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 2629 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0); 2630 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1); 2631 2632 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() && 2633 "Inputs to shuffles are not the same type"); 2634 2635 // Check that both shuffles use the same mask. The masks are known to be of 2636 // the same length because the result vector type is the same. 2637 // Check also that shuffles have only one use to avoid introducing extra 2638 // instructions. 2639 if (SVN0->hasOneUse() && SVN1->hasOneUse() && 2640 SVN0->getMask().equals(SVN1->getMask())) { 2641 SDValue ShOp = N0->getOperand(1); 2642 2643 // Don't try to fold this node if it requires introducing a 2644 // build vector of all zeros that might be illegal at this stage. 2645 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2646 if (!LegalTypes) 2647 ShOp = DAG.getConstant(0, VT); 2648 else 2649 ShOp = SDValue(); 2650 } 2651 2652 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C) 2653 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C) 2654 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0) 2655 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 2656 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2657 N0->getOperand(0), N1->getOperand(0)); 2658 AddToWorklist(NewNode.getNode()); 2659 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp, 2660 &SVN0->getMask()[0]); 2661 } 2662 2663 // Don't try to fold this node if it requires introducing a 2664 // build vector of all zeros that might be illegal at this stage. 2665 ShOp = N0->getOperand(0); 2666 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) { 2667 if (!LegalTypes) 2668 ShOp = DAG.getConstant(0, VT); 2669 else 2670 ShOp = SDValue(); 2671 } 2672 2673 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B)) 2674 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B)) 2675 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B)) 2676 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) { 2677 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 2678 N0->getOperand(1), N1->getOperand(1)); 2679 AddToWorklist(NewNode.getNode()); 2680 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode, 2681 &SVN0->getMask()[0]); 2682 } 2683 } 2684 } 2685 2686 return SDValue(); 2687 } 2688 2689 SDValue DAGCombiner::visitAND(SDNode *N) { 2690 SDValue N0 = N->getOperand(0); 2691 SDValue N1 = N->getOperand(1); 2692 SDValue LL, LR, RL, RR, CC0, CC1; 2693 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2694 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2695 EVT VT = N1.getValueType(); 2696 unsigned BitWidth = VT.getScalarType().getSizeInBits(); 2697 2698 // fold vector ops 2699 if (VT.isVector()) { 2700 SDValue FoldedVOp = SimplifyVBinOp(N); 2701 if (FoldedVOp.getNode()) return FoldedVOp; 2702 2703 // fold (and x, 0) -> 0, vector edition 2704 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2705 // do not return N0, because undef node may exist in N0 2706 return DAG.getConstant( 2707 APInt::getNullValue( 2708 N0.getValueType().getScalarType().getSizeInBits()), 2709 N0.getValueType()); 2710 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2711 // do not return N1, because undef node may exist in N1 2712 return DAG.getConstant( 2713 APInt::getNullValue( 2714 N1.getValueType().getScalarType().getSizeInBits()), 2715 N1.getValueType()); 2716 2717 // fold (and x, -1) -> x, vector edition 2718 if (ISD::isBuildVectorAllOnes(N0.getNode())) 2719 return N1; 2720 if (ISD::isBuildVectorAllOnes(N1.getNode())) 2721 return N0; 2722 } 2723 2724 // fold (and x, undef) -> 0 2725 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) 2726 return DAG.getConstant(0, VT); 2727 // fold (and c1, c2) -> c1&c2 2728 if (N0C && N1C) 2729 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C); 2730 // canonicalize constant to RHS 2731 if (N0C && !N1C) 2732 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 2733 // fold (and x, -1) -> x 2734 if (N1C && N1C->isAllOnesValue()) 2735 return N0; 2736 // if (and x, c) is known to be zero, return 0 2737 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 2738 APInt::getAllOnesValue(BitWidth))) 2739 return DAG.getConstant(0, VT); 2740 // reassociate and 2741 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1); 2742 if (RAND.getNode()) 2743 return RAND; 2744 // fold (and (or x, C), D) -> D if (C & D) == D 2745 if (N1C && N0.getOpcode() == ISD::OR) 2746 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 2747 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue()) 2748 return N1; 2749 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 2750 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 2751 SDValue N0Op0 = N0.getOperand(0); 2752 APInt Mask = ~N1C->getAPIntValue(); 2753 Mask = Mask.trunc(N0Op0.getValueSizeInBits()); 2754 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 2755 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 2756 N0.getValueType(), N0Op0); 2757 2758 // Replace uses of the AND with uses of the Zero extend node. 2759 CombineTo(N, Zext); 2760 2761 // We actually want to replace all uses of the any_extend with the 2762 // zero_extend, to avoid duplicating things. This will later cause this 2763 // AND to be folded. 2764 CombineTo(N0.getNode(), Zext); 2765 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2766 } 2767 } 2768 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 2769 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 2770 // already be zero by virtue of the width of the base type of the load. 2771 // 2772 // the 'X' node here can either be nothing or an extract_vector_elt to catch 2773 // more cases. 2774 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 2775 N0.getOperand(0).getOpcode() == ISD::LOAD) || 2776 N0.getOpcode() == ISD::LOAD) { 2777 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 2778 N0 : N0.getOperand(0) ); 2779 2780 // Get the constant (if applicable) the zero'th operand is being ANDed with. 2781 // This can be a pure constant or a vector splat, in which case we treat the 2782 // vector as a scalar and use the splat value. 2783 APInt Constant = APInt::getNullValue(1); 2784 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2785 Constant = C->getAPIntValue(); 2786 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 2787 APInt SplatValue, SplatUndef; 2788 unsigned SplatBitSize; 2789 bool HasAnyUndefs; 2790 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 2791 SplatBitSize, HasAnyUndefs); 2792 if (IsSplat) { 2793 // Undef bits can contribute to a possible optimisation if set, so 2794 // set them. 2795 SplatValue |= SplatUndef; 2796 2797 // The splat value may be something like "0x00FFFFFF", which means 0 for 2798 // the first vector value and FF for the rest, repeating. We need a mask 2799 // that will apply equally to all members of the vector, so AND all the 2800 // lanes of the constant together. 2801 EVT VT = Vector->getValueType(0); 2802 unsigned BitWidth = VT.getVectorElementType().getSizeInBits(); 2803 2804 // If the splat value has been compressed to a bitlength lower 2805 // than the size of the vector lane, we need to re-expand it to 2806 // the lane size. 2807 if (BitWidth > SplatBitSize) 2808 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 2809 SplatBitSize < BitWidth; 2810 SplatBitSize = SplatBitSize * 2) 2811 SplatValue |= SplatValue.shl(SplatBitSize); 2812 2813 Constant = APInt::getAllOnesValue(BitWidth); 2814 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 2815 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 2816 } 2817 } 2818 2819 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 2820 // actually legal and isn't going to get expanded, else this is a false 2821 // optimisation. 2822 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 2823 Load->getValueType(0), 2824 Load->getMemoryVT()); 2825 2826 // Resize the constant to the same size as the original memory access before 2827 // extension. If it is still the AllOnesValue then this AND is completely 2828 // unneeded. 2829 Constant = 2830 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits()); 2831 2832 bool B; 2833 switch (Load->getExtensionType()) { 2834 default: B = false; break; 2835 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 2836 case ISD::ZEXTLOAD: 2837 case ISD::NON_EXTLOAD: B = true; break; 2838 } 2839 2840 if (B && Constant.isAllOnesValue()) { 2841 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 2842 // preserve semantics once we get rid of the AND. 2843 SDValue NewLoad(Load, 0); 2844 if (Load->getExtensionType() == ISD::EXTLOAD) { 2845 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 2846 Load->getValueType(0), SDLoc(Load), 2847 Load->getChain(), Load->getBasePtr(), 2848 Load->getOffset(), Load->getMemoryVT(), 2849 Load->getMemOperand()); 2850 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 2851 if (Load->getNumValues() == 3) { 2852 // PRE/POST_INC loads have 3 values. 2853 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 2854 NewLoad.getValue(2) }; 2855 CombineTo(Load, To, 3, true); 2856 } else { 2857 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 2858 } 2859 } 2860 2861 // Fold the AND away, taking care not to fold to the old load node if we 2862 // replaced it. 2863 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 2864 2865 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2866 } 2867 } 2868 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y)) 2869 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 2870 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 2871 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 2872 2873 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 2874 LL.getValueType().isInteger()) { 2875 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0) 2876 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) { 2877 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2878 LR.getValueType(), LL, RL); 2879 AddToWorklist(ORNode.getNode()); 2880 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2881 } 2882 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1) 2883 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) { 2884 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0), 2885 LR.getValueType(), LL, RL); 2886 AddToWorklist(ANDNode.getNode()); 2887 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 2888 } 2889 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1) 2890 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) { 2891 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0), 2892 LR.getValueType(), LL, RL); 2893 AddToWorklist(ORNode.getNode()); 2894 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 2895 } 2896 } 2897 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2) 2898 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) && 2899 Op0 == Op1 && LL.getValueType().isInteger() && 2900 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() && 2901 cast<ConstantSDNode>(RR)->isAllOnesValue()) || 2902 (cast<ConstantSDNode>(LR)->isAllOnesValue() && 2903 cast<ConstantSDNode>(RR)->isNullValue()))) { 2904 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(), 2905 LL, DAG.getConstant(1, LL.getValueType())); 2906 AddToWorklist(ADDNode.getNode()); 2907 return DAG.getSetCC(SDLoc(N), VT, ADDNode, 2908 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE); 2909 } 2910 // canonicalize equivalent to ll == rl 2911 if (LL == RR && LR == RL) { 2912 Op1 = ISD::getSetCCSwappedOperands(Op1); 2913 std::swap(RL, RR); 2914 } 2915 if (LL == RL && LR == RR) { 2916 bool isInteger = LL.getValueType().isInteger(); 2917 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger); 2918 if (Result != ISD::SETCC_INVALID && 2919 (!LegalOperations || 2920 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 2921 TLI.isOperationLegal(ISD::SETCC, 2922 getSetCCResultType(N0.getSimpleValueType()))))) 2923 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 2924 LL, LR, Result); 2925 } 2926 } 2927 2928 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 2929 if (N0.getOpcode() == N1.getOpcode()) { 2930 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 2931 if (Tmp.getNode()) return Tmp; 2932 } 2933 2934 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 2935 // fold (and (sra)) -> (and (srl)) when possible. 2936 if (!VT.isVector() && 2937 SimplifyDemandedBits(SDValue(N, 0))) 2938 return SDValue(N, 0); 2939 2940 // fold (zext_inreg (extload x)) -> (zextload x) 2941 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 2942 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2943 EVT MemVT = LN0->getMemoryVT(); 2944 // If we zero all the possible extended bits, then we can turn this into 2945 // a zextload if we are running before legalize or the operation is legal. 2946 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2947 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2948 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2949 ((!LegalOperations && !LN0->isVolatile()) || 2950 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 2951 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2952 LN0->getChain(), LN0->getBasePtr(), 2953 MemVT, LN0->getMemOperand()); 2954 AddToWorklist(N); 2955 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2956 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2957 } 2958 } 2959 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 2960 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 2961 N0.hasOneUse()) { 2962 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 2963 EVT MemVT = LN0->getMemoryVT(); 2964 // If we zero all the possible extended bits, then we can turn this into 2965 // a zextload if we are running before legalize or the operation is legal. 2966 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits(); 2967 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 2968 BitWidth - MemVT.getScalarType().getSizeInBits())) && 2969 ((!LegalOperations && !LN0->isVolatile()) || 2970 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 2971 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 2972 LN0->getChain(), LN0->getBasePtr(), 2973 MemVT, LN0->getMemOperand()); 2974 AddToWorklist(N); 2975 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 2976 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2977 } 2978 } 2979 2980 // fold (and (load x), 255) -> (zextload x, i8) 2981 // fold (and (extload x, i16), 255) -> (zextload x, i8) 2982 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 2983 if (N1C && (N0.getOpcode() == ISD::LOAD || 2984 (N0.getOpcode() == ISD::ANY_EXTEND && 2985 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 2986 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND; 2987 LoadSDNode *LN0 = HasAnyExt 2988 ? cast<LoadSDNode>(N0.getOperand(0)) 2989 : cast<LoadSDNode>(N0); 2990 if (LN0->getExtensionType() != ISD::SEXTLOAD && 2991 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) { 2992 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits(); 2993 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){ 2994 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 2995 EVT LoadedVT = LN0->getMemoryVT(); 2996 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT; 2997 2998 if (ExtVT == LoadedVT && 2999 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3000 ExtVT))) { 3001 3002 SDValue NewLoad = 3003 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3004 LN0->getChain(), LN0->getBasePtr(), ExtVT, 3005 LN0->getMemOperand()); 3006 AddToWorklist(N); 3007 CombineTo(LN0, NewLoad, NewLoad.getValue(1)); 3008 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3009 } 3010 3011 // Do not change the width of a volatile load. 3012 // Do not generate loads of non-round integer types since these can 3013 // be expensive (and would be wrong if the type is not byte sized). 3014 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() && 3015 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, 3016 ExtVT))) { 3017 EVT PtrType = LN0->getOperand(1).getValueType(); 3018 3019 unsigned Alignment = LN0->getAlignment(); 3020 SDValue NewPtr = LN0->getBasePtr(); 3021 3022 // For big endian targets, we need to add an offset to the pointer 3023 // to load the correct bytes. For little endian systems, we merely 3024 // need to read fewer bytes from the same pointer. 3025 if (TLI.isBigEndian()) { 3026 unsigned LVTStoreBytes = LoadedVT.getStoreSize(); 3027 unsigned EVTStoreBytes = ExtVT.getStoreSize(); 3028 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes; 3029 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType, 3030 NewPtr, DAG.getConstant(PtrOff, PtrType)); 3031 Alignment = MinAlign(Alignment, PtrOff); 3032 } 3033 3034 AddToWorklist(NewPtr.getNode()); 3035 3036 SDValue Load = 3037 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, 3038 LN0->getChain(), NewPtr, 3039 LN0->getPointerInfo(), 3040 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 3041 LN0->isInvariant(), Alignment, LN0->getAAInfo()); 3042 AddToWorklist(N); 3043 CombineTo(LN0, Load, Load.getValue(1)); 3044 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3045 } 3046 } 3047 } 3048 } 3049 3050 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 3051 VT.getSizeInBits() <= 64) { 3052 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 3053 APInt ADDC = ADDI->getAPIntValue(); 3054 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3055 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 3056 // immediate for an add, but it is legal if its top c2 bits are set, 3057 // transform the ADD so the immediate doesn't need to be materialized 3058 // in a register. 3059 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 3060 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 3061 SRLI->getZExtValue()); 3062 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 3063 ADDC |= Mask; 3064 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 3065 SDValue NewAdd = 3066 DAG.getNode(ISD::ADD, SDLoc(N0), VT, 3067 N0.getOperand(0), DAG.getConstant(ADDC, VT)); 3068 CombineTo(N0.getNode(), NewAdd); 3069 return SDValue(N, 0); // Return N so it doesn't get rechecked! 3070 } 3071 } 3072 } 3073 } 3074 } 3075 } 3076 3077 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 3078 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 3079 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 3080 N0.getOperand(1), false); 3081 if (BSwap.getNode()) 3082 return BSwap; 3083 } 3084 3085 return SDValue(); 3086 } 3087 3088 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 3089 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 3090 bool DemandHighBits) { 3091 if (!LegalOperations) 3092 return SDValue(); 3093 3094 EVT VT = N->getValueType(0); 3095 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 3096 return SDValue(); 3097 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3098 return SDValue(); 3099 3100 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00) 3101 bool LookPassAnd0 = false; 3102 bool LookPassAnd1 = false; 3103 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 3104 std::swap(N0, N1); 3105 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 3106 std::swap(N0, N1); 3107 if (N0.getOpcode() == ISD::AND) { 3108 if (!N0.getNode()->hasOneUse()) 3109 return SDValue(); 3110 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3111 if (!N01C || N01C->getZExtValue() != 0xFF00) 3112 return SDValue(); 3113 N0 = N0.getOperand(0); 3114 LookPassAnd0 = true; 3115 } 3116 3117 if (N1.getOpcode() == ISD::AND) { 3118 if (!N1.getNode()->hasOneUse()) 3119 return SDValue(); 3120 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3121 if (!N11C || N11C->getZExtValue() != 0xFF) 3122 return SDValue(); 3123 N1 = N1.getOperand(0); 3124 LookPassAnd1 = true; 3125 } 3126 3127 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 3128 std::swap(N0, N1); 3129 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 3130 return SDValue(); 3131 if (!N0.getNode()->hasOneUse() || 3132 !N1.getNode()->hasOneUse()) 3133 return SDValue(); 3134 3135 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3136 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 3137 if (!N01C || !N11C) 3138 return SDValue(); 3139 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 3140 return SDValue(); 3141 3142 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 3143 SDValue N00 = N0->getOperand(0); 3144 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 3145 if (!N00.getNode()->hasOneUse()) 3146 return SDValue(); 3147 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 3148 if (!N001C || N001C->getZExtValue() != 0xFF) 3149 return SDValue(); 3150 N00 = N00.getOperand(0); 3151 LookPassAnd0 = true; 3152 } 3153 3154 SDValue N10 = N1->getOperand(0); 3155 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 3156 if (!N10.getNode()->hasOneUse()) 3157 return SDValue(); 3158 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 3159 if (!N101C || N101C->getZExtValue() != 0xFF00) 3160 return SDValue(); 3161 N10 = N10.getOperand(0); 3162 LookPassAnd1 = true; 3163 } 3164 3165 if (N00 != N10) 3166 return SDValue(); 3167 3168 // Make sure everything beyond the low halfword gets set to zero since the SRL 3169 // 16 will clear the top bits. 3170 unsigned OpSizeInBits = VT.getSizeInBits(); 3171 if (DemandHighBits && OpSizeInBits > 16) { 3172 // If the left-shift isn't masked out then the only way this is a bswap is 3173 // if all bits beyond the low 8 are 0. In that case the entire pattern 3174 // reduces to a left shift anyway: leave it for other parts of the combiner. 3175 if (!LookPassAnd0) 3176 return SDValue(); 3177 3178 // However, if the right shift isn't masked out then it might be because 3179 // it's not needed. See if we can spot that too. 3180 if (!LookPassAnd1 && 3181 !DAG.MaskedValueIsZero( 3182 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 3183 return SDValue(); 3184 } 3185 3186 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 3187 if (OpSizeInBits > 16) 3188 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res, 3189 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT))); 3190 return Res; 3191 } 3192 3193 /// Return true if the specified node is an element that makes up a 32-bit 3194 /// packed halfword byteswap. 3195 /// ((x & 0x000000ff) << 8) | 3196 /// ((x & 0x0000ff00) >> 8) | 3197 /// ((x & 0x00ff0000) << 8) | 3198 /// ((x & 0xff000000) >> 8) 3199 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 3200 if (!N.getNode()->hasOneUse()) 3201 return false; 3202 3203 unsigned Opc = N.getOpcode(); 3204 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 3205 return false; 3206 3207 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3208 if (!N1C) 3209 return false; 3210 3211 unsigned Num; 3212 switch (N1C->getZExtValue()) { 3213 default: 3214 return false; 3215 case 0xFF: Num = 0; break; 3216 case 0xFF00: Num = 1; break; 3217 case 0xFF0000: Num = 2; break; 3218 case 0xFF000000: Num = 3; break; 3219 } 3220 3221 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 3222 SDValue N0 = N.getOperand(0); 3223 if (Opc == ISD::AND) { 3224 if (Num == 0 || Num == 2) { 3225 // (x >> 8) & 0xff 3226 // (x >> 8) & 0xff0000 3227 if (N0.getOpcode() != ISD::SRL) 3228 return false; 3229 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3230 if (!C || C->getZExtValue() != 8) 3231 return false; 3232 } else { 3233 // (x << 8) & 0xff00 3234 // (x << 8) & 0xff000000 3235 if (N0.getOpcode() != ISD::SHL) 3236 return false; 3237 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3238 if (!C || C->getZExtValue() != 8) 3239 return false; 3240 } 3241 } else if (Opc == ISD::SHL) { 3242 // (x & 0xff) << 8 3243 // (x & 0xff0000) << 8 3244 if (Num != 0 && Num != 2) 3245 return false; 3246 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3247 if (!C || C->getZExtValue() != 8) 3248 return false; 3249 } else { // Opc == ISD::SRL 3250 // (x & 0xff00) >> 8 3251 // (x & 0xff000000) >> 8 3252 if (Num != 1 && Num != 3) 3253 return false; 3254 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 3255 if (!C || C->getZExtValue() != 8) 3256 return false; 3257 } 3258 3259 if (Parts[Num]) 3260 return false; 3261 3262 Parts[Num] = N0.getOperand(0).getNode(); 3263 return true; 3264 } 3265 3266 /// Match a 32-bit packed halfword bswap. That is 3267 /// ((x & 0x000000ff) << 8) | 3268 /// ((x & 0x0000ff00) >> 8) | 3269 /// ((x & 0x00ff0000) << 8) | 3270 /// ((x & 0xff000000) >> 8) 3271 /// => (rotl (bswap x), 16) 3272 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 3273 if (!LegalOperations) 3274 return SDValue(); 3275 3276 EVT VT = N->getValueType(0); 3277 if (VT != MVT::i32) 3278 return SDValue(); 3279 if (!TLI.isOperationLegal(ISD::BSWAP, VT)) 3280 return SDValue(); 3281 3282 // Look for either 3283 // (or (or (and), (and)), (or (and), (and))) 3284 // (or (or (or (and), (and)), (and)), (and)) 3285 if (N0.getOpcode() != ISD::OR) 3286 return SDValue(); 3287 SDValue N00 = N0.getOperand(0); 3288 SDValue N01 = N0.getOperand(1); 3289 SDNode *Parts[4] = {}; 3290 3291 if (N1.getOpcode() == ISD::OR && 3292 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 3293 // (or (or (and), (and)), (or (and), (and))) 3294 SDValue N000 = N00.getOperand(0); 3295 if (!isBSwapHWordElement(N000, Parts)) 3296 return SDValue(); 3297 3298 SDValue N001 = N00.getOperand(1); 3299 if (!isBSwapHWordElement(N001, Parts)) 3300 return SDValue(); 3301 SDValue N010 = N01.getOperand(0); 3302 if (!isBSwapHWordElement(N010, Parts)) 3303 return SDValue(); 3304 SDValue N011 = N01.getOperand(1); 3305 if (!isBSwapHWordElement(N011, Parts)) 3306 return SDValue(); 3307 } else { 3308 // (or (or (or (and), (and)), (and)), (and)) 3309 if (!isBSwapHWordElement(N1, Parts)) 3310 return SDValue(); 3311 if (!isBSwapHWordElement(N01, Parts)) 3312 return SDValue(); 3313 if (N00.getOpcode() != ISD::OR) 3314 return SDValue(); 3315 SDValue N000 = N00.getOperand(0); 3316 if (!isBSwapHWordElement(N000, Parts)) 3317 return SDValue(); 3318 SDValue N001 = N00.getOperand(1); 3319 if (!isBSwapHWordElement(N001, Parts)) 3320 return SDValue(); 3321 } 3322 3323 // Make sure the parts are all coming from the same node. 3324 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 3325 return SDValue(); 3326 3327 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, 3328 SDValue(Parts[0],0)); 3329 3330 // Result of the bswap should be rotated by 16. If it's not legal, then 3331 // do (x << 16) | (x >> 16). 3332 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT)); 3333 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 3334 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt); 3335 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 3336 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt); 3337 return DAG.getNode(ISD::OR, SDLoc(N), VT, 3338 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt), 3339 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt)); 3340 } 3341 3342 SDValue DAGCombiner::visitOR(SDNode *N) { 3343 SDValue N0 = N->getOperand(0); 3344 SDValue N1 = N->getOperand(1); 3345 SDValue LL, LR, RL, RR, CC0, CC1; 3346 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3347 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3348 EVT VT = N1.getValueType(); 3349 3350 // fold vector ops 3351 if (VT.isVector()) { 3352 SDValue FoldedVOp = SimplifyVBinOp(N); 3353 if (FoldedVOp.getNode()) return FoldedVOp; 3354 3355 // fold (or x, 0) -> x, vector edition 3356 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3357 return N1; 3358 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3359 return N0; 3360 3361 // fold (or x, -1) -> -1, vector edition 3362 if (ISD::isBuildVectorAllOnes(N0.getNode())) 3363 // do not return N0, because undef node may exist in N0 3364 return DAG.getConstant( 3365 APInt::getAllOnesValue( 3366 N0.getValueType().getScalarType().getSizeInBits()), 3367 N0.getValueType()); 3368 if (ISD::isBuildVectorAllOnes(N1.getNode())) 3369 // do not return N1, because undef node may exist in N1 3370 return DAG.getConstant( 3371 APInt::getAllOnesValue( 3372 N1.getValueType().getScalarType().getSizeInBits()), 3373 N1.getValueType()); 3374 3375 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1) 3376 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2) 3377 // Do this only if the resulting shuffle is legal. 3378 if (isa<ShuffleVectorSDNode>(N0) && 3379 isa<ShuffleVectorSDNode>(N1) && 3380 // Avoid folding a node with illegal type. 3381 TLI.isTypeLegal(VT) && 3382 N0->getOperand(1) == N1->getOperand(1) && 3383 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) { 3384 bool CanFold = true; 3385 unsigned NumElts = VT.getVectorNumElements(); 3386 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 3387 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 3388 // We construct two shuffle masks: 3389 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand 3390 // and N1 as the second operand. 3391 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand 3392 // and N0 as the second operand. 3393 // We do this because OR is commutable and therefore there might be 3394 // two ways to fold this node into a shuffle. 3395 SmallVector<int,4> Mask1; 3396 SmallVector<int,4> Mask2; 3397 3398 for (unsigned i = 0; i != NumElts && CanFold; ++i) { 3399 int M0 = SV0->getMaskElt(i); 3400 int M1 = SV1->getMaskElt(i); 3401 3402 // Both shuffle indexes are undef. Propagate Undef. 3403 if (M0 < 0 && M1 < 0) { 3404 Mask1.push_back(M0); 3405 Mask2.push_back(M0); 3406 continue; 3407 } 3408 3409 if (M0 < 0 || M1 < 0 || 3410 (M0 < (int)NumElts && M1 < (int)NumElts) || 3411 (M0 >= (int)NumElts && M1 >= (int)NumElts)) { 3412 CanFold = false; 3413 break; 3414 } 3415 3416 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts); 3417 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts); 3418 } 3419 3420 if (CanFold) { 3421 // Fold this sequence only if the resulting shuffle is 'legal'. 3422 if (TLI.isShuffleMaskLegal(Mask1, VT)) 3423 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), 3424 N1->getOperand(0), &Mask1[0]); 3425 if (TLI.isShuffleMaskLegal(Mask2, VT)) 3426 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0), 3427 N0->getOperand(0), &Mask2[0]); 3428 } 3429 } 3430 } 3431 3432 // fold (or x, undef) -> -1 3433 if (!LegalOperations && 3434 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) { 3435 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 3436 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 3437 } 3438 // fold (or c1, c2) -> c1|c2 3439 if (N0C && N1C) 3440 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C); 3441 // canonicalize constant to RHS 3442 if (N0C && !N1C) 3443 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 3444 // fold (or x, 0) -> x 3445 if (N1C && N1C->isNullValue()) 3446 return N0; 3447 // fold (or x, -1) -> -1 3448 if (N1C && N1C->isAllOnesValue()) 3449 return N1; 3450 // fold (or x, c) -> c iff (x & ~c) == 0 3451 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 3452 return N1; 3453 3454 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 3455 SDValue BSwap = MatchBSwapHWord(N, N0, N1); 3456 if (BSwap.getNode()) 3457 return BSwap; 3458 BSwap = MatchBSwapHWordLow(N, N0, N1); 3459 if (BSwap.getNode()) 3460 return BSwap; 3461 3462 // reassociate or 3463 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1); 3464 if (ROR.getNode()) 3465 return ROR; 3466 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 3467 // iff (c1 & c2) == 0. 3468 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3469 isa<ConstantSDNode>(N0.getOperand(1))) { 3470 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1)); 3471 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) { 3472 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1)) 3473 return DAG.getNode( 3474 ISD::AND, SDLoc(N), VT, 3475 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR); 3476 return SDValue(); 3477 } 3478 } 3479 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y)) 3480 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){ 3481 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get(); 3482 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get(); 3483 3484 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 && 3485 LL.getValueType().isInteger()) { 3486 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0) 3487 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0) 3488 if (cast<ConstantSDNode>(LR)->isNullValue() && 3489 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) { 3490 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR), 3491 LR.getValueType(), LL, RL); 3492 AddToWorklist(ORNode.getNode()); 3493 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1); 3494 } 3495 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1) 3496 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1) 3497 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 3498 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) { 3499 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR), 3500 LR.getValueType(), LL, RL); 3501 AddToWorklist(ANDNode.getNode()); 3502 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1); 3503 } 3504 } 3505 // canonicalize equivalent to ll == rl 3506 if (LL == RR && LR == RL) { 3507 Op1 = ISD::getSetCCSwappedOperands(Op1); 3508 std::swap(RL, RR); 3509 } 3510 if (LL == RL && LR == RR) { 3511 bool isInteger = LL.getValueType().isInteger(); 3512 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger); 3513 if (Result != ISD::SETCC_INVALID && 3514 (!LegalOperations || 3515 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) && 3516 TLI.isOperationLegal(ISD::SETCC, 3517 getSetCCResultType(N0.getValueType()))))) 3518 return DAG.getSetCC(SDLoc(N), N0.getValueType(), 3519 LL, LR, Result); 3520 } 3521 } 3522 3523 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 3524 if (N0.getOpcode() == N1.getOpcode()) { 3525 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3526 if (Tmp.getNode()) return Tmp; 3527 } 3528 3529 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 3530 if (N0.getOpcode() == ISD::AND && 3531 N1.getOpcode() == ISD::AND && 3532 N0.getOperand(1).getOpcode() == ISD::Constant && 3533 N1.getOperand(1).getOpcode() == ISD::Constant && 3534 // Don't increase # computations. 3535 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3536 // We can only do this xform if we know that bits from X that are set in C2 3537 // but not in C1 are already zero. Likewise for Y. 3538 const APInt &LHSMask = 3539 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 3540 const APInt &RHSMask = 3541 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue(); 3542 3543 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 3544 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 3545 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3546 N0.getOperand(0), N1.getOperand(0)); 3547 return DAG.getNode(ISD::AND, SDLoc(N), VT, X, 3548 DAG.getConstant(LHSMask | RHSMask, VT)); 3549 } 3550 } 3551 3552 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 3553 if (N0.getOpcode() == ISD::AND && 3554 N1.getOpcode() == ISD::AND && 3555 N0.getOperand(0) == N1.getOperand(0) && 3556 // Don't increase # computations. 3557 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 3558 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 3559 N0.getOperand(1), N1.getOperand(1)); 3560 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), X); 3561 } 3562 3563 // See if this is some rotate idiom. 3564 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 3565 return SDValue(Rot, 0); 3566 3567 // Simplify the operands using demanded-bits information. 3568 if (!VT.isVector() && 3569 SimplifyDemandedBits(SDValue(N, 0))) 3570 return SDValue(N, 0); 3571 3572 return SDValue(); 3573 } 3574 3575 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 3576 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) { 3577 if (Op.getOpcode() == ISD::AND) { 3578 if (isa<ConstantSDNode>(Op.getOperand(1))) { 3579 Mask = Op.getOperand(1); 3580 Op = Op.getOperand(0); 3581 } else { 3582 return false; 3583 } 3584 } 3585 3586 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 3587 Shift = Op; 3588 return true; 3589 } 3590 3591 return false; 3592 } 3593 3594 // Return true if we can prove that, whenever Neg and Pos are both in the 3595 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that 3596 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 3597 // 3598 // (or (shift1 X, Neg), (shift2 X, Pos)) 3599 // 3600 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 3601 // in direction shift1 by Neg. The range [0, OpSize) means that we only need 3602 // to consider shift amounts with defined behavior. 3603 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) { 3604 // If OpSize is a power of 2 then: 3605 // 3606 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1) 3607 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize). 3608 // 3609 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check 3610 // for the stronger condition: 3611 // 3612 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A] 3613 // 3614 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1) 3615 // we can just replace Neg with Neg' for the rest of the function. 3616 // 3617 // In other cases we check for the even stronger condition: 3618 // 3619 // Neg == OpSize - Pos [B] 3620 // 3621 // for all Neg and Pos. Note that the (or ...) then invokes undefined 3622 // behavior if Pos == 0 (and consequently Neg == OpSize). 3623 // 3624 // We could actually use [A] whenever OpSize is a power of 2, but the 3625 // only extra cases that it would match are those uninteresting ones 3626 // where Neg and Pos are never in range at the same time. E.g. for 3627 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 3628 // as well as (sub 32, Pos), but: 3629 // 3630 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 3631 // 3632 // always invokes undefined behavior for 32-bit X. 3633 // 3634 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise. 3635 unsigned MaskLoBits = 0; 3636 if (Neg.getOpcode() == ISD::AND && 3637 isPowerOf2_64(OpSize) && 3638 Neg.getOperand(1).getOpcode() == ISD::Constant && 3639 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) { 3640 Neg = Neg.getOperand(0); 3641 MaskLoBits = Log2_64(OpSize); 3642 } 3643 3644 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 3645 if (Neg.getOpcode() != ISD::SUB) 3646 return 0; 3647 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0)); 3648 if (!NegC) 3649 return 0; 3650 SDValue NegOp1 = Neg.getOperand(1); 3651 3652 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with 3653 // Pos'. The truncation is redundant for the purpose of the equality. 3654 if (MaskLoBits && 3655 Pos.getOpcode() == ISD::AND && 3656 Pos.getOperand(1).getOpcode() == ISD::Constant && 3657 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1) 3658 Pos = Pos.getOperand(0); 3659 3660 // The condition we need is now: 3661 // 3662 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask 3663 // 3664 // If NegOp1 == Pos then we need: 3665 // 3666 // OpSize & Mask == NegC & Mask 3667 // 3668 // (because "x & Mask" is a truncation and distributes through subtraction). 3669 APInt Width; 3670 if (Pos == NegOp1) 3671 Width = NegC->getAPIntValue(); 3672 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 3673 // Then the condition we want to prove becomes: 3674 // 3675 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask 3676 // 3677 // which, again because "x & Mask" is a truncation, becomes: 3678 // 3679 // NegC & Mask == (OpSize - PosC) & Mask 3680 // OpSize & Mask == (NegC + PosC) & Mask 3681 else if (Pos.getOpcode() == ISD::ADD && 3682 Pos.getOperand(0) == NegOp1 && 3683 Pos.getOperand(1).getOpcode() == ISD::Constant) 3684 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() + 3685 NegC->getAPIntValue()); 3686 else 3687 return false; 3688 3689 // Now we just need to check that OpSize & Mask == Width & Mask. 3690 if (MaskLoBits) 3691 // Opsize & Mask is 0 since Mask is Opsize - 1. 3692 return Width.getLoBits(MaskLoBits) == 0; 3693 return Width == OpSize; 3694 } 3695 3696 // A subroutine of MatchRotate used once we have found an OR of two opposite 3697 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 3698 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 3699 // former being preferred if supported. InnerPos and InnerNeg are Pos and 3700 // Neg with outer conversions stripped away. 3701 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 3702 SDValue Neg, SDValue InnerPos, 3703 SDValue InnerNeg, unsigned PosOpcode, 3704 unsigned NegOpcode, SDLoc DL) { 3705 // fold (or (shl x, (*ext y)), 3706 // (srl x, (*ext (sub 32, y)))) -> 3707 // (rotl x, y) or (rotr x, (sub 32, y)) 3708 // 3709 // fold (or (shl x, (*ext (sub 32, y))), 3710 // (srl x, (*ext y))) -> 3711 // (rotr x, y) or (rotl x, (sub 32, y)) 3712 EVT VT = Shifted.getValueType(); 3713 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) { 3714 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 3715 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 3716 HasPos ? Pos : Neg).getNode(); 3717 } 3718 3719 return nullptr; 3720 } 3721 3722 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 3723 // idioms for rotate, and if the target supports rotation instructions, generate 3724 // a rot[lr]. 3725 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) { 3726 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 3727 EVT VT = LHS.getValueType(); 3728 if (!TLI.isTypeLegal(VT)) return nullptr; 3729 3730 // The target must have at least one rotate flavor. 3731 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT); 3732 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT); 3733 if (!HasROTL && !HasROTR) return nullptr; 3734 3735 // Match "(X shl/srl V1) & V2" where V2 may not be present. 3736 SDValue LHSShift; // The shift. 3737 SDValue LHSMask; // AND value if any. 3738 if (!MatchRotateHalf(LHS, LHSShift, LHSMask)) 3739 return nullptr; // Not part of a rotate. 3740 3741 SDValue RHSShift; // The shift. 3742 SDValue RHSMask; // AND value if any. 3743 if (!MatchRotateHalf(RHS, RHSShift, RHSMask)) 3744 return nullptr; // Not part of a rotate. 3745 3746 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 3747 return nullptr; // Not shifting the same value. 3748 3749 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 3750 return nullptr; // Shifts must disagree. 3751 3752 // Canonicalize shl to left side in a shl/srl pair. 3753 if (RHSShift.getOpcode() == ISD::SHL) { 3754 std::swap(LHS, RHS); 3755 std::swap(LHSShift, RHSShift); 3756 std::swap(LHSMask , RHSMask ); 3757 } 3758 3759 unsigned OpSizeInBits = VT.getSizeInBits(); 3760 SDValue LHSShiftArg = LHSShift.getOperand(0); 3761 SDValue LHSShiftAmt = LHSShift.getOperand(1); 3762 SDValue RHSShiftArg = RHSShift.getOperand(0); 3763 SDValue RHSShiftAmt = RHSShift.getOperand(1); 3764 3765 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 3766 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 3767 if (LHSShiftAmt.getOpcode() == ISD::Constant && 3768 RHSShiftAmt.getOpcode() == ISD::Constant) { 3769 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue(); 3770 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue(); 3771 if ((LShVal + RShVal) != OpSizeInBits) 3772 return nullptr; 3773 3774 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 3775 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 3776 3777 // If there is an AND of either shifted operand, apply it to the result. 3778 if (LHSMask.getNode() || RHSMask.getNode()) { 3779 APInt Mask = APInt::getAllOnesValue(OpSizeInBits); 3780 3781 if (LHSMask.getNode()) { 3782 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal); 3783 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits; 3784 } 3785 if (RHSMask.getNode()) { 3786 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal); 3787 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits; 3788 } 3789 3790 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT)); 3791 } 3792 3793 return Rot.getNode(); 3794 } 3795 3796 // If there is a mask here, and we have a variable shift, we can't be sure 3797 // that we're masking out the right stuff. 3798 if (LHSMask.getNode() || RHSMask.getNode()) 3799 return nullptr; 3800 3801 // If the shift amount is sign/zext/any-extended just peel it off. 3802 SDValue LExtOp0 = LHSShiftAmt; 3803 SDValue RExtOp0 = RHSShiftAmt; 3804 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3805 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3806 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3807 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 3808 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 3809 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 3810 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 3811 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 3812 LExtOp0 = LHSShiftAmt.getOperand(0); 3813 RExtOp0 = RHSShiftAmt.getOperand(0); 3814 } 3815 3816 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 3817 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 3818 if (TryL) 3819 return TryL; 3820 3821 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 3822 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 3823 if (TryR) 3824 return TryR; 3825 3826 return nullptr; 3827 } 3828 3829 SDValue DAGCombiner::visitXOR(SDNode *N) { 3830 SDValue N0 = N->getOperand(0); 3831 SDValue N1 = N->getOperand(1); 3832 SDValue LHS, RHS, CC; 3833 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 3834 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3835 EVT VT = N0.getValueType(); 3836 3837 // fold vector ops 3838 if (VT.isVector()) { 3839 SDValue FoldedVOp = SimplifyVBinOp(N); 3840 if (FoldedVOp.getNode()) return FoldedVOp; 3841 3842 // fold (xor x, 0) -> x, vector edition 3843 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3844 return N1; 3845 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3846 return N0; 3847 } 3848 3849 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 3850 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 3851 return DAG.getConstant(0, VT); 3852 // fold (xor x, undef) -> undef 3853 if (N0.getOpcode() == ISD::UNDEF) 3854 return N0; 3855 if (N1.getOpcode() == ISD::UNDEF) 3856 return N1; 3857 // fold (xor c1, c2) -> c1^c2 3858 if (N0C && N1C) 3859 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C); 3860 // canonicalize constant to RHS 3861 if (N0C && !N1C) 3862 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0); 3863 // fold (xor x, 0) -> x 3864 if (N1C && N1C->isNullValue()) 3865 return N0; 3866 // reassociate xor 3867 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1); 3868 if (RXOR.getNode()) 3869 return RXOR; 3870 3871 // fold !(x cc y) -> (x !cc y) 3872 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 3873 bool isInt = LHS.getValueType().isInteger(); 3874 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 3875 isInt); 3876 3877 if (!LegalOperations || 3878 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 3879 switch (N0.getOpcode()) { 3880 default: 3881 llvm_unreachable("Unhandled SetCC Equivalent!"); 3882 case ISD::SETCC: 3883 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC); 3884 case ISD::SELECT_CC: 3885 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2), 3886 N0.getOperand(3), NotCC); 3887 } 3888 } 3889 } 3890 3891 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 3892 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND && 3893 N0.getNode()->hasOneUse() && 3894 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 3895 SDValue V = N0.getOperand(0); 3896 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V, 3897 DAG.getConstant(1, V.getValueType())); 3898 AddToWorklist(V.getNode()); 3899 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V); 3900 } 3901 3902 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 3903 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 && 3904 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3905 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3906 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 3907 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3908 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3909 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3910 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3911 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3912 } 3913 } 3914 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 3915 if (N1C && N1C->isAllOnesValue() && 3916 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) { 3917 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 3918 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 3919 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND; 3920 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 3921 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 3922 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 3923 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS); 3924 } 3925 } 3926 // fold (xor (and x, y), y) -> (and (not x), y) 3927 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 3928 N0->getOperand(1) == N1) { 3929 SDValue X = N0->getOperand(0); 3930 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 3931 AddToWorklist(NotX.getNode()); 3932 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1); 3933 } 3934 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2)) 3935 if (N1C && N0.getOpcode() == ISD::XOR) { 3936 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0)); 3937 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 3938 if (N00C) 3939 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1), 3940 DAG.getConstant(N1C->getAPIntValue() ^ 3941 N00C->getAPIntValue(), VT)); 3942 if (N01C) 3943 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0), 3944 DAG.getConstant(N1C->getAPIntValue() ^ 3945 N01C->getAPIntValue(), VT)); 3946 } 3947 // fold (xor x, x) -> 0 3948 if (N0 == N1) 3949 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes); 3950 3951 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 3952 if (N0.getOpcode() == N1.getOpcode()) { 3953 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N); 3954 if (Tmp.getNode()) return Tmp; 3955 } 3956 3957 // Simplify the expression using non-local knowledge. 3958 if (!VT.isVector() && 3959 SimplifyDemandedBits(SDValue(N, 0))) 3960 return SDValue(N, 0); 3961 3962 return SDValue(); 3963 } 3964 3965 /// Handle transforms common to the three shifts, when the shift amount is a 3966 /// constant. 3967 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 3968 // We can't and shouldn't fold opaque constants. 3969 if (Amt->isOpaque()) 3970 return SDValue(); 3971 3972 SDNode *LHS = N->getOperand(0).getNode(); 3973 if (!LHS->hasOneUse()) return SDValue(); 3974 3975 // We want to pull some binops through shifts, so that we have (and (shift)) 3976 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 3977 // thing happens with address calculations, so it's important to canonicalize 3978 // it. 3979 bool HighBitSet = false; // Can we transform this if the high bit is set? 3980 3981 switch (LHS->getOpcode()) { 3982 default: return SDValue(); 3983 case ISD::OR: 3984 case ISD::XOR: 3985 HighBitSet = false; // We can only transform sra if the high bit is clear. 3986 break; 3987 case ISD::AND: 3988 HighBitSet = true; // We can only transform sra if the high bit is set. 3989 break; 3990 case ISD::ADD: 3991 if (N->getOpcode() != ISD::SHL) 3992 return SDValue(); // only shl(add) not sr[al](add). 3993 HighBitSet = false; // We can only transform sra if the high bit is clear. 3994 break; 3995 } 3996 3997 // We require the RHS of the binop to be a constant and not opaque as well. 3998 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1)); 3999 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue(); 4000 4001 // FIXME: disable this unless the input to the binop is a shift by a constant. 4002 // If it is not a shift, it pessimizes some common cases like: 4003 // 4004 // void foo(int *X, int i) { X[i & 1235] = 1; } 4005 // int bar(int *X, int i) { return X[i & 255]; } 4006 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 4007 if ((BinOpLHSVal->getOpcode() != ISD::SHL && 4008 BinOpLHSVal->getOpcode() != ISD::SRA && 4009 BinOpLHSVal->getOpcode() != ISD::SRL) || 4010 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) 4011 return SDValue(); 4012 4013 EVT VT = N->getValueType(0); 4014 4015 // If this is a signed shift right, and the high bit is modified by the 4016 // logical operation, do not perform the transformation. The highBitSet 4017 // boolean indicates the value of the high bit of the constant which would 4018 // cause it to be modified for this operation. 4019 if (N->getOpcode() == ISD::SRA) { 4020 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 4021 if (BinOpRHSSignSet != HighBitSet) 4022 return SDValue(); 4023 } 4024 4025 if (!TLI.isDesirableToCommuteWithShift(LHS)) 4026 return SDValue(); 4027 4028 // Fold the constants, shifting the binop RHS by the shift amount. 4029 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 4030 N->getValueType(0), 4031 LHS->getOperand(1), N->getOperand(1)); 4032 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 4033 4034 // Create the new shift. 4035 SDValue NewShift = DAG.getNode(N->getOpcode(), 4036 SDLoc(LHS->getOperand(0)), 4037 VT, LHS->getOperand(0), N->getOperand(1)); 4038 4039 // Create the new binop. 4040 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 4041 } 4042 4043 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 4044 assert(N->getOpcode() == ISD::TRUNCATE); 4045 assert(N->getOperand(0).getOpcode() == ISD::AND); 4046 4047 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 4048 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) { 4049 SDValue N01 = N->getOperand(0).getOperand(1); 4050 4051 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) { 4052 EVT TruncVT = N->getValueType(0); 4053 SDValue N00 = N->getOperand(0).getOperand(0); 4054 APInt TruncC = N01C->getAPIntValue(); 4055 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits()); 4056 4057 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT, 4058 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00), 4059 DAG.getConstant(TruncC, TruncVT)); 4060 } 4061 } 4062 4063 return SDValue(); 4064 } 4065 4066 SDValue DAGCombiner::visitRotate(SDNode *N) { 4067 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 4068 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE && 4069 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) { 4070 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode()); 4071 if (NewOp1.getNode()) 4072 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), 4073 N->getOperand(0), NewOp1); 4074 } 4075 return SDValue(); 4076 } 4077 4078 SDValue DAGCombiner::visitSHL(SDNode *N) { 4079 SDValue N0 = N->getOperand(0); 4080 SDValue N1 = N->getOperand(1); 4081 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4082 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4083 EVT VT = N0.getValueType(); 4084 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 4085 4086 // fold vector ops 4087 if (VT.isVector()) { 4088 SDValue FoldedVOp = SimplifyVBinOp(N); 4089 if (FoldedVOp.getNode()) return FoldedVOp; 4090 4091 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 4092 // If setcc produces all-one true value then: 4093 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 4094 if (N1CV && N1CV->isConstant()) { 4095 if (N0.getOpcode() == ISD::AND) { 4096 SDValue N00 = N0->getOperand(0); 4097 SDValue N01 = N0->getOperand(1); 4098 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 4099 4100 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 4101 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 4102 TargetLowering::ZeroOrNegativeOneBooleanContent) { 4103 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV)) 4104 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 4105 } 4106 } else { 4107 N1C = isConstOrConstSplat(N1); 4108 } 4109 } 4110 } 4111 4112 // fold (shl c1, c2) -> c1<<c2 4113 if (N0C && N1C) 4114 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C); 4115 // fold (shl 0, x) -> 0 4116 if (N0C && N0C->isNullValue()) 4117 return N0; 4118 // fold (shl x, c >= size(x)) -> undef 4119 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4120 return DAG.getUNDEF(VT); 4121 // fold (shl x, 0) -> x 4122 if (N1C && N1C->isNullValue()) 4123 return N0; 4124 // fold (shl undef, x) -> 0 4125 if (N0.getOpcode() == ISD::UNDEF) 4126 return DAG.getConstant(0, VT); 4127 // if (shl x, c) is known to be zero, return 0 4128 if (DAG.MaskedValueIsZero(SDValue(N, 0), 4129 APInt::getAllOnesValue(OpSizeInBits))) 4130 return DAG.getConstant(0, VT); 4131 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 4132 if (N1.getOpcode() == ISD::TRUNCATE && 4133 N1.getOperand(0).getOpcode() == ISD::AND) { 4134 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4135 if (NewOp1.getNode()) 4136 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 4137 } 4138 4139 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4140 return SDValue(N, 0); 4141 4142 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 4143 if (N1C && N0.getOpcode() == ISD::SHL) { 4144 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4145 uint64_t c1 = N0C1->getZExtValue(); 4146 uint64_t c2 = N1C->getZExtValue(); 4147 if (c1 + c2 >= OpSizeInBits) 4148 return DAG.getConstant(0, VT); 4149 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4150 DAG.getConstant(c1 + c2, N1.getValueType())); 4151 } 4152 } 4153 4154 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 4155 // For this to be valid, the second form must not preserve any of the bits 4156 // that are shifted out by the inner shift in the first form. This means 4157 // the outer shift size must be >= the number of bits added by the ext. 4158 // As a corollary, we don't care what kind of ext it is. 4159 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 4160 N0.getOpcode() == ISD::ANY_EXTEND || 4161 N0.getOpcode() == ISD::SIGN_EXTEND) && 4162 N0.getOperand(0).getOpcode() == ISD::SHL) { 4163 SDValue N0Op0 = N0.getOperand(0); 4164 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4165 uint64_t c1 = N0Op0C1->getZExtValue(); 4166 uint64_t c2 = N1C->getZExtValue(); 4167 EVT InnerShiftVT = N0Op0.getValueType(); 4168 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 4169 if (c2 >= OpSizeInBits - InnerShiftSize) { 4170 if (c1 + c2 >= OpSizeInBits) 4171 return DAG.getConstant(0, VT); 4172 return DAG.getNode(ISD::SHL, SDLoc(N0), VT, 4173 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT, 4174 N0Op0->getOperand(0)), 4175 DAG.getConstant(c1 + c2, N1.getValueType())); 4176 } 4177 } 4178 } 4179 4180 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 4181 // Only fold this if the inner zext has no other uses to avoid increasing 4182 // the total number of instructions. 4183 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 4184 N0.getOperand(0).getOpcode() == ISD::SRL) { 4185 SDValue N0Op0 = N0.getOperand(0); 4186 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 4187 uint64_t c1 = N0Op0C1->getZExtValue(); 4188 if (c1 < VT.getScalarSizeInBits()) { 4189 uint64_t c2 = N1C->getZExtValue(); 4190 if (c1 == c2) { 4191 SDValue NewOp0 = N0.getOperand(0); 4192 EVT CountVT = NewOp0.getOperand(1).getValueType(); 4193 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(), 4194 NewOp0, DAG.getConstant(c2, CountVT)); 4195 AddToWorklist(NewSHL.getNode()); 4196 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 4197 } 4198 } 4199 } 4200 } 4201 4202 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 4203 // (and (srl x, (sub c1, c2), MASK) 4204 // Only fold this if the inner shift has no other uses -- if it does, folding 4205 // this will increase the total number of instructions. 4206 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4207 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 4208 uint64_t c1 = N0C1->getZExtValue(); 4209 if (c1 < OpSizeInBits) { 4210 uint64_t c2 = N1C->getZExtValue(); 4211 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 4212 SDValue Shift; 4213 if (c2 > c1) { 4214 Mask = Mask.shl(c2 - c1); 4215 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0), 4216 DAG.getConstant(c2 - c1, N1.getValueType())); 4217 } else { 4218 Mask = Mask.lshr(c1 - c2); 4219 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4220 DAG.getConstant(c1 - c2, N1.getValueType())); 4221 } 4222 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift, 4223 DAG.getConstant(Mask, VT)); 4224 } 4225 } 4226 } 4227 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 4228 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) { 4229 unsigned BitSize = VT.getScalarSizeInBits(); 4230 SDValue HiBitsMask = 4231 DAG.getConstant(APInt::getHighBitsSet(BitSize, 4232 BitSize - N1C->getZExtValue()), VT); 4233 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4234 HiBitsMask); 4235 } 4236 4237 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 4238 // Variant of version done on multiply, except mul by a power of 2 is turned 4239 // into a shift. 4240 APInt Val; 4241 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 4242 (isa<ConstantSDNode>(N0.getOperand(1)) || 4243 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) { 4244 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 4245 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 4246 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1); 4247 } 4248 4249 if (N1C) { 4250 SDValue NewSHL = visitShiftByConstant(N, N1C); 4251 if (NewSHL.getNode()) 4252 return NewSHL; 4253 } 4254 4255 return SDValue(); 4256 } 4257 4258 SDValue DAGCombiner::visitSRA(SDNode *N) { 4259 SDValue N0 = N->getOperand(0); 4260 SDValue N1 = N->getOperand(1); 4261 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4262 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4263 EVT VT = N0.getValueType(); 4264 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4265 4266 // fold vector ops 4267 if (VT.isVector()) { 4268 SDValue FoldedVOp = SimplifyVBinOp(N); 4269 if (FoldedVOp.getNode()) return FoldedVOp; 4270 4271 N1C = isConstOrConstSplat(N1); 4272 } 4273 4274 // fold (sra c1, c2) -> (sra c1, c2) 4275 if (N0C && N1C) 4276 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C); 4277 // fold (sra 0, x) -> 0 4278 if (N0C && N0C->isNullValue()) 4279 return N0; 4280 // fold (sra -1, x) -> -1 4281 if (N0C && N0C->isAllOnesValue()) 4282 return N0; 4283 // fold (sra x, (setge c, size(x))) -> undef 4284 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4285 return DAG.getUNDEF(VT); 4286 // fold (sra x, 0) -> x 4287 if (N1C && N1C->isNullValue()) 4288 return N0; 4289 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 4290 // sext_inreg. 4291 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 4292 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 4293 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 4294 if (VT.isVector()) 4295 ExtVT = EVT::getVectorVT(*DAG.getContext(), 4296 ExtVT, VT.getVectorNumElements()); 4297 if ((!LegalOperations || 4298 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 4299 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 4300 N0.getOperand(0), DAG.getValueType(ExtVT)); 4301 } 4302 4303 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 4304 if (N1C && N0.getOpcode() == ISD::SRA) { 4305 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) { 4306 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue(); 4307 if (Sum >= OpSizeInBits) 4308 Sum = OpSizeInBits - 1; 4309 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 4310 DAG.getConstant(Sum, N1.getValueType())); 4311 } 4312 } 4313 4314 // fold (sra (shl X, m), (sub result_size, n)) 4315 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 4316 // result_size - n != m. 4317 // If truncate is free for the target sext(shl) is likely to result in better 4318 // code. 4319 if (N0.getOpcode() == ISD::SHL && N1C) { 4320 // Get the two constanst of the shifts, CN0 = m, CN = n. 4321 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 4322 if (N01C) { 4323 LLVMContext &Ctx = *DAG.getContext(); 4324 // Determine what the truncate's result bitsize and type would be. 4325 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 4326 4327 if (VT.isVector()) 4328 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 4329 4330 // Determine the residual right-shift amount. 4331 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 4332 4333 // If the shift is not a no-op (in which case this should be just a sign 4334 // extend already), the truncated to type is legal, sign_extend is legal 4335 // on that type, and the truncate to that type is both legal and free, 4336 // perform the transform. 4337 if ((ShiftAmt > 0) && 4338 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 4339 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 4340 TLI.isTruncateFree(VT, TruncVT)) { 4341 4342 SDValue Amt = DAG.getConstant(ShiftAmt, 4343 getShiftAmountTy(N0.getOperand(0).getValueType())); 4344 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT, 4345 N0.getOperand(0), Amt); 4346 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT, 4347 Shift); 4348 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), 4349 N->getValueType(0), Trunc); 4350 } 4351 } 4352 } 4353 4354 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 4355 if (N1.getOpcode() == ISD::TRUNCATE && 4356 N1.getOperand(0).getOpcode() == ISD::AND) { 4357 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4358 if (NewOp1.getNode()) 4359 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 4360 } 4361 4362 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 4363 // if c1 is equal to the number of bits the trunc removes 4364 if (N0.getOpcode() == ISD::TRUNCATE && 4365 (N0.getOperand(0).getOpcode() == ISD::SRL || 4366 N0.getOperand(0).getOpcode() == ISD::SRA) && 4367 N0.getOperand(0).hasOneUse() && 4368 N0.getOperand(0).getOperand(1).hasOneUse() && 4369 N1C) { 4370 SDValue N0Op0 = N0.getOperand(0); 4371 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 4372 unsigned LargeShiftVal = LargeShift->getZExtValue(); 4373 EVT LargeVT = N0Op0.getValueType(); 4374 4375 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 4376 SDValue Amt = 4377 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), 4378 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 4379 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT, 4380 N0Op0.getOperand(0), Amt); 4381 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA); 4382 } 4383 } 4384 } 4385 4386 // Simplify, based on bits shifted out of the LHS. 4387 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4388 return SDValue(N, 0); 4389 4390 4391 // If the sign bit is known to be zero, switch this to a SRL. 4392 if (DAG.SignBitIsZero(N0)) 4393 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 4394 4395 if (N1C) { 4396 SDValue NewSRA = visitShiftByConstant(N, N1C); 4397 if (NewSRA.getNode()) 4398 return NewSRA; 4399 } 4400 4401 return SDValue(); 4402 } 4403 4404 SDValue DAGCombiner::visitSRL(SDNode *N) { 4405 SDValue N0 = N->getOperand(0); 4406 SDValue N1 = N->getOperand(1); 4407 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4408 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4409 EVT VT = N0.getValueType(); 4410 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits(); 4411 4412 // fold vector ops 4413 if (VT.isVector()) { 4414 SDValue FoldedVOp = SimplifyVBinOp(N); 4415 if (FoldedVOp.getNode()) return FoldedVOp; 4416 4417 N1C = isConstOrConstSplat(N1); 4418 } 4419 4420 // fold (srl c1, c2) -> c1 >>u c2 4421 if (N0C && N1C) 4422 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C); 4423 // fold (srl 0, x) -> 0 4424 if (N0C && N0C->isNullValue()) 4425 return N0; 4426 // fold (srl x, c >= size(x)) -> undef 4427 if (N1C && N1C->getZExtValue() >= OpSizeInBits) 4428 return DAG.getUNDEF(VT); 4429 // fold (srl x, 0) -> x 4430 if (N1C && N1C->isNullValue()) 4431 return N0; 4432 // if (srl x, c) is known to be zero, return 0 4433 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4434 APInt::getAllOnesValue(OpSizeInBits))) 4435 return DAG.getConstant(0, VT); 4436 4437 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 4438 if (N1C && N0.getOpcode() == ISD::SRL) { 4439 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) { 4440 uint64_t c1 = N01C->getZExtValue(); 4441 uint64_t c2 = N1C->getZExtValue(); 4442 if (c1 + c2 >= OpSizeInBits) 4443 return DAG.getConstant(0, VT); 4444 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), 4445 DAG.getConstant(c1 + c2, N1.getValueType())); 4446 } 4447 } 4448 4449 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 4450 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 4451 N0.getOperand(0).getOpcode() == ISD::SRL && 4452 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) { 4453 uint64_t c1 = 4454 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue(); 4455 uint64_t c2 = N1C->getZExtValue(); 4456 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 4457 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType(); 4458 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits(); 4459 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 4460 if (c1 + OpSizeInBits == InnerShiftSize) { 4461 if (c1 + c2 >= InnerShiftSize) 4462 return DAG.getConstant(0, VT); 4463 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, 4464 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT, 4465 N0.getOperand(0)->getOperand(0), 4466 DAG.getConstant(c1 + c2, ShiftCountVT))); 4467 } 4468 } 4469 4470 // fold (srl (shl x, c), c) -> (and x, cst2) 4471 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) { 4472 unsigned BitSize = N0.getScalarValueSizeInBits(); 4473 if (BitSize <= 64) { 4474 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize; 4475 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), 4476 DAG.getConstant(~0ULL >> ShAmt, VT)); 4477 } 4478 } 4479 4480 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 4481 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4482 // Shifting in all undef bits? 4483 EVT SmallVT = N0.getOperand(0).getValueType(); 4484 unsigned BitSize = SmallVT.getScalarSizeInBits(); 4485 if (N1C->getZExtValue() >= BitSize) 4486 return DAG.getUNDEF(VT); 4487 4488 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 4489 uint64_t ShiftAmt = N1C->getZExtValue(); 4490 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT, 4491 N0.getOperand(0), 4492 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT))); 4493 AddToWorklist(SmallShift.getNode()); 4494 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt); 4495 return DAG.getNode(ISD::AND, SDLoc(N), VT, 4496 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift), 4497 DAG.getConstant(Mask, VT)); 4498 } 4499 } 4500 4501 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 4502 // bit, which is unmodified by sra. 4503 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 4504 if (N0.getOpcode() == ISD::SRA) 4505 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 4506 } 4507 4508 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 4509 if (N1C && N0.getOpcode() == ISD::CTLZ && 4510 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 4511 APInt KnownZero, KnownOne; 4512 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne); 4513 4514 // If any of the input bits are KnownOne, then the input couldn't be all 4515 // zeros, thus the result of the srl will always be zero. 4516 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT); 4517 4518 // If all of the bits input the to ctlz node are known to be zero, then 4519 // the result of the ctlz is "32" and the result of the shift is one. 4520 APInt UnknownBits = ~KnownZero; 4521 if (UnknownBits == 0) return DAG.getConstant(1, VT); 4522 4523 // Otherwise, check to see if there is exactly one bit input to the ctlz. 4524 if ((UnknownBits & (UnknownBits - 1)) == 0) { 4525 // Okay, we know that only that the single bit specified by UnknownBits 4526 // could be set on input to the CTLZ node. If this bit is set, the SRL 4527 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 4528 // to an SRL/XOR pair, which is likely to simplify more. 4529 unsigned ShAmt = UnknownBits.countTrailingZeros(); 4530 SDValue Op = N0.getOperand(0); 4531 4532 if (ShAmt) { 4533 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op, 4534 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType()))); 4535 AddToWorklist(Op.getNode()); 4536 } 4537 4538 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 4539 Op, DAG.getConstant(1, VT)); 4540 } 4541 } 4542 4543 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 4544 if (N1.getOpcode() == ISD::TRUNCATE && 4545 N1.getOperand(0).getOpcode() == ISD::AND) { 4546 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()); 4547 if (NewOp1.getNode()) 4548 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 4549 } 4550 4551 // fold operands of srl based on knowledge that the low bits are not 4552 // demanded. 4553 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 4554 return SDValue(N, 0); 4555 4556 if (N1C) { 4557 SDValue NewSRL = visitShiftByConstant(N, N1C); 4558 if (NewSRL.getNode()) 4559 return NewSRL; 4560 } 4561 4562 // Attempt to convert a srl of a load into a narrower zero-extending load. 4563 SDValue NarrowLoad = ReduceLoadWidth(N); 4564 if (NarrowLoad.getNode()) 4565 return NarrowLoad; 4566 4567 // Here is a common situation. We want to optimize: 4568 // 4569 // %a = ... 4570 // %b = and i32 %a, 2 4571 // %c = srl i32 %b, 1 4572 // brcond i32 %c ... 4573 // 4574 // into 4575 // 4576 // %a = ... 4577 // %b = and %a, 2 4578 // %c = setcc eq %b, 0 4579 // brcond %c ... 4580 // 4581 // However when after the source operand of SRL is optimized into AND, the SRL 4582 // itself may not be optimized further. Look for it and add the BRCOND into 4583 // the worklist. 4584 if (N->hasOneUse()) { 4585 SDNode *Use = *N->use_begin(); 4586 if (Use->getOpcode() == ISD::BRCOND) 4587 AddToWorklist(Use); 4588 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 4589 // Also look pass the truncate. 4590 Use = *Use->use_begin(); 4591 if (Use->getOpcode() == ISD::BRCOND) 4592 AddToWorklist(Use); 4593 } 4594 } 4595 4596 return SDValue(); 4597 } 4598 4599 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 4600 SDValue N0 = N->getOperand(0); 4601 EVT VT = N->getValueType(0); 4602 4603 // fold (ctlz c1) -> c2 4604 if (isa<ConstantSDNode>(N0)) 4605 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 4606 return SDValue(); 4607 } 4608 4609 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 4610 SDValue N0 = N->getOperand(0); 4611 EVT VT = N->getValueType(0); 4612 4613 // fold (ctlz_zero_undef c1) -> c2 4614 if (isa<ConstantSDNode>(N0)) 4615 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4616 return SDValue(); 4617 } 4618 4619 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 4620 SDValue N0 = N->getOperand(0); 4621 EVT VT = N->getValueType(0); 4622 4623 // fold (cttz c1) -> c2 4624 if (isa<ConstantSDNode>(N0)) 4625 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 4626 return SDValue(); 4627 } 4628 4629 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 4630 SDValue N0 = N->getOperand(0); 4631 EVT VT = N->getValueType(0); 4632 4633 // fold (cttz_zero_undef c1) -> c2 4634 if (isa<ConstantSDNode>(N0)) 4635 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 4636 return SDValue(); 4637 } 4638 4639 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 4640 SDValue N0 = N->getOperand(0); 4641 EVT VT = N->getValueType(0); 4642 4643 // fold (ctpop c1) -> c2 4644 if (isa<ConstantSDNode>(N0)) 4645 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 4646 return SDValue(); 4647 } 4648 4649 4650 /// \brief Generate Min/Max node 4651 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS, 4652 SDValue True, SDValue False, 4653 ISD::CondCode CC, const TargetLowering &TLI, 4654 SelectionDAG &DAG) { 4655 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 4656 return SDValue(); 4657 4658 switch (CC) { 4659 case ISD::SETOLT: 4660 case ISD::SETOLE: 4661 case ISD::SETLT: 4662 case ISD::SETLE: 4663 case ISD::SETULT: 4664 case ISD::SETULE: { 4665 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 4666 if (TLI.isOperationLegal(Opcode, VT)) 4667 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4668 return SDValue(); 4669 } 4670 case ISD::SETOGT: 4671 case ISD::SETOGE: 4672 case ISD::SETGT: 4673 case ISD::SETGE: 4674 case ISD::SETUGT: 4675 case ISD::SETUGE: { 4676 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 4677 if (TLI.isOperationLegal(Opcode, VT)) 4678 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 4679 return SDValue(); 4680 } 4681 default: 4682 return SDValue(); 4683 } 4684 } 4685 4686 SDValue DAGCombiner::visitSELECT(SDNode *N) { 4687 SDValue N0 = N->getOperand(0); 4688 SDValue N1 = N->getOperand(1); 4689 SDValue N2 = N->getOperand(2); 4690 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 4691 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 4692 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 4693 EVT VT = N->getValueType(0); 4694 EVT VT0 = N0.getValueType(); 4695 4696 // fold (select C, X, X) -> X 4697 if (N1 == N2) 4698 return N1; 4699 // fold (select true, X, Y) -> X 4700 if (N0C && !N0C->isNullValue()) 4701 return N1; 4702 // fold (select false, X, Y) -> Y 4703 if (N0C && N0C->isNullValue()) 4704 return N2; 4705 // fold (select C, 1, X) -> (or C, X) 4706 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1) 4707 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4708 // fold (select C, 0, 1) -> (xor C, 1) 4709 // We can't do this reliably if integer based booleans have different contents 4710 // to floating point based booleans. This is because we can't tell whether we 4711 // have an integer-based boolean or a floating-point-based boolean unless we 4712 // can find the SETCC that produced it and inspect its operands. This is 4713 // fairly easy if C is the SETCC node, but it can potentially be 4714 // undiscoverable (or not reasonably discoverable). For example, it could be 4715 // in another basic block or it could require searching a complicated 4716 // expression. 4717 if (VT.isInteger() && 4718 (VT0 == MVT::i1 || (VT0.isInteger() && 4719 TLI.getBooleanContents(false, false) == 4720 TLI.getBooleanContents(false, true) && 4721 TLI.getBooleanContents(false, false) == 4722 TargetLowering::ZeroOrOneBooleanContent)) && 4723 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) { 4724 SDValue XORNode; 4725 if (VT == VT0) 4726 return DAG.getNode(ISD::XOR, SDLoc(N), VT0, 4727 N0, DAG.getConstant(1, VT0)); 4728 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0, 4729 N0, DAG.getConstant(1, VT0)); 4730 AddToWorklist(XORNode.getNode()); 4731 if (VT.bitsGT(VT0)) 4732 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode); 4733 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode); 4734 } 4735 // fold (select C, 0, X) -> (and (not C), X) 4736 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) { 4737 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4738 AddToWorklist(NOTNode.getNode()); 4739 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2); 4740 } 4741 // fold (select C, X, 1) -> (or (not C), X) 4742 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) { 4743 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 4744 AddToWorklist(NOTNode.getNode()); 4745 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1); 4746 } 4747 // fold (select C, X, 0) -> (and C, X) 4748 if (VT == MVT::i1 && N2C && N2C->isNullValue()) 4749 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4750 // fold (select X, X, Y) -> (or X, Y) 4751 // fold (select X, 1, Y) -> (or X, Y) 4752 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1))) 4753 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2); 4754 // fold (select X, Y, X) -> (and X, Y) 4755 // fold (select X, Y, 0) -> (and X, Y) 4756 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0))) 4757 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1); 4758 4759 // If we can fold this based on the true/false value, do so. 4760 if (SimplifySelectOps(N, N1, N2)) 4761 return SDValue(N, 0); // Don't revisit N. 4762 4763 // fold selects based on a setcc into other things, such as min/max/abs 4764 if (N0.getOpcode() == ISD::SETCC) { 4765 // select x, y (fcmp lt x, y) -> fminnum x, y 4766 // select x, y (fcmp gt x, y) -> fmaxnum x, y 4767 // 4768 // This is OK if we don't care about what happens if either operand is a 4769 // NaN. 4770 // 4771 4772 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for 4773 // no signed zeros as well as no nans. 4774 const TargetOptions &Options = DAG.getTarget().Options; 4775 if (Options.UnsafeFPMath && 4776 VT.isFloatingPoint() && N0.hasOneUse() && 4777 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) { 4778 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 4779 4780 SDValue FMinMax = 4781 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1), 4782 N1, N2, CC, TLI, DAG); 4783 if (FMinMax) 4784 return FMinMax; 4785 } 4786 4787 if ((!LegalOperations && 4788 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) || 4789 TLI.isOperationLegal(ISD::SELECT_CC, VT)) 4790 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, 4791 N0.getOperand(0), N0.getOperand(1), 4792 N1, N2, N0.getOperand(2)); 4793 return SimplifySelect(SDLoc(N), N0, N1, N2); 4794 } 4795 4796 return SDValue(); 4797 } 4798 4799 static 4800 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 4801 SDLoc DL(N); 4802 EVT LoVT, HiVT; 4803 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 4804 4805 // Split the inputs. 4806 SDValue Lo, Hi, LL, LH, RL, RH; 4807 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 4808 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 4809 4810 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 4811 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 4812 4813 return std::make_pair(Lo, Hi); 4814 } 4815 4816 // This function assumes all the vselect's arguments are CONCAT_VECTOR 4817 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 4818 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 4819 SDLoc dl(N); 4820 SDValue Cond = N->getOperand(0); 4821 SDValue LHS = N->getOperand(1); 4822 SDValue RHS = N->getOperand(2); 4823 EVT VT = N->getValueType(0); 4824 int NumElems = VT.getVectorNumElements(); 4825 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 4826 RHS.getOpcode() == ISD::CONCAT_VECTORS && 4827 Cond.getOpcode() == ISD::BUILD_VECTOR); 4828 4829 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 4830 // binary ones here. 4831 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 4832 return SDValue(); 4833 4834 // We're sure we have an even number of elements due to the 4835 // concat_vectors we have as arguments to vselect. 4836 // Skip BV elements until we find one that's not an UNDEF 4837 // After we find an UNDEF element, keep looping until we get to half the 4838 // length of the BV and see if all the non-undef nodes are the same. 4839 ConstantSDNode *BottomHalf = nullptr; 4840 for (int i = 0; i < NumElems / 2; ++i) { 4841 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4842 continue; 4843 4844 if (BottomHalf == nullptr) 4845 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4846 else if (Cond->getOperand(i).getNode() != BottomHalf) 4847 return SDValue(); 4848 } 4849 4850 // Do the same for the second half of the BuildVector 4851 ConstantSDNode *TopHalf = nullptr; 4852 for (int i = NumElems / 2; i < NumElems; ++i) { 4853 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF) 4854 continue; 4855 4856 if (TopHalf == nullptr) 4857 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 4858 else if (Cond->getOperand(i).getNode() != TopHalf) 4859 return SDValue(); 4860 } 4861 4862 assert(TopHalf && BottomHalf && 4863 "One half of the selector was all UNDEFs and the other was all the " 4864 "same value. This should have been addressed before this function."); 4865 return DAG.getNode( 4866 ISD::CONCAT_VECTORS, dl, VT, 4867 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 4868 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 4869 } 4870 4871 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 4872 4873 if (Level >= AfterLegalizeTypes) 4874 return SDValue(); 4875 4876 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 4877 SDValue Mask = MST->getMask(); 4878 SDValue Data = MST->getValue(); 4879 SDLoc DL(N); 4880 4881 // If the MSTORE data type requires splitting and the mask is provided by a 4882 // SETCC, then split both nodes and its operands before legalization. This 4883 // prevents the type legalizer from unrolling SETCC into scalar comparisons 4884 // and enables future optimizations (e.g. min/max pattern matching on X86). 4885 if (Mask.getOpcode() == ISD::SETCC) { 4886 4887 // Check if any splitting is required. 4888 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 4889 TargetLowering::TypeSplitVector) 4890 return SDValue(); 4891 4892 SDValue MaskLo, MaskHi, Lo, Hi; 4893 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 4894 4895 EVT LoVT, HiVT; 4896 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0)); 4897 4898 SDValue Chain = MST->getChain(); 4899 SDValue Ptr = MST->getBasePtr(); 4900 4901 EVT MemoryVT = MST->getMemoryVT(); 4902 unsigned Alignment = MST->getOriginalAlignment(); 4903 4904 // if Alignment is equal to the vector size, 4905 // take the half of it for the second part 4906 unsigned SecondHalfAlignment = 4907 (Alignment == Data->getValueType(0).getSizeInBits()/8) ? 4908 Alignment/2 : Alignment; 4909 4910 EVT LoMemVT, HiMemVT; 4911 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 4912 4913 SDValue DataLo, DataHi; 4914 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 4915 4916 MachineMemOperand *MMO = DAG.getMachineFunction(). 4917 getMachineMemOperand(MST->getPointerInfo(), 4918 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 4919 Alignment, MST->getAAInfo(), MST->getRanges()); 4920 4921 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 4922 MST->isTruncatingStore()); 4923 4924 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 4925 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 4926 DAG.getConstant(IncrementSize, Ptr.getValueType())); 4927 4928 MMO = DAG.getMachineFunction(). 4929 getMachineMemOperand(MST->getPointerInfo(), 4930 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), 4931 SecondHalfAlignment, MST->getAAInfo(), 4932 MST->getRanges()); 4933 4934 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 4935 MST->isTruncatingStore()); 4936 4937 AddToWorklist(Lo.getNode()); 4938 AddToWorklist(Hi.getNode()); 4939 4940 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 4941 } 4942 return SDValue(); 4943 } 4944 4945 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 4946 4947 if (Level >= AfterLegalizeTypes) 4948 return SDValue(); 4949 4950 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 4951 SDValue Mask = MLD->getMask(); 4952 SDLoc DL(N); 4953 4954 // If the MLOAD result requires splitting and the mask is provided by a 4955 // SETCC, then split both nodes and its operands before legalization. This 4956 // prevents the type legalizer from unrolling SETCC into scalar comparisons 4957 // and enables future optimizations (e.g. min/max pattern matching on X86). 4958 4959 if (Mask.getOpcode() == ISD::SETCC) { 4960 EVT VT = N->getValueType(0); 4961 4962 // Check if any splitting is required. 4963 if (TLI.getTypeAction(*DAG.getContext(), VT) != 4964 TargetLowering::TypeSplitVector) 4965 return SDValue(); 4966 4967 SDValue MaskLo, MaskHi, Lo, Hi; 4968 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 4969 4970 SDValue Src0 = MLD->getSrc0(); 4971 SDValue Src0Lo, Src0Hi; 4972 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL); 4973 4974 EVT LoVT, HiVT; 4975 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 4976 4977 SDValue Chain = MLD->getChain(); 4978 SDValue Ptr = MLD->getBasePtr(); 4979 EVT MemoryVT = MLD->getMemoryVT(); 4980 unsigned Alignment = MLD->getOriginalAlignment(); 4981 4982 // if Alignment is equal to the vector size, 4983 // take the half of it for the second part 4984 unsigned SecondHalfAlignment = 4985 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 4986 Alignment/2 : Alignment; 4987 4988 EVT LoMemVT, HiMemVT; 4989 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 4990 4991 MachineMemOperand *MMO = DAG.getMachineFunction(). 4992 getMachineMemOperand(MLD->getPointerInfo(), 4993 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 4994 Alignment, MLD->getAAInfo(), MLD->getRanges()); 4995 4996 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO, 4997 ISD::NON_EXTLOAD); 4998 4999 unsigned IncrementSize = LoMemVT.getSizeInBits()/8; 5000 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 5001 DAG.getConstant(IncrementSize, Ptr.getValueType())); 5002 5003 MMO = DAG.getMachineFunction(). 5004 getMachineMemOperand(MLD->getPointerInfo(), 5005 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), 5006 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges()); 5007 5008 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO, 5009 ISD::NON_EXTLOAD); 5010 5011 AddToWorklist(Lo.getNode()); 5012 AddToWorklist(Hi.getNode()); 5013 5014 // Build a factor node to remember that this load is independent of the 5015 // other one. 5016 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 5017 Hi.getValue(1)); 5018 5019 // Legalized the chain result - switch anything that used the old chain to 5020 // use the new one. 5021 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 5022 5023 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5024 5025 SDValue RetOps[] = { LoadRes, Chain }; 5026 return DAG.getMergeValues(RetOps, DL); 5027 } 5028 return SDValue(); 5029 } 5030 5031 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 5032 SDValue N0 = N->getOperand(0); 5033 SDValue N1 = N->getOperand(1); 5034 SDValue N2 = N->getOperand(2); 5035 SDLoc DL(N); 5036 5037 // Canonicalize integer abs. 5038 // vselect (setg[te] X, 0), X, -X -> 5039 // vselect (setgt X, -1), X, -X -> 5040 // vselect (setl[te] X, 0), -X, X -> 5041 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 5042 if (N0.getOpcode() == ISD::SETCC) { 5043 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 5044 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5045 bool isAbs = false; 5046 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 5047 5048 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 5049 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 5050 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 5051 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 5052 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 5053 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 5054 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5055 5056 if (isAbs) { 5057 EVT VT = LHS.getValueType(); 5058 SDValue Shift = DAG.getNode( 5059 ISD::SRA, DL, VT, LHS, 5060 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT)); 5061 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 5062 AddToWorklist(Shift.getNode()); 5063 AddToWorklist(Add.getNode()); 5064 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 5065 } 5066 } 5067 5068 // If the VSELECT result requires splitting and the mask is provided by a 5069 // SETCC, then split both nodes and its operands before legalization. This 5070 // prevents the type legalizer from unrolling SETCC into scalar comparisons 5071 // and enables future optimizations (e.g. min/max pattern matching on X86). 5072 if (N0.getOpcode() == ISD::SETCC) { 5073 EVT VT = N->getValueType(0); 5074 5075 // Check if any splitting is required. 5076 if (TLI.getTypeAction(*DAG.getContext(), VT) != 5077 TargetLowering::TypeSplitVector) 5078 return SDValue(); 5079 5080 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH; 5081 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG); 5082 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1); 5083 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2); 5084 5085 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL); 5086 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH); 5087 5088 // Add the new VSELECT nodes to the work list in case they need to be split 5089 // again. 5090 AddToWorklist(Lo.getNode()); 5091 AddToWorklist(Hi.getNode()); 5092 5093 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 5094 } 5095 5096 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 5097 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5098 return N1; 5099 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 5100 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5101 return N2; 5102 5103 // The ConvertSelectToConcatVector function is assuming both the above 5104 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 5105 // and addressed. 5106 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 5107 N2.getOpcode() == ISD::CONCAT_VECTORS && 5108 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 5109 SDValue CV = ConvertSelectToConcatVector(N, DAG); 5110 if (CV.getNode()) 5111 return CV; 5112 } 5113 5114 return SDValue(); 5115 } 5116 5117 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 5118 SDValue N0 = N->getOperand(0); 5119 SDValue N1 = N->getOperand(1); 5120 SDValue N2 = N->getOperand(2); 5121 SDValue N3 = N->getOperand(3); 5122 SDValue N4 = N->getOperand(4); 5123 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 5124 5125 // fold select_cc lhs, rhs, x, x, cc -> x 5126 if (N2 == N3) 5127 return N2; 5128 5129 // Determine if the condition we're dealing with is constant 5130 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 5131 N0, N1, CC, SDLoc(N), false); 5132 if (SCC.getNode()) { 5133 AddToWorklist(SCC.getNode()); 5134 5135 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 5136 if (!SCCC->isNullValue()) 5137 return N2; // cond always true -> true val 5138 else 5139 return N3; // cond always false -> false val 5140 } else if (SCC->getOpcode() == ISD::UNDEF) { 5141 // When the condition is UNDEF, just return the first operand. This is 5142 // coherent the DAG creation, no setcc node is created in this case 5143 return N2; 5144 } else if (SCC.getOpcode() == ISD::SETCC) { 5145 // Fold to a simpler select_cc 5146 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 5147 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 5148 SCC.getOperand(2)); 5149 } 5150 } 5151 5152 // If we can fold this based on the true/false value, do so. 5153 if (SimplifySelectOps(N, N2, N3)) 5154 return SDValue(N, 0); // Don't revisit N. 5155 5156 // fold select_cc into other things, such as min/max/abs 5157 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 5158 } 5159 5160 SDValue DAGCombiner::visitSETCC(SDNode *N) { 5161 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1), 5162 cast<CondCodeSDNode>(N->getOperand(2))->get(), 5163 SDLoc(N)); 5164 } 5165 5166 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext 5167 // dag node into a ConstantSDNode or a build_vector of constants. 5168 // This function is called by the DAGCombiner when visiting sext/zext/aext 5169 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 5170 // Vector extends are not folded if operations are legal; this is to 5171 // avoid introducing illegal build_vector dag nodes. 5172 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 5173 SelectionDAG &DAG, bool LegalTypes, 5174 bool LegalOperations) { 5175 unsigned Opcode = N->getOpcode(); 5176 SDValue N0 = N->getOperand(0); 5177 EVT VT = N->getValueType(0); 5178 5179 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 5180 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!"); 5181 5182 // fold (sext c1) -> c1 5183 // fold (zext c1) -> c1 5184 // fold (aext c1) -> c1 5185 if (isa<ConstantSDNode>(N0)) 5186 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode(); 5187 5188 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 5189 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 5190 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 5191 EVT SVT = VT.getScalarType(); 5192 if (!(VT.isVector() && 5193 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) && 5194 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 5195 return nullptr; 5196 5197 // We can fold this node into a build_vector. 5198 unsigned VTBits = SVT.getSizeInBits(); 5199 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits(); 5200 unsigned ShAmt = VTBits - EVTBits; 5201 SmallVector<SDValue, 8> Elts; 5202 unsigned NumElts = N0->getNumOperands(); 5203 SDLoc DL(N); 5204 5205 for (unsigned i=0; i != NumElts; ++i) { 5206 SDValue Op = N0->getOperand(i); 5207 if (Op->getOpcode() == ISD::UNDEF) { 5208 Elts.push_back(DAG.getUNDEF(SVT)); 5209 continue; 5210 } 5211 5212 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 5213 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 5214 if (Opcode == ISD::SIGN_EXTEND) 5215 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 5216 SVT)); 5217 else 5218 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(), 5219 SVT)); 5220 } 5221 5222 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode(); 5223 } 5224 5225 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 5226 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 5227 // transformation. Returns true if extension are possible and the above 5228 // mentioned transformation is profitable. 5229 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0, 5230 unsigned ExtOpc, 5231 SmallVectorImpl<SDNode *> &ExtendNodes, 5232 const TargetLowering &TLI) { 5233 bool HasCopyToRegUses = false; 5234 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType()); 5235 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 5236 UE = N0.getNode()->use_end(); 5237 UI != UE; ++UI) { 5238 SDNode *User = *UI; 5239 if (User == N) 5240 continue; 5241 if (UI.getUse().getResNo() != N0.getResNo()) 5242 continue; 5243 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 5244 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 5245 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 5246 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 5247 // Sign bits will be lost after a zext. 5248 return false; 5249 bool Add = false; 5250 for (unsigned i = 0; i != 2; ++i) { 5251 SDValue UseOp = User->getOperand(i); 5252 if (UseOp == N0) 5253 continue; 5254 if (!isa<ConstantSDNode>(UseOp)) 5255 return false; 5256 Add = true; 5257 } 5258 if (Add) 5259 ExtendNodes.push_back(User); 5260 continue; 5261 } 5262 // If truncates aren't free and there are users we can't 5263 // extend, it isn't worthwhile. 5264 if (!isTruncFree) 5265 return false; 5266 // Remember if this value is live-out. 5267 if (User->getOpcode() == ISD::CopyToReg) 5268 HasCopyToRegUses = true; 5269 } 5270 5271 if (HasCopyToRegUses) { 5272 bool BothLiveOut = false; 5273 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5274 UI != UE; ++UI) { 5275 SDUse &Use = UI.getUse(); 5276 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 5277 BothLiveOut = true; 5278 break; 5279 } 5280 } 5281 if (BothLiveOut) 5282 // Both unextended and extended values are live out. There had better be 5283 // a good reason for the transformation. 5284 return ExtendNodes.size(); 5285 } 5286 return true; 5287 } 5288 5289 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 5290 SDValue Trunc, SDValue ExtLoad, SDLoc DL, 5291 ISD::NodeType ExtType) { 5292 // Extend SetCC uses if necessary. 5293 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) { 5294 SDNode *SetCC = SetCCs[i]; 5295 SmallVector<SDValue, 4> Ops; 5296 5297 for (unsigned j = 0; j != 2; ++j) { 5298 SDValue SOp = SetCC->getOperand(j); 5299 if (SOp == Trunc) 5300 Ops.push_back(ExtLoad); 5301 else 5302 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 5303 } 5304 5305 Ops.push_back(SetCC->getOperand(2)); 5306 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 5307 } 5308 } 5309 5310 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 5311 SDValue N0 = N->getOperand(0); 5312 EVT VT = N->getValueType(0); 5313 5314 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5315 LegalOperations)) 5316 return SDValue(Res, 0); 5317 5318 // fold (sext (sext x)) -> (sext x) 5319 // fold (sext (aext x)) -> (sext x) 5320 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5321 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, 5322 N0.getOperand(0)); 5323 5324 if (N0.getOpcode() == ISD::TRUNCATE) { 5325 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 5326 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 5327 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5328 if (NarrowLoad.getNode()) { 5329 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5330 if (NarrowLoad.getNode() != N0.getNode()) { 5331 CombineTo(N0.getNode(), NarrowLoad); 5332 // CombineTo deleted the truncate, if needed, but not what's under it. 5333 AddToWorklist(oye); 5334 } 5335 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5336 } 5337 5338 // See if the value being truncated is already sign extended. If so, just 5339 // eliminate the trunc/sext pair. 5340 SDValue Op = N0.getOperand(0); 5341 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits(); 5342 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits(); 5343 unsigned DestBits = VT.getScalarType().getSizeInBits(); 5344 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 5345 5346 if (OpBits == DestBits) { 5347 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 5348 // bits, it is already ready. 5349 if (NumSignBits > DestBits-MidBits) 5350 return Op; 5351 } else if (OpBits < DestBits) { 5352 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 5353 // bits, just sext from i32. 5354 if (NumSignBits > OpBits-MidBits) 5355 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op); 5356 } else { 5357 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 5358 // bits, just truncate to i32. 5359 if (NumSignBits > OpBits-MidBits) 5360 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5361 } 5362 5363 // fold (sext (truncate x)) -> (sextinreg x). 5364 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 5365 N0.getValueType())) { 5366 if (OpBits < DestBits) 5367 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 5368 else if (OpBits > DestBits) 5369 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 5370 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op, 5371 DAG.getValueType(N0.getValueType())); 5372 } 5373 } 5374 5375 // fold (sext (load x)) -> (sext (truncate (sextload x))) 5376 // None of the supported targets knows how to perform load and sign extend 5377 // on vectors in one instruction. We only perform this transformation on 5378 // scalars. 5379 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5380 ISD::isUNINDEXEDLoad(N0.getNode()) && 5381 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5382 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) { 5383 bool DoXform = true; 5384 SmallVector<SDNode*, 4> SetCCs; 5385 if (!N0.hasOneUse()) 5386 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI); 5387 if (DoXform) { 5388 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5389 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5390 LN0->getChain(), 5391 LN0->getBasePtr(), N0.getValueType(), 5392 LN0->getMemOperand()); 5393 CombineTo(N, ExtLoad); 5394 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5395 N0.getValueType(), ExtLoad); 5396 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5397 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5398 ISD::SIGN_EXTEND); 5399 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5400 } 5401 } 5402 5403 // fold (sext (sextload x)) -> (sext (truncate (sextload x))) 5404 // fold (sext ( extload x)) -> (sext (truncate (sextload x))) 5405 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5406 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5407 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5408 EVT MemVT = LN0->getMemoryVT(); 5409 if ((!LegalOperations && !LN0->isVolatile()) || 5410 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) { 5411 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 5412 LN0->getChain(), 5413 LN0->getBasePtr(), MemVT, 5414 LN0->getMemOperand()); 5415 CombineTo(N, ExtLoad); 5416 CombineTo(N0.getNode(), 5417 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5418 N0.getValueType(), ExtLoad), 5419 ExtLoad.getValue(1)); 5420 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5421 } 5422 } 5423 5424 // fold (sext (and/or/xor (load x), cst)) -> 5425 // (and/or/xor (sextload x), (sext cst)) 5426 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5427 N0.getOpcode() == ISD::XOR) && 5428 isa<LoadSDNode>(N0.getOperand(0)) && 5429 N0.getOperand(1).getOpcode() == ISD::Constant && 5430 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) && 5431 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5432 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5433 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) { 5434 bool DoXform = true; 5435 SmallVector<SDNode*, 4> SetCCs; 5436 if (!N0.hasOneUse()) 5437 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND, 5438 SetCCs, TLI); 5439 if (DoXform) { 5440 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT, 5441 LN0->getChain(), LN0->getBasePtr(), 5442 LN0->getMemoryVT(), 5443 LN0->getMemOperand()); 5444 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5445 Mask = Mask.sext(VT.getSizeInBits()); 5446 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5447 ExtLoad, DAG.getConstant(Mask, VT)); 5448 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5449 SDLoc(N0.getOperand(0)), 5450 N0.getOperand(0).getValueType(), ExtLoad); 5451 CombineTo(N, And); 5452 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5453 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5454 ISD::SIGN_EXTEND); 5455 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5456 } 5457 } 5458 } 5459 5460 if (N0.getOpcode() == ISD::SETCC) { 5461 EVT N0VT = N0.getOperand(0).getValueType(); 5462 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 5463 // Only do this before legalize for now. 5464 if (VT.isVector() && !LegalOperations && 5465 TLI.getBooleanContents(N0VT) == 5466 TargetLowering::ZeroOrNegativeOneBooleanContent) { 5467 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 5468 // of the same size as the compared operands. Only optimize sext(setcc()) 5469 // if this is the case. 5470 EVT SVT = getSetCCResultType(N0VT); 5471 5472 // We know that the # elements of the results is the same as the 5473 // # elements of the compare (and the # elements of the compare result 5474 // for that matter). Check to see that they are the same size. If so, 5475 // we know that the element size of the sext'd result matches the 5476 // element size of the compare operands. 5477 if (VT.getSizeInBits() == SVT.getSizeInBits()) 5478 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5479 N0.getOperand(1), 5480 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5481 5482 // If the desired elements are smaller or larger than the source 5483 // elements we can use a matching integer vector type and then 5484 // truncate/sign extend 5485 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5486 if (SVT == MatchingVectorType) { 5487 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType, 5488 N0.getOperand(0), N0.getOperand(1), 5489 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5490 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT); 5491 } 5492 } 5493 5494 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0) 5495 unsigned ElementWidth = VT.getScalarType().getSizeInBits(); 5496 SDValue NegOne = 5497 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT); 5498 SDValue SCC = 5499 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5500 NegOne, DAG.getConstant(0, VT), 5501 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5502 if (SCC.getNode()) return SCC; 5503 5504 if (!VT.isVector()) { 5505 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType()); 5506 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) { 5507 SDLoc DL(N); 5508 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 5509 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, 5510 N0.getOperand(0), N0.getOperand(1), CC); 5511 return DAG.getSelect(DL, VT, SetCC, 5512 NegOne, DAG.getConstant(0, VT)); 5513 } 5514 } 5515 } 5516 5517 // fold (sext x) -> (zext x) if the sign bit is known zero. 5518 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 5519 DAG.SignBitIsZero(N0)) 5520 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0); 5521 5522 return SDValue(); 5523 } 5524 5525 // isTruncateOf - If N is a truncate of some other value, return true, record 5526 // the value being truncated in Op and which of Op's bits are zero in KnownZero. 5527 // This function computes KnownZero to avoid a duplicated call to 5528 // computeKnownBits in the caller. 5529 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 5530 APInt &KnownZero) { 5531 APInt KnownOne; 5532 if (N->getOpcode() == ISD::TRUNCATE) { 5533 Op = N->getOperand(0); 5534 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5535 return true; 5536 } 5537 5538 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 || 5539 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE) 5540 return false; 5541 5542 SDValue Op0 = N->getOperand(0); 5543 SDValue Op1 = N->getOperand(1); 5544 assert(Op0.getValueType() == Op1.getValueType()); 5545 5546 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0); 5547 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1); 5548 if (COp0 && COp0->isNullValue()) 5549 Op = Op1; 5550 else if (COp1 && COp1->isNullValue()) 5551 Op = Op0; 5552 else 5553 return false; 5554 5555 DAG.computeKnownBits(Op, KnownZero, KnownOne); 5556 5557 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue()) 5558 return false; 5559 5560 return true; 5561 } 5562 5563 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 5564 SDValue N0 = N->getOperand(0); 5565 EVT VT = N->getValueType(0); 5566 5567 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5568 LegalOperations)) 5569 return SDValue(Res, 0); 5570 5571 // fold (zext (zext x)) -> (zext x) 5572 // fold (zext (aext x)) -> (zext x) 5573 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 5574 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 5575 N0.getOperand(0)); 5576 5577 // fold (zext (truncate x)) -> (zext x) or 5578 // (zext (truncate x)) -> (truncate x) 5579 // This is valid when the truncated bits of x are already zero. 5580 // FIXME: We should extend this to work for vectors too. 5581 SDValue Op; 5582 APInt KnownZero; 5583 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) { 5584 APInt TruncatedBits = 5585 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ? 5586 APInt(Op.getValueSizeInBits(), 0) : 5587 APInt::getBitsSet(Op.getValueSizeInBits(), 5588 N0.getValueSizeInBits(), 5589 std::min(Op.getValueSizeInBits(), 5590 VT.getSizeInBits())); 5591 if (TruncatedBits == (KnownZero & TruncatedBits)) { 5592 if (VT.bitsGT(Op.getValueType())) 5593 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op); 5594 if (VT.bitsLT(Op.getValueType())) 5595 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5596 5597 return Op; 5598 } 5599 } 5600 5601 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5602 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n))) 5603 if (N0.getOpcode() == ISD::TRUNCATE) { 5604 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5605 if (NarrowLoad.getNode()) { 5606 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5607 if (NarrowLoad.getNode() != N0.getNode()) { 5608 CombineTo(N0.getNode(), NarrowLoad); 5609 // CombineTo deleted the truncate, if needed, but not what's under it. 5610 AddToWorklist(oye); 5611 } 5612 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5613 } 5614 } 5615 5616 // fold (zext (truncate x)) -> (and x, mask) 5617 if (N0.getOpcode() == ISD::TRUNCATE && 5618 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) { 5619 5620 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 5621 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 5622 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5623 if (NarrowLoad.getNode()) { 5624 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5625 if (NarrowLoad.getNode() != N0.getNode()) { 5626 CombineTo(N0.getNode(), NarrowLoad); 5627 // CombineTo deleted the truncate, if needed, but not what's under it. 5628 AddToWorklist(oye); 5629 } 5630 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5631 } 5632 5633 SDValue Op = N0.getOperand(0); 5634 if (Op.getValueType().bitsLT(VT)) { 5635 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op); 5636 AddToWorklist(Op.getNode()); 5637 } else if (Op.getValueType().bitsGT(VT)) { 5638 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op); 5639 AddToWorklist(Op.getNode()); 5640 } 5641 return DAG.getZeroExtendInReg(Op, SDLoc(N), 5642 N0.getValueType().getScalarType()); 5643 } 5644 5645 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 5646 // if either of the casts is not free. 5647 if (N0.getOpcode() == ISD::AND && 5648 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5649 N0.getOperand(1).getOpcode() == ISD::Constant && 5650 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5651 N0.getValueType()) || 5652 !TLI.isZExtFree(N0.getValueType(), VT))) { 5653 SDValue X = N0.getOperand(0).getOperand(0); 5654 if (X.getValueType().bitsLT(VT)) { 5655 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X); 5656 } else if (X.getValueType().bitsGT(VT)) { 5657 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 5658 } 5659 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5660 Mask = Mask.zext(VT.getSizeInBits()); 5661 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5662 X, DAG.getConstant(Mask, VT)); 5663 } 5664 5665 // fold (zext (load x)) -> (zext (truncate (zextload x))) 5666 // None of the supported targets knows how to perform load and vector_zext 5667 // on vectors in one instruction. We only perform this transformation on 5668 // scalars. 5669 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5670 ISD::isUNINDEXEDLoad(N0.getNode()) && 5671 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 5672 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) { 5673 bool DoXform = true; 5674 SmallVector<SDNode*, 4> SetCCs; 5675 if (!N0.hasOneUse()) 5676 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI); 5677 if (DoXform) { 5678 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5679 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5680 LN0->getChain(), 5681 LN0->getBasePtr(), N0.getValueType(), 5682 LN0->getMemOperand()); 5683 CombineTo(N, ExtLoad); 5684 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5685 N0.getValueType(), ExtLoad); 5686 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5687 5688 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5689 ISD::ZERO_EXTEND); 5690 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5691 } 5692 } 5693 5694 // fold (zext (and/or/xor (load x), cst)) -> 5695 // (and/or/xor (zextload x), (zext cst)) 5696 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 5697 N0.getOpcode() == ISD::XOR) && 5698 isa<LoadSDNode>(N0.getOperand(0)) && 5699 N0.getOperand(1).getOpcode() == ISD::Constant && 5700 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) && 5701 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 5702 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0)); 5703 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) { 5704 bool DoXform = true; 5705 SmallVector<SDNode*, 4> SetCCs; 5706 if (!N0.hasOneUse()) 5707 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND, 5708 SetCCs, TLI); 5709 if (DoXform) { 5710 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT, 5711 LN0->getChain(), LN0->getBasePtr(), 5712 LN0->getMemoryVT(), 5713 LN0->getMemOperand()); 5714 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5715 Mask = Mask.zext(VT.getSizeInBits()); 5716 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 5717 ExtLoad, DAG.getConstant(Mask, VT)); 5718 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, 5719 SDLoc(N0.getOperand(0)), 5720 N0.getOperand(0).getValueType(), ExtLoad); 5721 CombineTo(N, And); 5722 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1)); 5723 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5724 ISD::ZERO_EXTEND); 5725 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5726 } 5727 } 5728 } 5729 5730 // fold (zext (zextload x)) -> (zext (truncate (zextload x))) 5731 // fold (zext ( extload x)) -> (zext (truncate (zextload x))) 5732 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) && 5733 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 5734 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5735 EVT MemVT = LN0->getMemoryVT(); 5736 if ((!LegalOperations && !LN0->isVolatile()) || 5737 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) { 5738 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, 5739 LN0->getChain(), 5740 LN0->getBasePtr(), MemVT, 5741 LN0->getMemOperand()); 5742 CombineTo(N, ExtLoad); 5743 CombineTo(N0.getNode(), 5744 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), 5745 ExtLoad), 5746 ExtLoad.getValue(1)); 5747 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5748 } 5749 } 5750 5751 if (N0.getOpcode() == ISD::SETCC) { 5752 if (!LegalOperations && VT.isVector() && 5753 N0.getValueType().getVectorElementType() == MVT::i1) { 5754 EVT N0VT = N0.getOperand(0).getValueType(); 5755 if (getSetCCResultType(N0VT) == N0.getValueType()) 5756 return SDValue(); 5757 5758 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 5759 // Only do this before legalize for now. 5760 EVT EltVT = VT.getVectorElementType(); 5761 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(), 5762 DAG.getConstant(1, EltVT)); 5763 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5764 // We know that the # elements of the results is the same as the 5765 // # elements of the compare (and the # elements of the compare result 5766 // for that matter). Check to see that they are the same size. If so, 5767 // we know that the element size of the sext'd result matches the 5768 // element size of the compare operands. 5769 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5770 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5771 N0.getOperand(1), 5772 cast<CondCodeSDNode>(N0.getOperand(2))->get()), 5773 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, 5774 OneOps)); 5775 5776 // If the desired elements are smaller or larger than the source 5777 // elements we can use a matching integer vector type and then 5778 // truncate/sign extend 5779 EVT MatchingElementType = 5780 EVT::getIntegerVT(*DAG.getContext(), 5781 N0VT.getScalarType().getSizeInBits()); 5782 EVT MatchingVectorType = 5783 EVT::getVectorVT(*DAG.getContext(), MatchingElementType, 5784 N0VT.getVectorNumElements()); 5785 SDValue VsetCC = 5786 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5787 N0.getOperand(1), 5788 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5789 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5790 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT), 5791 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps)); 5792 } 5793 5794 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5795 SDValue SCC = 5796 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5797 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5798 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5799 if (SCC.getNode()) return SCC; 5800 } 5801 5802 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 5803 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 5804 isa<ConstantSDNode>(N0.getOperand(1)) && 5805 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 5806 N0.hasOneUse()) { 5807 SDValue ShAmt = N0.getOperand(1); 5808 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 5809 if (N0.getOpcode() == ISD::SHL) { 5810 SDValue InnerZExt = N0.getOperand(0); 5811 // If the original shl may be shifting out bits, do not perform this 5812 // transformation. 5813 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() - 5814 InnerZExt.getOperand(0).getValueType().getSizeInBits(); 5815 if (ShAmtVal > KnownZeroBits) 5816 return SDValue(); 5817 } 5818 5819 SDLoc DL(N); 5820 5821 // Ensure that the shift amount is wide enough for the shifted value. 5822 if (VT.getSizeInBits() >= 256) 5823 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 5824 5825 return DAG.getNode(N0.getOpcode(), DL, VT, 5826 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 5827 ShAmt); 5828 } 5829 5830 return SDValue(); 5831 } 5832 5833 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 5834 SDValue N0 = N->getOperand(0); 5835 EVT VT = N->getValueType(0); 5836 5837 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes, 5838 LegalOperations)) 5839 return SDValue(Res, 0); 5840 5841 // fold (aext (aext x)) -> (aext x) 5842 // fold (aext (zext x)) -> (zext x) 5843 // fold (aext (sext x)) -> (sext x) 5844 if (N0.getOpcode() == ISD::ANY_EXTEND || 5845 N0.getOpcode() == ISD::ZERO_EXTEND || 5846 N0.getOpcode() == ISD::SIGN_EXTEND) 5847 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 5848 5849 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 5850 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 5851 if (N0.getOpcode() == ISD::TRUNCATE) { 5852 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode()); 5853 if (NarrowLoad.getNode()) { 5854 SDNode* oye = N0.getNode()->getOperand(0).getNode(); 5855 if (NarrowLoad.getNode() != N0.getNode()) { 5856 CombineTo(N0.getNode(), NarrowLoad); 5857 // CombineTo deleted the truncate, if needed, but not what's under it. 5858 AddToWorklist(oye); 5859 } 5860 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5861 } 5862 } 5863 5864 // fold (aext (truncate x)) 5865 if (N0.getOpcode() == ISD::TRUNCATE) { 5866 SDValue TruncOp = N0.getOperand(0); 5867 if (TruncOp.getValueType() == VT) 5868 return TruncOp; // x iff x size == zext size. 5869 if (TruncOp.getValueType().bitsGT(VT)) 5870 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp); 5871 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp); 5872 } 5873 5874 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 5875 // if the trunc is not free. 5876 if (N0.getOpcode() == ISD::AND && 5877 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 5878 N0.getOperand(1).getOpcode() == ISD::Constant && 5879 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 5880 N0.getValueType())) { 5881 SDValue X = N0.getOperand(0).getOperand(0); 5882 if (X.getValueType().bitsLT(VT)) { 5883 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X); 5884 } else if (X.getValueType().bitsGT(VT)) { 5885 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X); 5886 } 5887 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 5888 Mask = Mask.zext(VT.getSizeInBits()); 5889 return DAG.getNode(ISD::AND, SDLoc(N), VT, 5890 X, DAG.getConstant(Mask, VT)); 5891 } 5892 5893 // fold (aext (load x)) -> (aext (truncate (extload x))) 5894 // None of the supported targets knows how to perform load and any_ext 5895 // on vectors in one instruction. We only perform this transformation on 5896 // scalars. 5897 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 5898 ISD::isUNINDEXEDLoad(N0.getNode()) && 5899 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 5900 bool DoXform = true; 5901 SmallVector<SDNode*, 4> SetCCs; 5902 if (!N0.hasOneUse()) 5903 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 5904 if (DoXform) { 5905 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5906 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 5907 LN0->getChain(), 5908 LN0->getBasePtr(), N0.getValueType(), 5909 LN0->getMemOperand()); 5910 CombineTo(N, ExtLoad); 5911 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5912 N0.getValueType(), ExtLoad); 5913 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1)); 5914 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N), 5915 ISD::ANY_EXTEND); 5916 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5917 } 5918 } 5919 5920 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 5921 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 5922 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 5923 if (N0.getOpcode() == ISD::LOAD && 5924 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5925 N0.hasOneUse()) { 5926 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5927 ISD::LoadExtType ExtType = LN0->getExtensionType(); 5928 EVT MemVT = LN0->getMemoryVT(); 5929 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 5930 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 5931 VT, LN0->getChain(), LN0->getBasePtr(), 5932 MemVT, LN0->getMemOperand()); 5933 CombineTo(N, ExtLoad); 5934 CombineTo(N0.getNode(), 5935 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 5936 N0.getValueType(), ExtLoad), 5937 ExtLoad.getValue(1)); 5938 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5939 } 5940 } 5941 5942 if (N0.getOpcode() == ISD::SETCC) { 5943 // For vectors: 5944 // aext(setcc) -> vsetcc 5945 // aext(setcc) -> truncate(vsetcc) 5946 // aext(setcc) -> aext(vsetcc) 5947 // Only do this before legalize for now. 5948 if (VT.isVector() && !LegalOperations) { 5949 EVT N0VT = N0.getOperand(0).getValueType(); 5950 // We know that the # elements of the results is the same as the 5951 // # elements of the compare (and the # elements of the compare result 5952 // for that matter). Check to see that they are the same size. If so, 5953 // we know that the element size of the sext'd result matches the 5954 // element size of the compare operands. 5955 if (VT.getSizeInBits() == N0VT.getSizeInBits()) 5956 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 5957 N0.getOperand(1), 5958 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5959 // If the desired elements are smaller or larger than the source 5960 // elements we can use a matching integer vector type and then 5961 // truncate/any extend 5962 else { 5963 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger(); 5964 SDValue VsetCC = 5965 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 5966 N0.getOperand(1), 5967 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 5968 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 5969 } 5970 } 5971 5972 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 5973 SDValue SCC = 5974 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1), 5975 DAG.getConstant(1, VT), DAG.getConstant(0, VT), 5976 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true); 5977 if (SCC.getNode()) 5978 return SCC; 5979 } 5980 5981 return SDValue(); 5982 } 5983 5984 /// See if the specified operand can be simplified with the knowledge that only 5985 /// the bits specified by Mask are used. If so, return the simpler operand, 5986 /// otherwise return a null SDValue. 5987 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) { 5988 switch (V.getOpcode()) { 5989 default: break; 5990 case ISD::Constant: { 5991 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode()); 5992 assert(CV && "Const value should be ConstSDNode."); 5993 const APInt &CVal = CV->getAPIntValue(); 5994 APInt NewVal = CVal & Mask; 5995 if (NewVal != CVal) 5996 return DAG.getConstant(NewVal, V.getValueType()); 5997 break; 5998 } 5999 case ISD::OR: 6000 case ISD::XOR: 6001 // If the LHS or RHS don't contribute bits to the or, drop them. 6002 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask)) 6003 return V.getOperand(1); 6004 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask)) 6005 return V.getOperand(0); 6006 break; 6007 case ISD::SRL: 6008 // Only look at single-use SRLs. 6009 if (!V.getNode()->hasOneUse()) 6010 break; 6011 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 6012 // See if we can recursively simplify the LHS. 6013 unsigned Amt = RHSC->getZExtValue(); 6014 6015 // Watch out for shift count overflow though. 6016 if (Amt >= Mask.getBitWidth()) break; 6017 APInt NewMask = Mask << Amt; 6018 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask); 6019 if (SimplifyLHS.getNode()) 6020 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(), 6021 SimplifyLHS, V.getOperand(1)); 6022 } 6023 } 6024 return SDValue(); 6025 } 6026 6027 /// If the result of a wider load is shifted to right of N bits and then 6028 /// truncated to a narrower type and where N is a multiple of number of bits of 6029 /// the narrower type, transform it to a narrower load from address + N / num of 6030 /// bits of new type. If the result is to be extended, also fold the extension 6031 /// to form a extending load. 6032 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 6033 unsigned Opc = N->getOpcode(); 6034 6035 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 6036 SDValue N0 = N->getOperand(0); 6037 EVT VT = N->getValueType(0); 6038 EVT ExtVT = VT; 6039 6040 // This transformation isn't valid for vector loads. 6041 if (VT.isVector()) 6042 return SDValue(); 6043 6044 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 6045 // extended to VT. 6046 if (Opc == ISD::SIGN_EXTEND_INREG) { 6047 ExtType = ISD::SEXTLOAD; 6048 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 6049 } else if (Opc == ISD::SRL) { 6050 // Another special-case: SRL is basically zero-extending a narrower value. 6051 ExtType = ISD::ZEXTLOAD; 6052 N0 = SDValue(N, 0); 6053 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6054 if (!N01) return SDValue(); 6055 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 6056 VT.getSizeInBits() - N01->getZExtValue()); 6057 } 6058 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT)) 6059 return SDValue(); 6060 6061 unsigned EVTBits = ExtVT.getSizeInBits(); 6062 6063 // Do not generate loads of non-round integer types since these can 6064 // be expensive (and would be wrong if the type is not byte sized). 6065 if (!ExtVT.isRound()) 6066 return SDValue(); 6067 6068 unsigned ShAmt = 0; 6069 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 6070 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6071 ShAmt = N01->getZExtValue(); 6072 // Is the shift amount a multiple of size of VT? 6073 if ((ShAmt & (EVTBits-1)) == 0) { 6074 N0 = N0.getOperand(0); 6075 // Is the load width a multiple of size of VT? 6076 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0) 6077 return SDValue(); 6078 } 6079 6080 // At this point, we must have a load or else we can't do the transform. 6081 if (!isa<LoadSDNode>(N0)) return SDValue(); 6082 6083 // Because a SRL must be assumed to *need* to zero-extend the high bits 6084 // (as opposed to anyext the high bits), we can't combine the zextload 6085 // lowering of SRL and an sextload. 6086 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD) 6087 return SDValue(); 6088 6089 // If the shift amount is larger than the input type then we're not 6090 // accessing any of the loaded bytes. If the load was a zextload/extload 6091 // then the result of the shift+trunc is zero/undef (handled elsewhere). 6092 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits()) 6093 return SDValue(); 6094 } 6095 } 6096 6097 // If the load is shifted left (and the result isn't shifted back right), 6098 // we can fold the truncate through the shift. 6099 unsigned ShLeftAmt = 0; 6100 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 6101 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 6102 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 6103 ShLeftAmt = N01->getZExtValue(); 6104 N0 = N0.getOperand(0); 6105 } 6106 } 6107 6108 // If we haven't found a load, we can't narrow it. Don't transform one with 6109 // multiple uses, this would require adding a new load. 6110 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse()) 6111 return SDValue(); 6112 6113 // Don't change the width of a volatile load. 6114 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6115 if (LN0->isVolatile()) 6116 return SDValue(); 6117 6118 // Verify that we are actually reducing a load width here. 6119 if (LN0->getMemoryVT().getSizeInBits() < EVTBits) 6120 return SDValue(); 6121 6122 // For the transform to be legal, the load must produce only two values 6123 // (the value loaded and the chain). Don't transform a pre-increment 6124 // load, for example, which produces an extra value. Otherwise the 6125 // transformation is not equivalent, and the downstream logic to replace 6126 // uses gets things wrong. 6127 if (LN0->getNumValues() > 2) 6128 return SDValue(); 6129 6130 // If the load that we're shrinking is an extload and we're not just 6131 // discarding the extension we can't simply shrink the load. Bail. 6132 // TODO: It would be possible to merge the extensions in some cases. 6133 if (LN0->getExtensionType() != ISD::NON_EXTLOAD && 6134 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt) 6135 return SDValue(); 6136 6137 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT)) 6138 return SDValue(); 6139 6140 EVT PtrType = N0.getOperand(1).getValueType(); 6141 6142 if (PtrType == MVT::Untyped || PtrType.isExtended()) 6143 // It's not possible to generate a constant of extended or untyped type. 6144 return SDValue(); 6145 6146 // For big endian targets, we need to adjust the offset to the pointer to 6147 // load the correct bytes. 6148 if (TLI.isBigEndian()) { 6149 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 6150 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 6151 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt; 6152 } 6153 6154 uint64_t PtrOff = ShAmt / 8; 6155 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 6156 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), 6157 PtrType, LN0->getBasePtr(), 6158 DAG.getConstant(PtrOff, PtrType)); 6159 AddToWorklist(NewPtr.getNode()); 6160 6161 SDValue Load; 6162 if (ExtType == ISD::NON_EXTLOAD) 6163 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 6164 LN0->getPointerInfo().getWithOffset(PtrOff), 6165 LN0->isVolatile(), LN0->isNonTemporal(), 6166 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6167 else 6168 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr, 6169 LN0->getPointerInfo().getWithOffset(PtrOff), 6170 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(), 6171 LN0->isInvariant(), NewAlign, LN0->getAAInfo()); 6172 6173 // Replace the old load's chain with the new load's chain. 6174 WorklistRemover DeadNodes(*this); 6175 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6176 6177 // Shift the result left, if we've swallowed a left shift. 6178 SDValue Result = Load; 6179 if (ShLeftAmt != 0) { 6180 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 6181 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 6182 ShImmTy = VT; 6183 // If the shift amount is as large as the result size (but, presumably, 6184 // no larger than the source) then the useful bits of the result are 6185 // zero; we can't simply return the shortened shift, because the result 6186 // of that operation is undefined. 6187 if (ShLeftAmt >= VT.getSizeInBits()) 6188 Result = DAG.getConstant(0, VT); 6189 else 6190 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT, 6191 Result, DAG.getConstant(ShLeftAmt, ShImmTy)); 6192 } 6193 6194 // Return the new loaded value. 6195 return Result; 6196 } 6197 6198 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 6199 SDValue N0 = N->getOperand(0); 6200 SDValue N1 = N->getOperand(1); 6201 EVT VT = N->getValueType(0); 6202 EVT EVT = cast<VTSDNode>(N1)->getVT(); 6203 unsigned VTBits = VT.getScalarType().getSizeInBits(); 6204 unsigned EVTBits = EVT.getScalarType().getSizeInBits(); 6205 6206 // fold (sext_in_reg c1) -> c1 6207 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF) 6208 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 6209 6210 // If the input is already sign extended, just drop the extension. 6211 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 6212 return N0; 6213 6214 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 6215 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 6216 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 6217 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6218 N0.getOperand(0), N1); 6219 6220 // fold (sext_in_reg (sext x)) -> (sext x) 6221 // fold (sext_in_reg (aext x)) -> (sext x) 6222 // if x is small enough. 6223 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 6224 SDValue N00 = N0.getOperand(0); 6225 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits && 6226 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 6227 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 6228 } 6229 6230 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 6231 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits))) 6232 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT); 6233 6234 // fold operands of sext_in_reg based on knowledge that the top bits are not 6235 // demanded. 6236 if (SimplifyDemandedBits(SDValue(N, 0))) 6237 return SDValue(N, 0); 6238 6239 // fold (sext_in_reg (load x)) -> (smaller sextload x) 6240 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 6241 SDValue NarrowLoad = ReduceLoadWidth(N); 6242 if (NarrowLoad.getNode()) 6243 return NarrowLoad; 6244 6245 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 6246 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 6247 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 6248 if (N0.getOpcode() == ISD::SRL) { 6249 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 6250 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 6251 // We can turn this into an SRA iff the input to the SRL is already sign 6252 // extended enough. 6253 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 6254 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 6255 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 6256 N0.getOperand(0), N0.getOperand(1)); 6257 } 6258 } 6259 6260 // fold (sext_inreg (extload x)) -> (sextload x) 6261 if (ISD::isEXTLoad(N0.getNode()) && 6262 ISD::isUNINDEXEDLoad(N0.getNode()) && 6263 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6264 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6265 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6266 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6267 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6268 LN0->getChain(), 6269 LN0->getBasePtr(), EVT, 6270 LN0->getMemOperand()); 6271 CombineTo(N, ExtLoad); 6272 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6273 AddToWorklist(ExtLoad.getNode()); 6274 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6275 } 6276 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 6277 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 6278 N0.hasOneUse() && 6279 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 6280 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 6281 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 6282 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6283 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 6284 LN0->getChain(), 6285 LN0->getBasePtr(), EVT, 6286 LN0->getMemOperand()); 6287 CombineTo(N, ExtLoad); 6288 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 6289 return SDValue(N, 0); // Return N so it doesn't get rechecked! 6290 } 6291 6292 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 6293 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 6294 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 6295 N0.getOperand(1), false); 6296 if (BSwap.getNode()) 6297 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6298 BSwap, N1); 6299 } 6300 6301 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs 6302 // into a build_vector. 6303 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 6304 SmallVector<SDValue, 8> Elts; 6305 unsigned NumElts = N0->getNumOperands(); 6306 unsigned ShAmt = VTBits - EVTBits; 6307 6308 for (unsigned i = 0; i != NumElts; ++i) { 6309 SDValue Op = N0->getOperand(i); 6310 if (Op->getOpcode() == ISD::UNDEF) { 6311 Elts.push_back(Op); 6312 continue; 6313 } 6314 6315 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op); 6316 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue()); 6317 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(), 6318 Op.getValueType())); 6319 } 6320 6321 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts); 6322 } 6323 6324 return SDValue(); 6325 } 6326 6327 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 6328 SDValue N0 = N->getOperand(0); 6329 EVT VT = N->getValueType(0); 6330 bool isLE = TLI.isLittleEndian(); 6331 6332 // noop truncate 6333 if (N0.getValueType() == N->getValueType(0)) 6334 return N0; 6335 // fold (truncate c1) -> c1 6336 if (isa<ConstantSDNode>(N0)) 6337 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 6338 // fold (truncate (truncate x)) -> (truncate x) 6339 if (N0.getOpcode() == ISD::TRUNCATE) 6340 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6341 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 6342 if (N0.getOpcode() == ISD::ZERO_EXTEND || 6343 N0.getOpcode() == ISD::SIGN_EXTEND || 6344 N0.getOpcode() == ISD::ANY_EXTEND) { 6345 if (N0.getOperand(0).getValueType().bitsLT(VT)) 6346 // if the source is smaller than the dest, we still need an extend 6347 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, 6348 N0.getOperand(0)); 6349 if (N0.getOperand(0).getValueType().bitsGT(VT)) 6350 // if the source is larger than the dest, than we just need the truncate 6351 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 6352 // if the source and dest are the same type, we can drop both the extend 6353 // and the truncate. 6354 return N0.getOperand(0); 6355 } 6356 6357 // Fold extract-and-trunc into a narrow extract. For example: 6358 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 6359 // i32 y = TRUNCATE(i64 x) 6360 // -- becomes -- 6361 // v16i8 b = BITCAST (v2i64 val) 6362 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 6363 // 6364 // Note: We only run this optimization after type legalization (which often 6365 // creates this pattern) and before operation legalization after which 6366 // we need to be more careful about the vector instructions that we generate. 6367 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 6368 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 6369 6370 EVT VecTy = N0.getOperand(0).getValueType(); 6371 EVT ExTy = N0.getValueType(); 6372 EVT TrTy = N->getValueType(0); 6373 6374 unsigned NumElem = VecTy.getVectorNumElements(); 6375 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 6376 6377 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 6378 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 6379 6380 SDValue EltNo = N0->getOperand(1); 6381 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 6382 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 6383 EVT IndexTy = TLI.getVectorIdxTy(); 6384 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 6385 6386 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N), 6387 NVT, N0.getOperand(0)); 6388 6389 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, 6390 SDLoc(N), TrTy, V, 6391 DAG.getConstant(Index, IndexTy)); 6392 } 6393 } 6394 6395 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 6396 if (N0.getOpcode() == ISD::SELECT) { 6397 EVT SrcVT = N0.getValueType(); 6398 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 6399 TLI.isTruncateFree(SrcVT, VT)) { 6400 SDLoc SL(N0); 6401 SDValue Cond = N0.getOperand(0); 6402 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 6403 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 6404 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 6405 } 6406 } 6407 6408 // Fold a series of buildvector, bitcast, and truncate if possible. 6409 // For example fold 6410 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 6411 // (2xi32 (buildvector x, y)). 6412 if (Level == AfterLegalizeVectorOps && VT.isVector() && 6413 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 6414 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 6415 N0.getOperand(0).hasOneUse()) { 6416 6417 SDValue BuildVect = N0.getOperand(0); 6418 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 6419 EVT TruncVecEltTy = VT.getVectorElementType(); 6420 6421 // Check that the element types match. 6422 if (BuildVectEltTy == TruncVecEltTy) { 6423 // Now we only need to compute the offset of the truncated elements. 6424 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 6425 unsigned TruncVecNumElts = VT.getVectorNumElements(); 6426 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 6427 6428 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 6429 "Invalid number of elements"); 6430 6431 SmallVector<SDValue, 8> Opnds; 6432 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 6433 Opnds.push_back(BuildVect.getOperand(i)); 6434 6435 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 6436 } 6437 } 6438 6439 // See if we can simplify the input to this truncate through knowledge that 6440 // only the low bits are being used. 6441 // For example "trunc (or (shl x, 8), y)" // -> trunc y 6442 // Currently we only perform this optimization on scalars because vectors 6443 // may have different active low bits. 6444 if (!VT.isVector()) { 6445 SDValue Shorter = 6446 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(), 6447 VT.getSizeInBits())); 6448 if (Shorter.getNode()) 6449 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 6450 } 6451 // fold (truncate (load x)) -> (smaller load x) 6452 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 6453 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 6454 SDValue Reduced = ReduceLoadWidth(N); 6455 if (Reduced.getNode()) 6456 return Reduced; 6457 // Handle the case where the load remains an extending load even 6458 // after truncation. 6459 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 6460 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6461 if (!LN0->isVolatile() && 6462 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 6463 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 6464 VT, LN0->getChain(), LN0->getBasePtr(), 6465 LN0->getMemoryVT(), 6466 LN0->getMemOperand()); 6467 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 6468 return NewLoad; 6469 } 6470 } 6471 } 6472 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 6473 // where ... are all 'undef'. 6474 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 6475 SmallVector<EVT, 8> VTs; 6476 SDValue V; 6477 unsigned Idx = 0; 6478 unsigned NumDefs = 0; 6479 6480 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 6481 SDValue X = N0.getOperand(i); 6482 if (X.getOpcode() != ISD::UNDEF) { 6483 V = X; 6484 Idx = i; 6485 NumDefs++; 6486 } 6487 // Stop if more than one members are non-undef. 6488 if (NumDefs > 1) 6489 break; 6490 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 6491 VT.getVectorElementType(), 6492 X.getValueType().getVectorNumElements())); 6493 } 6494 6495 if (NumDefs == 0) 6496 return DAG.getUNDEF(VT); 6497 6498 if (NumDefs == 1) { 6499 assert(V.getNode() && "The single defined operand is empty!"); 6500 SmallVector<SDValue, 8> Opnds; 6501 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 6502 if (i != Idx) { 6503 Opnds.push_back(DAG.getUNDEF(VTs[i])); 6504 continue; 6505 } 6506 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 6507 AddToWorklist(NV.getNode()); 6508 Opnds.push_back(NV); 6509 } 6510 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 6511 } 6512 } 6513 6514 // Simplify the operands using demanded-bits information. 6515 if (!VT.isVector() && 6516 SimplifyDemandedBits(SDValue(N, 0))) 6517 return SDValue(N, 0); 6518 6519 return SDValue(); 6520 } 6521 6522 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 6523 SDValue Elt = N->getOperand(i); 6524 if (Elt.getOpcode() != ISD::MERGE_VALUES) 6525 return Elt.getNode(); 6526 return Elt.getOperand(Elt.getResNo()).getNode(); 6527 } 6528 6529 /// build_pair (load, load) -> load 6530 /// if load locations are consecutive. 6531 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 6532 assert(N->getOpcode() == ISD::BUILD_PAIR); 6533 6534 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 6535 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 6536 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 6537 LD1->getAddressSpace() != LD2->getAddressSpace()) 6538 return SDValue(); 6539 EVT LD1VT = LD1->getValueType(0); 6540 6541 if (ISD::isNON_EXTLoad(LD2) && 6542 LD2->hasOneUse() && 6543 // If both are volatile this would reduce the number of volatile loads. 6544 // If one is volatile it might be ok, but play conservative and bail out. 6545 !LD1->isVolatile() && 6546 !LD2->isVolatile() && 6547 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) { 6548 unsigned Align = LD1->getAlignment(); 6549 unsigned NewAlign = TLI.getDataLayout()-> 6550 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6551 6552 if (NewAlign <= Align && 6553 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 6554 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), 6555 LD1->getBasePtr(), LD1->getPointerInfo(), 6556 false, false, false, Align); 6557 } 6558 6559 return SDValue(); 6560 } 6561 6562 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 6563 SDValue N0 = N->getOperand(0); 6564 EVT VT = N->getValueType(0); 6565 6566 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 6567 // Only do this before legalize, since afterward the target may be depending 6568 // on the bitconvert. 6569 // First check to see if this is all constant. 6570 if (!LegalTypes && 6571 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 6572 VT.isVector()) { 6573 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant(); 6574 6575 EVT DestEltVT = N->getValueType(0).getVectorElementType(); 6576 assert(!DestEltVT.isVector() && 6577 "Element type of vector ValueType must not be vector!"); 6578 if (isSimple) 6579 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT); 6580 } 6581 6582 // If the input is a constant, let getNode fold it. 6583 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 6584 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0); 6585 if (Res.getNode() != N) { 6586 if (!LegalOperations || 6587 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT)) 6588 return Res; 6589 6590 // Folding it resulted in an illegal node, and it's too late to 6591 // do that. Clean up the old node and forego the transformation. 6592 // Ideally this won't happen very often, because instcombine 6593 // and the earlier dagcombine runs (where illegal nodes are 6594 // permitted) should have folded most of them already. 6595 deleteAndRecombine(Res.getNode()); 6596 } 6597 } 6598 6599 // (conv (conv x, t1), t2) -> (conv x, t2) 6600 if (N0.getOpcode() == ISD::BITCAST) 6601 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, 6602 N0.getOperand(0)); 6603 6604 // fold (conv (load x)) -> (load (conv*)x) 6605 // If the resultant load doesn't need a higher alignment than the original! 6606 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 6607 // Do not change the width of a volatile load. 6608 !cast<LoadSDNode>(N0)->isVolatile() && 6609 // Do not remove the cast if the types differ in endian layout. 6610 TLI.hasBigEndianPartOrdering(N0.getValueType()) == 6611 TLI.hasBigEndianPartOrdering(VT) && 6612 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 6613 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 6614 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 6615 unsigned Align = TLI.getDataLayout()-> 6616 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 6617 unsigned OrigAlign = LN0->getAlignment(); 6618 6619 if (Align <= OrigAlign) { 6620 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), 6621 LN0->getBasePtr(), LN0->getPointerInfo(), 6622 LN0->isVolatile(), LN0->isNonTemporal(), 6623 LN0->isInvariant(), OrigAlign, 6624 LN0->getAAInfo()); 6625 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 6626 return Load; 6627 } 6628 } 6629 6630 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 6631 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 6632 // This often reduces constant pool loads. 6633 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 6634 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 6635 N0.getNode()->hasOneUse() && VT.isInteger() && 6636 !VT.isVector() && !N0.getValueType().isVector()) { 6637 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT, 6638 N0.getOperand(0)); 6639 AddToWorklist(NewConv.getNode()); 6640 6641 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6642 if (N0.getOpcode() == ISD::FNEG) 6643 return DAG.getNode(ISD::XOR, SDLoc(N), VT, 6644 NewConv, DAG.getConstant(SignBit, VT)); 6645 assert(N0.getOpcode() == ISD::FABS); 6646 return DAG.getNode(ISD::AND, SDLoc(N), VT, 6647 NewConv, DAG.getConstant(~SignBit, VT)); 6648 } 6649 6650 // fold (bitconvert (fcopysign cst, x)) -> 6651 // (or (and (bitconvert x), sign), (and cst, (not sign))) 6652 // Note that we don't handle (copysign x, cst) because this can always be 6653 // folded to an fneg or fabs. 6654 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 6655 isa<ConstantFPSDNode>(N0.getOperand(0)) && 6656 VT.isInteger() && !VT.isVector()) { 6657 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits(); 6658 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 6659 if (isTypeLegal(IntXVT)) { 6660 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6661 IntXVT, N0.getOperand(1)); 6662 AddToWorklist(X.getNode()); 6663 6664 // If X has a different width than the result/lhs, sext it or truncate it. 6665 unsigned VTWidth = VT.getSizeInBits(); 6666 if (OrigXWidth < VTWidth) { 6667 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 6668 AddToWorklist(X.getNode()); 6669 } else if (OrigXWidth > VTWidth) { 6670 // To get the sign bit in the right place, we have to shift it right 6671 // before truncating. 6672 X = DAG.getNode(ISD::SRL, SDLoc(X), 6673 X.getValueType(), X, 6674 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType())); 6675 AddToWorklist(X.getNode()); 6676 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 6677 AddToWorklist(X.getNode()); 6678 } 6679 6680 APInt SignBit = APInt::getSignBit(VT.getSizeInBits()); 6681 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 6682 X, DAG.getConstant(SignBit, VT)); 6683 AddToWorklist(X.getNode()); 6684 6685 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0), 6686 VT, N0.getOperand(0)); 6687 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 6688 Cst, DAG.getConstant(~SignBit, VT)); 6689 AddToWorklist(Cst.getNode()); 6690 6691 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 6692 } 6693 } 6694 6695 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 6696 if (N0.getOpcode() == ISD::BUILD_PAIR) { 6697 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT); 6698 if (CombineLD.getNode()) 6699 return CombineLD; 6700 } 6701 6702 return SDValue(); 6703 } 6704 6705 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 6706 EVT VT = N->getValueType(0); 6707 return CombineConsecutiveLoads(N, VT); 6708 } 6709 6710 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 6711 /// operands. DstEltVT indicates the destination element value type. 6712 SDValue DAGCombiner:: 6713 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 6714 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 6715 6716 // If this is already the right type, we're done. 6717 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 6718 6719 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 6720 unsigned DstBitSize = DstEltVT.getSizeInBits(); 6721 6722 // If this is a conversion of N elements of one type to N elements of another 6723 // type, convert each element. This handles FP<->INT cases. 6724 if (SrcBitSize == DstBitSize) { 6725 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6726 BV->getValueType(0).getVectorNumElements()); 6727 6728 // Due to the FP element handling below calling this routine recursively, 6729 // we can end up with a scalar-to-vector node here. 6730 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR) 6731 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6732 DAG.getNode(ISD::BITCAST, SDLoc(BV), 6733 DstEltVT, BV->getOperand(0))); 6734 6735 SmallVector<SDValue, 8> Ops; 6736 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6737 SDValue Op = BV->getOperand(i); 6738 // If the vector element type is not legal, the BUILD_VECTOR operands 6739 // are promoted and implicitly truncated. Make that explicit here. 6740 if (Op.getValueType() != SrcEltVT) 6741 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 6742 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV), 6743 DstEltVT, Op)); 6744 AddToWorklist(Ops.back().getNode()); 6745 } 6746 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6747 } 6748 6749 // Otherwise, we're growing or shrinking the elements. To avoid having to 6750 // handle annoying details of growing/shrinking FP values, we convert them to 6751 // int first. 6752 if (SrcEltVT.isFloatingPoint()) { 6753 // Convert the input float vector to a int vector where the elements are the 6754 // same sizes. 6755 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 6756 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 6757 SrcEltVT = IntVT; 6758 } 6759 6760 // Now we know the input is an integer vector. If the output is a FP type, 6761 // convert to integer first, then to FP of the right size. 6762 if (DstEltVT.isFloatingPoint()) { 6763 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 6764 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 6765 6766 // Next, convert to FP elements of the same size. 6767 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 6768 } 6769 6770 // Okay, we know the src/dst types are both integers of differing types. 6771 // Handling growing first. 6772 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 6773 if (SrcBitSize < DstBitSize) { 6774 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 6775 6776 SmallVector<SDValue, 8> Ops; 6777 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 6778 i += NumInputsPerOutput) { 6779 bool isLE = TLI.isLittleEndian(); 6780 APInt NewBits = APInt(DstBitSize, 0); 6781 bool EltIsUndef = true; 6782 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 6783 // Shift the previously computed bits over. 6784 NewBits <<= SrcBitSize; 6785 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 6786 if (Op.getOpcode() == ISD::UNDEF) continue; 6787 EltIsUndef = false; 6788 6789 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 6790 zextOrTrunc(SrcBitSize).zext(DstBitSize); 6791 } 6792 6793 if (EltIsUndef) 6794 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6795 else 6796 Ops.push_back(DAG.getConstant(NewBits, DstEltVT)); 6797 } 6798 6799 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 6800 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6801 } 6802 6803 // Finally, this must be the case where we are shrinking elements: each input 6804 // turns into multiple outputs. 6805 bool isS2V = ISD::isScalarToVector(BV); 6806 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 6807 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 6808 NumOutputsPerInput*BV->getNumOperands()); 6809 SmallVector<SDValue, 8> Ops; 6810 6811 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 6812 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) { 6813 for (unsigned j = 0; j != NumOutputsPerInput; ++j) 6814 Ops.push_back(DAG.getUNDEF(DstEltVT)); 6815 continue; 6816 } 6817 6818 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))-> 6819 getAPIntValue().zextOrTrunc(SrcBitSize); 6820 6821 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 6822 APInt ThisVal = OpVal.trunc(DstBitSize); 6823 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT)); 6824 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal) 6825 // Simply turn this into a SCALAR_TO_VECTOR of the new type. 6826 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT, 6827 Ops[0]); 6828 OpVal = OpVal.lshr(DstBitSize); 6829 } 6830 6831 // For big endian targets, swap the order of the pieces of each element. 6832 if (TLI.isBigEndian()) 6833 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 6834 } 6835 6836 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops); 6837 } 6838 6839 SDValue DAGCombiner::visitFADD(SDNode *N) { 6840 SDValue N0 = N->getOperand(0); 6841 SDValue N1 = N->getOperand(1); 6842 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 6843 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6844 EVT VT = N->getValueType(0); 6845 const TargetOptions &Options = DAG.getTarget().Options; 6846 6847 // fold vector ops 6848 if (VT.isVector()) { 6849 SDValue FoldedVOp = SimplifyVBinOp(N); 6850 if (FoldedVOp.getNode()) return FoldedVOp; 6851 } 6852 6853 // fold (fadd c1, c2) -> c1 + c2 6854 if (N0CFP && N1CFP) 6855 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1); 6856 6857 // canonicalize constant to RHS 6858 if (N0CFP && !N1CFP) 6859 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0); 6860 6861 // fold (fadd A, (fneg B)) -> (fsub A, B) 6862 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6863 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2) 6864 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, 6865 GetNegatedExpression(N1, DAG, LegalOperations)); 6866 6867 // fold (fadd (fneg A), B) -> (fsub B, A) 6868 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 6869 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2) 6870 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1, 6871 GetNegatedExpression(N0, DAG, LegalOperations)); 6872 6873 // If 'unsafe math' is enabled, fold lots of things. 6874 if (Options.UnsafeFPMath) { 6875 // No FP constant should be created after legalization as Instruction 6876 // Selection pass has a hard time dealing with FP constants. 6877 bool AllowNewConst = (Level < AfterLegalizeDAG); 6878 6879 // fold (fadd A, 0) -> A 6880 if (N1CFP && N1CFP->getValueAPF().isZero()) 6881 return N0; 6882 6883 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2)) 6884 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() && 6885 isa<ConstantFPSDNode>(N0.getOperand(1))) 6886 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0), 6887 DAG.getNode(ISD::FADD, SDLoc(N), VT, 6888 N0.getOperand(1), N1)); 6889 6890 // If allowed, fold (fadd (fneg x), x) -> 0.0 6891 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 6892 return DAG.getConstantFP(0.0, VT); 6893 6894 // If allowed, fold (fadd x, (fneg x)) -> 0.0 6895 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 6896 return DAG.getConstantFP(0.0, VT); 6897 6898 // We can fold chains of FADD's of the same value into multiplications. 6899 // This transform is not safe in general because we are reducing the number 6900 // of rounding steps. 6901 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 6902 if (N0.getOpcode() == ISD::FMUL) { 6903 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6904 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 6905 6906 // (fadd (fmul x, c), x) -> (fmul x, c+1) 6907 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 6908 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6909 SDValue(CFP01, 0), 6910 DAG.getConstantFP(1.0, VT)); 6911 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP); 6912 } 6913 6914 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 6915 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 6916 N1.getOperand(0) == N1.getOperand(1) && 6917 N0.getOperand(0) == N1.getOperand(0)) { 6918 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6919 SDValue(CFP01, 0), 6920 DAG.getConstantFP(2.0, VT)); 6921 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6922 N0.getOperand(0), NewCFP); 6923 } 6924 } 6925 6926 if (N1.getOpcode() == ISD::FMUL) { 6927 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6928 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1)); 6929 6930 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 6931 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 6932 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6933 SDValue(CFP11, 0), 6934 DAG.getConstantFP(1.0, VT)); 6935 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP); 6936 } 6937 6938 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 6939 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 6940 N0.getOperand(0) == N0.getOperand(1) && 6941 N1.getOperand(0) == N0.getOperand(0)) { 6942 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT, 6943 SDValue(CFP11, 0), 6944 DAG.getConstantFP(2.0, VT)); 6945 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP); 6946 } 6947 } 6948 6949 if (N0.getOpcode() == ISD::FADD && AllowNewConst) { 6950 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0)); 6951 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 6952 if (!CFP && N0.getOperand(0) == N0.getOperand(1) && 6953 (N0.getOperand(0) == N1)) 6954 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6955 N1, DAG.getConstantFP(3.0, VT)); 6956 } 6957 6958 if (N1.getOpcode() == ISD::FADD && AllowNewConst) { 6959 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0)); 6960 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 6961 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 6962 N1.getOperand(0) == N0) 6963 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6964 N0, DAG.getConstantFP(3.0, VT)); 6965 } 6966 6967 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 6968 if (AllowNewConst && 6969 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 6970 N0.getOperand(0) == N0.getOperand(1) && 6971 N1.getOperand(0) == N1.getOperand(1) && 6972 N0.getOperand(0) == N1.getOperand(0)) 6973 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 6974 N0.getOperand(0), DAG.getConstantFP(4.0, VT)); 6975 } 6976 } // enable-unsafe-fp-math 6977 6978 // FADD -> FMA combines: 6979 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 6980 TLI.isFMAFasterThanFMulAndFAdd(VT) && 6981 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 6982 6983 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 6984 if (N0.getOpcode() == ISD::FMUL && 6985 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT))) 6986 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6987 N0.getOperand(0), N0.getOperand(1), N1); 6988 6989 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 6990 // Note: Commutes FADD operands. 6991 if (N1.getOpcode() == ISD::FMUL && 6992 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT))) 6993 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 6994 N1.getOperand(0), N1.getOperand(1), N0); 6995 6996 // When FP_EXTEND nodes are free on the target, and there is an opportunity 6997 // to combine into FMA, arrange such nodes accordingly. 6998 if (TLI.isFPExtFree(VT)) { 6999 7000 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 7001 if (N0.getOpcode() == ISD::FP_EXTEND) { 7002 SDValue N00 = N0.getOperand(0); 7003 if (N00.getOpcode() == ISD::FMUL) 7004 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7005 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7006 N00.getOperand(0)), 7007 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7008 N00.getOperand(1)), N1); 7009 } 7010 7011 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x) 7012 // Note: Commutes FADD operands. 7013 if (N1.getOpcode() == ISD::FP_EXTEND) { 7014 SDValue N10 = N1.getOperand(0); 7015 if (N10.getOpcode() == ISD::FMUL) 7016 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7017 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7018 N10.getOperand(0)), 7019 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7020 N10.getOperand(1)), N0); 7021 } 7022 } 7023 7024 // More folding opportunities when target permits. 7025 if (TLI.enableAggressiveFMAFusion(VT)) { 7026 7027 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 7028 if (N0.getOpcode() == ISD::FMA && 7029 N0.getOperand(2).getOpcode() == ISD::FMUL) 7030 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7031 N0.getOperand(0), N0.getOperand(1), 7032 DAG.getNode(ISD::FMA, SDLoc(N), VT, 7033 N0.getOperand(2).getOperand(0), 7034 N0.getOperand(2).getOperand(1), 7035 N1)); 7036 7037 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 7038 if (N1->getOpcode() == ISD::FMA && 7039 N1.getOperand(2).getOpcode() == ISD::FMUL) 7040 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7041 N1.getOperand(0), N1.getOperand(1), 7042 DAG.getNode(ISD::FMA, SDLoc(N), VT, 7043 N1.getOperand(2).getOperand(0), 7044 N1.getOperand(2).getOperand(1), 7045 N0)); 7046 } 7047 } 7048 7049 return SDValue(); 7050 } 7051 7052 SDValue DAGCombiner::visitFSUB(SDNode *N) { 7053 SDValue N0 = N->getOperand(0); 7054 SDValue N1 = N->getOperand(1); 7055 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7056 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7057 EVT VT = N->getValueType(0); 7058 SDLoc dl(N); 7059 const TargetOptions &Options = DAG.getTarget().Options; 7060 7061 // fold vector ops 7062 if (VT.isVector()) { 7063 SDValue FoldedVOp = SimplifyVBinOp(N); 7064 if (FoldedVOp.getNode()) return FoldedVOp; 7065 } 7066 7067 // fold (fsub c1, c2) -> c1-c2 7068 if (N0CFP && N1CFP) 7069 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1); 7070 7071 // fold (fsub A, (fneg B)) -> (fadd A, B) 7072 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7073 return DAG.getNode(ISD::FADD, dl, VT, N0, 7074 GetNegatedExpression(N1, DAG, LegalOperations)); 7075 7076 // If 'unsafe math' is enabled, fold lots of things. 7077 if (Options.UnsafeFPMath) { 7078 // (fsub A, 0) -> A 7079 if (N1CFP && N1CFP->getValueAPF().isZero()) 7080 return N0; 7081 7082 // (fsub 0, B) -> -B 7083 if (N0CFP && N0CFP->getValueAPF().isZero()) { 7084 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options)) 7085 return GetNegatedExpression(N1, DAG, LegalOperations); 7086 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7087 return DAG.getNode(ISD::FNEG, dl, VT, N1); 7088 } 7089 7090 // (fsub x, x) -> 0.0 7091 if (N0 == N1) 7092 return DAG.getConstantFP(0.0f, VT); 7093 7094 // (fsub x, (fadd x, y)) -> (fneg y) 7095 // (fsub x, (fadd y, x)) -> (fneg y) 7096 if (N1.getOpcode() == ISD::FADD) { 7097 SDValue N10 = N1->getOperand(0); 7098 SDValue N11 = N1->getOperand(1); 7099 7100 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options)) 7101 return GetNegatedExpression(N11, DAG, LegalOperations); 7102 7103 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options)) 7104 return GetNegatedExpression(N10, DAG, LegalOperations); 7105 } 7106 } 7107 7108 // FSUB -> FMA combines: 7109 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 7110 TLI.isFMAFasterThanFMulAndFAdd(VT) && 7111 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) { 7112 7113 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 7114 if (N0.getOpcode() == ISD::FMUL && 7115 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT))) 7116 return DAG.getNode(ISD::FMA, dl, VT, 7117 N0.getOperand(0), N0.getOperand(1), 7118 DAG.getNode(ISD::FNEG, dl, VT, N1)); 7119 7120 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 7121 // Note: Commutes FSUB operands. 7122 if (N1.getOpcode() == ISD::FMUL && 7123 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT))) 7124 return DAG.getNode(ISD::FMA, dl, VT, 7125 DAG.getNode(ISD::FNEG, dl, VT, 7126 N1.getOperand(0)), 7127 N1.getOperand(1), N0); 7128 7129 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 7130 if (N0.getOpcode() == ISD::FNEG && 7131 N0.getOperand(0).getOpcode() == ISD::FMUL && 7132 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) || 7133 TLI.enableAggressiveFMAFusion(VT))) { 7134 SDValue N00 = N0.getOperand(0).getOperand(0); 7135 SDValue N01 = N0.getOperand(0).getOperand(1); 7136 return DAG.getNode(ISD::FMA, dl, VT, 7137 DAG.getNode(ISD::FNEG, dl, VT, N00), N01, 7138 DAG.getNode(ISD::FNEG, dl, VT, N1)); 7139 } 7140 7141 // When FP_EXTEND nodes are free on the target, and there is an opportunity 7142 // to combine into FMA, arrange such nodes accordingly. 7143 if (TLI.isFPExtFree(VT)) { 7144 7145 // fold (fsub (fpext (fmul x, y)), z) 7146 // -> (fma (fpext x), (fpext y), (fneg z)) 7147 if (N0.getOpcode() == ISD::FP_EXTEND) { 7148 SDValue N00 = N0.getOperand(0); 7149 if (N00.getOpcode() == ISD::FMUL) 7150 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7151 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7152 N00.getOperand(0)), 7153 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7154 N00.getOperand(1)), 7155 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1)); 7156 } 7157 7158 // fold (fsub x, (fpext (fmul y, z))) 7159 // -> (fma (fneg (fpext y)), (fpext z), x) 7160 // Note: Commutes FSUB operands. 7161 if (N1.getOpcode() == ISD::FP_EXTEND) { 7162 SDValue N10 = N1.getOperand(0); 7163 if (N10.getOpcode() == ISD::FMUL) 7164 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7165 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7166 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), 7167 VT, N10.getOperand(0))), 7168 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7169 N10.getOperand(1)), 7170 N0); 7171 } 7172 7173 // fold (fsub (fpext (fneg (fmul, x, y))), z) 7174 // -> (fma (fneg (fpext x)), (fpext y), (fneg z)) 7175 if (N0.getOpcode() == ISD::FP_EXTEND) { 7176 SDValue N00 = N0.getOperand(0); 7177 if (N00.getOpcode() == ISD::FNEG) { 7178 SDValue N000 = N00.getOperand(0); 7179 if (N000.getOpcode() == ISD::FMUL) { 7180 return DAG.getNode(ISD::FMA, dl, VT, 7181 DAG.getNode(ISD::FNEG, dl, VT, 7182 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), 7183 VT, N000.getOperand(0))), 7184 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7185 N000.getOperand(1)), 7186 DAG.getNode(ISD::FNEG, dl, VT, N1)); 7187 } 7188 } 7189 } 7190 7191 // fold (fsub (fneg (fpext (fmul, x, y))), z) 7192 // -> (fma (fneg (fpext x)), (fpext y), (fneg z)) 7193 if (N0.getOpcode() == ISD::FNEG) { 7194 SDValue N00 = N0.getOperand(0); 7195 if (N00.getOpcode() == ISD::FP_EXTEND) { 7196 SDValue N000 = N00.getOperand(0); 7197 if (N000.getOpcode() == ISD::FMUL) { 7198 return DAG.getNode(ISD::FMA, dl, VT, 7199 DAG.getNode(ISD::FNEG, dl, VT, 7200 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), 7201 VT, N000.getOperand(0))), 7202 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, 7203 N000.getOperand(1)), 7204 DAG.getNode(ISD::FNEG, dl, VT, N1)); 7205 } 7206 } 7207 } 7208 } 7209 7210 // More folding opportunities when target permits. 7211 if (TLI.enableAggressiveFMAFusion(VT)) { 7212 7213 // fold (fsub (fma x, y, (fmul u, v)), z) 7214 // -> (fma x, y (fma u, v, (fneg z))) 7215 if (N0.getOpcode() == ISD::FMA && 7216 N0.getOperand(2).getOpcode() == ISD::FMUL) 7217 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7218 N0.getOperand(0), N0.getOperand(1), 7219 DAG.getNode(ISD::FMA, SDLoc(N), VT, 7220 N0.getOperand(2).getOperand(0), 7221 N0.getOperand(2).getOperand(1), 7222 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7223 N1))); 7224 7225 // fold (fsub x, (fma y, z, (fmul u, v))) 7226 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 7227 if (N1.getOpcode() == ISD::FMA && 7228 N1.getOperand(2).getOpcode() == ISD::FMUL) { 7229 SDValue N20 = N1.getOperand(2).getOperand(0); 7230 SDValue N21 = N1.getOperand(2).getOperand(1); 7231 return DAG.getNode(ISD::FMA, SDLoc(N), VT, 7232 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7233 N1.getOperand(0)), 7234 N1.getOperand(1), 7235 DAG.getNode(ISD::FMA, SDLoc(N), VT, 7236 DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7237 N20), 7238 N21, N0)); 7239 } 7240 } 7241 } 7242 7243 return SDValue(); 7244 } 7245 7246 SDValue DAGCombiner::visitFMUL(SDNode *N) { 7247 SDValue N0 = N->getOperand(0); 7248 SDValue N1 = N->getOperand(1); 7249 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 7250 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 7251 EVT VT = N->getValueType(0); 7252 const TargetOptions &Options = DAG.getTarget().Options; 7253 7254 // fold vector ops 7255 if (VT.isVector()) { 7256 // This just handles C1 * C2 for vectors. Other vector folds are below. 7257 SDValue FoldedVOp = SimplifyVBinOp(N); 7258 if (FoldedVOp.getNode()) 7259 return FoldedVOp; 7260 // Canonicalize vector constant to RHS. 7261 if (N0.getOpcode() == ISD::BUILD_VECTOR && 7262 N1.getOpcode() != ISD::BUILD_VECTOR) 7263 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0)) 7264 if (BV0->isConstant()) 7265 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 7266 } 7267 7268 // fold (fmul c1, c2) -> c1*c2 7269 if (N0CFP && N1CFP) 7270 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1); 7271 7272 // canonicalize constant to RHS 7273 if (N0CFP && !N1CFP) 7274 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0); 7275 7276 // fold (fmul A, 1.0) -> A 7277 if (N1CFP && N1CFP->isExactlyValue(1.0)) 7278 return N0; 7279 7280 if (Options.UnsafeFPMath) { 7281 // fold (fmul A, 0) -> 0 7282 if (N1CFP && N1CFP->getValueAPF().isZero()) 7283 return N1; 7284 7285 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2)) 7286 if (N0.getOpcode() == ISD::FMUL) { 7287 // Fold scalars or any vector constants (not just splats). 7288 // This fold is done in general by InstCombine, but extra fmul insts 7289 // may have been generated during lowering. 7290 SDValue N01 = N0.getOperand(1); 7291 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 7292 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01); 7293 if ((N1CFP && isConstOrConstSplatFP(N01)) || 7294 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) { 7295 SDLoc SL(N); 7296 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1); 7297 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts); 7298 } 7299 } 7300 7301 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c)) 7302 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs 7303 // during an early run of DAGCombiner can prevent folding with fmuls 7304 // inserted during lowering. 7305 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) { 7306 SDLoc SL(N); 7307 const SDValue Two = DAG.getConstantFP(2.0, VT); 7308 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1); 7309 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts); 7310 } 7311 } 7312 7313 // fold (fmul X, 2.0) -> (fadd X, X) 7314 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 7315 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0); 7316 7317 // fold (fmul X, -1.0) -> (fneg X) 7318 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 7319 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7320 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 7321 7322 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 7323 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 7324 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 7325 // Both can be negated for free, check to see if at least one is cheaper 7326 // negated. 7327 if (LHSNeg == 2 || RHSNeg == 2) 7328 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, 7329 GetNegatedExpression(N0, DAG, LegalOperations), 7330 GetNegatedExpression(N1, DAG, LegalOperations)); 7331 } 7332 } 7333 7334 return SDValue(); 7335 } 7336 7337 SDValue DAGCombiner::visitFMA(SDNode *N) { 7338 SDValue N0 = N->getOperand(0); 7339 SDValue N1 = N->getOperand(1); 7340 SDValue N2 = N->getOperand(2); 7341 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7342 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7343 EVT VT = N->getValueType(0); 7344 SDLoc dl(N); 7345 const TargetOptions &Options = DAG.getTarget().Options; 7346 7347 // Constant fold FMA. 7348 if (isa<ConstantFPSDNode>(N0) && 7349 isa<ConstantFPSDNode>(N1) && 7350 isa<ConstantFPSDNode>(N2)) { 7351 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2); 7352 } 7353 7354 if (Options.UnsafeFPMath) { 7355 if (N0CFP && N0CFP->isZero()) 7356 return N2; 7357 if (N1CFP && N1CFP->isZero()) 7358 return N2; 7359 } 7360 if (N0CFP && N0CFP->isExactlyValue(1.0)) 7361 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 7362 if (N1CFP && N1CFP->isExactlyValue(1.0)) 7363 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 7364 7365 // Canonicalize (fma c, x, y) -> (fma x, c, y) 7366 if (N0CFP && !N1CFP) 7367 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 7368 7369 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 7370 if (Options.UnsafeFPMath && N1CFP && 7371 N2.getOpcode() == ISD::FMUL && 7372 N0 == N2.getOperand(0) && 7373 N2.getOperand(1).getOpcode() == ISD::ConstantFP) { 7374 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7375 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1))); 7376 } 7377 7378 7379 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 7380 if (Options.UnsafeFPMath && 7381 N0.getOpcode() == ISD::FMUL && N1CFP && 7382 N0.getOperand(1).getOpcode() == ISD::ConstantFP) { 7383 return DAG.getNode(ISD::FMA, dl, VT, 7384 N0.getOperand(0), 7385 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)), 7386 N2); 7387 } 7388 7389 // (fma x, 1, y) -> (fadd x, y) 7390 // (fma x, -1, y) -> (fadd (fneg x), y) 7391 if (N1CFP) { 7392 if (N1CFP->isExactlyValue(1.0)) 7393 return DAG.getNode(ISD::FADD, dl, VT, N0, N2); 7394 7395 if (N1CFP->isExactlyValue(-1.0) && 7396 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 7397 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0); 7398 AddToWorklist(RHSNeg.getNode()); 7399 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg); 7400 } 7401 } 7402 7403 // (fma x, c, x) -> (fmul x, (c+1)) 7404 if (Options.UnsafeFPMath && N1CFP && N0 == N2) 7405 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7406 DAG.getNode(ISD::FADD, dl, VT, 7407 N1, DAG.getConstantFP(1.0, VT))); 7408 7409 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 7410 if (Options.UnsafeFPMath && N1CFP && 7411 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) 7412 return DAG.getNode(ISD::FMUL, dl, VT, N0, 7413 DAG.getNode(ISD::FADD, dl, VT, 7414 N1, DAG.getConstantFP(-1.0, VT))); 7415 7416 7417 return SDValue(); 7418 } 7419 7420 SDValue DAGCombiner::visitFDIV(SDNode *N) { 7421 SDValue N0 = N->getOperand(0); 7422 SDValue N1 = N->getOperand(1); 7423 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7424 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7425 EVT VT = N->getValueType(0); 7426 SDLoc DL(N); 7427 const TargetOptions &Options = DAG.getTarget().Options; 7428 7429 // fold vector ops 7430 if (VT.isVector()) { 7431 SDValue FoldedVOp = SimplifyVBinOp(N); 7432 if (FoldedVOp.getNode()) return FoldedVOp; 7433 } 7434 7435 // fold (fdiv c1, c2) -> c1/c2 7436 if (N0CFP && N1CFP) 7437 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 7438 7439 if (Options.UnsafeFPMath) { 7440 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 7441 if (N1CFP) { 7442 // Compute the reciprocal 1.0 / c2. 7443 APFloat N1APF = N1CFP->getValueAPF(); 7444 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 7445 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 7446 // Only do the transform if the reciprocal is a legal fp immediate that 7447 // isn't too nasty (eg NaN, denormal, ...). 7448 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 7449 (!LegalOperations || 7450 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 7451 // backend)... we should handle this gracefully after Legalize. 7452 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) || 7453 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) || 7454 TLI.isFPImmLegal(Recip, VT))) 7455 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, 7456 DAG.getConstantFP(Recip, VT)); 7457 } 7458 7459 // If this FDIV is part of a reciprocal square root, it may be folded 7460 // into a target-specific square root estimate instruction. 7461 if (N1.getOpcode() == ISD::FSQRT) { 7462 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) { 7463 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7464 } 7465 } else if (N1.getOpcode() == ISD::FP_EXTEND && 7466 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7467 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 7468 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 7469 AddToWorklist(RV.getNode()); 7470 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7471 } 7472 } else if (N1.getOpcode() == ISD::FP_ROUND && 7473 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7474 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) { 7475 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 7476 AddToWorklist(RV.getNode()); 7477 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7478 } 7479 } else if (N1.getOpcode() == ISD::FMUL) { 7480 // Look through an FMUL. Even though this won't remove the FDIV directly, 7481 // it's still worthwhile to get rid of the FSQRT if possible. 7482 SDValue SqrtOp; 7483 SDValue OtherOp; 7484 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 7485 SqrtOp = N1.getOperand(0); 7486 OtherOp = N1.getOperand(1); 7487 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 7488 SqrtOp = N1.getOperand(1); 7489 OtherOp = N1.getOperand(0); 7490 } 7491 if (SqrtOp.getNode()) { 7492 // We found a FSQRT, so try to make this fold: 7493 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 7494 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) { 7495 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp); 7496 AddToWorklist(RV.getNode()); 7497 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7498 } 7499 } 7500 } 7501 7502 // Fold into a reciprocal estimate and multiply instead of a real divide. 7503 if (SDValue RV = BuildReciprocalEstimate(N1)) { 7504 AddToWorklist(RV.getNode()); 7505 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 7506 } 7507 } 7508 7509 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 7510 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) { 7511 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) { 7512 // Both can be negated for free, check to see if at least one is cheaper 7513 // negated. 7514 if (LHSNeg == 2 || RHSNeg == 2) 7515 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 7516 GetNegatedExpression(N0, DAG, LegalOperations), 7517 GetNegatedExpression(N1, DAG, LegalOperations)); 7518 } 7519 } 7520 7521 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 7522 // reciprocal. 7523 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 7524 // Notice that this is not always beneficial. One reason is different target 7525 // may have different costs for FDIV and FMUL, so sometimes the cost of two 7526 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 7527 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 7528 if (Options.UnsafeFPMath) { 7529 // Skip if current node is a reciprocal. 7530 if (N0CFP && N0CFP->isExactlyValue(1.0)) 7531 return SDValue(); 7532 7533 SmallVector<SDNode *, 4> Users; 7534 // Find all FDIV users of the same divisor. 7535 for (SDNode::use_iterator UI = N1.getNode()->use_begin(), 7536 UE = N1.getNode()->use_end(); 7537 UI != UE; ++UI) { 7538 SDNode *User = UI.getUse().getUser(); 7539 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1) 7540 Users.push_back(User); 7541 } 7542 7543 if (TLI.combineRepeatedFPDivisors(Users.size())) { 7544 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0 7545 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1); 7546 7547 // Dividend / Divisor -> Dividend * Reciprocal 7548 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) { 7549 if ((*I)->getOperand(0) != FPOne) { 7550 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT, 7551 (*I)->getOperand(0), Reciprocal); 7552 DAG.ReplaceAllUsesWith(*I, NewNode.getNode()); 7553 } 7554 } 7555 return SDValue(); 7556 } 7557 } 7558 7559 return SDValue(); 7560 } 7561 7562 SDValue DAGCombiner::visitFREM(SDNode *N) { 7563 SDValue N0 = N->getOperand(0); 7564 SDValue N1 = N->getOperand(1); 7565 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7566 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7567 EVT VT = N->getValueType(0); 7568 7569 // fold (frem c1, c2) -> fmod(c1,c2) 7570 if (N0CFP && N1CFP) 7571 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 7572 7573 return SDValue(); 7574 } 7575 7576 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 7577 if (DAG.getTarget().Options.UnsafeFPMath && 7578 !TLI.isFsqrtCheap()) { 7579 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5) 7580 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) { 7581 EVT VT = RV.getValueType(); 7582 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV); 7583 AddToWorklist(RV.getNode()); 7584 7585 // Unfortunately, RV is now NaN if the input was exactly 0. 7586 // Select out this case and force the answer to 0. 7587 SDValue Zero = DAG.getConstantFP(0.0, VT); 7588 SDValue ZeroCmp = 7589 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT), 7590 N->getOperand(0), Zero, ISD::SETEQ); 7591 AddToWorklist(ZeroCmp.getNode()); 7592 AddToWorklist(RV.getNode()); 7593 7594 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, 7595 SDLoc(N), VT, ZeroCmp, Zero, RV); 7596 return RV; 7597 } 7598 } 7599 return SDValue(); 7600 } 7601 7602 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 7603 SDValue N0 = N->getOperand(0); 7604 SDValue N1 = N->getOperand(1); 7605 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7606 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7607 EVT VT = N->getValueType(0); 7608 7609 if (N0CFP && N1CFP) // Constant fold 7610 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 7611 7612 if (N1CFP) { 7613 const APFloat& V = N1CFP->getValueAPF(); 7614 // copysign(x, c1) -> fabs(x) iff ispos(c1) 7615 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 7616 if (!V.isNegative()) { 7617 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 7618 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7619 } else { 7620 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 7621 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 7622 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 7623 } 7624 } 7625 7626 // copysign(fabs(x), y) -> copysign(x, y) 7627 // copysign(fneg(x), y) -> copysign(x, y) 7628 // copysign(copysign(x,z), y) -> copysign(x, y) 7629 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 7630 N0.getOpcode() == ISD::FCOPYSIGN) 7631 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7632 N0.getOperand(0), N1); 7633 7634 // copysign(x, abs(y)) -> abs(x) 7635 if (N1.getOpcode() == ISD::FABS) 7636 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 7637 7638 // copysign(x, copysign(y,z)) -> copysign(x, z) 7639 if (N1.getOpcode() == ISD::FCOPYSIGN) 7640 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7641 N0, N1.getOperand(1)); 7642 7643 // copysign(x, fp_extend(y)) -> copysign(x, y) 7644 // copysign(x, fp_round(y)) -> copysign(x, y) 7645 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND) 7646 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7647 N0, N1.getOperand(0)); 7648 7649 return SDValue(); 7650 } 7651 7652 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 7653 SDValue N0 = N->getOperand(0); 7654 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 7655 EVT VT = N->getValueType(0); 7656 EVT OpVT = N0.getValueType(); 7657 7658 // fold (sint_to_fp c1) -> c1fp 7659 if (N0C && 7660 // ...but only if the target supports immediate floating-point values 7661 (!LegalOperations || 7662 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 7663 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 7664 7665 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 7666 // but UINT_TO_FP is legal on this target, try to convert. 7667 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) && 7668 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) { 7669 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 7670 if (DAG.SignBitIsZero(N0)) 7671 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 7672 } 7673 7674 // The next optimizations are desirable only if SELECT_CC can be lowered. 7675 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 7676 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 7677 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 7678 !VT.isVector() && 7679 (!LegalOperations || 7680 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7681 SDValue Ops[] = 7682 { N0.getOperand(0), N0.getOperand(1), 7683 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT), 7684 N0.getOperand(2) }; 7685 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7686 } 7687 7688 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 7689 // (select_cc x, y, 1.0, 0.0,, cc) 7690 if (N0.getOpcode() == ISD::ZERO_EXTEND && 7691 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 7692 (!LegalOperations || 7693 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7694 SDValue Ops[] = 7695 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 7696 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT), 7697 N0.getOperand(0).getOperand(2) }; 7698 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7699 } 7700 } 7701 7702 return SDValue(); 7703 } 7704 7705 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 7706 SDValue N0 = N->getOperand(0); 7707 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 7708 EVT VT = N->getValueType(0); 7709 EVT OpVT = N0.getValueType(); 7710 7711 // fold (uint_to_fp c1) -> c1fp 7712 if (N0C && 7713 // ...but only if the target supports immediate floating-point values 7714 (!LegalOperations || 7715 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) 7716 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 7717 7718 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 7719 // but SINT_TO_FP is legal on this target, try to convert. 7720 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) && 7721 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) { 7722 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 7723 if (DAG.SignBitIsZero(N0)) 7724 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 7725 } 7726 7727 // The next optimizations are desirable only if SELECT_CC can be lowered. 7728 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 7729 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 7730 7731 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 7732 (!LegalOperations || 7733 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) { 7734 SDValue Ops[] = 7735 { N0.getOperand(0), N0.getOperand(1), 7736 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT), 7737 N0.getOperand(2) }; 7738 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops); 7739 } 7740 } 7741 7742 return SDValue(); 7743 } 7744 7745 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 7746 SDValue N0 = N->getOperand(0); 7747 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7748 EVT VT = N->getValueType(0); 7749 7750 // fold (fp_to_sint c1fp) -> c1 7751 if (N0CFP) 7752 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 7753 7754 return SDValue(); 7755 } 7756 7757 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 7758 SDValue N0 = N->getOperand(0); 7759 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7760 EVT VT = N->getValueType(0); 7761 7762 // fold (fp_to_uint c1fp) -> c1 7763 if (N0CFP) 7764 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 7765 7766 return SDValue(); 7767 } 7768 7769 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 7770 SDValue N0 = N->getOperand(0); 7771 SDValue N1 = N->getOperand(1); 7772 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7773 EVT VT = N->getValueType(0); 7774 7775 // fold (fp_round c1fp) -> c1fp 7776 if (N0CFP) 7777 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 7778 7779 // fold (fp_round (fp_extend x)) -> x 7780 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 7781 return N0.getOperand(0); 7782 7783 // fold (fp_round (fp_round x)) -> (fp_round x) 7784 if (N0.getOpcode() == ISD::FP_ROUND) { 7785 // This is a value preserving truncation if both round's are. 7786 bool IsTrunc = N->getConstantOperandVal(1) == 1 && 7787 N0.getNode()->getConstantOperandVal(1) == 1; 7788 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0), 7789 DAG.getIntPtrConstant(IsTrunc)); 7790 } 7791 7792 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 7793 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 7794 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 7795 N0.getOperand(0), N1); 7796 AddToWorklist(Tmp.getNode()); 7797 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 7798 Tmp, N0.getOperand(1)); 7799 } 7800 7801 return SDValue(); 7802 } 7803 7804 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 7805 SDValue N0 = N->getOperand(0); 7806 EVT VT = N->getValueType(0); 7807 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 7808 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7809 7810 // fold (fp_round_inreg c1fp) -> c1fp 7811 if (N0CFP && isTypeLegal(EVT)) { 7812 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT); 7813 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round); 7814 } 7815 7816 return SDValue(); 7817 } 7818 7819 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 7820 SDValue N0 = N->getOperand(0); 7821 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7822 EVT VT = N->getValueType(0); 7823 7824 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 7825 if (N->hasOneUse() && 7826 N->use_begin()->getOpcode() == ISD::FP_ROUND) 7827 return SDValue(); 7828 7829 // fold (fp_extend c1fp) -> c1fp 7830 if (N0CFP) 7831 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 7832 7833 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 7834 // value of X. 7835 if (N0.getOpcode() == ISD::FP_ROUND 7836 && N0.getNode()->getConstantOperandVal(1) == 1) { 7837 SDValue In = N0.getOperand(0); 7838 if (In.getValueType() == VT) return In; 7839 if (VT.bitsLT(In.getValueType())) 7840 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 7841 In, N0.getOperand(1)); 7842 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 7843 } 7844 7845 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 7846 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7847 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 7848 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7849 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 7850 LN0->getChain(), 7851 LN0->getBasePtr(), N0.getValueType(), 7852 LN0->getMemOperand()); 7853 CombineTo(N, ExtLoad); 7854 CombineTo(N0.getNode(), 7855 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 7856 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)), 7857 ExtLoad.getValue(1)); 7858 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7859 } 7860 7861 return SDValue(); 7862 } 7863 7864 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 7865 SDValue N0 = N->getOperand(0); 7866 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7867 EVT VT = N->getValueType(0); 7868 7869 // fold (fceil c1) -> fceil(c1) 7870 if (N0CFP) 7871 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 7872 7873 return SDValue(); 7874 } 7875 7876 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 7877 SDValue N0 = N->getOperand(0); 7878 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7879 EVT VT = N->getValueType(0); 7880 7881 // fold (ftrunc c1) -> ftrunc(c1) 7882 if (N0CFP) 7883 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 7884 7885 return SDValue(); 7886 } 7887 7888 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 7889 SDValue N0 = N->getOperand(0); 7890 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7891 EVT VT = N->getValueType(0); 7892 7893 // fold (ffloor c1) -> ffloor(c1) 7894 if (N0CFP) 7895 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 7896 7897 return SDValue(); 7898 } 7899 7900 // FIXME: FNEG and FABS have a lot in common; refactor. 7901 SDValue DAGCombiner::visitFNEG(SDNode *N) { 7902 SDValue N0 = N->getOperand(0); 7903 EVT VT = N->getValueType(0); 7904 7905 if (VT.isVector()) { 7906 SDValue FoldedVOp = SimplifyVUnaryOp(N); 7907 if (FoldedVOp.getNode()) return FoldedVOp; 7908 } 7909 7910 // Constant fold FNEG. 7911 if (isa<ConstantFPSDNode>(N0)) 7912 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0)); 7913 7914 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 7915 &DAG.getTarget().Options)) 7916 return GetNegatedExpression(N0, DAG, LegalOperations); 7917 7918 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 7919 // constant pool values. 7920 if (!TLI.isFNegFree(VT) && 7921 N0.getOpcode() == ISD::BITCAST && 7922 N0.getNode()->hasOneUse()) { 7923 SDValue Int = N0.getOperand(0); 7924 EVT IntVT = Int.getValueType(); 7925 if (IntVT.isInteger() && !IntVT.isVector()) { 7926 APInt SignMask; 7927 if (N0.getValueType().isVector()) { 7928 // For a vector, get a mask such as 0x80... per scalar element 7929 // and splat it. 7930 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 7931 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 7932 } else { 7933 // For a scalar, just generate 0x80... 7934 SignMask = APInt::getSignBit(IntVT.getSizeInBits()); 7935 } 7936 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int, 7937 DAG.getConstant(SignMask, IntVT)); 7938 AddToWorklist(Int.getNode()); 7939 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int); 7940 } 7941 } 7942 7943 // (fneg (fmul c, x)) -> (fmul -c, x) 7944 if (N0.getOpcode() == ISD::FMUL) { 7945 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 7946 if (CFP1) { 7947 APFloat CVal = CFP1->getValueAPF(); 7948 CVal.changeSign(); 7949 if (Level >= AfterLegalizeDAG && 7950 (TLI.isFPImmLegal(CVal, N->getValueType(0)) || 7951 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0)))) 7952 return DAG.getNode( 7953 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 7954 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1))); 7955 } 7956 } 7957 7958 return SDValue(); 7959 } 7960 7961 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 7962 SDValue N0 = N->getOperand(0); 7963 SDValue N1 = N->getOperand(1); 7964 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7965 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7966 7967 if (N0CFP && N1CFP) { 7968 const APFloat &C0 = N0CFP->getValueAPF(); 7969 const APFloat &C1 = N1CFP->getValueAPF(); 7970 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0)); 7971 } 7972 7973 if (N0CFP) { 7974 EVT VT = N->getValueType(0); 7975 // Canonicalize to constant on RHS. 7976 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0); 7977 } 7978 7979 return SDValue(); 7980 } 7981 7982 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 7983 SDValue N0 = N->getOperand(0); 7984 SDValue N1 = N->getOperand(1); 7985 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 7986 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 7987 7988 if (N0CFP && N1CFP) { 7989 const APFloat &C0 = N0CFP->getValueAPF(); 7990 const APFloat &C1 = N1CFP->getValueAPF(); 7991 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0)); 7992 } 7993 7994 if (N0CFP) { 7995 EVT VT = N->getValueType(0); 7996 // Canonicalize to constant on RHS. 7997 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0); 7998 } 7999 8000 return SDValue(); 8001 } 8002 8003 SDValue DAGCombiner::visitFABS(SDNode *N) { 8004 SDValue N0 = N->getOperand(0); 8005 EVT VT = N->getValueType(0); 8006 8007 if (VT.isVector()) { 8008 SDValue FoldedVOp = SimplifyVUnaryOp(N); 8009 if (FoldedVOp.getNode()) return FoldedVOp; 8010 } 8011 8012 // fold (fabs c1) -> fabs(c1) 8013 if (isa<ConstantFPSDNode>(N0)) 8014 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 8015 8016 // fold (fabs (fabs x)) -> (fabs x) 8017 if (N0.getOpcode() == ISD::FABS) 8018 return N->getOperand(0); 8019 8020 // fold (fabs (fneg x)) -> (fabs x) 8021 // fold (fabs (fcopysign x, y)) -> (fabs x) 8022 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 8023 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 8024 8025 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading 8026 // constant pool values. 8027 if (!TLI.isFAbsFree(VT) && 8028 N0.getOpcode() == ISD::BITCAST && 8029 N0.getNode()->hasOneUse()) { 8030 SDValue Int = N0.getOperand(0); 8031 EVT IntVT = Int.getValueType(); 8032 if (IntVT.isInteger() && !IntVT.isVector()) { 8033 APInt SignMask; 8034 if (N0.getValueType().isVector()) { 8035 // For a vector, get a mask such as 0x7f... per scalar element 8036 // and splat it. 8037 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits()); 8038 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 8039 } else { 8040 // For a scalar, just generate 0x7f... 8041 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits()); 8042 } 8043 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int, 8044 DAG.getConstant(SignMask, IntVT)); 8045 AddToWorklist(Int.getNode()); 8046 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int); 8047 } 8048 } 8049 8050 return SDValue(); 8051 } 8052 8053 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 8054 SDValue Chain = N->getOperand(0); 8055 SDValue N1 = N->getOperand(1); 8056 SDValue N2 = N->getOperand(2); 8057 8058 // If N is a constant we could fold this into a fallthrough or unconditional 8059 // branch. However that doesn't happen very often in normal code, because 8060 // Instcombine/SimplifyCFG should have handled the available opportunities. 8061 // If we did this folding here, it would be necessary to update the 8062 // MachineBasicBlock CFG, which is awkward. 8063 8064 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 8065 // on the target. 8066 if (N1.getOpcode() == ISD::SETCC && 8067 TLI.isOperationLegalOrCustom(ISD::BR_CC, 8068 N1.getOperand(0).getValueType())) { 8069 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8070 Chain, N1.getOperand(2), 8071 N1.getOperand(0), N1.getOperand(1), N2); 8072 } 8073 8074 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) || 8075 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) && 8076 (N1.getOperand(0).hasOneUse() && 8077 N1.getOperand(0).getOpcode() == ISD::SRL))) { 8078 SDNode *Trunc = nullptr; 8079 if (N1.getOpcode() == ISD::TRUNCATE) { 8080 // Look pass the truncate. 8081 Trunc = N1.getNode(); 8082 N1 = N1.getOperand(0); 8083 } 8084 8085 // Match this pattern so that we can generate simpler code: 8086 // 8087 // %a = ... 8088 // %b = and i32 %a, 2 8089 // %c = srl i32 %b, 1 8090 // brcond i32 %c ... 8091 // 8092 // into 8093 // 8094 // %a = ... 8095 // %b = and i32 %a, 2 8096 // %c = setcc eq %b, 0 8097 // brcond %c ... 8098 // 8099 // This applies only when the AND constant value has one bit set and the 8100 // SRL constant is equal to the log2 of the AND constant. The back-end is 8101 // smart enough to convert the result into a TEST/JMP sequence. 8102 SDValue Op0 = N1.getOperand(0); 8103 SDValue Op1 = N1.getOperand(1); 8104 8105 if (Op0.getOpcode() == ISD::AND && 8106 Op1.getOpcode() == ISD::Constant) { 8107 SDValue AndOp1 = Op0.getOperand(1); 8108 8109 if (AndOp1.getOpcode() == ISD::Constant) { 8110 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 8111 8112 if (AndConst.isPowerOf2() && 8113 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) { 8114 SDValue SetCC = 8115 DAG.getSetCC(SDLoc(N), 8116 getSetCCResultType(Op0.getValueType()), 8117 Op0, DAG.getConstant(0, Op0.getValueType()), 8118 ISD::SETNE); 8119 8120 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N), 8121 MVT::Other, Chain, SetCC, N2); 8122 // Don't add the new BRCond into the worklist or else SimplifySelectCC 8123 // will convert it back to (X & C1) >> C2. 8124 CombineTo(N, NewBRCond, false); 8125 // Truncate is dead. 8126 if (Trunc) 8127 deleteAndRecombine(Trunc); 8128 // Replace the uses of SRL with SETCC 8129 WorklistRemover DeadNodes(*this); 8130 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8131 deleteAndRecombine(N1.getNode()); 8132 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8133 } 8134 } 8135 } 8136 8137 if (Trunc) 8138 // Restore N1 if the above transformation doesn't match. 8139 N1 = N->getOperand(1); 8140 } 8141 8142 // Transform br(xor(x, y)) -> br(x != y) 8143 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 8144 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) { 8145 SDNode *TheXor = N1.getNode(); 8146 SDValue Op0 = TheXor->getOperand(0); 8147 SDValue Op1 = TheXor->getOperand(1); 8148 if (Op0.getOpcode() == Op1.getOpcode()) { 8149 // Avoid missing important xor optimizations. 8150 SDValue Tmp = visitXOR(TheXor); 8151 if (Tmp.getNode()) { 8152 if (Tmp.getNode() != TheXor) { 8153 DEBUG(dbgs() << "\nReplacing.8 "; 8154 TheXor->dump(&DAG); 8155 dbgs() << "\nWith: "; 8156 Tmp.getNode()->dump(&DAG); 8157 dbgs() << '\n'); 8158 WorklistRemover DeadNodes(*this); 8159 DAG.ReplaceAllUsesOfValueWith(N1, Tmp); 8160 deleteAndRecombine(TheXor); 8161 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8162 MVT::Other, Chain, Tmp, N2); 8163 } 8164 8165 // visitXOR has changed XOR's operands or replaced the XOR completely, 8166 // bail out. 8167 return SDValue(N, 0); 8168 } 8169 } 8170 8171 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 8172 bool Equal = false; 8173 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0)) 8174 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() && 8175 Op0.getOpcode() == ISD::XOR) { 8176 TheXor = Op0.getNode(); 8177 Equal = true; 8178 } 8179 8180 EVT SetCCVT = N1.getValueType(); 8181 if (LegalTypes) 8182 SetCCVT = getSetCCResultType(SetCCVT); 8183 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor), 8184 SetCCVT, 8185 Op0, Op1, 8186 Equal ? ISD::SETEQ : ISD::SETNE); 8187 // Replace the uses of XOR with SETCC 8188 WorklistRemover DeadNodes(*this); 8189 DAG.ReplaceAllUsesOfValueWith(N1, SetCC); 8190 deleteAndRecombine(N1.getNode()); 8191 return DAG.getNode(ISD::BRCOND, SDLoc(N), 8192 MVT::Other, Chain, SetCC, N2); 8193 } 8194 } 8195 8196 return SDValue(); 8197 } 8198 8199 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 8200 // 8201 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 8202 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 8203 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 8204 8205 // If N is a constant we could fold this into a fallthrough or unconditional 8206 // branch. However that doesn't happen very often in normal code, because 8207 // Instcombine/SimplifyCFG should have handled the available opportunities. 8208 // If we did this folding here, it would be necessary to update the 8209 // MachineBasicBlock CFG, which is awkward. 8210 8211 // Use SimplifySetCC to simplify SETCC's. 8212 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 8213 CondLHS, CondRHS, CC->get(), SDLoc(N), 8214 false); 8215 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 8216 8217 // fold to a simpler setcc 8218 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 8219 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 8220 N->getOperand(0), Simp.getOperand(2), 8221 Simp.getOperand(0), Simp.getOperand(1), 8222 N->getOperand(4)); 8223 8224 return SDValue(); 8225 } 8226 8227 /// Return true if 'Use' is a load or a store that uses N as its base pointer 8228 /// and that N may be folded in the load / store addressing mode. 8229 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 8230 SelectionDAG &DAG, 8231 const TargetLowering &TLI) { 8232 EVT VT; 8233 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 8234 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 8235 return false; 8236 VT = Use->getValueType(0); 8237 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 8238 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 8239 return false; 8240 VT = ST->getValue().getValueType(); 8241 } else 8242 return false; 8243 8244 TargetLowering::AddrMode AM; 8245 if (N->getOpcode() == ISD::ADD) { 8246 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8247 if (Offset) 8248 // [reg +/- imm] 8249 AM.BaseOffs = Offset->getSExtValue(); 8250 else 8251 // [reg +/- reg] 8252 AM.Scale = 1; 8253 } else if (N->getOpcode() == ISD::SUB) { 8254 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8255 if (Offset) 8256 // [reg +/- imm] 8257 AM.BaseOffs = -Offset->getSExtValue(); 8258 else 8259 // [reg +/- reg] 8260 AM.Scale = 1; 8261 } else 8262 return false; 8263 8264 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext())); 8265 } 8266 8267 /// Try turning a load/store into a pre-indexed load/store when the base 8268 /// pointer is an add or subtract and it has other uses besides the load/store. 8269 /// After the transformation, the new indexed load/store has effectively folded 8270 /// the add/subtract in and all of its other uses are redirected to the 8271 /// new load/store. 8272 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 8273 if (Level < AfterLegalizeDAG) 8274 return false; 8275 8276 bool isLoad = true; 8277 SDValue Ptr; 8278 EVT VT; 8279 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8280 if (LD->isIndexed()) 8281 return false; 8282 VT = LD->getMemoryVT(); 8283 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 8284 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 8285 return false; 8286 Ptr = LD->getBasePtr(); 8287 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 8288 if (ST->isIndexed()) 8289 return false; 8290 VT = ST->getMemoryVT(); 8291 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 8292 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 8293 return false; 8294 Ptr = ST->getBasePtr(); 8295 isLoad = false; 8296 } else { 8297 return false; 8298 } 8299 8300 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 8301 // out. There is no reason to make this a preinc/predec. 8302 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 8303 Ptr.getNode()->hasOneUse()) 8304 return false; 8305 8306 // Ask the target to do addressing mode selection. 8307 SDValue BasePtr; 8308 SDValue Offset; 8309 ISD::MemIndexedMode AM = ISD::UNINDEXED; 8310 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 8311 return false; 8312 8313 // Backends without true r+i pre-indexed forms may need to pass a 8314 // constant base with a variable offset so that constant coercion 8315 // will work with the patterns in canonical form. 8316 bool Swapped = false; 8317 if (isa<ConstantSDNode>(BasePtr)) { 8318 std::swap(BasePtr, Offset); 8319 Swapped = true; 8320 } 8321 8322 // Don't create a indexed load / store with zero offset. 8323 if (isa<ConstantSDNode>(Offset) && 8324 cast<ConstantSDNode>(Offset)->isNullValue()) 8325 return false; 8326 8327 // Try turning it into a pre-indexed load / store except when: 8328 // 1) The new base ptr is a frame index. 8329 // 2) If N is a store and the new base ptr is either the same as or is a 8330 // predecessor of the value being stored. 8331 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 8332 // that would create a cycle. 8333 // 4) All uses are load / store ops that use it as old base ptr. 8334 8335 // Check #1. Preinc'ing a frame index would require copying the stack pointer 8336 // (plus the implicit offset) to a register to preinc anyway. 8337 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 8338 return false; 8339 8340 // Check #2. 8341 if (!isLoad) { 8342 SDValue Val = cast<StoreSDNode>(N)->getValue(); 8343 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode())) 8344 return false; 8345 } 8346 8347 // If the offset is a constant, there may be other adds of constants that 8348 // can be folded with this one. We should do this to avoid having to keep 8349 // a copy of the original base pointer. 8350 SmallVector<SDNode *, 16> OtherUses; 8351 if (isa<ConstantSDNode>(Offset)) 8352 for (SDNode *Use : BasePtr.getNode()->uses()) { 8353 if (Use == Ptr.getNode()) 8354 continue; 8355 8356 if (Use->isPredecessorOf(N)) 8357 continue; 8358 8359 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) { 8360 OtherUses.clear(); 8361 break; 8362 } 8363 8364 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1); 8365 if (Op1.getNode() == BasePtr.getNode()) 8366 std::swap(Op0, Op1); 8367 assert(Op0.getNode() == BasePtr.getNode() && 8368 "Use of ADD/SUB but not an operand"); 8369 8370 if (!isa<ConstantSDNode>(Op1)) { 8371 OtherUses.clear(); 8372 break; 8373 } 8374 8375 // FIXME: In some cases, we can be smarter about this. 8376 if (Op1.getValueType() != Offset.getValueType()) { 8377 OtherUses.clear(); 8378 break; 8379 } 8380 8381 OtherUses.push_back(Use); 8382 } 8383 8384 if (Swapped) 8385 std::swap(BasePtr, Offset); 8386 8387 // Now check for #3 and #4. 8388 bool RealUse = false; 8389 8390 // Caches for hasPredecessorHelper 8391 SmallPtrSet<const SDNode *, 32> Visited; 8392 SmallVector<const SDNode *, 16> Worklist; 8393 8394 for (SDNode *Use : Ptr.getNode()->uses()) { 8395 if (Use == N) 8396 continue; 8397 if (N->hasPredecessorHelper(Use, Visited, Worklist)) 8398 return false; 8399 8400 // If Ptr may be folded in addressing mode of other use, then it's 8401 // not profitable to do this transformation. 8402 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 8403 RealUse = true; 8404 } 8405 8406 if (!RealUse) 8407 return false; 8408 8409 SDValue Result; 8410 if (isLoad) 8411 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 8412 BasePtr, Offset, AM); 8413 else 8414 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 8415 BasePtr, Offset, AM); 8416 ++PreIndexedNodes; 8417 ++NodesCombined; 8418 DEBUG(dbgs() << "\nReplacing.4 "; 8419 N->dump(&DAG); 8420 dbgs() << "\nWith: "; 8421 Result.getNode()->dump(&DAG); 8422 dbgs() << '\n'); 8423 WorklistRemover DeadNodes(*this); 8424 if (isLoad) { 8425 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 8426 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 8427 } else { 8428 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 8429 } 8430 8431 // Finally, since the node is now dead, remove it from the graph. 8432 deleteAndRecombine(N); 8433 8434 if (Swapped) 8435 std::swap(BasePtr, Offset); 8436 8437 // Replace other uses of BasePtr that can be updated to use Ptr 8438 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 8439 unsigned OffsetIdx = 1; 8440 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 8441 OffsetIdx = 0; 8442 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 8443 BasePtr.getNode() && "Expected BasePtr operand"); 8444 8445 // We need to replace ptr0 in the following expression: 8446 // x0 * offset0 + y0 * ptr0 = t0 8447 // knowing that 8448 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 8449 // 8450 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 8451 // indexed load/store and the expresion that needs to be re-written. 8452 // 8453 // Therefore, we have: 8454 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 8455 8456 ConstantSDNode *CN = 8457 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 8458 int X0, X1, Y0, Y1; 8459 APInt Offset0 = CN->getAPIntValue(); 8460 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 8461 8462 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 8463 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 8464 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 8465 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 8466 8467 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 8468 8469 APInt CNV = Offset0; 8470 if (X0 < 0) CNV = -CNV; 8471 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 8472 else CNV = CNV - Offset1; 8473 8474 // We can now generate the new expression. 8475 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0)); 8476 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 8477 8478 SDValue NewUse = DAG.getNode(Opcode, 8479 SDLoc(OtherUses[i]), 8480 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 8481 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 8482 deleteAndRecombine(OtherUses[i]); 8483 } 8484 8485 // Replace the uses of Ptr with uses of the updated base value. 8486 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 8487 deleteAndRecombine(Ptr.getNode()); 8488 8489 return true; 8490 } 8491 8492 /// Try to combine a load/store with a add/sub of the base pointer node into a 8493 /// post-indexed load/store. The transformation folded the add/subtract into the 8494 /// new indexed load/store effectively and all of its uses are redirected to the 8495 /// new load/store. 8496 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 8497 if (Level < AfterLegalizeDAG) 8498 return false; 8499 8500 bool isLoad = true; 8501 SDValue Ptr; 8502 EVT VT; 8503 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 8504 if (LD->isIndexed()) 8505 return false; 8506 VT = LD->getMemoryVT(); 8507 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 8508 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 8509 return false; 8510 Ptr = LD->getBasePtr(); 8511 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 8512 if (ST->isIndexed()) 8513 return false; 8514 VT = ST->getMemoryVT(); 8515 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 8516 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 8517 return false; 8518 Ptr = ST->getBasePtr(); 8519 isLoad = false; 8520 } else { 8521 return false; 8522 } 8523 8524 if (Ptr.getNode()->hasOneUse()) 8525 return false; 8526 8527 for (SDNode *Op : Ptr.getNode()->uses()) { 8528 if (Op == N || 8529 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 8530 continue; 8531 8532 SDValue BasePtr; 8533 SDValue Offset; 8534 ISD::MemIndexedMode AM = ISD::UNINDEXED; 8535 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 8536 // Don't create a indexed load / store with zero offset. 8537 if (isa<ConstantSDNode>(Offset) && 8538 cast<ConstantSDNode>(Offset)->isNullValue()) 8539 continue; 8540 8541 // Try turning it into a post-indexed load / store except when 8542 // 1) All uses are load / store ops that use it as base ptr (and 8543 // it may be folded as addressing mmode). 8544 // 2) Op must be independent of N, i.e. Op is neither a predecessor 8545 // nor a successor of N. Otherwise, if Op is folded that would 8546 // create a cycle. 8547 8548 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 8549 continue; 8550 8551 // Check for #1. 8552 bool TryNext = false; 8553 for (SDNode *Use : BasePtr.getNode()->uses()) { 8554 if (Use == Ptr.getNode()) 8555 continue; 8556 8557 // If all the uses are load / store addresses, then don't do the 8558 // transformation. 8559 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 8560 bool RealUse = false; 8561 for (SDNode *UseUse : Use->uses()) { 8562 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 8563 RealUse = true; 8564 } 8565 8566 if (!RealUse) { 8567 TryNext = true; 8568 break; 8569 } 8570 } 8571 } 8572 8573 if (TryNext) 8574 continue; 8575 8576 // Check for #2 8577 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) { 8578 SDValue Result = isLoad 8579 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 8580 BasePtr, Offset, AM) 8581 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 8582 BasePtr, Offset, AM); 8583 ++PostIndexedNodes; 8584 ++NodesCombined; 8585 DEBUG(dbgs() << "\nReplacing.5 "; 8586 N->dump(&DAG); 8587 dbgs() << "\nWith: "; 8588 Result.getNode()->dump(&DAG); 8589 dbgs() << '\n'); 8590 WorklistRemover DeadNodes(*this); 8591 if (isLoad) { 8592 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 8593 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 8594 } else { 8595 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 8596 } 8597 8598 // Finally, since the node is now dead, remove it from the graph. 8599 deleteAndRecombine(N); 8600 8601 // Replace the uses of Use with uses of the updated base value. 8602 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 8603 Result.getValue(isLoad ? 1 : 0)); 8604 deleteAndRecombine(Op); 8605 return true; 8606 } 8607 } 8608 } 8609 8610 return false; 8611 } 8612 8613 /// \brief Return the base-pointer arithmetic from an indexed \p LD. 8614 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 8615 ISD::MemIndexedMode AM = LD->getAddressingMode(); 8616 assert(AM != ISD::UNINDEXED); 8617 SDValue BP = LD->getOperand(1); 8618 SDValue Inc = LD->getOperand(2); 8619 8620 // Some backends use TargetConstants for load offsets, but don't expect 8621 // TargetConstants in general ADD nodes. We can convert these constants into 8622 // regular Constants (if the constant is not opaque). 8623 assert((Inc.getOpcode() != ISD::TargetConstant || 8624 !cast<ConstantSDNode>(Inc)->isOpaque()) && 8625 "Cannot split out indexing using opaque target constants"); 8626 if (Inc.getOpcode() == ISD::TargetConstant) { 8627 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 8628 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), 8629 ConstInc->getValueType(0)); 8630 } 8631 8632 unsigned Opc = 8633 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 8634 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 8635 } 8636 8637 SDValue DAGCombiner::visitLOAD(SDNode *N) { 8638 LoadSDNode *LD = cast<LoadSDNode>(N); 8639 SDValue Chain = LD->getChain(); 8640 SDValue Ptr = LD->getBasePtr(); 8641 8642 // If load is not volatile and there are no uses of the loaded value (and 8643 // the updated indexed value in case of indexed loads), change uses of the 8644 // chain value into uses of the chain input (i.e. delete the dead load). 8645 if (!LD->isVolatile()) { 8646 if (N->getValueType(1) == MVT::Other) { 8647 // Unindexed loads. 8648 if (!N->hasAnyUseOfValue(0)) { 8649 // It's not safe to use the two value CombineTo variant here. e.g. 8650 // v1, chain2 = load chain1, loc 8651 // v2, chain3 = load chain2, loc 8652 // v3 = add v2, c 8653 // Now we replace use of chain2 with chain1. This makes the second load 8654 // isomorphic to the one we are deleting, and thus makes this load live. 8655 DEBUG(dbgs() << "\nReplacing.6 "; 8656 N->dump(&DAG); 8657 dbgs() << "\nWith chain: "; 8658 Chain.getNode()->dump(&DAG); 8659 dbgs() << "\n"); 8660 WorklistRemover DeadNodes(*this); 8661 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 8662 8663 if (N->use_empty()) 8664 deleteAndRecombine(N); 8665 8666 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8667 } 8668 } else { 8669 // Indexed loads. 8670 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 8671 8672 // If this load has an opaque TargetConstant offset, then we cannot split 8673 // the indexing into an add/sub directly (that TargetConstant may not be 8674 // valid for a different type of node, and we cannot convert an opaque 8675 // target constant into a regular constant). 8676 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 8677 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 8678 8679 if (!N->hasAnyUseOfValue(0) && 8680 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 8681 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 8682 SDValue Index; 8683 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 8684 Index = SplitIndexingFromLoad(LD); 8685 // Try to fold the base pointer arithmetic into subsequent loads and 8686 // stores. 8687 AddUsersToWorklist(N); 8688 } else 8689 Index = DAG.getUNDEF(N->getValueType(1)); 8690 DEBUG(dbgs() << "\nReplacing.7 "; 8691 N->dump(&DAG); 8692 dbgs() << "\nWith: "; 8693 Undef.getNode()->dump(&DAG); 8694 dbgs() << " and 2 other values\n"); 8695 WorklistRemover DeadNodes(*this); 8696 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 8697 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 8698 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 8699 deleteAndRecombine(N); 8700 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8701 } 8702 } 8703 } 8704 8705 // If this load is directly stored, replace the load value with the stored 8706 // value. 8707 // TODO: Handle store large -> read small portion. 8708 // TODO: Handle TRUNCSTORE/LOADEXT 8709 if (ISD::isNormalLoad(N) && !LD->isVolatile()) { 8710 if (ISD::isNON_TRUNCStore(Chain.getNode())) { 8711 StoreSDNode *PrevST = cast<StoreSDNode>(Chain); 8712 if (PrevST->getBasePtr() == Ptr && 8713 PrevST->getValue().getValueType() == N->getValueType(0)) 8714 return CombineTo(N, Chain.getOperand(1), Chain); 8715 } 8716 } 8717 8718 // Try to infer better alignment information than the load already has. 8719 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 8720 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 8721 if (Align > LD->getMemOperand()->getBaseAlignment()) { 8722 SDValue NewLoad = 8723 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N), 8724 LD->getValueType(0), 8725 Chain, Ptr, LD->getPointerInfo(), 8726 LD->getMemoryVT(), 8727 LD->isVolatile(), LD->isNonTemporal(), 8728 LD->isInvariant(), Align, LD->getAAInfo()); 8729 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true); 8730 } 8731 } 8732 } 8733 8734 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 8735 : DAG.getSubtarget().useAA(); 8736 #ifndef NDEBUG 8737 if (CombinerAAOnlyFunc.getNumOccurrences() && 8738 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 8739 UseAA = false; 8740 #endif 8741 if (UseAA && LD->isUnindexed()) { 8742 // Walk up chain skipping non-aliasing memory nodes. 8743 SDValue BetterChain = FindBetterChain(N, Chain); 8744 8745 // If there is a better chain. 8746 if (Chain != BetterChain) { 8747 SDValue ReplLoad; 8748 8749 // Replace the chain to void dependency. 8750 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 8751 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 8752 BetterChain, Ptr, LD->getMemOperand()); 8753 } else { 8754 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 8755 LD->getValueType(0), 8756 BetterChain, Ptr, LD->getMemoryVT(), 8757 LD->getMemOperand()); 8758 } 8759 8760 // Create token factor to keep old chain connected. 8761 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 8762 MVT::Other, Chain, ReplLoad.getValue(1)); 8763 8764 // Make sure the new and old chains are cleaned up. 8765 AddToWorklist(Token.getNode()); 8766 8767 // Replace uses with load result and token factor. Don't add users 8768 // to work list. 8769 return CombineTo(N, ReplLoad.getValue(0), Token, false); 8770 } 8771 } 8772 8773 // Try transforming N to an indexed load. 8774 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 8775 return SDValue(N, 0); 8776 8777 // Try to slice up N to more direct loads if the slices are mapped to 8778 // different register banks or pairing can take place. 8779 if (SliceUpLoad(N)) 8780 return SDValue(N, 0); 8781 8782 return SDValue(); 8783 } 8784 8785 namespace { 8786 /// \brief Helper structure used to slice a load in smaller loads. 8787 /// Basically a slice is obtained from the following sequence: 8788 /// Origin = load Ty1, Base 8789 /// Shift = srl Ty1 Origin, CstTy Amount 8790 /// Inst = trunc Shift to Ty2 8791 /// 8792 /// Then, it will be rewriten into: 8793 /// Slice = load SliceTy, Base + SliceOffset 8794 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 8795 /// 8796 /// SliceTy is deduced from the number of bits that are actually used to 8797 /// build Inst. 8798 struct LoadedSlice { 8799 /// \brief Helper structure used to compute the cost of a slice. 8800 struct Cost { 8801 /// Are we optimizing for code size. 8802 bool ForCodeSize; 8803 /// Various cost. 8804 unsigned Loads; 8805 unsigned Truncates; 8806 unsigned CrossRegisterBanksCopies; 8807 unsigned ZExts; 8808 unsigned Shift; 8809 8810 Cost(bool ForCodeSize = false) 8811 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0), 8812 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {} 8813 8814 /// \brief Get the cost of one isolated slice. 8815 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 8816 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0), 8817 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) { 8818 EVT TruncType = LS.Inst->getValueType(0); 8819 EVT LoadedType = LS.getLoadedType(); 8820 if (TruncType != LoadedType && 8821 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 8822 ZExts = 1; 8823 } 8824 8825 /// \brief Account for slicing gain in the current cost. 8826 /// Slicing provide a few gains like removing a shift or a 8827 /// truncate. This method allows to grow the cost of the original 8828 /// load with the gain from this slice. 8829 void addSliceGain(const LoadedSlice &LS) { 8830 // Each slice saves a truncate. 8831 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 8832 if (!TLI.isTruncateFree(LS.Inst->getValueType(0), 8833 LS.Inst->getOperand(0).getValueType())) 8834 ++Truncates; 8835 // If there is a shift amount, this slice gets rid of it. 8836 if (LS.Shift) 8837 ++Shift; 8838 // If this slice can merge a cross register bank copy, account for it. 8839 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 8840 ++CrossRegisterBanksCopies; 8841 } 8842 8843 Cost &operator+=(const Cost &RHS) { 8844 Loads += RHS.Loads; 8845 Truncates += RHS.Truncates; 8846 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 8847 ZExts += RHS.ZExts; 8848 Shift += RHS.Shift; 8849 return *this; 8850 } 8851 8852 bool operator==(const Cost &RHS) const { 8853 return Loads == RHS.Loads && Truncates == RHS.Truncates && 8854 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 8855 ZExts == RHS.ZExts && Shift == RHS.Shift; 8856 } 8857 8858 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 8859 8860 bool operator<(const Cost &RHS) const { 8861 // Assume cross register banks copies are as expensive as loads. 8862 // FIXME: Do we want some more target hooks? 8863 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 8864 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 8865 // Unless we are optimizing for code size, consider the 8866 // expensive operation first. 8867 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 8868 return ExpensiveOpsLHS < ExpensiveOpsRHS; 8869 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 8870 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 8871 } 8872 8873 bool operator>(const Cost &RHS) const { return RHS < *this; } 8874 8875 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 8876 8877 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 8878 }; 8879 // The last instruction that represent the slice. This should be a 8880 // truncate instruction. 8881 SDNode *Inst; 8882 // The original load instruction. 8883 LoadSDNode *Origin; 8884 // The right shift amount in bits from the original load. 8885 unsigned Shift; 8886 // The DAG from which Origin came from. 8887 // This is used to get some contextual information about legal types, etc. 8888 SelectionDAG *DAG; 8889 8890 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 8891 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 8892 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 8893 8894 LoadedSlice(const LoadedSlice &LS) 8895 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {} 8896 8897 /// \brief Get the bits used in a chunk of bits \p BitWidth large. 8898 /// \return Result is \p BitWidth and has used bits set to 1 and 8899 /// not used bits set to 0. 8900 APInt getUsedBits() const { 8901 // Reproduce the trunc(lshr) sequence: 8902 // - Start from the truncated value. 8903 // - Zero extend to the desired bit width. 8904 // - Shift left. 8905 assert(Origin && "No original load to compare against."); 8906 unsigned BitWidth = Origin->getValueSizeInBits(0); 8907 assert(Inst && "This slice is not bound to an instruction"); 8908 assert(Inst->getValueSizeInBits(0) <= BitWidth && 8909 "Extracted slice is bigger than the whole type!"); 8910 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 8911 UsedBits.setAllBits(); 8912 UsedBits = UsedBits.zext(BitWidth); 8913 UsedBits <<= Shift; 8914 return UsedBits; 8915 } 8916 8917 /// \brief Get the size of the slice to be loaded in bytes. 8918 unsigned getLoadedSize() const { 8919 unsigned SliceSize = getUsedBits().countPopulation(); 8920 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 8921 return SliceSize / 8; 8922 } 8923 8924 /// \brief Get the type that will be loaded for this slice. 8925 /// Note: This may not be the final type for the slice. 8926 EVT getLoadedType() const { 8927 assert(DAG && "Missing context"); 8928 LLVMContext &Ctxt = *DAG->getContext(); 8929 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 8930 } 8931 8932 /// \brief Get the alignment of the load used for this slice. 8933 unsigned getAlignment() const { 8934 unsigned Alignment = Origin->getAlignment(); 8935 unsigned Offset = getOffsetFromBase(); 8936 if (Offset != 0) 8937 Alignment = MinAlign(Alignment, Alignment + Offset); 8938 return Alignment; 8939 } 8940 8941 /// \brief Check if this slice can be rewritten with legal operations. 8942 bool isLegal() const { 8943 // An invalid slice is not legal. 8944 if (!Origin || !Inst || !DAG) 8945 return false; 8946 8947 // Offsets are for indexed load only, we do not handle that. 8948 if (Origin->getOffset().getOpcode() != ISD::UNDEF) 8949 return false; 8950 8951 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 8952 8953 // Check that the type is legal. 8954 EVT SliceType = getLoadedType(); 8955 if (!TLI.isTypeLegal(SliceType)) 8956 return false; 8957 8958 // Check that the load is legal for this type. 8959 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 8960 return false; 8961 8962 // Check that the offset can be computed. 8963 // 1. Check its type. 8964 EVT PtrType = Origin->getBasePtr().getValueType(); 8965 if (PtrType == MVT::Untyped || PtrType.isExtended()) 8966 return false; 8967 8968 // 2. Check that it fits in the immediate. 8969 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 8970 return false; 8971 8972 // 3. Check that the computation is legal. 8973 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 8974 return false; 8975 8976 // Check that the zext is legal if it needs one. 8977 EVT TruncateType = Inst->getValueType(0); 8978 if (TruncateType != SliceType && 8979 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 8980 return false; 8981 8982 return true; 8983 } 8984 8985 /// \brief Get the offset in bytes of this slice in the original chunk of 8986 /// bits. 8987 /// \pre DAG != nullptr. 8988 uint64_t getOffsetFromBase() const { 8989 assert(DAG && "Missing context."); 8990 bool IsBigEndian = 8991 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian(); 8992 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 8993 uint64_t Offset = Shift / 8; 8994 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 8995 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 8996 "The size of the original loaded type is not a multiple of a" 8997 " byte."); 8998 // If Offset is bigger than TySizeInBytes, it means we are loading all 8999 // zeros. This should have been optimized before in the process. 9000 assert(TySizeInBytes > Offset && 9001 "Invalid shift amount for given loaded size"); 9002 if (IsBigEndian) 9003 Offset = TySizeInBytes - Offset - getLoadedSize(); 9004 return Offset; 9005 } 9006 9007 /// \brief Generate the sequence of instructions to load the slice 9008 /// represented by this object and redirect the uses of this slice to 9009 /// this new sequence of instructions. 9010 /// \pre this->Inst && this->Origin are valid Instructions and this 9011 /// object passed the legal check: LoadedSlice::isLegal returned true. 9012 /// \return The last instruction of the sequence used to load the slice. 9013 SDValue loadSlice() const { 9014 assert(Inst && Origin && "Unable to replace a non-existing slice."); 9015 const SDValue &OldBaseAddr = Origin->getBasePtr(); 9016 SDValue BaseAddr = OldBaseAddr; 9017 // Get the offset in that chunk of bytes w.r.t. the endianess. 9018 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 9019 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 9020 if (Offset) { 9021 // BaseAddr = BaseAddr + Offset. 9022 EVT ArithType = BaseAddr.getValueType(); 9023 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr, 9024 DAG->getConstant(Offset, ArithType)); 9025 } 9026 9027 // Create the type of the loaded slice according to its size. 9028 EVT SliceType = getLoadedType(); 9029 9030 // Create the load for the slice. 9031 SDValue LastInst = DAG->getLoad( 9032 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 9033 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(), 9034 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment()); 9035 // If the final type is not the same as the loaded type, this means that 9036 // we have to pad with zero. Create a zero extend for that. 9037 EVT FinalType = Inst->getValueType(0); 9038 if (SliceType != FinalType) 9039 LastInst = 9040 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 9041 return LastInst; 9042 } 9043 9044 /// \brief Check if this slice can be merged with an expensive cross register 9045 /// bank copy. E.g., 9046 /// i = load i32 9047 /// f = bitcast i32 i to float 9048 bool canMergeExpensiveCrossRegisterBankCopy() const { 9049 if (!Inst || !Inst->hasOneUse()) 9050 return false; 9051 SDNode *Use = *Inst->use_begin(); 9052 if (Use->getOpcode() != ISD::BITCAST) 9053 return false; 9054 assert(DAG && "Missing context"); 9055 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 9056 EVT ResVT = Use->getValueType(0); 9057 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 9058 const TargetRegisterClass *ArgRC = 9059 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 9060 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 9061 return false; 9062 9063 // At this point, we know that we perform a cross-register-bank copy. 9064 // Check if it is expensive. 9065 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 9066 // Assume bitcasts are cheap, unless both register classes do not 9067 // explicitly share a common sub class. 9068 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 9069 return false; 9070 9071 // Check if it will be merged with the load. 9072 // 1. Check the alignment constraint. 9073 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment( 9074 ResVT.getTypeForEVT(*DAG->getContext())); 9075 9076 if (RequiredAlignment > getAlignment()) 9077 return false; 9078 9079 // 2. Check that the load is a legal operation for that type. 9080 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 9081 return false; 9082 9083 // 3. Check that we do not have a zext in the way. 9084 if (Inst->getValueType(0) != getLoadedType()) 9085 return false; 9086 9087 return true; 9088 } 9089 }; 9090 } 9091 9092 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e., 9093 /// \p UsedBits looks like 0..0 1..1 0..0. 9094 static bool areUsedBitsDense(const APInt &UsedBits) { 9095 // If all the bits are one, this is dense! 9096 if (UsedBits.isAllOnesValue()) 9097 return true; 9098 9099 // Get rid of the unused bits on the right. 9100 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 9101 // Get rid of the unused bits on the left. 9102 if (NarrowedUsedBits.countLeadingZeros()) 9103 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 9104 // Check that the chunk of bits is completely used. 9105 return NarrowedUsedBits.isAllOnesValue(); 9106 } 9107 9108 /// \brief Check whether or not \p First and \p Second are next to each other 9109 /// in memory. This means that there is no hole between the bits loaded 9110 /// by \p First and the bits loaded by \p Second. 9111 static bool areSlicesNextToEachOther(const LoadedSlice &First, 9112 const LoadedSlice &Second) { 9113 assert(First.Origin == Second.Origin && First.Origin && 9114 "Unable to match different memory origins."); 9115 APInt UsedBits = First.getUsedBits(); 9116 assert((UsedBits & Second.getUsedBits()) == 0 && 9117 "Slices are not supposed to overlap."); 9118 UsedBits |= Second.getUsedBits(); 9119 return areUsedBitsDense(UsedBits); 9120 } 9121 9122 /// \brief Adjust the \p GlobalLSCost according to the target 9123 /// paring capabilities and the layout of the slices. 9124 /// \pre \p GlobalLSCost should account for at least as many loads as 9125 /// there is in the slices in \p LoadedSlices. 9126 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9127 LoadedSlice::Cost &GlobalLSCost) { 9128 unsigned NumberOfSlices = LoadedSlices.size(); 9129 // If there is less than 2 elements, no pairing is possible. 9130 if (NumberOfSlices < 2) 9131 return; 9132 9133 // Sort the slices so that elements that are likely to be next to each 9134 // other in memory are next to each other in the list. 9135 std::sort(LoadedSlices.begin(), LoadedSlices.end(), 9136 [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 9137 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 9138 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 9139 }); 9140 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 9141 // First (resp. Second) is the first (resp. Second) potentially candidate 9142 // to be placed in a paired load. 9143 const LoadedSlice *First = nullptr; 9144 const LoadedSlice *Second = nullptr; 9145 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 9146 // Set the beginning of the pair. 9147 First = Second) { 9148 9149 Second = &LoadedSlices[CurrSlice]; 9150 9151 // If First is NULL, it means we start a new pair. 9152 // Get to the next slice. 9153 if (!First) 9154 continue; 9155 9156 EVT LoadedType = First->getLoadedType(); 9157 9158 // If the types of the slices are different, we cannot pair them. 9159 if (LoadedType != Second->getLoadedType()) 9160 continue; 9161 9162 // Check if the target supplies paired loads for this type. 9163 unsigned RequiredAlignment = 0; 9164 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 9165 // move to the next pair, this type is hopeless. 9166 Second = nullptr; 9167 continue; 9168 } 9169 // Check if we meet the alignment requirement. 9170 if (RequiredAlignment > First->getAlignment()) 9171 continue; 9172 9173 // Check that both loads are next to each other in memory. 9174 if (!areSlicesNextToEachOther(*First, *Second)) 9175 continue; 9176 9177 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 9178 --GlobalLSCost.Loads; 9179 // Move to the next pair. 9180 Second = nullptr; 9181 } 9182 } 9183 9184 /// \brief Check the profitability of all involved LoadedSlice. 9185 /// Currently, it is considered profitable if there is exactly two 9186 /// involved slices (1) which are (2) next to each other in memory, and 9187 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 9188 /// 9189 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 9190 /// the elements themselves. 9191 /// 9192 /// FIXME: When the cost model will be mature enough, we can relax 9193 /// constraints (1) and (2). 9194 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 9195 const APInt &UsedBits, bool ForCodeSize) { 9196 unsigned NumberOfSlices = LoadedSlices.size(); 9197 if (StressLoadSlicing) 9198 return NumberOfSlices > 1; 9199 9200 // Check (1). 9201 if (NumberOfSlices != 2) 9202 return false; 9203 9204 // Check (2). 9205 if (!areUsedBitsDense(UsedBits)) 9206 return false; 9207 9208 // Check (3). 9209 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 9210 // The original code has one big load. 9211 OrigCost.Loads = 1; 9212 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 9213 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 9214 // Accumulate the cost of all the slices. 9215 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 9216 GlobalSlicingCost += SliceCost; 9217 9218 // Account as cost in the original configuration the gain obtained 9219 // with the current slices. 9220 OrigCost.addSliceGain(LS); 9221 } 9222 9223 // If the target supports paired load, adjust the cost accordingly. 9224 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 9225 return OrigCost > GlobalSlicingCost; 9226 } 9227 9228 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr) 9229 /// operations, split it in the various pieces being extracted. 9230 /// 9231 /// This sort of thing is introduced by SROA. 9232 /// This slicing takes care not to insert overlapping loads. 9233 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 9234 bool DAGCombiner::SliceUpLoad(SDNode *N) { 9235 if (Level < AfterLegalizeDAG) 9236 return false; 9237 9238 LoadSDNode *LD = cast<LoadSDNode>(N); 9239 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 9240 !LD->getValueType(0).isInteger()) 9241 return false; 9242 9243 // Keep track of already used bits to detect overlapping values. 9244 // In that case, we will just abort the transformation. 9245 APInt UsedBits(LD->getValueSizeInBits(0), 0); 9246 9247 SmallVector<LoadedSlice, 4> LoadedSlices; 9248 9249 // Check if this load is used as several smaller chunks of bits. 9250 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 9251 // of computation for each trunc. 9252 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 9253 UI != UIEnd; ++UI) { 9254 // Skip the uses of the chain. 9255 if (UI.getUse().getResNo() != 0) 9256 continue; 9257 9258 SDNode *User = *UI; 9259 unsigned Shift = 0; 9260 9261 // Check if this is a trunc(lshr). 9262 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 9263 isa<ConstantSDNode>(User->getOperand(1))) { 9264 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue(); 9265 User = *User->use_begin(); 9266 } 9267 9268 // At this point, User is a Truncate, iff we encountered, trunc or 9269 // trunc(lshr). 9270 if (User->getOpcode() != ISD::TRUNCATE) 9271 return false; 9272 9273 // The width of the type must be a power of 2 and greater than 8-bits. 9274 // Otherwise the load cannot be represented in LLVM IR. 9275 // Moreover, if we shifted with a non-8-bits multiple, the slice 9276 // will be across several bytes. We do not support that. 9277 unsigned Width = User->getValueSizeInBits(0); 9278 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 9279 return 0; 9280 9281 // Build the slice for this chain of computations. 9282 LoadedSlice LS(User, LD, Shift, &DAG); 9283 APInt CurrentUsedBits = LS.getUsedBits(); 9284 9285 // Check if this slice overlaps with another. 9286 if ((CurrentUsedBits & UsedBits) != 0) 9287 return false; 9288 // Update the bits used globally. 9289 UsedBits |= CurrentUsedBits; 9290 9291 // Check if the new slice would be legal. 9292 if (!LS.isLegal()) 9293 return false; 9294 9295 // Record the slice. 9296 LoadedSlices.push_back(LS); 9297 } 9298 9299 // Abort slicing if it does not seem to be profitable. 9300 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 9301 return false; 9302 9303 ++SlicedLoads; 9304 9305 // Rewrite each chain to use an independent load. 9306 // By construction, each chain can be represented by a unique load. 9307 9308 // Prepare the argument for the new token factor for all the slices. 9309 SmallVector<SDValue, 8> ArgChains; 9310 for (SmallVectorImpl<LoadedSlice>::const_iterator 9311 LSIt = LoadedSlices.begin(), 9312 LSItEnd = LoadedSlices.end(); 9313 LSIt != LSItEnd; ++LSIt) { 9314 SDValue SliceInst = LSIt->loadSlice(); 9315 CombineTo(LSIt->Inst, SliceInst, true); 9316 if (SliceInst.getNode()->getOpcode() != ISD::LOAD) 9317 SliceInst = SliceInst.getOperand(0); 9318 assert(SliceInst->getOpcode() == ISD::LOAD && 9319 "It takes more than a zext to get to the loaded slice!!"); 9320 ArgChains.push_back(SliceInst.getValue(1)); 9321 } 9322 9323 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 9324 ArgChains); 9325 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 9326 return true; 9327 } 9328 9329 /// Check to see if V is (and load (ptr), imm), where the load is having 9330 /// specific bytes cleared out. If so, return the byte size being masked out 9331 /// and the shift amount. 9332 static std::pair<unsigned, unsigned> 9333 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 9334 std::pair<unsigned, unsigned> Result(0, 0); 9335 9336 // Check for the structure we're looking for. 9337 if (V->getOpcode() != ISD::AND || 9338 !isa<ConstantSDNode>(V->getOperand(1)) || 9339 !ISD::isNormalLoad(V->getOperand(0).getNode())) 9340 return Result; 9341 9342 // Check the chain and pointer. 9343 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 9344 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 9345 9346 // The store should be chained directly to the load or be an operand of a 9347 // tokenfactor. 9348 if (LD == Chain.getNode()) 9349 ; // ok. 9350 else if (Chain->getOpcode() != ISD::TokenFactor) 9351 return Result; // Fail. 9352 else { 9353 bool isOk = false; 9354 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) 9355 if (Chain->getOperand(i).getNode() == LD) { 9356 isOk = true; 9357 break; 9358 } 9359 if (!isOk) return Result; 9360 } 9361 9362 // This only handles simple types. 9363 if (V.getValueType() != MVT::i16 && 9364 V.getValueType() != MVT::i32 && 9365 V.getValueType() != MVT::i64) 9366 return Result; 9367 9368 // Check the constant mask. Invert it so that the bits being masked out are 9369 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 9370 // follow the sign bit for uniformity. 9371 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 9372 unsigned NotMaskLZ = countLeadingZeros(NotMask); 9373 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 9374 unsigned NotMaskTZ = countTrailingZeros(NotMask); 9375 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 9376 if (NotMaskLZ == 64) return Result; // All zero mask. 9377 9378 // See if we have a continuous run of bits. If so, we have 0*1+0* 9379 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64) 9380 return Result; 9381 9382 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 9383 if (V.getValueType() != MVT::i64 && NotMaskLZ) 9384 NotMaskLZ -= 64-V.getValueSizeInBits(); 9385 9386 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 9387 switch (MaskedBytes) { 9388 case 1: 9389 case 2: 9390 case 4: break; 9391 default: return Result; // All one mask, or 5-byte mask. 9392 } 9393 9394 // Verify that the first bit starts at a multiple of mask so that the access 9395 // is aligned the same as the access width. 9396 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 9397 9398 Result.first = MaskedBytes; 9399 Result.second = NotMaskTZ/8; 9400 return Result; 9401 } 9402 9403 9404 /// Check to see if IVal is something that provides a value as specified by 9405 /// MaskInfo. If so, replace the specified store with a narrower store of 9406 /// truncated IVal. 9407 static SDNode * 9408 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 9409 SDValue IVal, StoreSDNode *St, 9410 DAGCombiner *DC) { 9411 unsigned NumBytes = MaskInfo.first; 9412 unsigned ByteShift = MaskInfo.second; 9413 SelectionDAG &DAG = DC->getDAG(); 9414 9415 // Check to see if IVal is all zeros in the part being masked in by the 'or' 9416 // that uses this. If not, this is not a replacement. 9417 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 9418 ByteShift*8, (ByteShift+NumBytes)*8); 9419 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 9420 9421 // Check that it is legal on the target to do this. It is legal if the new 9422 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 9423 // legalization. 9424 MVT VT = MVT::getIntegerVT(NumBytes*8); 9425 if (!DC->isTypeLegal(VT)) 9426 return nullptr; 9427 9428 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 9429 // shifted by ByteShift and truncated down to NumBytes. 9430 if (ByteShift) 9431 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal, 9432 DAG.getConstant(ByteShift*8, 9433 DC->getShiftAmountTy(IVal.getValueType()))); 9434 9435 // Figure out the offset for the store and the alignment of the access. 9436 unsigned StOffset; 9437 unsigned NewAlign = St->getAlignment(); 9438 9439 if (DAG.getTargetLoweringInfo().isLittleEndian()) 9440 StOffset = ByteShift; 9441 else 9442 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 9443 9444 SDValue Ptr = St->getBasePtr(); 9445 if (StOffset) { 9446 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(), 9447 Ptr, DAG.getConstant(StOffset, Ptr.getValueType())); 9448 NewAlign = MinAlign(NewAlign, StOffset); 9449 } 9450 9451 // Truncate down to the new size. 9452 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 9453 9454 ++OpsNarrowed; 9455 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr, 9456 St->getPointerInfo().getWithOffset(StOffset), 9457 false, false, NewAlign).getNode(); 9458 } 9459 9460 9461 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 9462 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 9463 /// narrowing the load and store if it would end up being a win for performance 9464 /// or code size. 9465 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 9466 StoreSDNode *ST = cast<StoreSDNode>(N); 9467 if (ST->isVolatile()) 9468 return SDValue(); 9469 9470 SDValue Chain = ST->getChain(); 9471 SDValue Value = ST->getValue(); 9472 SDValue Ptr = ST->getBasePtr(); 9473 EVT VT = Value.getValueType(); 9474 9475 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 9476 return SDValue(); 9477 9478 unsigned Opc = Value.getOpcode(); 9479 9480 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 9481 // is a byte mask indicating a consecutive number of bytes, check to see if 9482 // Y is known to provide just those bytes. If so, we try to replace the 9483 // load + replace + store sequence with a single (narrower) store, which makes 9484 // the load dead. 9485 if (Opc == ISD::OR) { 9486 std::pair<unsigned, unsigned> MaskedLoad; 9487 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 9488 if (MaskedLoad.first) 9489 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 9490 Value.getOperand(1), ST,this)) 9491 return SDValue(NewST, 0); 9492 9493 // Or is commutative, so try swapping X and Y. 9494 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 9495 if (MaskedLoad.first) 9496 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 9497 Value.getOperand(0), ST,this)) 9498 return SDValue(NewST, 0); 9499 } 9500 9501 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 9502 Value.getOperand(1).getOpcode() != ISD::Constant) 9503 return SDValue(); 9504 9505 SDValue N0 = Value.getOperand(0); 9506 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9507 Chain == SDValue(N0.getNode(), 1)) { 9508 LoadSDNode *LD = cast<LoadSDNode>(N0); 9509 if (LD->getBasePtr() != Ptr || 9510 LD->getPointerInfo().getAddrSpace() != 9511 ST->getPointerInfo().getAddrSpace()) 9512 return SDValue(); 9513 9514 // Find the type to narrow it the load / op / store to. 9515 SDValue N1 = Value.getOperand(1); 9516 unsigned BitWidth = N1.getValueSizeInBits(); 9517 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 9518 if (Opc == ISD::AND) 9519 Imm ^= APInt::getAllOnesValue(BitWidth); 9520 if (Imm == 0 || Imm.isAllOnesValue()) 9521 return SDValue(); 9522 unsigned ShAmt = Imm.countTrailingZeros(); 9523 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 9524 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 9525 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 9526 // The narrowing should be profitable, the load/store operation should be 9527 // legal (or custom) and the store size should be equal to the NewVT width. 9528 while (NewBW < BitWidth && 9529 (NewVT.getStoreSizeInBits() != NewBW || 9530 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 9531 !TLI.isNarrowingProfitable(VT, NewVT))) { 9532 NewBW = NextPowerOf2(NewBW); 9533 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 9534 } 9535 if (NewBW >= BitWidth) 9536 return SDValue(); 9537 9538 // If the lsb changed does not start at the type bitwidth boundary, 9539 // start at the previous one. 9540 if (ShAmt % NewBW) 9541 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 9542 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 9543 std::min(BitWidth, ShAmt + NewBW)); 9544 if ((Imm & Mask) == Imm) { 9545 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 9546 if (Opc == ISD::AND) 9547 NewImm ^= APInt::getAllOnesValue(NewBW); 9548 uint64_t PtrOff = ShAmt / 8; 9549 // For big endian targets, we need to adjust the offset to the pointer to 9550 // load the correct bytes. 9551 if (TLI.isBigEndian()) 9552 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 9553 9554 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 9555 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 9556 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy)) 9557 return SDValue(); 9558 9559 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 9560 Ptr.getValueType(), Ptr, 9561 DAG.getConstant(PtrOff, Ptr.getValueType())); 9562 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0), 9563 LD->getChain(), NewPtr, 9564 LD->getPointerInfo().getWithOffset(PtrOff), 9565 LD->isVolatile(), LD->isNonTemporal(), 9566 LD->isInvariant(), NewAlign, 9567 LD->getAAInfo()); 9568 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 9569 DAG.getConstant(NewImm, NewVT)); 9570 SDValue NewST = DAG.getStore(Chain, SDLoc(N), 9571 NewVal, NewPtr, 9572 ST->getPointerInfo().getWithOffset(PtrOff), 9573 false, false, NewAlign); 9574 9575 AddToWorklist(NewPtr.getNode()); 9576 AddToWorklist(NewLD.getNode()); 9577 AddToWorklist(NewVal.getNode()); 9578 WorklistRemover DeadNodes(*this); 9579 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 9580 ++OpsNarrowed; 9581 return NewST; 9582 } 9583 } 9584 9585 return SDValue(); 9586 } 9587 9588 /// For a given floating point load / store pair, if the load value isn't used 9589 /// by any other operations, then consider transforming the pair to integer 9590 /// load / store operations if the target deems the transformation profitable. 9591 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 9592 StoreSDNode *ST = cast<StoreSDNode>(N); 9593 SDValue Chain = ST->getChain(); 9594 SDValue Value = ST->getValue(); 9595 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 9596 Value.hasOneUse() && 9597 Chain == SDValue(Value.getNode(), 1)) { 9598 LoadSDNode *LD = cast<LoadSDNode>(Value); 9599 EVT VT = LD->getMemoryVT(); 9600 if (!VT.isFloatingPoint() || 9601 VT != ST->getMemoryVT() || 9602 LD->isNonTemporal() || 9603 ST->isNonTemporal() || 9604 LD->getPointerInfo().getAddrSpace() != 0 || 9605 ST->getPointerInfo().getAddrSpace() != 0) 9606 return SDValue(); 9607 9608 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 9609 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 9610 !TLI.isOperationLegal(ISD::STORE, IntVT) || 9611 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 9612 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 9613 return SDValue(); 9614 9615 unsigned LDAlign = LD->getAlignment(); 9616 unsigned STAlign = ST->getAlignment(); 9617 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 9618 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy); 9619 if (LDAlign < ABIAlign || STAlign < ABIAlign) 9620 return SDValue(); 9621 9622 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value), 9623 LD->getChain(), LD->getBasePtr(), 9624 LD->getPointerInfo(), 9625 false, false, false, LDAlign); 9626 9627 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N), 9628 NewLD, ST->getBasePtr(), 9629 ST->getPointerInfo(), 9630 false, false, STAlign); 9631 9632 AddToWorklist(NewLD.getNode()); 9633 AddToWorklist(NewST.getNode()); 9634 WorklistRemover DeadNodes(*this); 9635 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 9636 ++LdStFP2Int; 9637 return NewST; 9638 } 9639 9640 return SDValue(); 9641 } 9642 9643 /// Helper struct to parse and store a memory address as base + index + offset. 9644 /// We ignore sign extensions when it is safe to do so. 9645 /// The following two expressions are not equivalent. To differentiate we need 9646 /// to store whether there was a sign extension involved in the index 9647 /// computation. 9648 /// (load (i64 add (i64 copyfromreg %c) 9649 /// (i64 signextend (add (i8 load %index) 9650 /// (i8 1)))) 9651 /// vs 9652 /// 9653 /// (load (i64 add (i64 copyfromreg %c) 9654 /// (i64 signextend (i32 add (i32 signextend (i8 load %index)) 9655 /// (i32 1))))) 9656 struct BaseIndexOffset { 9657 SDValue Base; 9658 SDValue Index; 9659 int64_t Offset; 9660 bool IsIndexSignExt; 9661 9662 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {} 9663 9664 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset, 9665 bool IsIndexSignExt) : 9666 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {} 9667 9668 bool equalBaseIndex(const BaseIndexOffset &Other) { 9669 return Other.Base == Base && Other.Index == Index && 9670 Other.IsIndexSignExt == IsIndexSignExt; 9671 } 9672 9673 /// Parses tree in Ptr for base, index, offset addresses. 9674 static BaseIndexOffset match(SDValue Ptr) { 9675 bool IsIndexSignExt = false; 9676 9677 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD 9678 // instruction, then it could be just the BASE or everything else we don't 9679 // know how to handle. Just use Ptr as BASE and give up. 9680 if (Ptr->getOpcode() != ISD::ADD) 9681 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 9682 9683 // We know that we have at least an ADD instruction. Try to pattern match 9684 // the simple case of BASE + OFFSET. 9685 if (isa<ConstantSDNode>(Ptr->getOperand(1))) { 9686 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue(); 9687 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset, 9688 IsIndexSignExt); 9689 } 9690 9691 // Inside a loop the current BASE pointer is calculated using an ADD and a 9692 // MUL instruction. In this case Ptr is the actual BASE pointer. 9693 // (i64 add (i64 %array_ptr) 9694 // (i64 mul (i64 %induction_var) 9695 // (i64 %element_size))) 9696 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL) 9697 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 9698 9699 // Look at Base + Index + Offset cases. 9700 SDValue Base = Ptr->getOperand(0); 9701 SDValue IndexOffset = Ptr->getOperand(1); 9702 9703 // Skip signextends. 9704 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) { 9705 IndexOffset = IndexOffset->getOperand(0); 9706 IsIndexSignExt = true; 9707 } 9708 9709 // Either the case of Base + Index (no offset) or something else. 9710 if (IndexOffset->getOpcode() != ISD::ADD) 9711 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt); 9712 9713 // Now we have the case of Base + Index + offset. 9714 SDValue Index = IndexOffset->getOperand(0); 9715 SDValue Offset = IndexOffset->getOperand(1); 9716 9717 if (!isa<ConstantSDNode>(Offset)) 9718 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt); 9719 9720 // Ignore signextends. 9721 if (Index->getOpcode() == ISD::SIGN_EXTEND) { 9722 Index = Index->getOperand(0); 9723 IsIndexSignExt = true; 9724 } else IsIndexSignExt = false; 9725 9726 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue(); 9727 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt); 9728 } 9729 }; 9730 9731 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 9732 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, 9733 unsigned NumElem, bool IsConstantSrc, bool UseVector) { 9734 // Make sure we have something to merge. 9735 if (NumElem < 2) 9736 return false; 9737 9738 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8; 9739 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 9740 unsigned EarliestNodeUsed = 0; 9741 9742 for (unsigned i=0; i < NumElem; ++i) { 9743 // Find a chain for the new wide-store operand. Notice that some 9744 // of the store nodes that we found may not be selected for inclusion 9745 // in the wide store. The chain we use needs to be the chain of the 9746 // earliest store node which is *used* and replaced by the wide store. 9747 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 9748 EarliestNodeUsed = i; 9749 } 9750 9751 // The earliest Node in the DAG. 9752 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 9753 SDLoc DL(StoreNodes[0].MemNode); 9754 9755 SDValue StoredVal; 9756 if (UseVector) { 9757 // Find a legal type for the vector store. 9758 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 9759 assert(TLI.isTypeLegal(Ty) && "Illegal vector store"); 9760 if (IsConstantSrc) { 9761 // A vector store with a constant source implies that the constant is 9762 // zero; we only handle merging stores of constant zeros because the zero 9763 // can be materialized without a load. 9764 // It may be beneficial to loosen this restriction to allow non-zero 9765 // store merging. 9766 StoredVal = DAG.getConstant(0, Ty); 9767 } else { 9768 SmallVector<SDValue, 8> Ops; 9769 for (unsigned i = 0; i < NumElem ; ++i) { 9770 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9771 SDValue Val = St->getValue(); 9772 // All of the operands of a BUILD_VECTOR must have the same type. 9773 if (Val.getValueType() != MemVT) 9774 return false; 9775 Ops.push_back(Val); 9776 } 9777 9778 // Build the extracted vector elements back into a vector. 9779 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops); 9780 } 9781 } else { 9782 // We should always use a vector store when merging extracted vector 9783 // elements, so this path implies a store of constants. 9784 assert(IsConstantSrc && "Merged vector elements should use vector store"); 9785 9786 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 9787 APInt StoreInt(StoreBW, 0); 9788 9789 // Construct a single integer constant which is made of the smaller 9790 // constant inputs. 9791 bool IsLE = TLI.isLittleEndian(); 9792 for (unsigned i = 0; i < NumElem ; ++i) { 9793 unsigned Idx = IsLE ? (NumElem - 1 - i) : i; 9794 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 9795 SDValue Val = St->getValue(); 9796 StoreInt <<= ElementSizeBytes*8; 9797 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 9798 StoreInt |= C->getAPIntValue().zext(StoreBW); 9799 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 9800 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW); 9801 } else { 9802 llvm_unreachable("Invalid constant element type"); 9803 } 9804 } 9805 9806 // Create the new Load and Store operations. 9807 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 9808 StoredVal = DAG.getConstant(StoreInt, StoreTy); 9809 } 9810 9811 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal, 9812 FirstInChain->getBasePtr(), 9813 FirstInChain->getPointerInfo(), 9814 false, false, 9815 FirstInChain->getAlignment()); 9816 9817 // Replace the first store with the new store 9818 CombineTo(EarliestOp, NewStore); 9819 // Erase all other stores. 9820 for (unsigned i = 0; i < NumElem ; ++i) { 9821 if (StoreNodes[i].MemNode == EarliestOp) 9822 continue; 9823 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 9824 // ReplaceAllUsesWith will replace all uses that existed when it was 9825 // called, but graph optimizations may cause new ones to appear. For 9826 // example, the case in pr14333 looks like 9827 // 9828 // St's chain -> St -> another store -> X 9829 // 9830 // And the only difference from St to the other store is the chain. 9831 // When we change it's chain to be St's chain they become identical, 9832 // get CSEed and the net result is that X is now a use of St. 9833 // Since we know that St is redundant, just iterate. 9834 while (!St->use_empty()) 9835 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain()); 9836 deleteAndRecombine(St); 9837 } 9838 9839 return true; 9840 } 9841 9842 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) { 9843 EVT MemVT = St->getMemoryVT(); 9844 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8; 9845 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes(). 9846 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat); 9847 9848 // Don't merge vectors into wider inputs. 9849 if (MemVT.isVector() || !MemVT.isSimple()) 9850 return false; 9851 9852 // Perform an early exit check. Do not bother looking at stored values that 9853 // are not constants, loads, or extracted vector elements. 9854 SDValue StoredVal = St->getValue(); 9855 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 9856 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 9857 isa<ConstantFPSDNode>(StoredVal); 9858 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT); 9859 9860 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc) 9861 return false; 9862 9863 // Only look at ends of store sequences. 9864 SDValue Chain = SDValue(St, 0); 9865 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE) 9866 return false; 9867 9868 // This holds the base pointer, index, and the offset in bytes from the base 9869 // pointer. 9870 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr()); 9871 9872 // We must have a base and an offset. 9873 if (!BasePtr.Base.getNode()) 9874 return false; 9875 9876 // Do not handle stores to undef base pointers. 9877 if (BasePtr.Base.getOpcode() == ISD::UNDEF) 9878 return false; 9879 9880 // Save the LoadSDNodes that we find in the chain. 9881 // We need to make sure that these nodes do not interfere with 9882 // any of the store nodes. 9883 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes; 9884 9885 // Save the StoreSDNodes that we find in the chain. 9886 SmallVector<MemOpLink, 8> StoreNodes; 9887 9888 // Walk up the chain and look for nodes with offsets from the same 9889 // base pointer. Stop when reaching an instruction with a different kind 9890 // or instruction which has a different base pointer. 9891 unsigned Seq = 0; 9892 StoreSDNode *Index = St; 9893 while (Index) { 9894 // If the chain has more than one use, then we can't reorder the mem ops. 9895 if (Index != St && !SDValue(Index, 0)->hasOneUse()) 9896 break; 9897 9898 // Find the base pointer and offset for this memory node. 9899 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr()); 9900 9901 // Check that the base pointer is the same as the original one. 9902 if (!Ptr.equalBaseIndex(BasePtr)) 9903 break; 9904 9905 // Check that the alignment is the same. 9906 if (Index->getAlignment() != St->getAlignment()) 9907 break; 9908 9909 // The memory operands must not be volatile. 9910 if (Index->isVolatile() || Index->isIndexed()) 9911 break; 9912 9913 // No truncation. 9914 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index)) 9915 if (St->isTruncatingStore()) 9916 break; 9917 9918 // The stored memory type must be the same. 9919 if (Index->getMemoryVT() != MemVT) 9920 break; 9921 9922 // We do not allow unaligned stores because we want to prevent overriding 9923 // stores. 9924 if (Index->getAlignment()*8 != MemVT.getSizeInBits()) 9925 break; 9926 9927 // We found a potential memory operand to merge. 9928 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++)); 9929 9930 // Find the next memory operand in the chain. If the next operand in the 9931 // chain is a store then move up and continue the scan with the next 9932 // memory operand. If the next operand is a load save it and use alias 9933 // information to check if it interferes with anything. 9934 SDNode *NextInChain = Index->getChain().getNode(); 9935 while (1) { 9936 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) { 9937 // We found a store node. Use it for the next iteration. 9938 Index = STn; 9939 break; 9940 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) { 9941 if (Ldn->isVolatile()) { 9942 Index = nullptr; 9943 break; 9944 } 9945 9946 // Save the load node for later. Continue the scan. 9947 AliasLoadNodes.push_back(Ldn); 9948 NextInChain = Ldn->getChain().getNode(); 9949 continue; 9950 } else { 9951 Index = nullptr; 9952 break; 9953 } 9954 } 9955 } 9956 9957 // Check if there is anything to merge. 9958 if (StoreNodes.size() < 2) 9959 return false; 9960 9961 // Sort the memory operands according to their distance from the base pointer. 9962 std::sort(StoreNodes.begin(), StoreNodes.end(), 9963 [](MemOpLink LHS, MemOpLink RHS) { 9964 return LHS.OffsetFromBase < RHS.OffsetFromBase || 9965 (LHS.OffsetFromBase == RHS.OffsetFromBase && 9966 LHS.SequenceNum > RHS.SequenceNum); 9967 }); 9968 9969 // Scan the memory operations on the chain and find the first non-consecutive 9970 // store memory address. 9971 unsigned LastConsecutiveStore = 0; 9972 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 9973 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) { 9974 9975 // Check that the addresses are consecutive starting from the second 9976 // element in the list of stores. 9977 if (i > 0) { 9978 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 9979 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 9980 break; 9981 } 9982 9983 bool Alias = false; 9984 // Check if this store interferes with any of the loads that we found. 9985 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld) 9986 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) { 9987 Alias = true; 9988 break; 9989 } 9990 // We found a load that alias with this store. Stop the sequence. 9991 if (Alias) 9992 break; 9993 9994 // Mark this node as useful. 9995 LastConsecutiveStore = i; 9996 } 9997 9998 // The node with the lowest store address. 9999 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 10000 10001 // Store the constants into memory as one consecutive store. 10002 if (IsConstantSrc) { 10003 unsigned LastLegalType = 0; 10004 unsigned LastLegalVectorType = 0; 10005 bool NonZero = false; 10006 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10007 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10008 SDValue StoredVal = St->getValue(); 10009 10010 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) { 10011 NonZero |= !C->isNullValue(); 10012 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) { 10013 NonZero |= !C->getConstantFPValue()->isNullValue(); 10014 } else { 10015 // Non-constant. 10016 break; 10017 } 10018 10019 // Find a legal type for the constant store. 10020 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10021 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10022 if (TLI.isTypeLegal(StoreTy)) 10023 LastLegalType = i+1; 10024 // Or check whether a truncstore is legal. 10025 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10026 TargetLowering::TypePromoteInteger) { 10027 EVT LegalizedStoredValueTy = 10028 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 10029 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy)) 10030 LastLegalType = i+1; 10031 } 10032 10033 // Find a legal type for the vector store. 10034 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10035 if (TLI.isTypeLegal(Ty)) 10036 LastLegalVectorType = i + 1; 10037 } 10038 10039 // We only use vectors if the constant is known to be zero and the 10040 // function is not marked with the noimplicitfloat attribute. 10041 if (NonZero || NoVectors) 10042 LastLegalVectorType = 0; 10043 10044 // Check if we found a legal integer type to store. 10045 if (LastLegalType == 0 && LastLegalVectorType == 0) 10046 return false; 10047 10048 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 10049 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType; 10050 10051 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10052 true, UseVector); 10053 } 10054 10055 // When extracting multiple vector elements, try to store them 10056 // in one vector store rather than a sequence of scalar stores. 10057 if (IsExtractVecEltSrc) { 10058 unsigned NumElem = 0; 10059 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) { 10060 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10061 SDValue StoredVal = St->getValue(); 10062 // This restriction could be loosened. 10063 // Bail out if any stored values are not elements extracted from a vector. 10064 // It should be possible to handle mixed sources, but load sources need 10065 // more careful handling (see the block of code below that handles 10066 // consecutive loads). 10067 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10068 return false; 10069 10070 // Find a legal type for the vector store. 10071 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10072 if (TLI.isTypeLegal(Ty)) 10073 NumElem = i + 1; 10074 } 10075 10076 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 10077 false, true); 10078 } 10079 10080 // Below we handle the case of multiple consecutive stores that 10081 // come from multiple consecutive loads. We merge them into a single 10082 // wide load and a single wide store. 10083 10084 // Look for load nodes which are used by the stored values. 10085 SmallVector<MemOpLink, 8> LoadNodes; 10086 10087 // Find acceptable loads. Loads need to have the same chain (token factor), 10088 // must not be zext, volatile, indexed, and they must be consecutive. 10089 BaseIndexOffset LdBasePtr; 10090 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) { 10091 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10092 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue()); 10093 if (!Ld) break; 10094 10095 // Loads must only have one use. 10096 if (!Ld->hasNUsesOfValue(1, 0)) 10097 break; 10098 10099 // Check that the alignment is the same as the stores. 10100 if (Ld->getAlignment() != St->getAlignment()) 10101 break; 10102 10103 // The memory operands must not be volatile. 10104 if (Ld->isVolatile() || Ld->isIndexed()) 10105 break; 10106 10107 // We do not accept ext loads. 10108 if (Ld->getExtensionType() != ISD::NON_EXTLOAD) 10109 break; 10110 10111 // The stored memory type must be the same. 10112 if (Ld->getMemoryVT() != MemVT) 10113 break; 10114 10115 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr()); 10116 // If this is not the first ptr that we check. 10117 if (LdBasePtr.Base.getNode()) { 10118 // The base ptr must be the same. 10119 if (!LdPtr.equalBaseIndex(LdBasePtr)) 10120 break; 10121 } else { 10122 // Check that all other base pointers are the same as this one. 10123 LdBasePtr = LdPtr; 10124 } 10125 10126 // We found a potential memory operand to merge. 10127 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0)); 10128 } 10129 10130 if (LoadNodes.size() < 2) 10131 return false; 10132 10133 // If we have load/store pair instructions and we only have two values, 10134 // don't bother. 10135 unsigned RequiredAlignment; 10136 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) && 10137 St->getAlignment() >= RequiredAlignment) 10138 return false; 10139 10140 // Scan the memory operations on the chain and find the first non-consecutive 10141 // load memory address. These variables hold the index in the store node 10142 // array. 10143 unsigned LastConsecutiveLoad = 0; 10144 // This variable refers to the size and not index in the array. 10145 unsigned LastLegalVectorType = 0; 10146 unsigned LastLegalIntegerType = 0; 10147 StartAddress = LoadNodes[0].OffsetFromBase; 10148 SDValue FirstChain = LoadNodes[0].MemNode->getChain(); 10149 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 10150 // All loads much share the same chain. 10151 if (LoadNodes[i].MemNode->getChain() != FirstChain) 10152 break; 10153 10154 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 10155 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 10156 break; 10157 LastConsecutiveLoad = i; 10158 10159 // Find a legal type for the vector store. 10160 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1); 10161 if (TLI.isTypeLegal(StoreTy)) 10162 LastLegalVectorType = i + 1; 10163 10164 // Find a legal type for the integer store. 10165 unsigned StoreBW = (i+1) * ElementSizeBytes * 8; 10166 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10167 if (TLI.isTypeLegal(StoreTy)) 10168 LastLegalIntegerType = i + 1; 10169 // Or check whether a truncstore and extload is legal. 10170 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) == 10171 TargetLowering::TypePromoteInteger) { 10172 EVT LegalizedStoredValueTy = 10173 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy); 10174 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) && 10175 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10176 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) && 10177 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy)) 10178 LastLegalIntegerType = i+1; 10179 } 10180 } 10181 10182 // Only use vector types if the vector type is larger than the integer type. 10183 // If they are the same, use integers. 10184 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors; 10185 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType); 10186 10187 // We add +1 here because the LastXXX variables refer to location while 10188 // the NumElem refers to array/index size. 10189 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1; 10190 NumElem = std::min(LastLegalType, NumElem); 10191 10192 if (NumElem < 2) 10193 return false; 10194 10195 // The earliest Node in the DAG. 10196 unsigned EarliestNodeUsed = 0; 10197 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode; 10198 for (unsigned i=1; i<NumElem; ++i) { 10199 // Find a chain for the new wide-store operand. Notice that some 10200 // of the store nodes that we found may not be selected for inclusion 10201 // in the wide store. The chain we use needs to be the chain of the 10202 // earliest store node which is *used* and replaced by the wide store. 10203 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum) 10204 EarliestNodeUsed = i; 10205 } 10206 10207 // Find if it is better to use vectors or integers to load and store 10208 // to memory. 10209 EVT JointMemOpVT; 10210 if (UseVectorTy) { 10211 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem); 10212 } else { 10213 unsigned StoreBW = NumElem * ElementSizeBytes * 8; 10214 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW); 10215 } 10216 10217 SDLoc LoadDL(LoadNodes[0].MemNode); 10218 SDLoc StoreDL(StoreNodes[0].MemNode); 10219 10220 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 10221 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, 10222 FirstLoad->getChain(), 10223 FirstLoad->getBasePtr(), 10224 FirstLoad->getPointerInfo(), 10225 false, false, false, 10226 FirstLoad->getAlignment()); 10227 10228 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad, 10229 FirstInChain->getBasePtr(), 10230 FirstInChain->getPointerInfo(), false, false, 10231 FirstInChain->getAlignment()); 10232 10233 // Replace one of the loads with the new load. 10234 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode); 10235 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 10236 SDValue(NewLoad.getNode(), 1)); 10237 10238 // Remove the rest of the load chains. 10239 for (unsigned i = 1; i < NumElem ; ++i) { 10240 // Replace all chain users of the old load nodes with the chain of the new 10241 // load node. 10242 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 10243 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain()); 10244 } 10245 10246 // Replace the first store with the new store. 10247 CombineTo(EarliestOp, NewStore); 10248 // Erase all other stores. 10249 for (unsigned i = 0; i < NumElem ; ++i) { 10250 // Remove all Store nodes. 10251 if (StoreNodes[i].MemNode == EarliestOp) 10252 continue; 10253 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 10254 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain()); 10255 deleteAndRecombine(St); 10256 } 10257 10258 return true; 10259 } 10260 10261 SDValue DAGCombiner::visitSTORE(SDNode *N) { 10262 StoreSDNode *ST = cast<StoreSDNode>(N); 10263 SDValue Chain = ST->getChain(); 10264 SDValue Value = ST->getValue(); 10265 SDValue Ptr = ST->getBasePtr(); 10266 10267 // If this is a store of a bit convert, store the input value if the 10268 // resultant store does not need a higher alignment than the original. 10269 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 10270 ST->isUnindexed()) { 10271 unsigned OrigAlign = ST->getAlignment(); 10272 EVT SVT = Value.getOperand(0).getValueType(); 10273 unsigned Align = TLI.getDataLayout()-> 10274 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext())); 10275 if (Align <= OrigAlign && 10276 ((!LegalOperations && !ST->isVolatile()) || 10277 TLI.isOperationLegalOrCustom(ISD::STORE, SVT))) 10278 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), 10279 Ptr, ST->getPointerInfo(), ST->isVolatile(), 10280 ST->isNonTemporal(), OrigAlign, 10281 ST->getAAInfo()); 10282 } 10283 10284 // Turn 'store undef, Ptr' -> nothing. 10285 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed()) 10286 return Chain; 10287 10288 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 10289 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) { 10290 // NOTE: If the original store is volatile, this transform must not increase 10291 // the number of stores. For example, on x86-32 an f64 can be stored in one 10292 // processor operation but an i64 (which is not legal) requires two. So the 10293 // transform should not be done in this case. 10294 if (Value.getOpcode() != ISD::TargetConstantFP) { 10295 SDValue Tmp; 10296 switch (CFP->getSimpleValueType(0).SimpleTy) { 10297 default: llvm_unreachable("Unknown FP type"); 10298 case MVT::f16: // We don't do this for these yet. 10299 case MVT::f80: 10300 case MVT::f128: 10301 case MVT::ppcf128: 10302 break; 10303 case MVT::f32: 10304 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 10305 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 10306 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 10307 bitcastToAPInt().getZExtValue(), MVT::i32); 10308 return DAG.getStore(Chain, SDLoc(N), Tmp, 10309 Ptr, ST->getMemOperand()); 10310 } 10311 break; 10312 case MVT::f64: 10313 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 10314 !ST->isVolatile()) || 10315 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 10316 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 10317 getZExtValue(), MVT::i64); 10318 return DAG.getStore(Chain, SDLoc(N), Tmp, 10319 Ptr, ST->getMemOperand()); 10320 } 10321 10322 if (!ST->isVolatile() && 10323 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 10324 // Many FP stores are not made apparent until after legalize, e.g. for 10325 // argument passing. Since this is so common, custom legalize the 10326 // 64-bit integer store into two 32-bit stores. 10327 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 10328 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32); 10329 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32); 10330 if (TLI.isBigEndian()) std::swap(Lo, Hi); 10331 10332 unsigned Alignment = ST->getAlignment(); 10333 bool isVolatile = ST->isVolatile(); 10334 bool isNonTemporal = ST->isNonTemporal(); 10335 AAMDNodes AAInfo = ST->getAAInfo(); 10336 10337 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo, 10338 Ptr, ST->getPointerInfo(), 10339 isVolatile, isNonTemporal, 10340 ST->getAlignment(), AAInfo); 10341 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr, 10342 DAG.getConstant(4, Ptr.getValueType())); 10343 Alignment = MinAlign(Alignment, 4U); 10344 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi, 10345 Ptr, ST->getPointerInfo().getWithOffset(4), 10346 isVolatile, isNonTemporal, 10347 Alignment, AAInfo); 10348 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, 10349 St0, St1); 10350 } 10351 10352 break; 10353 } 10354 } 10355 } 10356 10357 // Try to infer better alignment information than the store already has. 10358 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 10359 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 10360 if (Align > ST->getAlignment()) 10361 return DAG.getTruncStore(Chain, SDLoc(N), Value, 10362 Ptr, ST->getPointerInfo(), ST->getMemoryVT(), 10363 ST->isVolatile(), ST->isNonTemporal(), Align, 10364 ST->getAAInfo()); 10365 } 10366 } 10367 10368 // Try transforming a pair floating point load / store ops to integer 10369 // load / store ops. 10370 SDValue NewST = TransformFPLoadStorePair(N); 10371 if (NewST.getNode()) 10372 return NewST; 10373 10374 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA 10375 : DAG.getSubtarget().useAA(); 10376 #ifndef NDEBUG 10377 if (CombinerAAOnlyFunc.getNumOccurrences() && 10378 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 10379 UseAA = false; 10380 #endif 10381 if (UseAA && ST->isUnindexed()) { 10382 // Walk up chain skipping non-aliasing memory nodes. 10383 SDValue BetterChain = FindBetterChain(N, Chain); 10384 10385 // If there is a better chain. 10386 if (Chain != BetterChain) { 10387 SDValue ReplStore; 10388 10389 // Replace the chain to avoid dependency. 10390 if (ST->isTruncatingStore()) { 10391 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr, 10392 ST->getMemoryVT(), ST->getMemOperand()); 10393 } else { 10394 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr, 10395 ST->getMemOperand()); 10396 } 10397 10398 // Create token to keep both nodes around. 10399 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 10400 MVT::Other, Chain, ReplStore); 10401 10402 // Make sure the new and old chains are cleaned up. 10403 AddToWorklist(Token.getNode()); 10404 10405 // Don't add users to work list. 10406 return CombineTo(N, Token, false); 10407 } 10408 } 10409 10410 // Try transforming N to an indexed store. 10411 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10412 return SDValue(N, 0); 10413 10414 // FIXME: is there such a thing as a truncating indexed store? 10415 if (ST->isTruncatingStore() && ST->isUnindexed() && 10416 Value.getValueType().isInteger()) { 10417 // See if we can simplify the input to this truncstore with knowledge that 10418 // only the low bits are being used. For example: 10419 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 10420 SDValue Shorter = 10421 GetDemandedBits(Value, 10422 APInt::getLowBitsSet( 10423 Value.getValueType().getScalarType().getSizeInBits(), 10424 ST->getMemoryVT().getScalarType().getSizeInBits())); 10425 AddToWorklist(Value.getNode()); 10426 if (Shorter.getNode()) 10427 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, 10428 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 10429 10430 // Otherwise, see if we can simplify the operation with 10431 // SimplifyDemandedBits, which only works if the value has a single use. 10432 if (SimplifyDemandedBits(Value, 10433 APInt::getLowBitsSet( 10434 Value.getValueType().getScalarType().getSizeInBits(), 10435 ST->getMemoryVT().getScalarType().getSizeInBits()))) 10436 return SDValue(N, 0); 10437 } 10438 10439 // If this is a load followed by a store to the same location, then the store 10440 // is dead/noop. 10441 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 10442 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 10443 ST->isUnindexed() && !ST->isVolatile() && 10444 // There can't be any side effects between the load and store, such as 10445 // a call or store. 10446 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 10447 // The store is dead, remove it. 10448 return Chain; 10449 } 10450 } 10451 10452 // If this is a store followed by a store with the same value to the same 10453 // location, then the store is dead/noop. 10454 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 10455 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() && 10456 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() && 10457 ST1->isUnindexed() && !ST1->isVolatile()) { 10458 // The store is dead, remove it. 10459 return Chain; 10460 } 10461 } 10462 10463 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 10464 // truncating store. We can do this even if this is already a truncstore. 10465 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 10466 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 10467 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 10468 ST->getMemoryVT())) { 10469 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 10470 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 10471 } 10472 10473 // Only perform this optimization before the types are legal, because we 10474 // don't want to perform this optimization on every DAGCombine invocation. 10475 if (!LegalTypes) { 10476 bool EverChanged = false; 10477 10478 do { 10479 // There can be multiple store sequences on the same chain. 10480 // Keep trying to merge store sequences until we are unable to do so 10481 // or until we merge the last store on the chain. 10482 bool Changed = MergeConsecutiveStores(ST); 10483 EverChanged |= Changed; 10484 if (!Changed) break; 10485 } while (ST->getOpcode() != ISD::DELETED_NODE); 10486 10487 if (EverChanged) 10488 return SDValue(N, 0); 10489 } 10490 10491 return ReduceLoadOpStoreWidth(N); 10492 } 10493 10494 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 10495 SDValue InVec = N->getOperand(0); 10496 SDValue InVal = N->getOperand(1); 10497 SDValue EltNo = N->getOperand(2); 10498 SDLoc dl(N); 10499 10500 // If the inserted element is an UNDEF, just use the input vector. 10501 if (InVal.getOpcode() == ISD::UNDEF) 10502 return InVec; 10503 10504 EVT VT = InVec.getValueType(); 10505 10506 // If we can't generate a legal BUILD_VECTOR, exit 10507 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 10508 return SDValue(); 10509 10510 // Check that we know which element is being inserted 10511 if (!isa<ConstantSDNode>(EltNo)) 10512 return SDValue(); 10513 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 10514 10515 // Canonicalize insert_vector_elt dag nodes. 10516 // Example: 10517 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 10518 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 10519 // 10520 // Do this only if the child insert_vector node has one use; also 10521 // do this only if indices are both constants and Idx1 < Idx0. 10522 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 10523 && isa<ConstantSDNode>(InVec.getOperand(2))) { 10524 unsigned OtherElt = 10525 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue(); 10526 if (Elt < OtherElt) { 10527 // Swap nodes. 10528 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT, 10529 InVec.getOperand(0), InVal, EltNo); 10530 AddToWorklist(NewOp.getNode()); 10531 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 10532 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 10533 } 10534 } 10535 10536 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 10537 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 10538 // vector elements. 10539 SmallVector<SDValue, 8> Ops; 10540 // Do not combine these two vectors if the output vector will not replace 10541 // the input vector. 10542 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 10543 Ops.append(InVec.getNode()->op_begin(), 10544 InVec.getNode()->op_end()); 10545 } else if (InVec.getOpcode() == ISD::UNDEF) { 10546 unsigned NElts = VT.getVectorNumElements(); 10547 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType())); 10548 } else { 10549 return SDValue(); 10550 } 10551 10552 // Insert the element 10553 if (Elt < Ops.size()) { 10554 // All the operands of BUILD_VECTOR must have the same type; 10555 // we enforce that here. 10556 EVT OpVT = Ops[0].getValueType(); 10557 if (InVal.getValueType() != OpVT) 10558 InVal = OpVT.bitsGT(InVal.getValueType()) ? 10559 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) : 10560 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal); 10561 Ops[Elt] = InVal; 10562 } 10563 10564 // Return the new vector 10565 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops); 10566 } 10567 10568 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad( 10569 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) { 10570 EVT ResultVT = EVE->getValueType(0); 10571 EVT VecEltVT = InVecVT.getVectorElementType(); 10572 unsigned Align = OriginalLoad->getAlignment(); 10573 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment( 10574 VecEltVT.getTypeForEVT(*DAG.getContext())); 10575 10576 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 10577 return SDValue(); 10578 10579 Align = NewAlign; 10580 10581 SDValue NewPtr = OriginalLoad->getBasePtr(); 10582 SDValue Offset; 10583 EVT PtrType = NewPtr.getValueType(); 10584 MachinePointerInfo MPI; 10585 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 10586 int Elt = ConstEltNo->getZExtValue(); 10587 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 10588 if (TLI.isBigEndian()) 10589 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff; 10590 Offset = DAG.getConstant(PtrOff, PtrType); 10591 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 10592 } else { 10593 Offset = DAG.getNode( 10594 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo, 10595 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType())); 10596 if (TLI.isBigEndian()) 10597 Offset = DAG.getNode( 10598 ISD::SUB, SDLoc(EVE), EltNo.getValueType(), 10599 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset); 10600 MPI = OriginalLoad->getPointerInfo(); 10601 } 10602 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset); 10603 10604 // The replacement we need to do here is a little tricky: we need to 10605 // replace an extractelement of a load with a load. 10606 // Use ReplaceAllUsesOfValuesWith to do the replacement. 10607 // Note that this replacement assumes that the extractvalue is the only 10608 // use of the load; that's okay because we don't want to perform this 10609 // transformation in other cases anyway. 10610 SDValue Load; 10611 SDValue Chain; 10612 if (ResultVT.bitsGT(VecEltVT)) { 10613 // If the result type of vextract is wider than the load, then issue an 10614 // extending load instead. 10615 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 10616 VecEltVT) 10617 ? ISD::ZEXTLOAD 10618 : ISD::EXTLOAD; 10619 Load = DAG.getExtLoad( 10620 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI, 10621 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 10622 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 10623 Chain = Load.getValue(1); 10624 } else { 10625 Load = DAG.getLoad( 10626 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, 10627 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(), 10628 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo()); 10629 Chain = Load.getValue(1); 10630 if (ResultVT.bitsLT(VecEltVT)) 10631 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 10632 else 10633 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load); 10634 } 10635 WorklistRemover DeadNodes(*this); 10636 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 10637 SDValue To[] = { Load, Chain }; 10638 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 10639 // Since we're explicitly calling ReplaceAllUses, add the new node to the 10640 // worklist explicitly as well. 10641 AddToWorklist(Load.getNode()); 10642 AddUsersToWorklist(Load.getNode()); // Add users too 10643 // Make sure to revisit this node to clean it up; it will usually be dead. 10644 AddToWorklist(EVE); 10645 ++OpsNarrowed; 10646 return SDValue(EVE, 0); 10647 } 10648 10649 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 10650 // (vextract (scalar_to_vector val, 0) -> val 10651 SDValue InVec = N->getOperand(0); 10652 EVT VT = InVec.getValueType(); 10653 EVT NVT = N->getValueType(0); 10654 10655 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) { 10656 // Check if the result type doesn't match the inserted element type. A 10657 // SCALAR_TO_VECTOR may truncate the inserted element and the 10658 // EXTRACT_VECTOR_ELT may widen the extracted vector. 10659 SDValue InOp = InVec.getOperand(0); 10660 if (InOp.getValueType() != NVT) { 10661 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 10662 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT); 10663 } 10664 return InOp; 10665 } 10666 10667 SDValue EltNo = N->getOperand(1); 10668 bool ConstEltNo = isa<ConstantSDNode>(EltNo); 10669 10670 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 10671 // We only perform this optimization before the op legalization phase because 10672 // we may introduce new vector instructions which are not backed by TD 10673 // patterns. For example on AVX, extracting elements from a wide vector 10674 // without using extract_subvector. However, if we can find an underlying 10675 // scalar value, then we can always use that. 10676 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE 10677 && ConstEltNo) { 10678 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 10679 int NumElem = VT.getVectorNumElements(); 10680 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec); 10681 // Find the new index to extract from. 10682 int OrigElt = SVOp->getMaskElt(Elt); 10683 10684 // Extracting an undef index is undef. 10685 if (OrigElt == -1) 10686 return DAG.getUNDEF(NVT); 10687 10688 // Select the right vector half to extract from. 10689 SDValue SVInVec; 10690 if (OrigElt < NumElem) { 10691 SVInVec = InVec->getOperand(0); 10692 } else { 10693 SVInVec = InVec->getOperand(1); 10694 OrigElt -= NumElem; 10695 } 10696 10697 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 10698 SDValue InOp = SVInVec.getOperand(OrigElt); 10699 if (InOp.getValueType() != NVT) { 10700 assert(InOp.getValueType().isInteger() && NVT.isInteger()); 10701 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT); 10702 } 10703 10704 return InOp; 10705 } 10706 10707 // FIXME: We should handle recursing on other vector shuffles and 10708 // scalar_to_vector here as well. 10709 10710 if (!LegalOperations) { 10711 EVT IndexTy = TLI.getVectorIdxTy(); 10712 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, 10713 SVInVec, DAG.getConstant(OrigElt, IndexTy)); 10714 } 10715 } 10716 10717 bool BCNumEltsChanged = false; 10718 EVT ExtVT = VT.getVectorElementType(); 10719 EVT LVT = ExtVT; 10720 10721 // If the result of load has to be truncated, then it's not necessarily 10722 // profitable. 10723 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT)) 10724 return SDValue(); 10725 10726 if (InVec.getOpcode() == ISD::BITCAST) { 10727 // Don't duplicate a load with other uses. 10728 if (!InVec.hasOneUse()) 10729 return SDValue(); 10730 10731 EVT BCVT = InVec.getOperand(0).getValueType(); 10732 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 10733 return SDValue(); 10734 if (VT.getVectorNumElements() != BCVT.getVectorNumElements()) 10735 BCNumEltsChanged = true; 10736 InVec = InVec.getOperand(0); 10737 ExtVT = BCVT.getVectorElementType(); 10738 } 10739 10740 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size) 10741 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() && 10742 ISD::isNormalLoad(InVec.getNode()) && 10743 !N->getOperand(1)->hasPredecessor(InVec.getNode())) { 10744 SDValue Index = N->getOperand(1); 10745 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) 10746 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index, 10747 OrigLoad); 10748 } 10749 10750 // Perform only after legalization to ensure build_vector / vector_shuffle 10751 // optimizations have already been done. 10752 if (!LegalOperations) return SDValue(); 10753 10754 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 10755 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 10756 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 10757 10758 if (ConstEltNo) { 10759 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 10760 10761 LoadSDNode *LN0 = nullptr; 10762 const ShuffleVectorSDNode *SVN = nullptr; 10763 if (ISD::isNormalLoad(InVec.getNode())) { 10764 LN0 = cast<LoadSDNode>(InVec); 10765 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR && 10766 InVec.getOperand(0).getValueType() == ExtVT && 10767 ISD::isNormalLoad(InVec.getOperand(0).getNode())) { 10768 // Don't duplicate a load with other uses. 10769 if (!InVec.hasOneUse()) 10770 return SDValue(); 10771 10772 LN0 = cast<LoadSDNode>(InVec.getOperand(0)); 10773 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) { 10774 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 10775 // => 10776 // (load $addr+1*size) 10777 10778 // Don't duplicate a load with other uses. 10779 if (!InVec.hasOneUse()) 10780 return SDValue(); 10781 10782 // If the bit convert changed the number of elements, it is unsafe 10783 // to examine the mask. 10784 if (BCNumEltsChanged) 10785 return SDValue(); 10786 10787 // Select the input vector, guarding against out of range extract vector. 10788 unsigned NumElems = VT.getVectorNumElements(); 10789 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt); 10790 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1); 10791 10792 if (InVec.getOpcode() == ISD::BITCAST) { 10793 // Don't duplicate a load with other uses. 10794 if (!InVec.hasOneUse()) 10795 return SDValue(); 10796 10797 InVec = InVec.getOperand(0); 10798 } 10799 if (ISD::isNormalLoad(InVec.getNode())) { 10800 LN0 = cast<LoadSDNode>(InVec); 10801 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems; 10802 EltNo = DAG.getConstant(Elt, EltNo.getValueType()); 10803 } 10804 } 10805 10806 // Make sure we found a non-volatile load and the extractelement is 10807 // the only use. 10808 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 10809 return SDValue(); 10810 10811 // If Idx was -1 above, Elt is going to be -1, so just return undef. 10812 if (Elt == -1) 10813 return DAG.getUNDEF(LVT); 10814 10815 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0); 10816 } 10817 10818 return SDValue(); 10819 } 10820 10821 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 10822 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 10823 // We perform this optimization post type-legalization because 10824 // the type-legalizer often scalarizes integer-promoted vectors. 10825 // Performing this optimization before may create bit-casts which 10826 // will be type-legalized to complex code sequences. 10827 // We perform this optimization only before the operation legalizer because we 10828 // may introduce illegal operations. 10829 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 10830 return SDValue(); 10831 10832 unsigned NumInScalars = N->getNumOperands(); 10833 SDLoc dl(N); 10834 EVT VT = N->getValueType(0); 10835 10836 // Check to see if this is a BUILD_VECTOR of a bunch of values 10837 // which come from any_extend or zero_extend nodes. If so, we can create 10838 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 10839 // optimizations. We do not handle sign-extend because we can't fill the sign 10840 // using shuffles. 10841 EVT SourceType = MVT::Other; 10842 bool AllAnyExt = true; 10843 10844 for (unsigned i = 0; i != NumInScalars; ++i) { 10845 SDValue In = N->getOperand(i); 10846 // Ignore undef inputs. 10847 if (In.getOpcode() == ISD::UNDEF) continue; 10848 10849 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 10850 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 10851 10852 // Abort if the element is not an extension. 10853 if (!ZeroExt && !AnyExt) { 10854 SourceType = MVT::Other; 10855 break; 10856 } 10857 10858 // The input is a ZeroExt or AnyExt. Check the original type. 10859 EVT InTy = In.getOperand(0).getValueType(); 10860 10861 // Check that all of the widened source types are the same. 10862 if (SourceType == MVT::Other) 10863 // First time. 10864 SourceType = InTy; 10865 else if (InTy != SourceType) { 10866 // Multiple income types. Abort. 10867 SourceType = MVT::Other; 10868 break; 10869 } 10870 10871 // Check if all of the extends are ANY_EXTENDs. 10872 AllAnyExt &= AnyExt; 10873 } 10874 10875 // In order to have valid types, all of the inputs must be extended from the 10876 // same source type and all of the inputs must be any or zero extend. 10877 // Scalar sizes must be a power of two. 10878 EVT OutScalarTy = VT.getScalarType(); 10879 bool ValidTypes = SourceType != MVT::Other && 10880 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 10881 isPowerOf2_32(SourceType.getSizeInBits()); 10882 10883 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 10884 // turn into a single shuffle instruction. 10885 if (!ValidTypes) 10886 return SDValue(); 10887 10888 bool isLE = TLI.isLittleEndian(); 10889 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 10890 assert(ElemRatio > 1 && "Invalid element size ratio"); 10891 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 10892 DAG.getConstant(0, SourceType); 10893 10894 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 10895 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 10896 10897 // Populate the new build_vector 10898 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 10899 SDValue Cast = N->getOperand(i); 10900 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 10901 Cast.getOpcode() == ISD::ZERO_EXTEND || 10902 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode"); 10903 SDValue In; 10904 if (Cast.getOpcode() == ISD::UNDEF) 10905 In = DAG.getUNDEF(SourceType); 10906 else 10907 In = Cast->getOperand(0); 10908 unsigned Index = isLE ? (i * ElemRatio) : 10909 (i * ElemRatio + (ElemRatio - 1)); 10910 10911 assert(Index < Ops.size() && "Invalid index"); 10912 Ops[Index] = In; 10913 } 10914 10915 // The type of the new BUILD_VECTOR node. 10916 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 10917 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 10918 "Invalid vector size"); 10919 // Check if the new vector type is legal. 10920 if (!isTypeLegal(VecVT)) return SDValue(); 10921 10922 // Make the new BUILD_VECTOR. 10923 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops); 10924 10925 // The new BUILD_VECTOR node has the potential to be further optimized. 10926 AddToWorklist(BV.getNode()); 10927 // Bitcast to the desired type. 10928 return DAG.getNode(ISD::BITCAST, dl, VT, BV); 10929 } 10930 10931 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) { 10932 EVT VT = N->getValueType(0); 10933 10934 unsigned NumInScalars = N->getNumOperands(); 10935 SDLoc dl(N); 10936 10937 EVT SrcVT = MVT::Other; 10938 unsigned Opcode = ISD::DELETED_NODE; 10939 unsigned NumDefs = 0; 10940 10941 for (unsigned i = 0; i != NumInScalars; ++i) { 10942 SDValue In = N->getOperand(i); 10943 unsigned Opc = In.getOpcode(); 10944 10945 if (Opc == ISD::UNDEF) 10946 continue; 10947 10948 // If all scalar values are floats and converted from integers. 10949 if (Opcode == ISD::DELETED_NODE && 10950 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) { 10951 Opcode = Opc; 10952 } 10953 10954 if (Opc != Opcode) 10955 return SDValue(); 10956 10957 EVT InVT = In.getOperand(0).getValueType(); 10958 10959 // If all scalar values are typed differently, bail out. It's chosen to 10960 // simplify BUILD_VECTOR of integer types. 10961 if (SrcVT == MVT::Other) 10962 SrcVT = InVT; 10963 if (SrcVT != InVT) 10964 return SDValue(); 10965 NumDefs++; 10966 } 10967 10968 // If the vector has just one element defined, it's not worth to fold it into 10969 // a vectorized one. 10970 if (NumDefs < 2) 10971 return SDValue(); 10972 10973 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP) 10974 && "Should only handle conversion from integer to float."); 10975 assert(SrcVT != MVT::Other && "Cannot determine source type!"); 10976 10977 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars); 10978 10979 if (!TLI.isOperationLegalOrCustom(Opcode, NVT)) 10980 return SDValue(); 10981 10982 SmallVector<SDValue, 8> Opnds; 10983 for (unsigned i = 0; i != NumInScalars; ++i) { 10984 SDValue In = N->getOperand(i); 10985 10986 if (In.getOpcode() == ISD::UNDEF) 10987 Opnds.push_back(DAG.getUNDEF(SrcVT)); 10988 else 10989 Opnds.push_back(In.getOperand(0)); 10990 } 10991 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds); 10992 AddToWorklist(BV.getNode()); 10993 10994 return DAG.getNode(Opcode, dl, VT, BV); 10995 } 10996 10997 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 10998 unsigned NumInScalars = N->getNumOperands(); 10999 SDLoc dl(N); 11000 EVT VT = N->getValueType(0); 11001 11002 // A vector built entirely of undefs is undef. 11003 if (ISD::allOperandsUndef(N)) 11004 return DAG.getUNDEF(VT); 11005 11006 SDValue V = reduceBuildVecExtToExtBuildVec(N); 11007 if (V.getNode()) 11008 return V; 11009 11010 V = reduceBuildVecConvertToConvertBuildVec(N); 11011 if (V.getNode()) 11012 return V; 11013 11014 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 11015 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from 11016 // at most two distinct vectors, turn this into a shuffle node. 11017 11018 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 11019 if (!isTypeLegal(VT)) 11020 return SDValue(); 11021 11022 // May only combine to shuffle after legalize if shuffle is legal. 11023 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 11024 return SDValue(); 11025 11026 SDValue VecIn1, VecIn2; 11027 bool UsesZeroVector = false; 11028 for (unsigned i = 0; i != NumInScalars; ++i) { 11029 SDValue Op = N->getOperand(i); 11030 // Ignore undef inputs. 11031 if (Op.getOpcode() == ISD::UNDEF) continue; 11032 11033 // See if we can combine this build_vector into a blend with a zero vector. 11034 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant && 11035 cast<ConstantSDNode>(Op.getNode())->isNullValue()) || 11036 (Op.getOpcode() == ISD::ConstantFP && 11037 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) { 11038 UsesZeroVector = true; 11039 continue; 11040 } 11041 11042 // If this input is something other than a EXTRACT_VECTOR_ELT with a 11043 // constant index, bail out. 11044 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11045 !isa<ConstantSDNode>(Op.getOperand(1))) { 11046 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11047 break; 11048 } 11049 11050 // We allow up to two distinct input vectors. 11051 SDValue ExtractedFromVec = Op.getOperand(0); 11052 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2) 11053 continue; 11054 11055 if (!VecIn1.getNode()) { 11056 VecIn1 = ExtractedFromVec; 11057 } else if (!VecIn2.getNode() && !UsesZeroVector) { 11058 VecIn2 = ExtractedFromVec; 11059 } else { 11060 // Too many inputs. 11061 VecIn1 = VecIn2 = SDValue(nullptr, 0); 11062 break; 11063 } 11064 } 11065 11066 // If everything is good, we can make a shuffle operation. 11067 if (VecIn1.getNode()) { 11068 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements(); 11069 SmallVector<int, 8> Mask; 11070 for (unsigned i = 0; i != NumInScalars; ++i) { 11071 unsigned Opcode = N->getOperand(i).getOpcode(); 11072 if (Opcode == ISD::UNDEF) { 11073 Mask.push_back(-1); 11074 continue; 11075 } 11076 11077 // Operands can also be zero. 11078 if (Opcode != ISD::EXTRACT_VECTOR_ELT) { 11079 assert(UsesZeroVector && 11080 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) && 11081 "Unexpected node found!"); 11082 Mask.push_back(NumInScalars+i); 11083 continue; 11084 } 11085 11086 // If extracting from the first vector, just use the index directly. 11087 SDValue Extract = N->getOperand(i); 11088 SDValue ExtVal = Extract.getOperand(1); 11089 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue(); 11090 if (Extract.getOperand(0) == VecIn1) { 11091 Mask.push_back(ExtIndex); 11092 continue; 11093 } 11094 11095 // Otherwise, use InIdx + InputVecSize 11096 Mask.push_back(InNumElements + ExtIndex); 11097 } 11098 11099 // Avoid introducing illegal shuffles with zero. 11100 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT)) 11101 return SDValue(); 11102 11103 // We can't generate a shuffle node with mismatched input and output types. 11104 // Attempt to transform a single input vector to the correct type. 11105 if ((VT != VecIn1.getValueType())) { 11106 // If the input vector type has a different base type to the output 11107 // vector type, bail out. 11108 EVT VTElemType = VT.getVectorElementType(); 11109 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) || 11110 (VecIn2.getNode() && 11111 (VecIn2.getValueType().getVectorElementType() != VTElemType))) 11112 return SDValue(); 11113 11114 // If the input vector is too small, widen it. 11115 // We only support widening of vectors which are half the size of the 11116 // output registers. For example XMM->YMM widening on X86 with AVX. 11117 EVT VecInT = VecIn1.getValueType(); 11118 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) { 11119 // If we only have one small input, widen it by adding undef values. 11120 if (!VecIn2.getNode()) 11121 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, 11122 DAG.getUNDEF(VecIn1.getValueType())); 11123 else if (VecIn1.getValueType() == VecIn2.getValueType()) { 11124 // If we have two small inputs of the same type, try to concat them. 11125 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2); 11126 VecIn2 = SDValue(nullptr, 0); 11127 } else 11128 return SDValue(); 11129 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) { 11130 // If the input vector is too large, try to split it. 11131 // We don't support having two input vectors that are too large. 11132 if (VecIn2.getNode()) 11133 return SDValue(); 11134 11135 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements())) 11136 return SDValue(); 11137 11138 // Try to replace VecIn1 with two extract_subvectors 11139 // No need to update the masks, they should still be correct. 11140 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11141 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy())); 11142 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 11143 DAG.getConstant(0, TLI.getVectorIdxTy())); 11144 UsesZeroVector = false; 11145 } else 11146 return SDValue(); 11147 } 11148 11149 if (UsesZeroVector) 11150 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) : 11151 DAG.getConstantFP(0.0, VT); 11152 else 11153 // If VecIn2 is unused then change it to undef. 11154 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT); 11155 11156 // Check that we were able to transform all incoming values to the same 11157 // type. 11158 if (VecIn2.getValueType() != VecIn1.getValueType() || 11159 VecIn1.getValueType() != VT) 11160 return SDValue(); 11161 11162 // Return the new VECTOR_SHUFFLE node. 11163 SDValue Ops[2]; 11164 Ops[0] = VecIn1; 11165 Ops[1] = VecIn2; 11166 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]); 11167 } 11168 11169 return SDValue(); 11170 } 11171 11172 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 11173 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of 11174 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector 11175 // inputs come from at most two distinct vectors, turn this into a shuffle 11176 // node. 11177 11178 // If we only have one input vector, we don't need to do any concatenation. 11179 if (N->getNumOperands() == 1) 11180 return N->getOperand(0); 11181 11182 // Check if all of the operands are undefs. 11183 EVT VT = N->getValueType(0); 11184 if (ISD::allOperandsUndef(N)) 11185 return DAG.getUNDEF(VT); 11186 11187 // Optimize concat_vectors where one of the vectors is undef. 11188 if (N->getNumOperands() == 2 && 11189 N->getOperand(1)->getOpcode() == ISD::UNDEF) { 11190 SDValue In = N->getOperand(0); 11191 assert(In.getValueType().isVector() && "Must concat vectors"); 11192 11193 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr). 11194 if (In->getOpcode() == ISD::BITCAST && 11195 !In->getOperand(0)->getValueType(0).isVector()) { 11196 SDValue Scalar = In->getOperand(0); 11197 EVT SclTy = Scalar->getValueType(0); 11198 11199 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 11200 return SDValue(); 11201 11202 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, 11203 VT.getSizeInBits() / SclTy.getSizeInBits()); 11204 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 11205 return SDValue(); 11206 11207 SDLoc dl = SDLoc(N); 11208 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar); 11209 return DAG.getNode(ISD::BITCAST, dl, VT, Res); 11210 } 11211 } 11212 11213 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 11214 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 11215 if (N->getNumOperands() == 2 && 11216 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 11217 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) { 11218 EVT VT = N->getValueType(0); 11219 SDValue N0 = N->getOperand(0); 11220 SDValue N1 = N->getOperand(1); 11221 SmallVector<SDValue, 8> Opnds; 11222 unsigned BuildVecNumElts = N0.getNumOperands(); 11223 11224 EVT SclTy0 = N0.getOperand(0)->getValueType(0); 11225 EVT SclTy1 = N1.getOperand(0)->getValueType(0); 11226 if (SclTy0.isFloatingPoint()) { 11227 for (unsigned i = 0; i != BuildVecNumElts; ++i) 11228 Opnds.push_back(N0.getOperand(i)); 11229 for (unsigned i = 0; i != BuildVecNumElts; ++i) 11230 Opnds.push_back(N1.getOperand(i)); 11231 } else { 11232 // If BUILD_VECTOR are from built from integer, they may have different 11233 // operand types. Get the smaller type and truncate all operands to it. 11234 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1; 11235 for (unsigned i = 0; i != BuildVecNumElts; ++i) 11236 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy, 11237 N0.getOperand(i))); 11238 for (unsigned i = 0; i != BuildVecNumElts; ++i) 11239 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy, 11240 N1.getOperand(i))); 11241 } 11242 11243 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds); 11244 } 11245 11246 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 11247 // nodes often generate nop CONCAT_VECTOR nodes. 11248 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 11249 // place the incoming vectors at the exact same location. 11250 SDValue SingleSource = SDValue(); 11251 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 11252 11253 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 11254 SDValue Op = N->getOperand(i); 11255 11256 if (Op.getOpcode() == ISD::UNDEF) 11257 continue; 11258 11259 // Check if this is the identity extract: 11260 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 11261 return SDValue(); 11262 11263 // Find the single incoming vector for the extract_subvector. 11264 if (SingleSource.getNode()) { 11265 if (Op.getOperand(0) != SingleSource) 11266 return SDValue(); 11267 } else { 11268 SingleSource = Op.getOperand(0); 11269 11270 // Check the source type is the same as the type of the result. 11271 // If not, this concat may extend the vector, so we can not 11272 // optimize it away. 11273 if (SingleSource.getValueType() != N->getValueType(0)) 11274 return SDValue(); 11275 } 11276 11277 unsigned IdentityIndex = i * PartNumElem; 11278 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 11279 // The extract index must be constant. 11280 if (!CS) 11281 return SDValue(); 11282 11283 // Check that we are reading from the identity index. 11284 if (CS->getZExtValue() != IdentityIndex) 11285 return SDValue(); 11286 } 11287 11288 if (SingleSource.getNode()) 11289 return SingleSource; 11290 11291 return SDValue(); 11292 } 11293 11294 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 11295 EVT NVT = N->getValueType(0); 11296 SDValue V = N->getOperand(0); 11297 11298 if (V->getOpcode() == ISD::CONCAT_VECTORS) { 11299 // Combine: 11300 // (extract_subvec (concat V1, V2, ...), i) 11301 // Into: 11302 // Vi if possible 11303 // Only operand 0 is checked as 'concat' assumes all inputs of the same 11304 // type. 11305 if (V->getOperand(0).getValueType() != NVT) 11306 return SDValue(); 11307 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11308 unsigned NumElems = NVT.getVectorNumElements(); 11309 assert((Idx % NumElems) == 0 && 11310 "IDX in concat is not a multiple of the result vector length."); 11311 return V->getOperand(Idx / NumElems); 11312 } 11313 11314 // Skip bitcasting 11315 if (V->getOpcode() == ISD::BITCAST) 11316 V = V.getOperand(0); 11317 11318 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) { 11319 SDLoc dl(N); 11320 // Handle only simple case where vector being inserted and vector 11321 // being extracted are of same type, and are half size of larger vectors. 11322 EVT BigVT = V->getOperand(0).getValueType(); 11323 EVT SmallVT = V->getOperand(1).getValueType(); 11324 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits()) 11325 return SDValue(); 11326 11327 // Only handle cases where both indexes are constants with the same type. 11328 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11329 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2)); 11330 11331 if (InsIdx && ExtIdx && 11332 InsIdx->getValueType(0).getSizeInBits() <= 64 && 11333 ExtIdx->getValueType(0).getSizeInBits() <= 64) { 11334 // Combine: 11335 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 11336 // Into: 11337 // indices are equal or bit offsets are equal => V1 11338 // otherwise => (extract_subvec V1, ExtIdx) 11339 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() == 11340 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits()) 11341 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1)); 11342 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, 11343 DAG.getNode(ISD::BITCAST, dl, 11344 N->getOperand(0).getValueType(), 11345 V->getOperand(0)), N->getOperand(1)); 11346 } 11347 } 11348 11349 return SDValue(); 11350 } 11351 11352 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements, 11353 SDValue V, SelectionDAG &DAG) { 11354 SDLoc DL(V); 11355 EVT VT = V.getValueType(); 11356 11357 switch (V.getOpcode()) { 11358 default: 11359 return V; 11360 11361 case ISD::CONCAT_VECTORS: { 11362 EVT OpVT = V->getOperand(0).getValueType(); 11363 int OpSize = OpVT.getVectorNumElements(); 11364 SmallBitVector OpUsedElements(OpSize, false); 11365 bool FoundSimplification = false; 11366 SmallVector<SDValue, 4> NewOps; 11367 NewOps.reserve(V->getNumOperands()); 11368 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) { 11369 SDValue Op = V->getOperand(i); 11370 bool OpUsed = false; 11371 for (int j = 0; j < OpSize; ++j) 11372 if (UsedElements[i * OpSize + j]) { 11373 OpUsedElements[j] = true; 11374 OpUsed = true; 11375 } 11376 NewOps.push_back( 11377 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG) 11378 : DAG.getUNDEF(OpVT)); 11379 FoundSimplification |= Op == NewOps.back(); 11380 OpUsedElements.reset(); 11381 } 11382 if (FoundSimplification) 11383 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps); 11384 return V; 11385 } 11386 11387 case ISD::INSERT_SUBVECTOR: { 11388 SDValue BaseV = V->getOperand(0); 11389 SDValue SubV = V->getOperand(1); 11390 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2)); 11391 if (!IdxN) 11392 return V; 11393 11394 int SubSize = SubV.getValueType().getVectorNumElements(); 11395 int Idx = IdxN->getZExtValue(); 11396 bool SubVectorUsed = false; 11397 SmallBitVector SubUsedElements(SubSize, false); 11398 for (int i = 0; i < SubSize; ++i) 11399 if (UsedElements[i + Idx]) { 11400 SubVectorUsed = true; 11401 SubUsedElements[i] = true; 11402 UsedElements[i + Idx] = false; 11403 } 11404 11405 // Now recurse on both the base and sub vectors. 11406 SDValue SimplifiedSubV = 11407 SubVectorUsed 11408 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG) 11409 : DAG.getUNDEF(SubV.getValueType()); 11410 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG); 11411 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV) 11412 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 11413 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2)); 11414 return V; 11415 } 11416 } 11417 } 11418 11419 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0, 11420 SDValue N1, SelectionDAG &DAG) { 11421 EVT VT = SVN->getValueType(0); 11422 int NumElts = VT.getVectorNumElements(); 11423 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false); 11424 for (int M : SVN->getMask()) 11425 if (M >= 0 && M < NumElts) 11426 N0UsedElements[M] = true; 11427 else if (M >= NumElts) 11428 N1UsedElements[M - NumElts] = true; 11429 11430 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG); 11431 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG); 11432 if (S0 == N0 && S1 == N1) 11433 return SDValue(); 11434 11435 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask()); 11436 } 11437 11438 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 11439 // or turn a shuffle of a single concat into simpler shuffle then concat. 11440 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 11441 EVT VT = N->getValueType(0); 11442 unsigned NumElts = VT.getVectorNumElements(); 11443 11444 SDValue N0 = N->getOperand(0); 11445 SDValue N1 = N->getOperand(1); 11446 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11447 11448 SmallVector<SDValue, 4> Ops; 11449 EVT ConcatVT = N0.getOperand(0).getValueType(); 11450 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 11451 unsigned NumConcats = NumElts / NumElemsPerConcat; 11452 11453 // Special case: shuffle(concat(A,B)) can be more efficiently represented 11454 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 11455 // half vector elements. 11456 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF && 11457 std::all_of(SVN->getMask().begin() + NumElemsPerConcat, 11458 SVN->getMask().end(), [](int i) { return i == -1; })) { 11459 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1), 11460 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat)); 11461 N1 = DAG.getUNDEF(ConcatVT); 11462 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 11463 } 11464 11465 // Look at every vector that's inserted. We're looking for exact 11466 // subvector-sized copies from a concatenated vector 11467 for (unsigned I = 0; I != NumConcats; ++I) { 11468 // Make sure we're dealing with a copy. 11469 unsigned Begin = I * NumElemsPerConcat; 11470 bool AllUndef = true, NoUndef = true; 11471 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) { 11472 if (SVN->getMaskElt(J) >= 0) 11473 AllUndef = false; 11474 else 11475 NoUndef = false; 11476 } 11477 11478 if (NoUndef) { 11479 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0) 11480 return SDValue(); 11481 11482 for (unsigned J = 1; J != NumElemsPerConcat; ++J) 11483 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J)) 11484 return SDValue(); 11485 11486 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat; 11487 if (FirstElt < N0.getNumOperands()) 11488 Ops.push_back(N0.getOperand(FirstElt)); 11489 else 11490 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands())); 11491 11492 } else if (AllUndef) { 11493 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType())); 11494 } else { // Mixed with general masks and undefs, can't do optimization. 11495 return SDValue(); 11496 } 11497 } 11498 11499 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 11500 } 11501 11502 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 11503 EVT VT = N->getValueType(0); 11504 unsigned NumElts = VT.getVectorNumElements(); 11505 11506 SDValue N0 = N->getOperand(0); 11507 SDValue N1 = N->getOperand(1); 11508 11509 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 11510 11511 // Canonicalize shuffle undef, undef -> undef 11512 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF) 11513 return DAG.getUNDEF(VT); 11514 11515 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 11516 11517 // Canonicalize shuffle v, v -> v, undef 11518 if (N0 == N1) { 11519 SmallVector<int, 8> NewMask; 11520 for (unsigned i = 0; i != NumElts; ++i) { 11521 int Idx = SVN->getMaskElt(i); 11522 if (Idx >= (int)NumElts) Idx -= NumElts; 11523 NewMask.push_back(Idx); 11524 } 11525 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 11526 &NewMask[0]); 11527 } 11528 11529 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 11530 if (N0.getOpcode() == ISD::UNDEF) { 11531 SmallVector<int, 8> NewMask; 11532 for (unsigned i = 0; i != NumElts; ++i) { 11533 int Idx = SVN->getMaskElt(i); 11534 if (Idx >= 0) { 11535 if (Idx >= (int)NumElts) 11536 Idx -= NumElts; 11537 else 11538 Idx = -1; // remove reference to lhs 11539 } 11540 NewMask.push_back(Idx); 11541 } 11542 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT), 11543 &NewMask[0]); 11544 } 11545 11546 // Remove references to rhs if it is undef 11547 if (N1.getOpcode() == ISD::UNDEF) { 11548 bool Changed = false; 11549 SmallVector<int, 8> NewMask; 11550 for (unsigned i = 0; i != NumElts; ++i) { 11551 int Idx = SVN->getMaskElt(i); 11552 if (Idx >= (int)NumElts) { 11553 Idx = -1; 11554 Changed = true; 11555 } 11556 NewMask.push_back(Idx); 11557 } 11558 if (Changed) 11559 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]); 11560 } 11561 11562 // If it is a splat, check if the argument vector is another splat or a 11563 // build_vector. 11564 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 11565 SDNode *V = N0.getNode(); 11566 11567 // If this is a bit convert that changes the element type of the vector but 11568 // not the number of vector elements, look through it. Be careful not to 11569 // look though conversions that change things like v4f32 to v2f64. 11570 if (V->getOpcode() == ISD::BITCAST) { 11571 SDValue ConvInput = V->getOperand(0); 11572 if (ConvInput.getValueType().isVector() && 11573 ConvInput.getValueType().getVectorNumElements() == NumElts) 11574 V = ConvInput.getNode(); 11575 } 11576 11577 if (V->getOpcode() == ISD::BUILD_VECTOR) { 11578 assert(V->getNumOperands() == NumElts && 11579 "BUILD_VECTOR has wrong number of operands"); 11580 SDValue Base; 11581 bool AllSame = true; 11582 for (unsigned i = 0; i != NumElts; ++i) { 11583 if (V->getOperand(i).getOpcode() != ISD::UNDEF) { 11584 Base = V->getOperand(i); 11585 break; 11586 } 11587 } 11588 // Splat of <u, u, u, u>, return <u, u, u, u> 11589 if (!Base.getNode()) 11590 return N0; 11591 for (unsigned i = 0; i != NumElts; ++i) { 11592 if (V->getOperand(i) != Base) { 11593 AllSame = false; 11594 break; 11595 } 11596 } 11597 // Splat of <x, x, x, x>, return <x, x, x, x> 11598 if (AllSame) 11599 return N0; 11600 11601 // If the splatted element is a constant, just build the vector out of 11602 // constants directly. 11603 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex()); 11604 if (isa<ConstantSDNode>(Splatted) || isa<ConstantFPSDNode>(Splatted)) { 11605 SmallVector<SDValue, 8> Ops; 11606 for (unsigned i = 0; i != NumElts; ++i) { 11607 Ops.push_back(Splatted); 11608 } 11609 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), 11610 V->getValueType(0), Ops); 11611 11612 // We may have jumped through bitcasts, so the type of the 11613 // BUILD_VECTOR may not match the type of the shuffle. 11614 if (V->getValueType(0) != VT) 11615 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV); 11616 return NewBV; 11617 } 11618 } 11619 } 11620 11621 // There are various patterns used to build up a vector from smaller vectors, 11622 // subvectors, or elements. Scan chains of these and replace unused insertions 11623 // or components with undef. 11624 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG)) 11625 return S; 11626 11627 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 11628 Level < AfterLegalizeVectorOps && 11629 (N1.getOpcode() == ISD::UNDEF || 11630 (N1.getOpcode() == ISD::CONCAT_VECTORS && 11631 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 11632 SDValue V = partitionShuffleOfConcats(N, DAG); 11633 11634 if (V.getNode()) 11635 return V; 11636 } 11637 11638 // Canonicalize shuffles according to rules: 11639 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 11640 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 11641 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 11642 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 11643 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 11644 TLI.isTypeLegal(VT)) { 11645 // The incoming shuffle must be of the same type as the result of the 11646 // current shuffle. 11647 assert(N1->getOperand(0).getValueType() == VT && 11648 "Shuffle types don't match"); 11649 11650 SDValue SV0 = N1->getOperand(0); 11651 SDValue SV1 = N1->getOperand(1); 11652 bool HasSameOp0 = N0 == SV0; 11653 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF; 11654 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 11655 // Commute the operands of this shuffle so that next rule 11656 // will trigger. 11657 return DAG.getCommutedVectorShuffle(*SVN); 11658 } 11659 11660 // Try to fold according to rules: 11661 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 11662 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 11663 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 11664 // Don't try to fold shuffles with illegal type. 11665 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 11666 TLI.isTypeLegal(VT)) { 11667 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 11668 11669 // The incoming shuffle must be of the same type as the result of the 11670 // current shuffle. 11671 assert(OtherSV->getOperand(0).getValueType() == VT && 11672 "Shuffle types don't match"); 11673 11674 SDValue SV0, SV1; 11675 SmallVector<int, 4> Mask; 11676 // Compute the combined shuffle mask for a shuffle with SV0 as the first 11677 // operand, and SV1 as the second operand. 11678 for (unsigned i = 0; i != NumElts; ++i) { 11679 int Idx = SVN->getMaskElt(i); 11680 if (Idx < 0) { 11681 // Propagate Undef. 11682 Mask.push_back(Idx); 11683 continue; 11684 } 11685 11686 SDValue CurrentVec; 11687 if (Idx < (int)NumElts) { 11688 // This shuffle index refers to the inner shuffle N0. Lookup the inner 11689 // shuffle mask to identify which vector is actually referenced. 11690 Idx = OtherSV->getMaskElt(Idx); 11691 if (Idx < 0) { 11692 // Propagate Undef. 11693 Mask.push_back(Idx); 11694 continue; 11695 } 11696 11697 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 11698 : OtherSV->getOperand(1); 11699 } else { 11700 // This shuffle index references an element within N1. 11701 CurrentVec = N1; 11702 } 11703 11704 // Simple case where 'CurrentVec' is UNDEF. 11705 if (CurrentVec.getOpcode() == ISD::UNDEF) { 11706 Mask.push_back(-1); 11707 continue; 11708 } 11709 11710 // Canonicalize the shuffle index. We don't know yet if CurrentVec 11711 // will be the first or second operand of the combined shuffle. 11712 Idx = Idx % NumElts; 11713 if (!SV0.getNode() || SV0 == CurrentVec) { 11714 // Ok. CurrentVec is the left hand side. 11715 // Update the mask accordingly. 11716 SV0 = CurrentVec; 11717 Mask.push_back(Idx); 11718 continue; 11719 } 11720 11721 // Bail out if we cannot convert the shuffle pair into a single shuffle. 11722 if (SV1.getNode() && SV1 != CurrentVec) 11723 return SDValue(); 11724 11725 // Ok. CurrentVec is the right hand side. 11726 // Update the mask accordingly. 11727 SV1 = CurrentVec; 11728 Mask.push_back(Idx + NumElts); 11729 } 11730 11731 // Check if all indices in Mask are Undef. In case, propagate Undef. 11732 bool isUndefMask = true; 11733 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 11734 isUndefMask &= Mask[i] < 0; 11735 11736 if (isUndefMask) 11737 return DAG.getUNDEF(VT); 11738 11739 if (!SV0.getNode()) 11740 SV0 = DAG.getUNDEF(VT); 11741 if (!SV1.getNode()) 11742 SV1 = DAG.getUNDEF(VT); 11743 11744 // Avoid introducing shuffles with illegal mask. 11745 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 11746 // Compute the commuted shuffle mask and test again. 11747 for (unsigned i = 0; i != NumElts; ++i) { 11748 int idx = Mask[i]; 11749 if (idx < 0) 11750 continue; 11751 else if (idx < (int)NumElts) 11752 Mask[i] = idx + NumElts; 11753 else 11754 Mask[i] = idx - NumElts; 11755 } 11756 11757 if (!TLI.isShuffleMaskLegal(Mask, VT)) 11758 return SDValue(); 11759 11760 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 11761 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 11762 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 11763 std::swap(SV0, SV1); 11764 } 11765 11766 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 11767 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 11768 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 11769 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]); 11770 } 11771 11772 return SDValue(); 11773 } 11774 11775 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 11776 SDValue N0 = N->getOperand(0); 11777 SDValue N2 = N->getOperand(2); 11778 11779 // If the input vector is a concatenation, and the insert replaces 11780 // one of the halves, we can optimize into a single concat_vectors. 11781 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 11782 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) { 11783 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue(); 11784 EVT VT = N->getValueType(0); 11785 11786 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) -> 11787 // (concat_vectors Z, Y) 11788 if (InsIdx == 0) 11789 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11790 N->getOperand(1), N0.getOperand(1)); 11791 11792 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) -> 11793 // (concat_vectors X, Z) 11794 if (InsIdx == VT.getVectorNumElements()/2) 11795 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 11796 N0.getOperand(0), N->getOperand(1)); 11797 } 11798 11799 return SDValue(); 11800 } 11801 11802 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 11803 /// with the destination vector and a zero vector. 11804 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 11805 /// vector_shuffle V, Zero, <0, 4, 2, 4> 11806 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 11807 EVT VT = N->getValueType(0); 11808 SDLoc dl(N); 11809 SDValue LHS = N->getOperand(0); 11810 SDValue RHS = N->getOperand(1); 11811 if (N->getOpcode() == ISD::AND) { 11812 if (RHS.getOpcode() == ISD::BITCAST) 11813 RHS = RHS.getOperand(0); 11814 if (RHS.getOpcode() == ISD::BUILD_VECTOR) { 11815 SmallVector<int, 8> Indices; 11816 unsigned NumElts = RHS.getNumOperands(); 11817 for (unsigned i = 0; i != NumElts; ++i) { 11818 SDValue Elt = RHS.getOperand(i); 11819 if (!isa<ConstantSDNode>(Elt)) 11820 return SDValue(); 11821 11822 if (cast<ConstantSDNode>(Elt)->isAllOnesValue()) 11823 Indices.push_back(i); 11824 else if (cast<ConstantSDNode>(Elt)->isNullValue()) 11825 Indices.push_back(NumElts+i); 11826 else 11827 return SDValue(); 11828 } 11829 11830 // Let's see if the target supports this vector_shuffle. 11831 EVT RVT = RHS.getValueType(); 11832 if (!TLI.isVectorClearMaskLegal(Indices, RVT)) 11833 return SDValue(); 11834 11835 // Return the new VECTOR_SHUFFLE node. 11836 EVT EltVT = RVT.getVectorElementType(); 11837 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(), 11838 DAG.getConstant(0, EltVT)); 11839 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps); 11840 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS); 11841 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]); 11842 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf); 11843 } 11844 } 11845 11846 return SDValue(); 11847 } 11848 11849 /// Visit a binary vector operation, like ADD. 11850 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 11851 assert(N->getValueType(0).isVector() && 11852 "SimplifyVBinOp only works on vectors!"); 11853 11854 SDValue LHS = N->getOperand(0); 11855 SDValue RHS = N->getOperand(1); 11856 SDValue Shuffle = XformToShuffleWithZero(N); 11857 if (Shuffle.getNode()) return Shuffle; 11858 11859 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold 11860 // this operation. 11861 if (LHS.getOpcode() == ISD::BUILD_VECTOR && 11862 RHS.getOpcode() == ISD::BUILD_VECTOR) { 11863 // Check if both vectors are constants. If not bail out. 11864 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() && 11865 cast<BuildVectorSDNode>(RHS)->isConstant())) 11866 return SDValue(); 11867 11868 SmallVector<SDValue, 8> Ops; 11869 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 11870 SDValue LHSOp = LHS.getOperand(i); 11871 SDValue RHSOp = RHS.getOperand(i); 11872 11873 // Can't fold divide by zero. 11874 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV || 11875 N->getOpcode() == ISD::FDIV) { 11876 if ((RHSOp.getOpcode() == ISD::Constant && 11877 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) || 11878 (RHSOp.getOpcode() == ISD::ConstantFP && 11879 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero())) 11880 break; 11881 } 11882 11883 EVT VT = LHSOp.getValueType(); 11884 EVT RVT = RHSOp.getValueType(); 11885 if (RVT != VT) { 11886 // Integer BUILD_VECTOR operands may have types larger than the element 11887 // size (e.g., when the element type is not legal). Prior to type 11888 // legalization, the types may not match between the two BUILD_VECTORS. 11889 // Truncate one of the operands to make them match. 11890 if (RVT.getSizeInBits() > VT.getSizeInBits()) { 11891 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp); 11892 } else { 11893 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp); 11894 VT = RVT; 11895 } 11896 } 11897 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT, 11898 LHSOp, RHSOp); 11899 if (FoldOp.getOpcode() != ISD::UNDEF && 11900 FoldOp.getOpcode() != ISD::Constant && 11901 FoldOp.getOpcode() != ISD::ConstantFP) 11902 break; 11903 Ops.push_back(FoldOp); 11904 AddToWorklist(FoldOp.getNode()); 11905 } 11906 11907 if (Ops.size() == LHS.getNumOperands()) 11908 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops); 11909 } 11910 11911 // Type legalization might introduce new shuffles in the DAG. 11912 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask))) 11913 // -> (shuffle (VBinOp (A, B)), Undef, Mask). 11914 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) && 11915 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() && 11916 LHS.getOperand(1).getOpcode() == ISD::UNDEF && 11917 RHS.getOperand(1).getOpcode() == ISD::UNDEF) { 11918 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS); 11919 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS); 11920 11921 if (SVN0->getMask().equals(SVN1->getMask())) { 11922 EVT VT = N->getValueType(0); 11923 SDValue UndefVector = LHS.getOperand(1); 11924 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT, 11925 LHS.getOperand(0), RHS.getOperand(0)); 11926 AddUsersToWorklist(N); 11927 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector, 11928 &SVN0->getMask()[0]); 11929 } 11930 } 11931 11932 return SDValue(); 11933 } 11934 11935 /// Visit a binary vector operation, like FABS/FNEG. 11936 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) { 11937 assert(N->getValueType(0).isVector() && 11938 "SimplifyVUnaryOp only works on vectors!"); 11939 11940 SDValue N0 = N->getOperand(0); 11941 11942 if (N0.getOpcode() != ISD::BUILD_VECTOR) 11943 return SDValue(); 11944 11945 // Operand is a BUILD_VECTOR node, see if we can constant fold it. 11946 SmallVector<SDValue, 8> Ops; 11947 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 11948 SDValue Op = N0.getOperand(i); 11949 if (Op.getOpcode() != ISD::UNDEF && 11950 Op.getOpcode() != ISD::ConstantFP) 11951 break; 11952 EVT EltVT = Op.getValueType(); 11953 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op); 11954 if (FoldOp.getOpcode() != ISD::UNDEF && 11955 FoldOp.getOpcode() != ISD::ConstantFP) 11956 break; 11957 Ops.push_back(FoldOp); 11958 AddToWorklist(FoldOp.getNode()); 11959 } 11960 11961 if (Ops.size() != N0.getNumOperands()) 11962 return SDValue(); 11963 11964 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops); 11965 } 11966 11967 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0, 11968 SDValue N1, SDValue N2){ 11969 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 11970 11971 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 11972 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 11973 11974 // If we got a simplified select_cc node back from SimplifySelectCC, then 11975 // break it down into a new SETCC node, and a new SELECT node, and then return 11976 // the SELECT node, since we were called with a SELECT node. 11977 if (SCC.getNode()) { 11978 // Check to see if we got a select_cc back (to turn into setcc/select). 11979 // Otherwise, just return whatever node we got back, like fabs. 11980 if (SCC.getOpcode() == ISD::SELECT_CC) { 11981 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 11982 N0.getValueType(), 11983 SCC.getOperand(0), SCC.getOperand(1), 11984 SCC.getOperand(4)); 11985 AddToWorklist(SETCC.getNode()); 11986 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 11987 SCC.getOperand(2), SCC.getOperand(3)); 11988 } 11989 11990 return SCC; 11991 } 11992 return SDValue(); 11993 } 11994 11995 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 11996 /// being selected between, see if we can simplify the select. Callers of this 11997 /// should assume that TheSelect is deleted if this returns true. As such, they 11998 /// should return the appropriate thing (e.g. the node) back to the top-level of 11999 /// the DAG combiner loop to avoid it being looked at. 12000 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 12001 SDValue RHS) { 12002 12003 // Cannot simplify select with vector condition 12004 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 12005 12006 // If this is a select from two identical things, try to pull the operation 12007 // through the select. 12008 if (LHS.getOpcode() != RHS.getOpcode() || 12009 !LHS.hasOneUse() || !RHS.hasOneUse()) 12010 return false; 12011 12012 // If this is a load and the token chain is identical, replace the select 12013 // of two loads with a load through a select of the address to load from. 12014 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 12015 // constants have been dropped into the constant pool. 12016 if (LHS.getOpcode() == ISD::LOAD) { 12017 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 12018 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 12019 12020 // Token chains must be identical. 12021 if (LHS.getOperand(0) != RHS.getOperand(0) || 12022 // Do not let this transformation reduce the number of volatile loads. 12023 LLD->isVolatile() || RLD->isVolatile() || 12024 // If this is an EXTLOAD, the VT's must match. 12025 LLD->getMemoryVT() != RLD->getMemoryVT() || 12026 // If this is an EXTLOAD, the kind of extension must match. 12027 (LLD->getExtensionType() != RLD->getExtensionType() && 12028 // The only exception is if one of the extensions is anyext. 12029 LLD->getExtensionType() != ISD::EXTLOAD && 12030 RLD->getExtensionType() != ISD::EXTLOAD) || 12031 // FIXME: this discards src value information. This is 12032 // over-conservative. It would be beneficial to be able to remember 12033 // both potential memory locations. Since we are discarding 12034 // src value info, don't do the transformation if the memory 12035 // locations are not in the default address space. 12036 LLD->getPointerInfo().getAddrSpace() != 0 || 12037 RLD->getPointerInfo().getAddrSpace() != 0 || 12038 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 12039 LLD->getBasePtr().getValueType())) 12040 return false; 12041 12042 // Check that the select condition doesn't reach either load. If so, 12043 // folding this will induce a cycle into the DAG. If not, this is safe to 12044 // xform, so create a select of the addresses. 12045 SDValue Addr; 12046 if (TheSelect->getOpcode() == ISD::SELECT) { 12047 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 12048 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) || 12049 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode))) 12050 return false; 12051 // The loads must not depend on one another. 12052 if (LLD->isPredecessorOf(RLD) || 12053 RLD->isPredecessorOf(LLD)) 12054 return false; 12055 Addr = DAG.getSelect(SDLoc(TheSelect), 12056 LLD->getBasePtr().getValueType(), 12057 TheSelect->getOperand(0), LLD->getBasePtr(), 12058 RLD->getBasePtr()); 12059 } else { // Otherwise SELECT_CC 12060 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 12061 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 12062 12063 if ((LLD->hasAnyUseOfValue(1) && 12064 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) || 12065 (RLD->hasAnyUseOfValue(1) && 12066 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS)))) 12067 return false; 12068 12069 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 12070 LLD->getBasePtr().getValueType(), 12071 TheSelect->getOperand(0), 12072 TheSelect->getOperand(1), 12073 LLD->getBasePtr(), RLD->getBasePtr(), 12074 TheSelect->getOperand(4)); 12075 } 12076 12077 SDValue Load; 12078 // It is safe to replace the two loads if they have different alignments, 12079 // but the new load must be the minimum (most restrictive) alignment of the 12080 // inputs. 12081 bool isInvariant = LLD->isInvariant() & RLD->isInvariant(); 12082 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 12083 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 12084 Load = DAG.getLoad(TheSelect->getValueType(0), 12085 SDLoc(TheSelect), 12086 // FIXME: Discards pointer and AA info. 12087 LLD->getChain(), Addr, MachinePointerInfo(), 12088 LLD->isVolatile(), LLD->isNonTemporal(), 12089 isInvariant, Alignment); 12090 } else { 12091 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ? 12092 RLD->getExtensionType() : LLD->getExtensionType(), 12093 SDLoc(TheSelect), 12094 TheSelect->getValueType(0), 12095 // FIXME: Discards pointer and AA info. 12096 LLD->getChain(), Addr, MachinePointerInfo(), 12097 LLD->getMemoryVT(), LLD->isVolatile(), 12098 LLD->isNonTemporal(), isInvariant, Alignment); 12099 } 12100 12101 // Users of the select now use the result of the load. 12102 CombineTo(TheSelect, Load); 12103 12104 // Users of the old loads now use the new load's chain. We know the 12105 // old-load value is dead now. 12106 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 12107 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 12108 return true; 12109 } 12110 12111 return false; 12112 } 12113 12114 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 12115 /// where 'cond' is the comparison specified by CC. 12116 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, 12117 SDValue N2, SDValue N3, 12118 ISD::CondCode CC, bool NotExtCompare) { 12119 // (x ? y : y) -> y. 12120 if (N2 == N3) return N2; 12121 12122 EVT VT = N2.getValueType(); 12123 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 12124 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 12125 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 12126 12127 // Determine if the condition we're dealing with is constant 12128 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), 12129 N0, N1, CC, DL, false); 12130 if (SCC.getNode()) AddToWorklist(SCC.getNode()); 12131 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode()); 12132 12133 // fold select_cc true, x, y -> x 12134 if (SCCC && !SCCC->isNullValue()) 12135 return N2; 12136 // fold select_cc false, x, y -> y 12137 if (SCCC && SCCC->isNullValue()) 12138 return N3; 12139 12140 // Check to see if we can simplify the select into an fabs node 12141 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) { 12142 // Allow either -0.0 or 0.0 12143 if (CFP->getValueAPF().isZero()) { 12144 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs 12145 if ((CC == ISD::SETGE || CC == ISD::SETGT) && 12146 N0 == N2 && N3.getOpcode() == ISD::FNEG && 12147 N2 == N3.getOperand(0)) 12148 return DAG.getNode(ISD::FABS, DL, VT, N0); 12149 12150 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs 12151 if ((CC == ISD::SETLT || CC == ISD::SETLE) && 12152 N0 == N3 && N2.getOpcode() == ISD::FNEG && 12153 N2.getOperand(0) == N3) 12154 return DAG.getNode(ISD::FABS, DL, VT, N3); 12155 } 12156 } 12157 12158 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 12159 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 12160 // in it. This is a win when the constant is not otherwise available because 12161 // it replaces two constant pool loads with one. We only do this if the FP 12162 // type is known to be legal, because if it isn't, then we are before legalize 12163 // types an we want the other legalization to happen first (e.g. to avoid 12164 // messing with soft float) and if the ConstantFP is not legal, because if 12165 // it is legal, we may not need to store the FP constant in a constant pool. 12166 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2)) 12167 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) { 12168 if (TLI.isTypeLegal(N2.getValueType()) && 12169 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) != 12170 TargetLowering::Legal && 12171 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) && 12172 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) && 12173 // If both constants have multiple uses, then we won't need to do an 12174 // extra load, they are likely around in registers for other users. 12175 (TV->hasOneUse() || FV->hasOneUse())) { 12176 Constant *Elts[] = { 12177 const_cast<ConstantFP*>(FV->getConstantFPValue()), 12178 const_cast<ConstantFP*>(TV->getConstantFPValue()) 12179 }; 12180 Type *FPTy = Elts[0]->getType(); 12181 const DataLayout &TD = *TLI.getDataLayout(); 12182 12183 // Create a ConstantArray of the two constants. 12184 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 12185 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(), 12186 TD.getPrefTypeAlignment(FPTy)); 12187 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 12188 12189 // Get the offsets to the 0 and 1 element of the array so that we can 12190 // select between them. 12191 SDValue Zero = DAG.getIntPtrConstant(0); 12192 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 12193 SDValue One = DAG.getIntPtrConstant(EltSize); 12194 12195 SDValue Cond = DAG.getSetCC(DL, 12196 getSetCCResultType(N0.getValueType()), 12197 N0, N1, CC); 12198 AddToWorklist(Cond.getNode()); 12199 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), 12200 Cond, One, Zero); 12201 AddToWorklist(CstOffset.getNode()); 12202 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, 12203 CstOffset); 12204 AddToWorklist(CPIdx.getNode()); 12205 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 12206 MachinePointerInfo::getConstantPool(), false, 12207 false, false, Alignment); 12208 12209 } 12210 } 12211 12212 // Check to see if we can perform the "gzip trick", transforming 12213 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A) 12214 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT && 12215 (N1C->isNullValue() || // (a < 0) ? b : 0 12216 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0 12217 EVT XType = N0.getValueType(); 12218 EVT AType = N2.getValueType(); 12219 if (XType.bitsGE(AType)) { 12220 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a 12221 // single-bit constant. 12222 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) { 12223 unsigned ShCtV = N2C->getAPIntValue().logBase2(); 12224 ShCtV = XType.getSizeInBits()-ShCtV-1; 12225 SDValue ShCt = DAG.getConstant(ShCtV, 12226 getShiftAmountTy(N0.getValueType())); 12227 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), 12228 XType, N0, ShCt); 12229 AddToWorklist(Shift.getNode()); 12230 12231 if (XType.bitsGT(AType)) { 12232 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 12233 AddToWorklist(Shift.getNode()); 12234 } 12235 12236 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 12237 } 12238 12239 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), 12240 XType, N0, 12241 DAG.getConstant(XType.getSizeInBits()-1, 12242 getShiftAmountTy(N0.getValueType()))); 12243 AddToWorklist(Shift.getNode()); 12244 12245 if (XType.bitsGT(AType)) { 12246 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 12247 AddToWorklist(Shift.getNode()); 12248 } 12249 12250 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 12251 } 12252 } 12253 12254 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 12255 // where y is has a single bit set. 12256 // A plaintext description would be, we can turn the SELECT_CC into an AND 12257 // when the condition can be materialized as an all-ones register. Any 12258 // single bit-test can be materialized as an all-ones register with 12259 // shift-left and shift-right-arith. 12260 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 12261 N0->getValueType(0) == VT && 12262 N1C && N1C->isNullValue() && 12263 N2C && N2C->isNullValue()) { 12264 SDValue AndLHS = N0->getOperand(0); 12265 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 12266 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 12267 // Shift the tested bit over the sign bit. 12268 APInt AndMask = ConstAndRHS->getAPIntValue(); 12269 SDValue ShlAmt = 12270 DAG.getConstant(AndMask.countLeadingZeros(), 12271 getShiftAmountTy(AndLHS.getValueType())); 12272 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 12273 12274 // Now arithmetic right shift it all the way over, so the result is either 12275 // all-ones, or zero. 12276 SDValue ShrAmt = 12277 DAG.getConstant(AndMask.getBitWidth()-1, 12278 getShiftAmountTy(Shl.getValueType())); 12279 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 12280 12281 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 12282 } 12283 } 12284 12285 // fold select C, 16, 0 -> shl C, 4 12286 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() && 12287 TLI.getBooleanContents(N0.getValueType()) == 12288 TargetLowering::ZeroOrOneBooleanContent) { 12289 12290 // If the caller doesn't want us to simplify this into a zext of a compare, 12291 // don't do it. 12292 if (NotExtCompare && N2C->getAPIntValue() == 1) 12293 return SDValue(); 12294 12295 // Get a SetCC of the condition 12296 // NOTE: Don't create a SETCC if it's not legal on this target. 12297 if (!LegalOperations || 12298 TLI.isOperationLegal(ISD::SETCC, 12299 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) { 12300 SDValue Temp, SCC; 12301 // cast from setcc result type to select result type 12302 if (LegalTypes) { 12303 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), 12304 N0, N1, CC); 12305 if (N2.getValueType().bitsLT(SCC.getValueType())) 12306 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), 12307 N2.getValueType()); 12308 else 12309 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 12310 N2.getValueType(), SCC); 12311 } else { 12312 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 12313 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), 12314 N2.getValueType(), SCC); 12315 } 12316 12317 AddToWorklist(SCC.getNode()); 12318 AddToWorklist(Temp.getNode()); 12319 12320 if (N2C->getAPIntValue() == 1) 12321 return Temp; 12322 12323 // shl setcc result by log2 n2c 12324 return DAG.getNode( 12325 ISD::SHL, DL, N2.getValueType(), Temp, 12326 DAG.getConstant(N2C->getAPIntValue().logBase2(), 12327 getShiftAmountTy(Temp.getValueType()))); 12328 } 12329 } 12330 12331 // Check to see if this is the equivalent of setcc 12332 // FIXME: Turn all of these into setcc if setcc if setcc is legal 12333 // otherwise, go ahead with the folds. 12334 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) { 12335 EVT XType = N0.getValueType(); 12336 if (!LegalOperations || 12337 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) { 12338 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC); 12339 if (Res.getValueType() != VT) 12340 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res); 12341 return Res; 12342 } 12343 12344 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X)))) 12345 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 12346 (!LegalOperations || 12347 TLI.isOperationLegal(ISD::CTLZ, XType))) { 12348 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0); 12349 return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 12350 DAG.getConstant(Log2_32(XType.getSizeInBits()), 12351 getShiftAmountTy(Ctlz.getValueType()))); 12352 } 12353 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1)) 12354 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 12355 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0), 12356 XType, DAG.getConstant(0, XType), N0); 12357 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType); 12358 return DAG.getNode(ISD::SRL, DL, XType, 12359 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0), 12360 DAG.getConstant(XType.getSizeInBits()-1, 12361 getShiftAmountTy(XType))); 12362 } 12363 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1)) 12364 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) { 12365 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0, 12366 DAG.getConstant(XType.getSizeInBits()-1, 12367 getShiftAmountTy(N0.getValueType()))); 12368 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType)); 12369 } 12370 } 12371 12372 // Check to see if this is an integer abs. 12373 // select_cc setg[te] X, 0, X, -X -> 12374 // select_cc setgt X, -1, X, -X -> 12375 // select_cc setl[te] X, 0, -X, X -> 12376 // select_cc setlt X, 1, -X, X -> 12377 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 12378 if (N1C) { 12379 ConstantSDNode *SubC = nullptr; 12380 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) || 12381 (N1C->isAllOnesValue() && CC == ISD::SETGT)) && 12382 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) 12383 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0)); 12384 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) || 12385 (N1C->isOne() && CC == ISD::SETLT)) && 12386 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) 12387 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0)); 12388 12389 EVT XType = N0.getValueType(); 12390 if (SubC && SubC->isNullValue() && XType.isInteger()) { 12391 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType, 12392 N0, 12393 DAG.getConstant(XType.getSizeInBits()-1, 12394 getShiftAmountTy(N0.getValueType()))); 12395 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), 12396 XType, N0, Shift); 12397 AddToWorklist(Shift.getNode()); 12398 AddToWorklist(Add.getNode()); 12399 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift); 12400 } 12401 } 12402 12403 return SDValue(); 12404 } 12405 12406 /// This is a stub for TargetLowering::SimplifySetCC. 12407 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, 12408 SDValue N1, ISD::CondCode Cond, 12409 SDLoc DL, bool foldBooleans) { 12410 TargetLowering::DAGCombinerInfo 12411 DagCombineInfo(DAG, Level, false, this); 12412 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 12413 } 12414 12415 /// Given an ISD::SDIV node expressing a divide by constant, return 12416 /// a DAG expression to select that will generate the same value by multiplying 12417 /// by a magic number. 12418 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 12419 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 12420 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 12421 if (!C) 12422 return SDValue(); 12423 12424 // Avoid division by zero. 12425 if (!C->getAPIntValue()) 12426 return SDValue(); 12427 12428 std::vector<SDNode*> Built; 12429 SDValue S = 12430 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 12431 12432 for (SDNode *N : Built) 12433 AddToWorklist(N); 12434 return S; 12435 } 12436 12437 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 12438 /// DAG expression that will generate the same value by right shifting. 12439 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 12440 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 12441 if (!C) 12442 return SDValue(); 12443 12444 // Avoid division by zero. 12445 if (!C->getAPIntValue()) 12446 return SDValue(); 12447 12448 std::vector<SDNode *> Built; 12449 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built); 12450 12451 for (SDNode *N : Built) 12452 AddToWorklist(N); 12453 return S; 12454 } 12455 12456 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 12457 /// expression that will generate the same value by multiplying by a magic 12458 /// number. 12459 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 12460 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 12461 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 12462 if (!C) 12463 return SDValue(); 12464 12465 // Avoid division by zero. 12466 if (!C->getAPIntValue()) 12467 return SDValue(); 12468 12469 std::vector<SDNode*> Built; 12470 SDValue S = 12471 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built); 12472 12473 for (SDNode *N : Built) 12474 AddToWorklist(N); 12475 return S; 12476 } 12477 12478 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) { 12479 if (Level >= AfterLegalizeDAG) 12480 return SDValue(); 12481 12482 // Expose the DAG combiner to the target combiner implementations. 12483 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 12484 12485 unsigned Iterations = 0; 12486 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) { 12487 if (Iterations) { 12488 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 12489 // For the reciprocal, we need to find the zero of the function: 12490 // F(X) = A X - 1 [which has a zero at X = 1/A] 12491 // => 12492 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 12493 // does not require additional intermediate precision] 12494 EVT VT = Op.getValueType(); 12495 SDLoc DL(Op); 12496 SDValue FPOne = DAG.getConstantFP(1.0, VT); 12497 12498 AddToWorklist(Est.getNode()); 12499 12500 // Newton iterations: Est = Est + Est (1 - Arg * Est) 12501 for (unsigned i = 0; i < Iterations; ++i) { 12502 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est); 12503 AddToWorklist(NewEst.getNode()); 12504 12505 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst); 12506 AddToWorklist(NewEst.getNode()); 12507 12508 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 12509 AddToWorklist(NewEst.getNode()); 12510 12511 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst); 12512 AddToWorklist(Est.getNode()); 12513 } 12514 } 12515 return Est; 12516 } 12517 12518 return SDValue(); 12519 } 12520 12521 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 12522 /// For the reciprocal sqrt, we need to find the zero of the function: 12523 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 12524 /// => 12525 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 12526 /// As a result, we precompute A/2 prior to the iteration loop. 12527 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est, 12528 unsigned Iterations) { 12529 EVT VT = Arg.getValueType(); 12530 SDLoc DL(Arg); 12531 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT); 12532 12533 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 12534 // this entire sequence requires only one FP constant. 12535 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg); 12536 AddToWorklist(HalfArg.getNode()); 12537 12538 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg); 12539 AddToWorklist(HalfArg.getNode()); 12540 12541 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 12542 for (unsigned i = 0; i < Iterations; ++i) { 12543 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 12544 AddToWorklist(NewEst.getNode()); 12545 12546 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst); 12547 AddToWorklist(NewEst.getNode()); 12548 12549 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst); 12550 AddToWorklist(NewEst.getNode()); 12551 12552 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst); 12553 AddToWorklist(Est.getNode()); 12554 } 12555 return Est; 12556 } 12557 12558 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 12559 /// For the reciprocal sqrt, we need to find the zero of the function: 12560 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 12561 /// => 12562 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 12563 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est, 12564 unsigned Iterations) { 12565 EVT VT = Arg.getValueType(); 12566 SDLoc DL(Arg); 12567 SDValue MinusThree = DAG.getConstantFP(-3.0, VT); 12568 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT); 12569 12570 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est) 12571 for (unsigned i = 0; i < Iterations; ++i) { 12572 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf); 12573 AddToWorklist(HalfEst.getNode()); 12574 12575 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est); 12576 AddToWorklist(Est.getNode()); 12577 12578 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg); 12579 AddToWorklist(Est.getNode()); 12580 12581 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree); 12582 AddToWorklist(Est.getNode()); 12583 12584 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst); 12585 AddToWorklist(Est.getNode()); 12586 } 12587 return Est; 12588 } 12589 12590 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) { 12591 if (Level >= AfterLegalizeDAG) 12592 return SDValue(); 12593 12594 // Expose the DAG combiner to the target combiner implementations. 12595 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this); 12596 unsigned Iterations = 0; 12597 bool UseOneConstNR = false; 12598 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) { 12599 AddToWorklist(Est.getNode()); 12600 if (Iterations) { 12601 Est = UseOneConstNR ? 12602 BuildRsqrtNROneConst(Op, Est, Iterations) : 12603 BuildRsqrtNRTwoConst(Op, Est, Iterations); 12604 } 12605 return Est; 12606 } 12607 12608 return SDValue(); 12609 } 12610 12611 /// Return true if base is a frame index, which is known not to alias with 12612 /// anything but itself. Provides base object and offset as results. 12613 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset, 12614 const GlobalValue *&GV, const void *&CV) { 12615 // Assume it is a primitive operation. 12616 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr; 12617 12618 // If it's an adding a simple constant then integrate the offset. 12619 if (Base.getOpcode() == ISD::ADD) { 12620 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) { 12621 Base = Base.getOperand(0); 12622 Offset += C->getZExtValue(); 12623 } 12624 } 12625 12626 // Return the underlying GlobalValue, and update the Offset. Return false 12627 // for GlobalAddressSDNode since the same GlobalAddress may be represented 12628 // by multiple nodes with different offsets. 12629 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) { 12630 GV = G->getGlobal(); 12631 Offset += G->getOffset(); 12632 return false; 12633 } 12634 12635 // Return the underlying Constant value, and update the Offset. Return false 12636 // for ConstantSDNodes since the same constant pool entry may be represented 12637 // by multiple nodes with different offsets. 12638 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) { 12639 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal() 12640 : (const void *)C->getConstVal(); 12641 Offset += C->getOffset(); 12642 return false; 12643 } 12644 // If it's any of the following then it can't alias with anything but itself. 12645 return isa<FrameIndexSDNode>(Base); 12646 } 12647 12648 /// Return true if there is any possibility that the two addresses overlap. 12649 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const { 12650 // If they are the same then they must be aliases. 12651 if (Op0->getBasePtr() == Op1->getBasePtr()) return true; 12652 12653 // If they are both volatile then they cannot be reordered. 12654 if (Op0->isVolatile() && Op1->isVolatile()) return true; 12655 12656 // Gather base node and offset information. 12657 SDValue Base1, Base2; 12658 int64_t Offset1, Offset2; 12659 const GlobalValue *GV1, *GV2; 12660 const void *CV1, *CV2; 12661 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(), 12662 Base1, Offset1, GV1, CV1); 12663 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(), 12664 Base2, Offset2, GV2, CV2); 12665 12666 // If they have a same base address then check to see if they overlap. 12667 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2))) 12668 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 12669 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 12670 12671 // It is possible for different frame indices to alias each other, mostly 12672 // when tail call optimization reuses return address slots for arguments. 12673 // To catch this case, look up the actual index of frame indices to compute 12674 // the real alias relationship. 12675 if (isFrameIndex1 && isFrameIndex2) { 12676 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 12677 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex()); 12678 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex()); 12679 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 || 12680 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1); 12681 } 12682 12683 // Otherwise, if we know what the bases are, and they aren't identical, then 12684 // we know they cannot alias. 12685 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2)) 12686 return false; 12687 12688 // If we know required SrcValue1 and SrcValue2 have relatively large alignment 12689 // compared to the size and offset of the access, we may be able to prove they 12690 // do not alias. This check is conservative for now to catch cases created by 12691 // splitting vector types. 12692 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) && 12693 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) && 12694 (Op0->getMemoryVT().getSizeInBits() >> 3 == 12695 Op1->getMemoryVT().getSizeInBits() >> 3) && 12696 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) { 12697 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment(); 12698 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment(); 12699 12700 // There is no overlap between these relatively aligned accesses of similar 12701 // size, return no alias. 12702 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 || 12703 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1) 12704 return false; 12705 } 12706 12707 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 12708 ? CombinerGlobalAA 12709 : DAG.getSubtarget().useAA(); 12710 #ifndef NDEBUG 12711 if (CombinerAAOnlyFunc.getNumOccurrences() && 12712 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 12713 UseAA = false; 12714 #endif 12715 if (UseAA && 12716 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) { 12717 // Use alias analysis information. 12718 int64_t MinOffset = std::min(Op0->getSrcValueOffset(), 12719 Op1->getSrcValueOffset()); 12720 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) + 12721 Op0->getSrcValueOffset() - MinOffset; 12722 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) + 12723 Op1->getSrcValueOffset() - MinOffset; 12724 AliasAnalysis::AliasResult AAResult = 12725 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(), 12726 Overlap1, 12727 UseTBAA ? Op0->getAAInfo() : AAMDNodes()), 12728 AliasAnalysis::Location(Op1->getMemOperand()->getValue(), 12729 Overlap2, 12730 UseTBAA ? Op1->getAAInfo() : AAMDNodes())); 12731 if (AAResult == AliasAnalysis::NoAlias) 12732 return false; 12733 } 12734 12735 // Otherwise we have to assume they alias. 12736 return true; 12737 } 12738 12739 /// Walk up chain skipping non-aliasing memory nodes, 12740 /// looking for aliasing nodes and adding them to the Aliases vector. 12741 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 12742 SmallVectorImpl<SDValue> &Aliases) { 12743 SmallVector<SDValue, 8> Chains; // List of chains to visit. 12744 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 12745 12746 // Get alias information for node. 12747 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile(); 12748 12749 // Starting off. 12750 Chains.push_back(OriginalChain); 12751 unsigned Depth = 0; 12752 12753 // Look at each chain and determine if it is an alias. If so, add it to the 12754 // aliases list. If not, then continue up the chain looking for the next 12755 // candidate. 12756 while (!Chains.empty()) { 12757 SDValue Chain = Chains.back(); 12758 Chains.pop_back(); 12759 12760 // For TokenFactor nodes, look at each operand and only continue up the 12761 // chain until we find two aliases. If we've seen two aliases, assume we'll 12762 // find more and revert to original chain since the xform is unlikely to be 12763 // profitable. 12764 // 12765 // FIXME: The depth check could be made to return the last non-aliasing 12766 // chain we found before we hit a tokenfactor rather than the original 12767 // chain. 12768 if (Depth > 6 || Aliases.size() == 2) { 12769 Aliases.clear(); 12770 Aliases.push_back(OriginalChain); 12771 return; 12772 } 12773 12774 // Don't bother if we've been before. 12775 if (!Visited.insert(Chain.getNode()).second) 12776 continue; 12777 12778 switch (Chain.getOpcode()) { 12779 case ISD::EntryToken: 12780 // Entry token is ideal chain operand, but handled in FindBetterChain. 12781 break; 12782 12783 case ISD::LOAD: 12784 case ISD::STORE: { 12785 // Get alias information for Chain. 12786 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) && 12787 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile(); 12788 12789 // If chain is alias then stop here. 12790 if (!(IsLoad && IsOpLoad) && 12791 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) { 12792 Aliases.push_back(Chain); 12793 } else { 12794 // Look further up the chain. 12795 Chains.push_back(Chain.getOperand(0)); 12796 ++Depth; 12797 } 12798 break; 12799 } 12800 12801 case ISD::TokenFactor: 12802 // We have to check each of the operands of the token factor for "small" 12803 // token factors, so we queue them up. Adding the operands to the queue 12804 // (stack) in reverse order maintains the original order and increases the 12805 // likelihood that getNode will find a matching token factor (CSE.) 12806 if (Chain.getNumOperands() > 16) { 12807 Aliases.push_back(Chain); 12808 break; 12809 } 12810 for (unsigned n = Chain.getNumOperands(); n;) 12811 Chains.push_back(Chain.getOperand(--n)); 12812 ++Depth; 12813 break; 12814 12815 default: 12816 // For all other instructions we will just have to take what we can get. 12817 Aliases.push_back(Chain); 12818 break; 12819 } 12820 } 12821 12822 // We need to be careful here to also search for aliases through the 12823 // value operand of a store, etc. Consider the following situation: 12824 // Token1 = ... 12825 // L1 = load Token1, %52 12826 // S1 = store Token1, L1, %51 12827 // L2 = load Token1, %52+8 12828 // S2 = store Token1, L2, %51+8 12829 // Token2 = Token(S1, S2) 12830 // L3 = load Token2, %53 12831 // S3 = store Token2, L3, %52 12832 // L4 = load Token2, %53+8 12833 // S4 = store Token2, L4, %52+8 12834 // If we search for aliases of S3 (which loads address %52), and we look 12835 // only through the chain, then we'll miss the trivial dependence on L1 12836 // (which also loads from %52). We then might change all loads and 12837 // stores to use Token1 as their chain operand, which could result in 12838 // copying %53 into %52 before copying %52 into %51 (which should 12839 // happen first). 12840 // 12841 // The problem is, however, that searching for such data dependencies 12842 // can become expensive, and the cost is not directly related to the 12843 // chain depth. Instead, we'll rule out such configurations here by 12844 // insisting that we've visited all chain users (except for users 12845 // of the original chain, which is not necessary). When doing this, 12846 // we need to look through nodes we don't care about (otherwise, things 12847 // like register copies will interfere with trivial cases). 12848 12849 SmallVector<const SDNode *, 16> Worklist; 12850 for (const SDNode *N : Visited) 12851 if (N != OriginalChain.getNode()) 12852 Worklist.push_back(N); 12853 12854 while (!Worklist.empty()) { 12855 const SDNode *M = Worklist.pop_back_val(); 12856 12857 // We have already visited M, and want to make sure we've visited any uses 12858 // of M that we care about. For uses that we've not visisted, and don't 12859 // care about, queue them to the worklist. 12860 12861 for (SDNode::use_iterator UI = M->use_begin(), 12862 UIE = M->use_end(); UI != UIE; ++UI) 12863 if (UI.getUse().getValueType() == MVT::Other && 12864 Visited.insert(*UI).second) { 12865 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) { 12866 // We've not visited this use, and we care about it (it could have an 12867 // ordering dependency with the original node). 12868 Aliases.clear(); 12869 Aliases.push_back(OriginalChain); 12870 return; 12871 } 12872 12873 // We've not visited this use, but we don't care about it. Mark it as 12874 // visited and enqueue it to the worklist. 12875 Worklist.push_back(*UI); 12876 } 12877 } 12878 } 12879 12880 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 12881 /// (aliasing node.) 12882 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 12883 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor. 12884 12885 // Accumulate all the aliases to this node. 12886 GatherAllAliases(N, OldChain, Aliases); 12887 12888 // If no operands then chain to entry token. 12889 if (Aliases.size() == 0) 12890 return DAG.getEntryNode(); 12891 12892 // If a single operand then chain to it. We don't need to revisit it. 12893 if (Aliases.size() == 1) 12894 return Aliases[0]; 12895 12896 // Construct a custom tailored token factor. 12897 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases); 12898 } 12899 12900 /// This is the entry point for the file. 12901 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, 12902 CodeGenOpt::Level OptLevel) { 12903 /// This is the main entry point to this class. 12904 DAGCombiner(*this, AA, OptLevel).Run(Level); 12905 } 12906